From d9d5b7b5c58a7b044b78ee7993f0a15e5b79f689 Mon Sep 17 00:00:00 2001
From: miepzerino <o.skotnik@gmail.com>
Date: Thu, 03 Apr 2025 18:28:15 +0000
Subject: [PATCH] #42 started performance fixes for chunk generation

---
 Assets/Scripts/GenerateTileMap.cs |  184 ++++++++++++++++++++++++++++++++++++++-------
 1 files changed, 153 insertions(+), 31 deletions(-)

diff --git a/Assets/Scripts/GenerateTileMap.cs b/Assets/Scripts/GenerateTileMap.cs
index 7bf0667..28d1cc4 100644
--- a/Assets/Scripts/GenerateTileMap.cs
+++ b/Assets/Scripts/GenerateTileMap.cs
@@ -1,6 +1,9 @@
 using System;
 using System.Collections;
 using System.Collections.Generic;
+using System.Linq;
+using Unity.Collections;
+using Unity.Jobs;
 using Unity.VisualScripting;
 using UnityEngine;
 using UnityEngine.Tilemaps;
@@ -52,6 +55,10 @@
     private Transform playerTransform; // Reference to player/camera
     private Vector2Int lastLoadedChunk;
     private GameManager gameManager;
+    private Dictionary<Vector2Int, HashSet<Vector3Int>> activeChunkTiles = new Dictionary<Vector2Int, HashSet<Vector3Int>>();
+    public TilePool tilePool; // Reference to the TilePool script
+    private bool isGenerating = false;
+
 
     private void Awake()
     {
@@ -70,20 +77,38 @@
 
         // Position adjusted to center horizontally, but align top at y=0
         transform.position = new Vector3((maxWidth / 2) * -1, -1, transform.position.z);
+        tilePool.InitializePool(forestRuleTile);
 
         LoadGenerateablesFromResources();
     }
     private void Update()
     {
-        if (playerTransform == null) return;
-        Debug.Log($"Player Position: {playerTransform.position}");
+        if (playerTransform == null || isGenerating) return;
+
         Vector2Int currentChunk = GetChunkPosition(playerTransform.position);
-        Debug.Log($"Current Chunk: {currentChunk}");
         if (currentChunk != lastLoadedChunk)
         {
-            StartCoroutine(UpdateLoadedChunks(currentChunk));
+            isGenerating = true;
+            StopAllCoroutines();
+
+            var chunksToUnload = loadedChunks.Keys
+                .Where(chunk => Mathf.Abs(chunk.x - currentChunk.x) > LOAD_DISTANCE ||
+                               Mathf.Abs(chunk.y - currentChunk.y) > LOAD_DISTANCE)
+                .ToList();
+
+            foreach (var chunk in chunksToUnload)
+            {
+                UnloadChunk(chunk);
+            }
+
+            StartCoroutine(UpdateLoadedChunksWithCompletion(currentChunk));
             lastLoadedChunk = currentChunk;
         }
+    }
+    private IEnumerator UpdateLoadedChunksWithCompletion(Vector2Int currentChunk)
+    {
+        yield return UpdateLoadedChunks(currentChunk);
+        isGenerating = false;
     }
     // When a tile is destroyed in a chunk, update GameManager's list
     private void AddDestroyedTile(Vector3Int tilePos)
@@ -92,6 +117,45 @@
         {
             gameManager.destroyedTiles.Add(tilePos);
         }
+    }
+    private void SetTileWithPool(Vector3Int position, CustomRuleTile tileType)
+    {
+        var chunk = new Vector2Int(
+            Mathf.FloorToInt(position.x / (float)CHUNK_SIZE),
+            Mathf.FloorToInt(position.y / (float)CHUNK_SIZE)
+        );
+
+        if (!activeChunkTiles.ContainsKey(chunk))
+        {
+            activeChunkTiles[chunk] = new HashSet<Vector3Int>();
+        }
+
+        var tileData = tilePool.GetTileData(position, tileType);
+        if (tileData != null)
+        {
+            tilemap.SetTile(position, tileData.tileType);
+            activeChunkTiles[chunk].Add(position);
+
+            // Refresh neighboring tiles to maintain proper rule tile connections
+            for (int nx = -1; nx <= 1; nx++)
+            {
+                for (int ny = -1; ny <= 1; ny++)
+                {
+                    if (nx == 0 && ny == 0) continue;
+                    Vector3Int neighbor = new Vector3Int(position.x + nx, position.y + ny, position.z);
+                    if (tilemap.HasTile(neighbor))
+                    {
+                        tilemap.RefreshTile(neighbor);
+                    }
+                }
+            }
+        }
+    }
+
+    private void RemoveTileWithPool(Vector3Int position)
+    {
+        tilemap.SetTile(position, null);
+        tilePool.ReturnTileData(position);
     }
 
     // When checking if a tile is destroyed, use GameManager's list
