| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895 |
- using UnityEngine;
- using System.Collections.Generic;
- public class MapMaker2 : MonoBehaviour
- {
- [Header("Map Settings")]
- public int initialMapSize = 150;
- public int expansionSize = 50;
- public float playerDistanceThreshold = 20f;
- [Header("Simple Mode")]
- [Tooltip("Use simple static map generation (no exploration/expansion)")]
- public bool useSimpleMode = true;
- [Header("Exploration Settings")]
- [Tooltip("Use exploration system instead of expansion")]
- public bool useExplorationSystem = true;
- public void SetMapData(MapData newMapData)
- {
- mapData = newMapData;
- // Update the visualization
- if (mapVisualizer != null)
- {
- mapVisualizer.VisualizeMap(mapData);
- }
- else
- {
- Debug.LogWarning("⚠️ MapVisualizer is null, cannot update visualization");
- }
- }
- public MapData GetMapData()
- {
- return mapData;
- }
- [Header("Exploration Settings")]
- public int explorationMapSize = 300;
- public int explorationInitialVisible = 80;
- [Header("Expansion Settings")]
- [Tooltip("Cooldown time between map expansions in seconds")]
- public float expansionCooldown = 5f;
- [Tooltip("Chance for terrain to continue from existing edge (0-1)")]
- [Range(0f, 1f)]
- public float terrainContinuityChance = 0.7f;
- [Header("Generation Settings")]
- public int seed = 12345;
- [Header("Visualization")]
- public MapVisualizer mapVisualizer;
- [Header("Debug")]
- public bool debugMode = false;
- private MapData mapData;
- private TerrainGenerator terrainGenerator;
- private FeatureGenerator featureGenerator;
- private ExpansionManager expansionManager;
- private ExplorationManager explorationManager;
- private Transform player;
- private float lastExpansionTime = 0f;
- void Start()
- {
- InitializeMap();
- if (useSimpleMode)
- {
- GenerateCompleteMapWithTeamMarker();
- }
- else if (useExplorationSystem)
- {
- InitializeExplorationSystem();
- }
- else
- {
- GenerateInitialMap();
- }
- }
- void Update()
- {
- // In simple mode, no expansion or exploration updates needed
- if (useSimpleMode)
- {
- // Only handle finding the player reference if missing
- if (player == null)
- {
- GameObject teamMarker = GameObject.Find("TeamMarker");
- if (teamMarker != null)
- {
- player = teamMarker.transform;
- }
- }
- return;
- }
- // Only handle finding the player reference, not continuous exploration checks
- if (player == null)
- {
- // Debug log every few seconds to show player reference status
- if (Time.time % 3f < Time.deltaTime)
- {
- Debug.LogWarning($"🚫 MapMaker2 Update: Player reference is null! useExplorationSystem: {useExplorationSystem}");
- // Try to find TeamMarker if not found
- GameObject teamMarker = GameObject.Find("TeamMarker");
- if (teamMarker != null)
- {
- player = teamMarker.transform;
- }
- }
- }
- else if (!useExplorationSystem)
- {
- // Only run expansion checks for the old system
- CheckForExpansion();
- }
- // Exploration system is now event-driven, no Update checks needed!
- }
- private void InitializeMap()
- {
- Random.InitState(seed);
- mapData = new MapData(initialMapSize, initialMapSize);
- terrainGenerator = new TerrainGenerator();
- featureGenerator = new FeatureGenerator();
- expansionManager = new ExpansionManager(this);
- explorationManager = new ExplorationManager(this);
- // Find player object - try multiple approaches
- GameObject playerObj = GameObject.FindGameObjectWithTag("Player");
- // If no "Player" tag found, try finding by name patterns
- if (playerObj == null)
- {
- // Try common player names
- string[] playerNames = { "TeamMarker", "Player", "PlayerCharacter", "Team", "MainCharacter" };
- foreach (string name in playerNames)
- {
- playerObj = GameObject.Find(name);
- if (playerObj != null)
- {
- Debug.LogWarning($"Found player object by name '{name}' but it doesn't have 'Player' tag. Consider adding the tag.");
- break;
- }
- }
- }
- if (playerObj != null)
- {
- player = playerObj.transform;
- }
- else
- {
- Debug.LogWarning("No player object found! Trying to find any object that might be the player...");
- }
- // Initialize visualizer if not set
- if (mapVisualizer == null)
- mapVisualizer = GetComponent<MapVisualizer>();
- }
- private void GenerateInitialMap()
- {
- // Generate base terrain
- terrainGenerator.GenerateTerrain(mapData);
- // Generate features
- featureGenerator.GenerateFeatures(mapData);
- // Visualize the map
- VisualizeMap();
- }
- /// <summary>
- /// Generate complete map with team marker placement - Simple Mode
- /// </summary>
- private void GenerateCompleteMapWithTeamMarker()
- {
- // Generate the full beautiful map using original generators
- terrainGenerator.GenerateTerrain(mapData);
- featureGenerator.GenerateFeatures(mapData);
- // Find a good settlement for team marker placement
- Vector2Int? settlementPos = FindBestSettlementForTeamMarker();
- if (!settlementPos.HasValue)
- {
- // Fallback to center if no settlements found
- Vector2Int centerPos = new Vector2Int(mapData.Width / 2, mapData.Height / 2);
- // PlaceTeamMarkerAt(centerPos);
- Debug.LogWarning($"⚠️ No settlements found, placed team marker at center: {centerPos}");
- }
- // Visualize the map
- VisualizeMap();
- }
- /// <summary>
- /// Find the best settlement position for team marker placement
- /// </summary>
- private Vector2Int? FindBestSettlementForTeamMarker()
- {
- List<Vector2Int> settlements = new List<Vector2Int>();
- // Find all towns and villages
- for (int x = 0; x < mapData.Width; x++)
- {
- for (int y = 0; y < mapData.Height; y++)
- {
- MapTile tile = mapData.GetTile(x, y);
- if (tile != null && (tile.featureType == FeatureType.Town || tile.featureType == FeatureType.Village))
- {
- settlements.Add(new Vector2Int(x, y));
- }
- }
- }
- if (settlements.Count == 0) return null;
- // Prefer towns over villages, and those closer to center
- Vector2 center = new Vector2(mapData.Width / 2f, mapData.Height / 2f);
- Vector2Int bestSettlement = settlements[0];
- float bestScore = float.MinValue;
- foreach (Vector2Int settlement in settlements)
- {
- MapTile tile = mapData.GetTile(settlement.x, settlement.y);
- float score = 0;
- // Prefer towns (higher score)
- if (tile.featureType == FeatureType.Town) score += 100;
- else score += 50; // Village
- // Prefer locations closer to center (but not exactly center)
- float distanceToCenter = Vector2.Distance(settlement, center);
- score += Mathf.Max(0, 50 - distanceToCenter); // Closer to center = higher score
- if (score > bestScore)
- {
- bestScore = score;
- bestSettlement = settlement;
- }
- }
- return bestSettlement;
- }
- /// <summary>
- /// Place team marker at specified map coordinates
- /// </summary>
- private void PlaceTeamMarkerAt(Vector2Int mapPos)
- {
- // Remove existing team marker
- GameObject existingMarker = GameObject.Find("TeamMarker");
- if (existingMarker != null)
- {
- DestroyImmediate(existingMarker);
- }
- // Create new team marker
- GameObject teamMarker = new GameObject("TeamMarkerMapMaker2");
- // Position it correctly in world space
- teamMarker.transform.position = new Vector3(mapPos.x, 0.5f, mapPos.y);
- // Add visual representation
- GameObject visualMarker = GameObject.CreatePrimitive(PrimitiveType.Sphere);
- visualMarker.transform.SetParent(teamMarker.transform);
- visualMarker.transform.localPosition = Vector3.zero;
- visualMarker.transform.localScale = Vector3.one * 0.8f;
- // Make it green and distinctive
- Renderer renderer = visualMarker.GetComponent<Renderer>();
- if (renderer != null)
- {
- renderer.material.color = Color.green;
- }
- // Add a tag for easy finding
- teamMarker.tag = "Player";
- // Update player reference
- player = teamMarker.transform;
- }
- private void CheckForExpansion()
- {
- // Check if mapVisualizer is available and has valid tileSize
- if (mapVisualizer == null)
- {
- Debug.LogWarning("MapVisualizer is null! Cannot check for expansion.");
- return;
- }
- float tileSize = mapVisualizer.tileSize;
- if (tileSize <= 0)
- {
- Debug.LogWarning($"Invalid tile size: {tileSize}. Using default value of 1.");
- tileSize = 1f;
- }
- // Debug player position
- Vector2 playerPos = new Vector2(player.position.x / tileSize, player.position.z / tileSize);
- // Debug log every few seconds
- if (Time.time % 2f < Time.deltaTime) // Log every 2 seconds
- {
- }
- // Check cooldown to prevent rapid expansions
- if (Time.time - lastExpansionTime < expansionCooldown)
- return;
- if (expansionManager.ShouldExpand(playerPos, mapData))
- {
- ExpandMap(playerPos);
- }
- }
- private void ExpandMap(Vector2 playerPos)
- {
- lastExpansionTime = Time.time;
- expansionManager.ExpandMap(mapData, playerPos, expansionSize);
- VisualizeMap(); // Update visualization
- }
- private void VisualizeMap()
- {
- if (mapVisualizer != null)
- {
- mapVisualizer.VisualizeMap(mapData);
- }
- }
- public TerrainGenerator GetTerrainGenerator() => terrainGenerator;
- public FeatureGenerator GetFeatureGenerator() => featureGenerator;
- public ExplorationManager GetExplorationManager() => explorationManager;
- // Public method to manually set player reference if automatic detection fails
- public void SetPlayer(Transform playerTransform)
- {
- player = playerTransform;
- }
- /// <summary>
- /// Enable Simple Mode - Beautiful map generation without exploration/expansion
- /// </summary>
- [ContextMenu("🎮 Enable Simple Mode (Beautiful Map + Team Marker)")]
- public void EnableSimpleMode()
- {
- useSimpleMode = true;
- useExplorationSystem = false;
- // Clear existing map visualization
- if (mapVisualizer != null)
- mapVisualizer.ClearAllTiles();
- // Regenerate with simple mode
- mapData = new MapData(initialMapSize, initialMapSize);
- GenerateCompleteMapWithTeamMarker();
- }
- // For debugging - regenerate map
- [ContextMenu("Regenerate Map")]
- public void RegenerateMap()
- {
- if (mapVisualizer != null)
- mapVisualizer.ClearAllTiles();
- // Preserve current map size instead of resetting to initial size
- int currentWidth = mapData != null ? mapData.Width : initialMapSize;
- int currentHeight = mapData != null ? mapData.Height : initialMapSize;
- Random.InitState(seed);
- mapData = new MapData(currentWidth, currentHeight);
- terrainGenerator = new TerrainGenerator();
- featureGenerator = new FeatureGenerator();
- GenerateInitialMap();
- }
- // For debugging - reset to original size
- [ContextMenu("Reset to Original Size")]
- public void ResetToOriginalSize()
- {
- if (mapVisualizer != null)
- mapVisualizer.ClearAllTiles();
- InitializeMap();
- GenerateInitialMap();
- }
- // For debugging - force map expansion
- [ContextMenu("Force Map Expansion")]
- public void ForceExpansion()
- {
- Vector2 playerPos;
- if (player != null)
- {
- float tileSize = mapVisualizer != null && mapVisualizer.tileSize > 0 ? mapVisualizer.tileSize : 1f;
- playerPos = new Vector2(player.position.x / tileSize, player.position.z / tileSize);
- }
- else
- {
- // If no player, expand from center-right edge to test the system
- playerPos = new Vector2(mapData.Width - 10, mapData.Height / 2);
- Debug.LogWarning("No player found, using test position for forced expansion");
- }
- lastExpansionTime = 0f; // Reset cooldown
- ExpandMap(playerPos);
- }
- // For debugging - manually set TeamMarker as player
- [ContextMenu("Set TeamMarker as Player")]
- public void SetTeamMarkerAsPlayer()
- {
- GameObject teamMarker = GameObject.Find("TeamMarker");
- if (teamMarker != null)
- {
- SetPlayer(teamMarker.transform);
- }
- else
- {
- Debug.LogError("TeamMarker object not found!");
- }
- }
- // === Exploration System Methods ===
- private void InitializeExplorationSystem()
- {
- if (explorationManager == null)
- {
- Debug.LogError("❌ ExplorationManager is null! Cannot initialize exploration system.");
- return;
- }
- explorationManager.fullMapWidth = explorationMapSize;
- explorationManager.fullMapHeight = explorationMapSize;
- explorationManager.initialVisibleSize = explorationInitialVisible;
- explorationManager.InitializeExploration();
- }
- private void ExploreNewAreas(Vector2 playerPos)
- {
- lastExpansionTime = Time.time;
- explorationManager.ExploreNewAreas(playerPos, mapData);
- VisualizeMap(); // Update visualization
- }
- // === Public Methods for Event-Driven Exploration ===
- /// <summary>
- /// Check for exploration when team position changes (event-driven)
- /// </summary>
- public void OnTeamPositionChanged(Vector2Int newPosition)
- {
- if (!useExplorationSystem || explorationManager == null)
- return;
- // Optimization: Only check if team moved a significant distance or cooldown passed
- if (Time.time - lastExpansionTime < expansionCooldown)
- return;
- // Convert tile position to world position for exploration system
- Vector2 worldPos = new Vector2(newPosition.x, newPosition.y);
- if (explorationManager.ShouldExplore(worldPos, mapData))
- {
- ExploreNewAreas(worldPos);
- }
- }
- // === Methods needed by ExplorationManager ===
- public void GenerateCompleteMap(MapData targetMapData)
- {
- // Generate base terrain
- terrainGenerator.GenerateTerrain(targetMapData);
- // Generate features
- featureGenerator.GenerateFeatures(targetMapData);
- }
- [ContextMenu("Enable Exploration System")]
- public void EnableExplorationSystem()
- {
- useExplorationSystem = true;
- }
- [ContextMenu("Test Exploration Now")]
- public void TestExplorationNow()
- {
- if (!useExplorationSystem)
- {
- Debug.LogWarning("⚠️ Exploration system is not enabled! Enable it first.");
- return;
- }
- // Debug player detection
- if (player == null)
- {
- // Try to find player again
- GameObject playerObj = GameObject.FindGameObjectWithTag("Player");
- if (playerObj == null)
- {
- playerObj = GameObject.Find("TeamMarker");
- }
- if (playerObj != null)
- {
- player = playerObj.transform;
- }
- else
- {
- Debug.LogError("❌ Cannot find player object! Make sure TeamMarker has 'Player' tag or is named 'TeamMarker'");
- return;
- }
- }
- if (explorationManager == null)
- {
- Debug.LogError("❌ ExplorationManager is null! This should be created in InitializeMap()");
- return;
- }
- float tileSize = mapVisualizer != null && mapVisualizer.tileSize > 0 ? mapVisualizer.tileSize : 1f;
- Vector2 playerPos = new Vector2(player.position.x / tileSize, player.position.z / tileSize);
- // Force exploration regardless of cooldown
- lastExpansionTime = 0f;
- ExploreNewAreas(playerPos);
- }
- [ContextMenu("DEBUG: Show Full 300x300 Map")]
- public void ShowFullMap()
- {
- if (!useExplorationSystem || explorationManager == null)
- {
- Debug.LogError("❌ Exploration system not enabled or null!");
- return;
- }
- explorationManager.ShowFullMap();
- }
- [ContextMenu("DEBUG: Show Exploration State")]
- public void DebugExplorationState()
- {
- if (!useExplorationSystem || explorationManager == null)
- {
- Debug.LogError("❌ Exploration system not enabled or null!");
- return;
- }
- if (player == null)
- {
- GameObject teamMarker = GameObject.Find("TeamMarker");
- if (teamMarker != null) player = teamMarker.transform;
- }
- if (player == null)
- {
- Debug.LogError("❌ No player/team marker found!");
- return;
- }
- float tileSize = mapVisualizer != null && mapVisualizer.tileSize > 0 ? mapVisualizer.tileSize : 1f;
- Vector2 playerPos = new Vector2(player.position.x / tileSize, player.position.z / tileSize);
- explorationManager.DebugExplorationState(playerPos, mapData);
- }
- [ContextMenu("Disable Exploration System")]
- public void DisableExplorationSystem()
- {
- useExplorationSystem = false;
- }
- [ContextMenu("PERF: Toggle Performance Mode")]
- public void TogglePerformanceMode()
- {
- if (explorationManager != null)
- {
- explorationManager.TogglePerformanceMode();
- }
- else
- {
- Debug.LogError("❌ Exploration manager not available!");
- }
- }
- [ContextMenu("PERF: Test 500x500 Map")]
- public void TestLargeMap500()
- {
- if (explorationManager != null)
- {
- explorationManager.SetMapSize(500, 500);
- }
- else
- {
- Debug.LogError("❌ Exploration manager not available!");
- }
- }
- [ContextMenu("PERF: Test 1000x1000 Map")]
- public void TestMassiveMap1000()
- {
- if (explorationManager != null)
- {
- explorationManager.SetMapSize(1000, 1000);
- }
- else
- {
- Debug.LogError("❌ Exploration manager not available!");
- }
- }
- [ContextMenu("PERF: Reset to 300x300")]
- public void ResetToStandardSize()
- {
- if (explorationManager != null)
- {
- explorationManager.SetMapSize(300, 300);
- }
- else
- {
- Debug.LogError("❌ Exploration manager not available!");
- }
- }
- [ContextMenu("FIX: Synchronize Team Marker Position")]
- public void SynchronizeTeamMarkerPosition()
- {
- if (explorationManager != null)
- {
- explorationManager.SynchronizeTeamMarkerPosition();
- }
- else
- {
- Debug.LogError("❌ Exploration manager not available!");
- }
- }
- [ContextMenu("TEST: Debug Full Map Coordinate Fix")]
- public void TestFullMapCoordinateFix()
- {
- if (!useExplorationSystem || explorationManager == null)
- {
- Debug.LogError("❌ Exploration system not enabled or null!");
- return;
- }
- GameObject teamMarker = GameObject.Find("TeamMarker");
- if (teamMarker == null)
- {
- Debug.LogError("❌ Team marker not found!");
- return;
- }
- Vector3 worldPos = teamMarker.transform.position;
- Vector2Int worldTilePos = new Vector2Int(
- Mathf.RoundToInt(worldPos.x),
- Mathf.RoundToInt(worldPos.y)
- );
- // Show full map and check if position is preserved
- explorationManager.ShowFullMap();
- // Check position after full map is shown
- Vector3 newWorldPos = teamMarker.transform.position;
- Vector2Int newWorldTilePos = new Vector2Int(
- Mathf.RoundToInt(newWorldPos.x),
- Mathf.RoundToInt(newWorldPos.y)
- );
- if (worldTilePos != newWorldTilePos)
- {
- Debug.LogError($"❌ COORDINATE FIX FAILED: Position changed from {worldTilePos} to {newWorldTilePos}");
- }
- else
- {
- }
- }
- [ContextMenu("FIX: Reset Team Marker to Map Center")]
- public void ResetTeamMarkerToCenter()
- {
- if (!useExplorationSystem || explorationManager == null)
- {
- Debug.LogError("❌ Exploration system not enabled or null!");
- return;
- }
- explorationManager.ResetTeamMarkerToMapCenter();
- }
- [ContextMenu("FIX: Clear Saved Team Position")]
- public void ClearSavedTeamPosition()
- {
- // Clear saved position from PlayerPrefs
- string keyX = $"TeamPosition_{seed}_X";
- string keyY = $"TeamPosition_{seed}_Y";
- if (PlayerPrefs.HasKey(keyX)) PlayerPrefs.DeleteKey(keyX);
- if (PlayerPrefs.HasKey(keyY)) PlayerPrefs.DeleteKey(keyY);
- PlayerPrefs.Save();
- }
- [ContextMenu("DEBUG: Show Coordinate State")]
- public void DebugCoordinateState()
- {
- if (explorationManager != null)
- {
- explorationManager.DebugCoordinateState();
- }
- else
- {
- Debug.LogError("❌ Exploration manager not available!");
- }
- }
- [ContextMenu("FIX: Force Coordinate Sync")]
- public void ForceCoordinateSync()
- {
- if (explorationManager != null)
- {
- explorationManager.ForceCoordinateSync();
- }
- else
- {
- Debug.LogError("❌ Exploration manager not available!");
- }
- }
- [ContextMenu("TEST: Simple Coordinate Conversion")]
- public void TestSimpleCoordinateConversion()
- {
- if (!useExplorationSystem || explorationManager == null)
- {
- Debug.LogError("❌ Exploration system not enabled or null!");
- return;
- }
- explorationManager.TestSimpleCoordinateConversion();
- }
- [ContextMenu("TEST: Positioning After Fix")]
- public void TestPositioningAfterFix()
- {
- if (!useExplorationSystem || explorationManager == null)
- {
- Debug.LogError("❌ Exploration system not enabled or null!");
- return;
- }
- explorationManager.TestPositioningAfterFix();
- }
- [ContextMenu("TEST: Full Map Tile Coverage")]
- public void TestFullMapTileCoverage()
- {
- if (!useExplorationSystem || explorationManager == null)
- {
- Debug.LogError("❌ Exploration system not enabled or null!");
- return;
- }
- explorationManager.TestFullMapTileCoverage();
- }
- [ContextMenu("TEST: Visual Tile Rendering")]
- public void TestVisualTileRendering()
- {
- if (!useExplorationSystem || explorationManager == null)
- {
- Debug.LogError("❌ Exploration system not enabled or null!");
- return;
- }
- explorationManager.TestVisualTileRendering();
- }
- [ContextMenu("TEST: Detailed Coordinate Conversion")]
- public void TestDetailedCoordinateConversion()
- {
- if (!useExplorationSystem || explorationManager == null)
- {
- Debug.LogError("❌ Exploration system not enabled or null!");
- return;
- }
- explorationManager.TestCoordinateConversion();
- }
- /// <summary>
- /// Public method to synchronize team position - can be called by travel system
- /// </summary>
- public void SyncTeamPosition()
- {
- if (useExplorationSystem && explorationManager != null)
- {
- explorationManager.SynchronizeTeamMarkerPosition();
- }
- }
- // Expose map size properties for ExplorationManager
- public int mapWidth
- {
- get => mapData?.Width ?? initialMapSize;
- set { /* Can be used by exploration system */ }
- }
- public int mapHeight
- {
- get => mapData?.Height ?? initialMapSize;
- set { /* Can be used by exploration system */ }
- }
- }
|