diff --git a/Game/Dungeon/DungeonGeneratorV3.cs b/Game/Dungeon/DungeonGeneratorV3.cs index 199a041..662236a 100644 --- a/Game/Dungeon/DungeonGeneratorV3.cs +++ b/Game/Dungeon/DungeonGeneratorV3.cs @@ -938,39 +938,23 @@ public class DungeonGeneratorV3 if (worldX >= 0 && worldX < MapWidth && worldY >= 0 && worldY < MapHeight) { - // Find or create tile definition - var tileDef = _tileDefinitions.Values - .FirstOrDefault(td => td.TileMapSheetId == t.SheetId && td.FrameIndex == t.FrameIndex); + // Ensure the sheet is loaded for client rendering + EnsureSheetLoaded(t.SheetId); - if (tileDef != null) + // Room template tiles are assumed walkable (they define the room interior) + // Walls will be placed around them by PlaceWallTiles + layout.Tiles[worldX, worldY] = 1; // Non-zero to indicate tile is placed + layout.Walkable[worldX, worldY] = true; + + layout.TileDetails.Add(new PlacedTile { - layout.Tiles[worldX, worldY] = tileDef.Id; - layout.Walkable[worldX, worldY] = tileDef.IsWalkable; - - layout.TileDetails.Add(new PlacedTile - { - X = worldX, - Y = worldY, - TileDefinitionId = tileDef.Id, - SheetId = t.SheetId, - FrameIndex = t.FrameIndex, - Layer = 0 - }); - } - else - { - // No tile definition, just mark walkable and store sheet/frame - layout.Walkable[worldX, worldY] = true; - layout.TileDetails.Add(new PlacedTile - { - X = worldX, - Y = worldY, - TileDefinitionId = 0, - SheetId = t.SheetId, - FrameIndex = t.FrameIndex, - Layer = 0 - }); - } + X = worldX, + Y = worldY, + TileDefinitionId = 0, // No TileDefinition - using template directly + SheetId = t.SheetId, + FrameIndex = t.FrameIndex, + Layer = 0 + }); } } } @@ -1201,8 +1185,8 @@ public class DungeonGeneratorV3 /// Fill all walkable cells with floor tiles. /// /// For each walkable cell without a tile: - /// 1. Call SelectFloorTile to get appropriate tile (with socket matching) - /// 2. Set layout.Tiles and add to TileDetails + /// 1. Call SelectFloorTile to get appropriate template (with socket matching) + /// 2. Parse TilesJson from template and add to TileDetails /// private void FillFloorTiles(DungeonLayoutV2 layout) { @@ -1219,9 +1203,8 @@ public class DungeonGeneratorV3 LogTileTemplate(t, "Floor"); } - TileDefinition? firstSelectedTile = null; + bool loggedFirst = false; int tileCount = 0; - int fallbackCount = 0; for (int y = 0; y < MapHeight; y++) { @@ -1230,210 +1213,151 @@ public class DungeonGeneratorV3 // Only fill walkable cells that don't have tiles yet if (layout.Walkable[x, y] && layout.Tiles[x, y] == 0) { - var tile = SelectFloorTile(x, y, layout, out bool usedFallback); - if (tile != null) + var result = SelectFloorTemplate(x, y, layout); + if (result != null) { - if (firstSelectedTile == null) + if (!loggedFirst) { - firstSelectedTile = tile; - Log($"First selected floor tile: ID={tile.Id}, Name='{tile.Name}', Sheet={tile.TileMapSheetId}, Frame={tile.FrameIndex}"); + loggedFirst = true; + Log($"First selected floor: Template='{result.Value.TemplateName}', Sheet={result.Value.SheetId}, Frame={result.Value.FrameIndex}"); } - layout.Tiles[x, y] = tile.Id; + layout.Tiles[x, y] = result.Value.TemplateId; // Use template ID for tracking layout.TileDetails.Add(new PlacedTile { X = x, Y = y, - TileDefinitionId = tile.Id, - SheetId = tile.TileMapSheetId, - FrameIndex = tile.FrameIndex, + TileDefinitionId = 0, // No TileDefinition - using template directly + SheetId = result.Value.SheetId, + FrameIndex = result.Value.FrameIndex, Layer = 0 }); tileCount++; - if (usedFallback) fallbackCount++; if (LogEveryTile) { - Log($" Floor ({x},{y}): TileDef={tile.Id}, Sheet={tile.TileMapSheetId}, Frame={tile.FrameIndex}{(usedFallback ? " [FALLBACK]" : "")}"); + Log($" Floor ({x},{y}): Template='{result.Value.TemplateName}', Sheet={result.Value.SheetId}, Frame={result.Value.FrameIndex}"); } } } } } - Log($"Placed {tileCount} floor tiles ({fallbackCount} used fallback)"); + Log($"Placed {tileCount} floor tiles"); } /// - /// Select a floor tile for the given position. - /// - /// SELECTION PROCESS (with socket matching): - /// 1. If _floorTemplates has templates: - /// a. Filter to socket-compatible templates (if UseSocketMatching) - /// b. Try each template in weighted order until one resolves to a TileDefinition - /// c. Try template.PrimaryTileDefinitionId first - /// d. If no PrimaryTileDefinitionId, parse template.TilesJson - /// e. Track placed template for future socket matching - /// 2. FALLBACK: Return first walkable TileDefinition (ordered by ID) + /// Result of selecting a tile template - contains all info needed for placement. /// - private TileDefinition? SelectFloorTile(int x, int y, DungeonLayoutV2 layout, out bool usedFallback) + private struct TemplateSelectionResult { - usedFallback = false; - - // First try to use floor templates - if (_floorTemplates.Count > 0) - { - // Get socket-compatible templates - var compatibleTemplates = GetCompatibleTemplates(_floorTemplates, x, y, layout); - - // Shuffle templates by weight, then try each until one resolves - var shuffledTemplates = ShuffleByWeight(compatibleTemplates); - - foreach (var template in shuffledTemplates) - { - var tileDef = TryResolveFloorTemplate(template, x, y, compatibleTemplates.Count); - if (tileDef != null) - { - // Track placement for socket matching - _placedTemplates[$"{x},{y}"] = template.Id; - - if (!UsedFloorTemplates.Contains(template.Name)) - UsedFloorTemplates.Add(template.Name); - - return tileDef; - } - } - - // No template resolved - log warning - Log($"SelectFloorTile({x},{y}): WARNING - None of {compatibleTemplates.Count} compatible templates could resolve to a TileDefinition!"); - } - - // FALLBACK: use the FIRST walkable tile consistently (not random) - usedFallback = true; - var walkableTiles = _tileDefinitions.Values.Where(t => t.IsWalkable).OrderBy(t => t.Id).ToList(); - if (walkableTiles.Count > 0) - { - LogVerbose($"SelectFloorTile({x},{y}): FALLBACK TileDef {walkableTiles[0].Id} '{walkableTiles[0].Name}'"); - return walkableTiles[0]; - } - - LogVerbose($"SelectFloorTile({x},{y}): No walkable tiles found!"); - return _tileDefinitions.Values.FirstOrDefault(); + public int TemplateId; + public string TemplateName; + public int SheetId; + public int FrameIndex; } /// - /// Try to resolve a floor template to a TileDefinition. - /// Returns null if the template cannot be resolved. + /// Select a floor template for the given position. + /// Returns the template's tile placement info directly from TilesJson. /// - private TileDefinition? TryResolveFloorTemplate(TileTemplate template, int x, int y, int compatibleCount) + private TemplateSelectionResult? SelectFloorTemplate(int x, int y, DungeonLayoutV2 layout) { - LogVerbose($"SelectFloorTile({x},{y}): Trying template '{template.Name}' (ID={template.Id}) [Compatible: {compatibleCount}/{_floorTemplates.Count}]"); - - // Method 1: Try PrimaryTileDefinitionId first - if (template.PrimaryTileDefinitionId.HasValue) + if (_floorTemplates.Count == 0) { - LogVerbose($" Trying PrimaryTileDefinitionId: {template.PrimaryTileDefinitionId.Value}"); - if (_tileDefinitions.TryGetValue(template.PrimaryTileDefinitionId.Value, out var tileDef)) - { - LogVerbose($" -> Found TileDef {tileDef.Id} '{tileDef.Name}'"); - return tileDef; - } - LogVerbose($" -> NOT FOUND in _tileDefinitions!"); + LogVerbose($"SelectFloorTemplate({x},{y}): No floor templates available!"); + return null; } - // Method 2: Try to parse TilesJson for the template - if (!string.IsNullOrEmpty(template.TilesJson)) - { - LogVerbose($" Trying TilesJson: {template.TilesJson}"); - try - { - var tiles = JsonSerializer.Deserialize>(template.TilesJson, _jsonOptions); - if (tiles == null) - { - LogVerbose($" -> Deserialized to NULL!"); - } - else if (tiles.Count == 0) - { - LogVerbose($" -> Deserialized to EMPTY list!"); - } - else - { - var first = tiles[0]; - LogVerbose($" -> Parsed: SheetId={first.SheetId}, FrameIndex={first.FrameIndex}"); - - var match = _tileDefinitions.Values - .FirstOrDefault(t => t.TileMapSheetId == first.SheetId && t.FrameIndex == first.FrameIndex); - if (match != null) - { - LogVerbose($" -> Match: TileDef {match.Id} '{match.Name}'"); - return match; - } - else - { - LogVerbose($" -> No TileDefinition for Sheet={first.SheetId}, Frame={first.FrameIndex}"); - } - } - } - catch (Exception ex) - { - LogVerbose($" -> ERROR parsing TilesJson: {ex.Message}"); - } - } - else - { - LogVerbose($" TilesJson is empty/null"); - } + // Get socket-compatible templates + var compatibleTemplates = GetCompatibleTemplates(_floorTemplates, x, y, layout); - return null; // Could not resolve this template - } - - // Overload for backward compatibility (without layout parameter) - private TileDefinition? SelectFloorTile(int x, int y, out bool usedFallback) - { - // Create a minimal layout for compatibility - usedFallback = false; + // Shuffle templates by weight, then try each until one has valid TilesJson + var shuffledTemplates = ShuffleByWeight(compatibleTemplates); - if (_floorTemplates.Count > 0) + foreach (var template in shuffledTemplates) { - var template = SelectWeightedTemplate(_floorTemplates); - if (template != null) + var result = TryParseTemplateTile(template, x, y, "Floor", compatibleTemplates.Count, _floorTemplates.Count); + if (result != null) { - if (template.PrimaryTileDefinitionId.HasValue) - { - if (_tileDefinitions.TryGetValue(template.PrimaryTileDefinitionId.Value, out var tileDef)) - { - if (!UsedFloorTemplates.Contains(template.Name)) - UsedFloorTemplates.Add(template.Name); - return tileDef; - } - } + // Track placement for socket matching + _placedTemplates[$"{x},{y}"] = template.Id; - if (!string.IsNullOrEmpty(template.TilesJson)) - { - try - { - var tiles = JsonSerializer.Deserialize>(template.TilesJson, _jsonOptions); - if (tiles?.Count > 0) - { - var first = tiles[0]; - var match = _tileDefinitions.Values - .FirstOrDefault(t => t.TileMapSheetId == first.SheetId && t.FrameIndex == first.FrameIndex); - if (match != null) - { - if (!UsedFloorTemplates.Contains(template.Name)) - UsedFloorTemplates.Add(template.Name); - return match; - } - } - } - catch { } - } + if (!UsedFloorTemplates.Contains(template.Name)) + UsedFloorTemplates.Add(template.Name); + + return result; } } - usedFallback = true; - var walkableTiles = _tileDefinitions.Values.Where(t => t.IsWalkable).OrderBy(t => t.Id).ToList(); - return walkableTiles.FirstOrDefault() ?? _tileDefinitions.Values.FirstOrDefault(); + Log($"SelectFloorTemplate({x},{y}): WARNING - None of {compatibleTemplates.Count} compatible templates had valid TilesJson!"); + return null; + } + + /// + /// Try to parse a template's TilesJson to get tile placement info. + /// Returns null if TilesJson is missing or invalid. + /// + private TemplateSelectionResult? TryParseTemplateTile(TileTemplate template, int x, int y, string tileType, int compatibleCount, int totalCount) + { + LogVerbose($"Select{tileType}Template({x},{y}): Trying template '{template.Name}' (ID={template.Id}) [Compatible: {compatibleCount}/{totalCount}]"); + + if (string.IsNullOrEmpty(template.TilesJson)) + { + LogVerbose($" -> TilesJson is empty/null"); + return null; + } + + LogVerbose($" Parsing TilesJson: {template.TilesJson}"); + + try + { + var tiles = JsonSerializer.Deserialize>(template.TilesJson, _jsonOptions); + if (tiles == null || tiles.Count == 0) + { + LogVerbose($" -> Deserialized to NULL or EMPTY!"); + return null; + } + + var first = tiles[0]; + LogVerbose($" -> Parsed: SheetId={first.SheetId}, FrameIndex={first.FrameIndex}"); + + // Ensure the sheet is tracked for client rendering + EnsureSheetLoaded(first.SheetId); + + return new TemplateSelectionResult + { + TemplateId = template.Id, + TemplateName = template.Name, + SheetId = first.SheetId, + FrameIndex = first.FrameIndex + }; + } + catch (Exception ex) + { + LogVerbose($" -> ERROR parsing TilesJson: {ex.Message}"); + return null; + } + } + + /// + /// Ensure a tile sheet is loaded and tracked for client rendering. + /// + private void EnsureSheetLoaded(int sheetId) + { + if (!_tileSheets.ContainsKey(sheetId)) + { + var sheet = _db.TileMapSheets.Find(sheetId); + if (sheet != null) + { + _tileSheets[sheetId] = sheet; + LogVerbose($" -> Loaded TileMapSheet {sheetId}: '{sheet.Name}'"); + } + else + { + Log($" -> WARNING: TileMapSheet {sheetId} not found in database!"); + } + } } /// @@ -1456,7 +1380,6 @@ public class DungeonGeneratorV3 } int wallCount = 0; - int fallbackCount = 0; // Find cells adjacent to walkable that aren't walkable themselves for (int y = 0; y < MapHeight; y++) @@ -1465,20 +1388,25 @@ public class DungeonGeneratorV3 { if (!layout.Walkable[x, y] && HasAdjacentWalkable(layout, x, y) && layout.Tiles[x, y] == 0) { - var tile = SelectWallTile(x, y, layout); - if (tile != null) + var result = SelectWallTemplate(x, y, layout); + if (result != null) { - layout.Tiles[x, y] = tile.Id; + layout.Tiles[x, y] = result.Value.TemplateId; layout.TileDetails.Add(new PlacedTile { X = x, Y = y, - TileDefinitionId = tile.Id, - SheetId = tile.TileMapSheetId, - FrameIndex = tile.FrameIndex, + TileDefinitionId = 0, // No TileDefinition - using template directly + SheetId = result.Value.SheetId, + FrameIndex = result.Value.FrameIndex, Layer = 0 }); wallCount++; + + if (LogEveryTile) + { + Log($" Wall ({x},{y}): Template='{result.Value.TemplateName}', Sheet={result.Value.SheetId}, Frame={result.Value.FrameIndex}"); + } } } } @@ -1503,55 +1431,39 @@ public class DungeonGeneratorV3 } /// - /// Select a wall tile for the given position. - /// - /// SELECTION PROCESS (with socket matching): - /// 1. If _wallTemplates has templates: - /// a. Filter to socket-compatible templates (if UseSocketMatching) - /// b. Try each template in weighted order until one resolves to a TileDefinition - /// c. Try template.PrimaryTileDefinitionId first - /// d. If no PrimaryTileDefinitionId, parse template.TilesJson - /// e. Track placed template for future socket matching - /// 2. FALLBACK: Return first non-walkable TileDefinition + /// Select a wall template for the given position. + /// Returns the template's tile placement info directly from TilesJson. /// - private TileDefinition? SelectWallTile(int x, int y, DungeonLayoutV2 layout) + private TemplateSelectionResult? SelectWallTemplate(int x, int y, DungeonLayoutV2 layout) { - if (_wallTemplates.Count > 0) + if (_wallTemplates.Count == 0) { - // Get socket-compatible templates - var compatibleTemplates = GetCompatibleTemplates(_wallTemplates, x, y, layout); - - // Shuffle templates by weight, then try each until one resolves - var shuffledTemplates = ShuffleByWeight(compatibleTemplates); - - foreach (var template in shuffledTemplates) - { - var tileDef = TryResolveTemplate(template, x, y, compatibleTemplates.Count); - if (tileDef != null) - { - // Track placement for socket matching - _placedTemplates[$"{x},{y}"] = template.Id; - - if (!UsedWallTemplates.Contains(template.Name)) - UsedWallTemplates.Add(template.Name); - - return tileDef; - } - } - - // No template resolved - log warning - Log($"SelectWallTile({x},{y}): WARNING - None of {compatibleTemplates.Count} compatible templates could resolve to a TileDefinition!"); + LogVerbose($"SelectWallTemplate({x},{y}): No wall templates available!"); + return null; } - // FALLBACK: use the FIRST non-walkable tile consistently - var wallTiles = _tileDefinitions.Values.Where(t => !t.IsWalkable).OrderBy(t => t.Id).ToList(); - if (wallTiles.Count > 0) + // Get socket-compatible templates + var compatibleTemplates = GetCompatibleTemplates(_wallTemplates, x, y, layout); + + // Shuffle templates by weight, then try each until one has valid TilesJson + var shuffledTemplates = ShuffleByWeight(compatibleTemplates); + + foreach (var template in shuffledTemplates) { - LogVerbose($"SelectWallTile({x},{y}): FALLBACK TileDef {wallTiles[0].Id} '{wallTiles[0].Name}'"); - return wallTiles[0]; + var result = TryParseTemplateTile(template, x, y, "Wall", compatibleTemplates.Count, _wallTemplates.Count); + if (result != null) + { + // Track placement for socket matching + _placedTemplates[$"{x},{y}"] = template.Id; + + if (!UsedWallTemplates.Contains(template.Name)) + UsedWallTemplates.Add(template.Name); + + return result; + } } - - LogVerbose($"SelectWallTile({x},{y}): No non-walkable tiles found!"); + + Log($"SelectWallTemplate({x},{y}): WARNING - None of {compatibleTemplates.Count} compatible templates had valid TilesJson!"); return null; } @@ -1567,6 +1479,8 @@ public class DungeonGeneratorV3 while (remaining.Count > 0) { var totalWeight = remaining.Sum(t => t.Weight); + if (totalWeight == 0) break; + var roll = _rng.Next(totalWeight); var cumulative = 0; @@ -1585,72 +1499,6 @@ public class DungeonGeneratorV3 return result; } - /// - /// Try to resolve a template to a TileDefinition. - /// Returns null if the template cannot be resolved. - /// - private TileDefinition? TryResolveTemplate(TileTemplate template, int x, int y, int compatibleCount) - { - LogVerbose($"SelectWallTile({x},{y}): Trying template '{template.Name}' (ID={template.Id}) [Compatible: {compatibleCount}/{_wallTemplates.Count}]"); - - // Method 1: Try PrimaryTileDefinitionId first - if (template.PrimaryTileDefinitionId.HasValue) - { - LogVerbose($" Trying PrimaryTileDefinitionId: {template.PrimaryTileDefinitionId.Value}"); - if (_tileDefinitions.TryGetValue(template.PrimaryTileDefinitionId.Value, out var tileDef)) - { - LogVerbose($" -> Found TileDef {tileDef.Id} '{tileDef.Name}'"); - return tileDef; - } - LogVerbose($" -> NOT FOUND in _tileDefinitions!"); - } - - // Method 2: Try to parse TilesJson for the template - if (!string.IsNullOrEmpty(template.TilesJson)) - { - LogVerbose($" Trying TilesJson: {template.TilesJson}"); - try - { - var tiles = JsonSerializer.Deserialize>(template.TilesJson, _jsonOptions); - if (tiles == null) - { - LogVerbose($" -> Deserialized to NULL!"); - } - else if (tiles.Count == 0) - { - LogVerbose($" -> Deserialized to EMPTY list!"); - } - else - { - var first = tiles[0]; - LogVerbose($" -> Parsed: SheetId={first.SheetId}, FrameIndex={first.FrameIndex}"); - - var match = _tileDefinitions.Values - .FirstOrDefault(t => t.TileMapSheetId == first.SheetId && t.FrameIndex == first.FrameIndex); - if (match != null) - { - LogVerbose($" -> Match: TileDef {match.Id} '{match.Name}'"); - return match; - } - else - { - LogVerbose($" -> No TileDefinition for Sheet={first.SheetId}, Frame={first.FrameIndex}"); - } - } - } - catch (Exception ex) - { - LogVerbose($" -> ERROR parsing TilesJson: {ex.Message}"); - } - } - else - { - LogVerbose($" TilesJson is empty/null"); - } - - return null; // Could not resolve this template - } - // ============================================================ // SOCKET MATCHING METHODS // ============================================================ @@ -1884,13 +1732,6 @@ public class DungeonGeneratorV3 { var first = tiles[0]; Log($" -> Parsed: SheetId={first.SheetId}, FrameIndex={first.FrameIndex}"); - - var match = _tileDefinitions.Values - .FirstOrDefault(td => td.TileMapSheetId == first.SheetId && td.FrameIndex == first.FrameIndex); - if (match != null) - Log($" -> Resolves to TileDef {match.Id}: '{match.Name}' (Walkable={match.IsWalkable})"); - else - Log($" -> WARNING: No TileDefinition for Sheet={first.SheetId}, Frame={first.FrameIndex}!"); } } catch (Exception ex)