@@ -123,16 +187,25 @@
 
     private void UnloadChunk(Vector2Int chunk)
     {
+        if (!loadedChunks.ContainsKey(chunk)) return;
+
         int startX = chunk.x * CHUNK_SIZE;
         int startY = chunk.y * CHUNK_SIZE;
 
-        for (int x = startX; x < startX + CHUNK_SIZE; x++)
+        // Clear rule cache for this chunk
+        forestRuleTile.ClearRuleCache();
+
+        // Remove all tiles in the chunk
+        if (activeChunkTiles.TryGetValue(chunk, out var tiles))
         {
-            for (int y = startY; y > startY - CHUNK_SIZE; y--)
+            foreach (var pos in tiles)
             {
-                tilemap.SetTile(new Vector3Int(x, y), null);
+                RemoveTileWithPool(pos);
             }
+            activeChunkTiles.Remove(chunk);
         }
+
+        loadedChunks.Remove(chunk);
     }
     private void LoadGenerateablesFromResources()
     {
@@ -232,42 +305,91 @@
     private IEnumerator GenerateChunk(Vector2Int chunk, List<Vector3Int> destroyedTiles)
     {
         int startX = chunk.x * CHUNK_SIZE;
-        int startY = (chunk.y * CHUNK_SIZE);
+        int startY = chunk.y * CHUNK_SIZE;
 
-        // Generate ground in chunk
-        for (int x = startX; x < startX + CHUNK_SIZE; x++)
+        // Clear rule cache for this chunk's area
+        forestRuleTile.ClearRuleCache();
+
+        NativeArray<bool> terrainMap = default;
+        NativeArray<float> noiseMap = default;
+
+        try
         {
-            if (x < 1 || x >= maxWidth) continue;
+            terrainMap = new NativeArray<bool>(CHUNK_SIZE * CHUNK_SIZE, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);
+            noiseMap = new NativeArray<float>(CHUNK_SIZE * CHUNK_SIZE, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);
 
-            for (int y = startY; y > startY - CHUNK_SIZE; y--)
+            var job = new TerrainGenerationJob
             {
-                if (y < -groundDepth || y >= 0) continue;
-                Vector3Int tilePos = new Vector3Int(x, y);
-                if (IsTileDestroyed(tilePos))
-                    continue;
+                ChunkStartX = startX,
+                ChunkStartY = startY,
+                ChunkSize = CHUNK_SIZE,
+                Scale = scale,
+                OffsetX = offsetX,
+                OffsetY = offsetY,
+                MaxWidth = maxWidth,
+                MaxDepth = maxDepth,
+                TerrainMap = terrainMap,
+                NoiseMap = noiseMap
+            };
 
-                float xPerlin = ((float)x / maxWidth) * scale + offsetX;
-                float yPerlin = ((float)Mathf.Abs(y) / maxDepth) * scale + offsetY;
-                float perlinNoise = Mathf.PerlinNoise(xPerlin, yPerlin);
+            // Schedule and complete job immediately to prevent frame lifetime issues
+            job.Schedule(CHUNK_SIZE * CHUNK_SIZE, 32).Complete();
 
-                if (perlinNoise <= 0.7f)
+            // Copy data from job before yielding
+            var tilesToUpdate = new List<(Vector3Int pos, CustomRuleTile tile)>();
+
+            for (int i = 0; i < terrainMap.Length; i++)
+            {
+                if (terrainMap[i])
                 {
-                    tilemap.SetTile(tilePos, forestRuleTile);
+                    int x = startX + (i % CHUNK_SIZE);
+                    int y = startY - (i / CHUNK_SIZE);
+                    Vector3Int tilePos = new Vector3Int(x, y);
+
+                    if (!IsTileDestroyed(tilePos))
+                    {
+                        tilesToUpdate.Add((tilePos, forestRuleTile));
+                    }
                 }
             }
-        }
 
-        // Generate ores in chunk
-        if (generateables != null)
-        {
-            yield return GenerateOresInChunk(chunk, destroyedTiles);
+            // Dispose native arrays before yielding
+            terrainMap.Dispose();
+            noiseMap.Dispose();
+            terrainMap = default;
+            noiseMap = default;
+
+            // Now we can safely yield and process tiles
+            const int BATCH_SIZE = 32;
+            for (int i = 0; i < tilesToUpdate.Count; i += BATCH_SIZE)
+            {
+                int batchCount = Math.Min(BATCH_SIZE, tilesToUpdate.Count - i);
+                for (int j = 0; j < batchCount; j++)
+                {
+                    var (pos, tile) = tilesToUpdate[i + j];
+                    SetTileWithPool(pos, tile);
+                }
+                yield return null;
+            }
+
+            // Generate ores
+            if (generateables != null)
+            {
+                yield return GenerateOresInChunk(chunk, destroyedTiles);
+            }
+
+            // Generate borders if needed
+            if (startX == 0 || startX + CHUNK_SIZE >= maxWidth ||
+                startY == 0 || startY - CHUNK_SIZE <= -groundDepth)
+            {
+                yield return GenerateBorders();
+            }
         }
-        // Don't generate borders for each chunk
-        // Only generate borders when at world edges
-        if (startX == 0 || startX + CHUNK_SIZE >= maxWidth ||
-            startY == 0 || startY - CHUNK_SIZE <= -groundDepth)
+        finally
         {
-            yield return GenerateBorders();
+            // Ensure arrays are always disposed
+            if (terrainMap.IsCreated) terrainMap.Dispose();
+            if (noiseMap.IsCreated) noiseMap.Dispose();
         }
     }
 

--
Gitblit v1.9.3