diff --git a/Game/Dungeon/DungeonGeneratorV2.cs b/Game/Dungeon/DungeonGeneratorV2.cs index b9bbffb..aaeb238 100644 --- a/Game/Dungeon/DungeonGeneratorV2.cs +++ b/Game/Dungeon/DungeonGeneratorV2.cs @@ -465,19 +465,6 @@ public class DungeonGeneratorV2 var closedCount = _tileSocketsStrict.Values.Count(s => s.IsAllClosed); var mixedCount = _tileSocketsStrict.Count - openCount - closedCount; Console.WriteLine($"[DungeonGenV2] Socket distribution: AllOpen={openCount}, AllClosed={closedCount}, Mixed={mixedCount}"); - - // DEBUG: Log a few specific tiles to verify socket loading - foreach (var t in _tileDefinitions.Values.Where(td => td.Type == TileType.Floor).Take(10)) - { - if (_tileSocketsStrict.TryGetValue(t.Id, out var sockets)) - { - Console.WriteLine($"[Socket DEBUG] Tile {t.Id} frame={t.FrameIndex} '{t.Name}': " + - $"N={t.SocketN}({(int)t.SocketN})→{sockets.GetSocketId("N")}, " + - $"E={t.SocketE}({(int)t.SocketE})→{sockets.GetSocketId("E")}, " + - $"S={t.SocketS}({(int)t.SocketS})→{sockets.GetSocketId("S")}, " + - $"W={t.SocketW}({(int)t.SocketW})→{sockets.GetSocketId("W")}"); - } - } Console.WriteLine($"[DungeonGenV2] Socket distribution: AllOpen={openCount}, AllClosed={closedCount}, Mixed={mixedCount}"); // Determine if we should use strict sockets @@ -647,60 +634,20 @@ public class DungeonGeneratorV2 string primaryTag = $"TileBaseCore_{familyId}"; string varianceTag = $"TileBase_{familyId}"; - // Debug: Log what we're looking for - if (required.Count > 0) - { - Console.WriteLine($"[Socket] ({x},{y}) Required sockets: {string.Join(", ", required.Select(kv => $"{kv.Key}={kv.Value}"))}"); - } - - // Get ALL floor tiles in family first, then filter - var allPrimary = _tileDefinitions.Values + var primary = _tileDefinitions.Values .Where(t => t.Type == TileType.Floor) .Where(t => HasTag(t, primaryTag)) + .Where(t => SatisfiesSocketRequirementsStrict(t.Id, required)) .ToList(); - - var allVariance = _tileDefinitions.Values + + var variance = _tileDefinitions.Values .Where(t => t.Type == TileType.Floor) .Where(t => HasTag(t, varianceTag)) - .ToList(); - - // Debug: Show why tiles are being filtered out - if (required.Count > 0 && allVariance.Count > 0) - { - Console.WriteLine($"[Socket] ({x},{y}) Checking {allVariance.Count} variance tiles against requirements:"); - foreach (var t in allVariance.Take(5)) - { - var sockets = _tileSocketsStrict.GetValueOrDefault(t.Id); - bool passes = SatisfiesSocketRequirementsStrict(t.Id, required); - - var failReasons = new List(); - foreach (var (edge, reqSocket) in required) - { - var tileSocket = sockets.GetSocketId(edge); - if (!tileSocket.Equals(reqSocket, StringComparison.OrdinalIgnoreCase)) - { - failReasons.Add($"{edge}: need {reqSocket}, have {tileSocket}"); - } - } - - Console.WriteLine($"[Socket] Tile {t.Id} frame={t.FrameIndex}: {(passes ? "PASS" : "FAIL")} {string.Join(", ", failReasons)}"); - } - } - - var primary = allPrimary .Where(t => SatisfiesSocketRequirementsStrict(t.Id, required)) .ToList(); - var variance = allVariance - .Where(t => SatisfiesSocketRequirementsStrict(t.Id, required)) - .ToList(); - - // Debug: Log pool sizes - Console.WriteLine($"[Socket] ({x},{y}) Primary pool: {primary.Count}/{allPrimary.Count}, Variance pool: {variance.Count}/{allVariance.Count}"); - if (primary.Count == 0 && variance.Count == 0) { - Console.WriteLine($"[Socket] ({x},{y}) NO COMPATIBLE TILES FOUND!"); return null; } @@ -708,13 +655,7 @@ public class DungeonGeneratorV2 var pool = pickVariance ? variance : primary; if (pool.Count == 0) pool = pickVariance ? primary : variance; - var chosen = pool[_rng.Next(pool.Count)]; - - // Debug: Log what we picked - var chosenSockets = _tileSocketsStrict.GetValueOrDefault(chosen.Id); - Console.WriteLine($"[Socket] ({x},{y}) PICKED tile {chosen.Id} frame={chosen.FrameIndex}: N={chosenSockets.GetSocketId("N")}, E={chosenSockets.GetSocketId("E")}, S={chosenSockets.GetSocketId("S")}, W={chosenSockets.GetSocketId("W")}"); - - return chosen; + return pool[_rng.Next(pool.Count)]; } /// @@ -940,23 +881,17 @@ public class DungeonGeneratorV2 private void CarveBasicRoom(DungeonLayoutV2 layout, DungeonRoomV2 room) { - const bool VerboseFloorLogging = false; // Set to true for detailed debugging - int familyId = _activeFamilyId; - - if (VerboseFloorLogging) - Console.WriteLine($"[DungeonGenV2][Floors] CarveBasicRoom START room=({room.X},{room.Y}) size=({room.Width}x{room.Height}) familyId={familyId} useStrict={_useStrictSockets}"); - - TileDefinition? roomPrimary = _useStrictSockets - ? PickRandomFloorTileStrict(layout, room.X, room.Y, familyId, varianceChance: 0.0) - : PickRandomFloorTile(layout, room.X, room.Y, familyId, varianceChance: 0.0); - - if (VerboseFloorLogging && roomPrimary != null) - { - Console.WriteLine($"[DungeonGenV2][Floors] roomPrimary chosen id={roomPrimary.Id} name='{roomPrimary.Name}'"); - } - - int placedCount = 0; + string primaryTag = $"TileBaseCore_{familyId}"; + string varianceTag = $"TileBase_{familyId}"; + + // Get all floor tiles in this family + var primaryTiles = _tileDefinitions.Values + .Where(t => t.Type == TileType.Floor && HasTag(t, primaryTag)) + .ToList(); + var varianceTiles = _tileDefinitions.Values + .Where(t => t.Type == TileType.Floor && HasTag(t, varianceTag)) + .ToList(); for (int x = room.X; x < room.X + room.Width; x++) { @@ -965,80 +900,64 @@ public class DungeonGeneratorV2 if (x < 0 || x >= MapWidth || y < 0 || y >= MapHeight) continue; + // Mark as walkable if (layout.Walkable != null) layout.Walkable[x, y] = true; + // Remove any existing tile layout.TileDetails.RemoveAll(t => t.X == x && t.Y == y); TileDefinition? chosen = null; if (_useStrictSockets) { - // Use strict socket matching - var required = GetRequiredSocketsStrict(layout, x, y); - bool primaryFits = roomPrimary != null && SatisfiesSocketRequirementsStrict(roomPrimary.Id, required); + // Build requirements from neighbors that already have tiles + var requirements = new Dictionary(StringComparer.OrdinalIgnoreCase); - double roll = _rng.NextDouble(); - bool wantVariance = roll < 0.25; + if (y > 0 && HasPlacedTile(layout, x, y - 1)) + requirements["N"] = GetSocketIdStrict(layout.Tiles[x, y - 1], "S"); + if (x > 0 && HasPlacedTile(layout, x - 1, y)) + requirements["W"] = GetSocketIdStrict(layout.Tiles[x - 1, y], "E"); - if (primaryFits && !wantVariance) - { - chosen = roomPrimary; - } - else - { - chosen = PickRandomFloorTileStrict(layout, x, y, familyId, wantVariance ? 1.0 : 0.25); - if (chosen == null && primaryFits) - chosen = roomPrimary; - } + // Filter tiles that satisfy requirements + Func satisfiesReqs = t => { + foreach (var (edge, reqSocket) in requirements) + { + var tileSocket = GetSocketIdStrict(t.Id, edge); + if (!tileSocket.Equals(reqSocket, StringComparison.OrdinalIgnoreCase)) + return false; + } + return true; + }; + + var compatiblePrimary = primaryTiles.Where(satisfiesReqs).ToList(); + var compatibleVariance = varianceTiles.Where(satisfiesReqs).ToList(); + + // 75% primary, 25% variance + bool wantVariance = _rng.NextDouble() < 0.25; + + if (wantVariance && compatibleVariance.Count > 0) + chosen = compatibleVariance[_rng.Next(compatibleVariance.Count)]; + else if (compatiblePrimary.Count > 0) + chosen = compatiblePrimary[_rng.Next(compatiblePrimary.Count)]; + else if (compatibleVariance.Count > 0) + chosen = compatibleVariance[_rng.Next(compatibleVariance.Count)]; } else { - // Use legacy tag-based socket matching - bool primaryFits = roomPrimary != null && SatisfiesSocketRequirements(layout, x, y, roomPrimary); - - double roll = _rng.NextDouble(); - bool wantVariance = roll < 0.25; - - if (primaryFits) - { - if (wantVariance) - { - chosen = PickRandomFloorTile(layout, x, y, familyId, varianceChance: 1.0); - if (chosen == null) - chosen = roomPrimary; - } - else - { - chosen = roomPrimary; - } - } - else - { - chosen = PickRandomFloorTile(layout, x, y, familyId, varianceChance: 0.25); - } + // Legacy: just pick any floor tile + var pool = _rng.NextDouble() < 0.25 ? varianceTiles : primaryTiles; + if (pool.Count == 0) pool = varianceTiles.Count > 0 ? varianceTiles : primaryTiles; + if (pool.Count > 0) + chosen = pool[_rng.Next(pool.Count)]; } - // Hard fallback - prefer all-Open tiles to avoid socket conflicts + // Fallback to any floor tile if (chosen == null) - { - chosen = _tileDefinitions.Values - .Where(t => t.Type == TileType.Floor) - .Where(t => { - if (!_tileSocketsStrict.TryGetValue(t.Id, out var sockets)) return false; - return sockets.IsAllOpen; - }) - .FirstOrDefault(); - - // Last resort - any floor tile - chosen ??= _tileDefinitions.Values.FirstOrDefault(t => t.Type == TileType.Floor); - - if (chosen != null) - Console.WriteLine($"[Socket] ({x},{y}) HARD FALLBACK to tile {chosen.Id}"); - } + chosen = _tileDefinitions.Values.FirstOrDefault(t => t.Type == TileType.Floor); - int floorId = chosen?.Id ?? -1; - layout.Tiles[x, y] = floorId > 0 ? floorId : 1; + int floorId = chosen?.Id ?? 1; + layout.Tiles[x, y] = floorId; if (floorId > 0 && chosen != null) { @@ -1051,14 +970,11 @@ public class DungeonGeneratorV2 FrameIndex = chosen.FrameIndex, Layer = 0 }); - placedCount++; } } } - if (VerboseFloorLogging) - Console.WriteLine($"[DungeonGenV2][Floors] CarveBasicRoom END placed={placedCount}"); - + // Repair pass to fix any remaining mismatches RepairRoomFloorSockets(layout, room); } @@ -1074,111 +990,136 @@ public class DungeonGeneratorV2 return true; } + /// + /// Simple, straightforward repair pass: + /// For each tile, check all 4 neighbors, build requirements, find compatible tiles, pick one. + /// Runs multiple iterations until stable. + /// private void RepairRoomFloorSockets(DungeonLayoutV2 layout, DungeonRoomV2 room) { - int familyId = _activeFamilyId; - int repairCount = 0; - int checkCount = 0; - - for (int x = room.X; x < room.X + room.Width; x++) - { - for (int y = room.Y; y < room.Y + room.Height; y++) - { - if (x < 0 || x >= MapWidth || y < 0 || y >= MapHeight) - continue; - - // Only repair cells that have placed tiles - if (!HasPlacedTile(layout, x, y)) - continue; - - int id = layout.Tiles[x, y]; - if (!_tileDefinitions.TryGetValue(id, out var cur)) - continue; - - checkCount++; - TileDefinition? replacement = null; - - if (_useStrictSockets) - { - // Use strict socket checking for all 4 directions - if (!IsCompatibleWithNeighborsStrict(layout, x, y, id)) - { - var curSockets = _tileSocketsStrict.GetValueOrDefault(id); - Console.WriteLine($"[Socket] REPAIR ({x},{y}) tile {id} frame={cur.FrameIndex} incompatible: N={curSockets.GetSocketId("N")}, E={curSockets.GetSocketId("E")}, S={curSockets.GetSocketId("S")}, W={curSockets.GetSocketId("W")}"); - - // Log what neighbors require - if (y > 0 && HasPlacedTile(layout, x, y - 1)) - { - var nSockets = _tileSocketsStrict.GetValueOrDefault(layout.Tiles[x, y - 1]); - Console.WriteLine($"[Socket] North neighbor {layout.Tiles[x, y - 1]} has S={nSockets.GetSocketId("S")}"); - } - if (x > 0 && HasPlacedTile(layout, x - 1, y)) - { - var wSockets = _tileSocketsStrict.GetValueOrDefault(layout.Tiles[x - 1, y]); - Console.WriteLine($"[Socket] West neighbor {layout.Tiles[x - 1, y]} has E={wSockets.GetSocketId("E")}"); - } - if (y < MapHeight - 1 && HasPlacedTile(layout, x, y + 1)) - { - var sSockets = _tileSocketsStrict.GetValueOrDefault(layout.Tiles[x, y + 1]); - Console.WriteLine($"[Socket] South neighbor {layout.Tiles[x, y + 1]} has N={sSockets.GetSocketId("N")}"); - } - if (x < MapWidth - 1 && HasPlacedTile(layout, x + 1, y)) - { - var eSockets = _tileSocketsStrict.GetValueOrDefault(layout.Tiles[x + 1, y]); - Console.WriteLine($"[Socket] East neighbor {layout.Tiles[x + 1, y]} has W={eSockets.GetSocketId("W")}"); - } - - replacement = PickRandomFloorTileStrict(layout, x, y, familyId, varianceChance: 0.0); - - if (replacement == null) - { - Console.WriteLine($"[Socket] No replacement found! Trying all-Open fallback..."); - replacement = _tileDefinitions.Values - .Where(t => t.Type == TileType.Floor) - .Where(t => HasTag(t, $"TileBaseCore_{familyId}") || HasTag(t, $"TileBase_{familyId}")) - .Where(t => { - if (!_tileSocketsStrict.TryGetValue(t.Id, out var sockets)) return false; - return sockets.IsAllOpen; - }) - .FirstOrDefault(); - } - } - } - else - { - // Use legacy tag-based checking - var required = BuildRequiredSocketTags_AllDirs(layout, x, y); - if (!HasAllTags(cur, required)) - { - replacement = PickRandomFloorTile_AllDirs(layout, x, y, familyId, varianceChance: 0.25); - } - } - - if (replacement == null || replacement.Id == cur.Id) - continue; - - Console.WriteLine($"[Socket] REPAIR ({x},{y}) replacing {cur.Id} with {replacement.Id}"); - repairCount++; - - layout.Tiles[x, y] = replacement.Id; - - if (layout.Walkable != null) - layout.Walkable[x, y] = true; - - layout.TileDetails.RemoveAll(t => t.X == x && t.Y == y); - layout.TileDetails.Add(new PlacedTile - { - X = x, - Y = y, - TileDefinitionId = replacement.Id, - SheetId = replacement.TileMapSheetId, - FrameIndex = replacement.FrameIndex, - Layer = 0 - }); - } - } + if (!_useStrictSockets) return; - Console.WriteLine($"[Socket] RepairRoomFloorSockets: checked {checkCount} tiles, repaired {repairCount}"); + int familyId = _activeFamilyId; + int maxIterations = 10; + + for (int iteration = 0; iteration < maxIterations; iteration++) + { + int repairCount = 0; + + for (int x = room.X; x < room.X + room.Width; x++) + { + for (int y = room.Y; y < room.Y + room.Height; y++) + { + if (x < 0 || x >= MapWidth || y < 0 || y >= MapHeight) + continue; + + if (!HasPlacedTile(layout, x, y)) + continue; + + int currentTileId = layout.Tiles[x, y]; + + // Build requirements from ALL 4 neighbors + var requirements = new Dictionary(StringComparer.OrdinalIgnoreCase); + + // North neighbor at (x, y-1) - their S edge determines our N + if (y > 0 && HasPlacedTile(layout, x, y - 1)) + { + requirements["N"] = GetSocketIdStrict(layout.Tiles[x, y - 1], "S"); + } + + // South neighbor at (x, y+1) - their N edge determines our S + if (y < MapHeight - 1 && HasPlacedTile(layout, x, y + 1)) + { + requirements["S"] = GetSocketIdStrict(layout.Tiles[x, y + 1], "N"); + } + + // West neighbor at (x-1, y) - their E edge determines our W + if (x > 0 && HasPlacedTile(layout, x - 1, y)) + { + requirements["W"] = GetSocketIdStrict(layout.Tiles[x - 1, y], "E"); + } + + // East neighbor at (x+1, y) - their W edge determines our E + if (x < MapWidth - 1 && HasPlacedTile(layout, x + 1, y)) + { + requirements["E"] = GetSocketIdStrict(layout.Tiles[x + 1, y], "W"); + } + + // Check if current tile satisfies all requirements + bool currentTileOk = true; + foreach (var (edge, reqSocket) in requirements) + { + var currentSocket = GetSocketIdStrict(currentTileId, edge); + if (!currentSocket.Equals(reqSocket, StringComparison.OrdinalIgnoreCase)) + { + currentTileOk = false; + break; + } + } + + if (currentTileOk) + continue; // Tile is fine, move on + + // Find all tiles that satisfy requirements + var compatibleTiles = _tileDefinitions.Values + .Where(t => t.Type == TileType.Floor) + .Where(t => HasTag(t, $"TileBaseCore_{familyId}") || HasTag(t, $"TileBase_{familyId}")) + .Where(t => { + foreach (var (edge, reqSocket) in requirements) + { + var tileSocket = GetSocketIdStrict(t.Id, edge); + if (!tileSocket.Equals(reqSocket, StringComparison.OrdinalIgnoreCase)) + return false; + } + return true; + }) + .ToList(); + + TileDefinition? replacement = null; + + if (compatibleTiles.Count > 0) + { + // Pick a random compatible tile + replacement = compatibleTiles[_rng.Next(compatibleTiles.Count)]; + } + else + { + // No compatible tile exists - use all-Open to break the pattern + replacement = _tileDefinitions.Values + .Where(t => t.Type == TileType.Floor) + .Where(t => HasTag(t, $"TileBaseCore_{familyId}") || HasTag(t, $"TileBase_{familyId}")) + .Where(t => _tileSocketsStrict.TryGetValue(t.Id, out var s) && s.IsAllOpen) + .FirstOrDefault(); + } + + if (replacement == null || replacement.Id == currentTileId) + continue; + + // Replace the tile + layout.Tiles[x, y] = replacement.Id; + if (layout.Walkable != null) + layout.Walkable[x, y] = true; + + layout.TileDetails.RemoveAll(t => t.X == x && t.Y == y); + layout.TileDetails.Add(new PlacedTile + { + X = x, + Y = y, + TileDefinitionId = replacement.Id, + SheetId = replacement.TileMapSheetId, + FrameIndex = replacement.FrameIndex, + Layer = 0 + }); + + repairCount++; + } + } + + Console.WriteLine($"[Socket] Repair iteration {iteration + 1}: {repairCount} tiles fixed"); + + if (repairCount == 0) + break; // Stable, we're done + } } private List BuildRequiredSocketTags_AllDirs(DungeonLayoutV2 layout, int x, int y)