diff --git a/Game/Dungeon/DungeonGeneratorV2.cs b/Game/Dungeon/DungeonGeneratorV2.cs index aaeb238..7240306 100644 --- a/Game/Dungeon/DungeonGeneratorV2.cs +++ b/Game/Dungeon/DungeonGeneratorV2.cs @@ -892,6 +892,22 @@ public class DungeonGeneratorV2 var varianceTiles = _tileDefinitions.Values .Where(t => t.Type == TileType.Floor && HasTag(t, varianceTag)) .ToList(); + + // Separate all-Open tiles from pattern tiles (those with Custom sockets) + var allOpenPrimary = primaryTiles + .Where(t => _tileSocketsStrict.TryGetValue(t.Id, out var s) && s.IsAllOpen) + .ToList(); + var allOpenVariance = varianceTiles + .Where(t => _tileSocketsStrict.TryGetValue(t.Id, out var s) && s.IsAllOpen) + .ToList(); + + // Pattern tiles should only be used when we can verify all 4 constraints are satisfiable + var patternPrimary = primaryTiles + .Where(t => _tileSocketsStrict.TryGetValue(t.Id, out var s) && !s.IsAllOpen) + .ToList(); + var patternVariance = varianceTiles + .Where(t => _tileSocketsStrict.TryGetValue(t.Id, out var s) && !s.IsAllOpen) + .ToList(); for (int x = room.X; x < room.X + room.Width; x++) { @@ -919,7 +935,13 @@ public class DungeonGeneratorV2 if (x > 0 && HasPlacedTile(layout, x - 1, y)) requirements["W"] = GetSocketIdStrict(layout.Tiles[x - 1, y], "E"); - // Filter tiles that satisfy requirements + // Check if any requirement is a Custom socket type + bool hasCustomRequirement = requirements.Values + .Any(r => r.StartsWith("Custom:", StringComparison.OrdinalIgnoreCase)); + + // If we have Custom requirements, we MUST find a matching tile + // Otherwise, prefer all-Open tiles to avoid creating unsatisfiable constraints + Func satisfiesReqs = t => { foreach (var (edge, reqSocket) in requirements) { @@ -930,18 +952,51 @@ public class DungeonGeneratorV2 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)]; + if (hasCustomRequirement) + { + // Must match the Custom requirement exactly + var compatiblePrimary = primaryTiles.Where(satisfiesReqs).ToList(); + var compatibleVariance = varianceTiles.Where(satisfiesReqs).ToList(); + + 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 + { + // No Custom requirements - strongly prefer all-Open tiles + // This prevents pattern tiles from spreading and creating unsatisfiable constraints + var compatibleOpenPrimary = allOpenPrimary.Where(satisfiesReqs).ToList(); + var compatibleOpenVariance = allOpenVariance.Where(satisfiesReqs).ToList(); + + bool wantVariance = _rng.NextDouble() < 0.25; + + if (wantVariance && compatibleOpenVariance.Count > 0) + chosen = compatibleOpenVariance[_rng.Next(compatibleOpenVariance.Count)]; + else if (compatibleOpenPrimary.Count > 0) + chosen = compatibleOpenPrimary[_rng.Next(compatibleOpenPrimary.Count)]; + else if (compatibleOpenVariance.Count > 0) + chosen = compatibleOpenVariance[_rng.Next(compatibleOpenVariance.Count)]; + + // Only fall back to pattern tiles if no Open tiles work + // This should be rare and indicates a tile configuration issue + if (chosen == null) + { + var compatiblePatternPrimary = patternPrimary.Where(satisfiesReqs).ToList(); + var compatiblePatternVariance = patternVariance.Where(satisfiesReqs).ToList(); + + if (wantVariance && compatiblePatternVariance.Count > 0) + chosen = compatiblePatternVariance[_rng.Next(compatiblePatternVariance.Count)]; + else if (compatiblePatternPrimary.Count > 0) + chosen = compatiblePatternPrimary[_rng.Next(compatiblePatternPrimary.Count)]; + else if (compatiblePatternVariance.Count > 0) + chosen = compatiblePatternVariance[_rng.Next(compatiblePatternVariance.Count)]; + } + } } else { @@ -991,8 +1046,11 @@ public class DungeonGeneratorV2 } /// - /// Simple, straightforward repair pass: - /// For each tile, check all 4 neighbors, build requirements, find compatible tiles, pick one. + /// Enhanced repair pass with constraint relaxation: + /// 1. First tries to find perfect match satisfying all constraints + /// 2. If impossible, scores tiles by how many constraints they satisfy + /// 3. Prefers Open sockets over Custom when requirements conflict + /// 4. Falls back to all-Open tile to break impossible patterns /// Runs multiple iterations until stable. /// private void RepairRoomFloorSockets(DungeonLayoutV2 layout, DungeonRoomV2 room) @@ -1000,11 +1058,29 @@ public class DungeonGeneratorV2 if (!_useStrictSockets) return; int familyId = _activeFamilyId; - int maxIterations = 10; + int maxIterations = 15; // Increased for more complex patterns + + // Pre-cache tiles in this family + var familyTiles = _tileDefinitions.Values + .Where(t => t.Type == TileType.Floor) + .Where(t => HasTag(t, $"TileBaseCore_{familyId}") || HasTag(t, $"TileBase_{familyId}")) + .ToList(); + + // Find the fallback all-Open tile once + var allOpenTile = familyTiles + .Where(t => _tileSocketsStrict.TryGetValue(t.Id, out var s) && s.IsAllOpen) + .FirstOrDefault(); + + if (allOpenTile == null) + { + Console.WriteLine($"[Socket] WARNING: No all-Open fallback tile in family {familyId}!"); + return; + } for (int iteration = 0; iteration < maxIterations; iteration++) { int repairCount = 0; + int relaxedCount = 0; for (int x = room.X; x < room.X + room.Width; x++) { @@ -1021,75 +1097,53 @@ public class DungeonGeneratorV2 // 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) + int currentScore = ScoreSocketMatch(currentTileId, requirements); + + if (currentScore == requirements.Count) + continue; // Perfect match, skip + + // Find best matching tile + TileDefinition? replacement = null; + int bestScore = currentScore; + bool bestIsAllOpen = false; + + foreach (var candidate in familyTiles) { - var currentSocket = GetSocketIdStrict(currentTileId, edge); - if (!currentSocket.Equals(reqSocket, StringComparison.OrdinalIgnoreCase)) + int score = ScoreSocketMatch(candidate.Id, requirements); + bool isAllOpen = _tileSocketsStrict.TryGetValue(candidate.Id, out var s) && s.IsAllOpen; + + // Prefer higher scores, break ties by preferring all-Open + if (score > bestScore || (score == bestScore && isAllOpen && !bestIsAllOpen)) { - currentTileOk = false; - break; + bestScore = score; + replacement = candidate; + bestIsAllOpen = isAllOpen; } } - 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) + // If no tile can satisfy even one requirement, use all-Open fallback + if (replacement == null || bestScore < requirements.Count) { - // 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(); + // Check if all-Open would cause fewer conflicts + int allOpenScore = ScoreSocketMatchRelaxed(allOpenTile.Id, requirements); + if (allOpenScore >= bestScore) + { + replacement = allOpenTile; + relaxedCount++; + } } if (replacement == null || replacement.Id == currentTileId) @@ -1115,12 +1169,58 @@ public class DungeonGeneratorV2 } } - Console.WriteLine($"[Socket] Repair iteration {iteration + 1}: {repairCount} tiles fixed"); + Console.WriteLine($"[Socket] Repair iteration {iteration + 1}: {repairCount} tiles fixed ({relaxedCount} relaxed to all-Open)"); if (repairCount == 0) break; // Stable, we're done } } + + /// + /// Score how well a tile matches socket requirements (strict matching) + /// + private int ScoreSocketMatch(int tileId, Dictionary requirements) + { + int score = 0; + foreach (var (edge, reqSocket) in requirements) + { + var tileSocket = GetSocketIdStrict(tileId, edge); + if (tileSocket.Equals(reqSocket, StringComparison.OrdinalIgnoreCase)) + score++; + } + return score; + } + + /// + /// Score socket match with relaxed rules: + /// - Open ↔ Open = match + /// - Open ↔ Custom:X = partial match (0.5 points - allows Open tiles to "heal" pattern boundaries) + /// - Custom:X ↔ Custom:X = match + /// + private int ScoreSocketMatchRelaxed(int tileId, Dictionary requirements) + { + int score = 0; + foreach (var (edge, reqSocket) in requirements) + { + var tileSocket = GetSocketIdStrict(tileId, edge); + + if (tileSocket.Equals(reqSocket, StringComparison.OrdinalIgnoreCase)) + { + score += 2; // Perfect match + } + else if (tileSocket.Equals("Open", StringComparison.OrdinalIgnoreCase) && + reqSocket.StartsWith("Custom:", StringComparison.OrdinalIgnoreCase)) + { + score += 1; // Partial match - Open can "absorb" custom patterns + } + else if (reqSocket.Equals("Open", StringComparison.OrdinalIgnoreCase) && + tileSocket.StartsWith("Custom:", StringComparison.OrdinalIgnoreCase)) + { + score += 1; // Partial match - Custom can connect to Open + } + } + return score; + } private List BuildRequiredSocketTags_AllDirs(DungeonLayoutV2 layout, int x, int y) { @@ -1486,8 +1586,27 @@ public class DungeonGeneratorV2 } } + + /// + /// Generate walls around floor tiles with 2-tile depth (face + top/cap) + /// + /// Wall Tag System: + /// - Cardinal walls: wall_north, wall_south, wall_east, wall_west (facing direction) + /// - Top/cap tiles: wall_north_top, wall_south_top, etc. (above face tiles) + /// - Outer corners: corner_ne, corner_nw, corner_se, corner_sw + /// - Inner corners: inner_ne, inner_nw, inner_se, inner_sw (for L-shaped rooms) + /// - Each corner also has _top variant + /// - void modifier: for tiles facing pure void/outside + /// + /// Socket Configuration (walls should use these): + /// - Walls use Custom:WallH (horizontal connection) and Custom:WallV (vertical) + /// - Wall tops connect to face tiles via Custom:WallTop + /// - Wall faces connect to floor via Open or Custom:Floor + /// private void GenerateAutoWalls(DungeonLayoutV2 layout) { + int familyId = _activeFamilyId; + var wallTiles = _tileDefinitions.Values.Where(t => t.Type == TileType.Wall).ToList(); if (wallTiles.Count == 0) { @@ -1497,53 +1616,114 @@ public class DungeonGeneratorV2 Console.WriteLine($"[DungeonGenV2] Found {wallTiles.Count} wall tiles for auto-wall generation"); - bool HasTag(TileDefinition t, string tag) + // Helper to check tags + bool TileHasTag(TileDefinition t, string tag) { if (string.IsNullOrWhiteSpace(t.Tags)) return false; return t.Tags .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) .Any(s => s.Equals(tag, StringComparison.OrdinalIgnoreCase)); } - - var wallNorth = wallTiles.FirstOrDefault(t => HasTag(t, "north")) ?? wallTiles[0]; - var wallSouth = wallTiles.FirstOrDefault(t => HasTag(t, "south")) ?? wallTiles[0]; - var wallEast = wallTiles.FirstOrDefault(t => HasTag(t, "east")) ?? wallTiles[0]; - var wallWest = wallTiles.FirstOrDefault(t => HasTag(t, "west")) ?? wallTiles[0]; - - var wallCornerNE = wallTiles.FirstOrDefault(t => HasTag(t, "corner_ne") && !HasTag(t, "void")) - ?? wallTiles.FirstOrDefault(t => HasTag(t, "corner_ne")) - ?? wallTiles[0]; - var wallCornerNW = wallTiles.FirstOrDefault(t => HasTag(t, "corner_nw") && !HasTag(t, "void")) - ?? wallTiles.FirstOrDefault(t => HasTag(t, "corner_nw")) - ?? wallTiles[0]; - var wallCornerSE = wallTiles.FirstOrDefault(t => HasTag(t, "corner_se") && !HasTag(t, "void")) - ?? wallTiles.FirstOrDefault(t => HasTag(t, "corner_se")) - ?? wallTiles[0]; - var wallCornerSW = wallTiles.FirstOrDefault(t => HasTag(t, "corner_sw") && !HasTag(t, "void")) - ?? wallTiles.FirstOrDefault(t => HasTag(t, "corner_sw")) - ?? wallTiles[0]; - - var wallCornerNEVoid = wallTiles.FirstOrDefault(t => HasTag(t, "corner_ne") && HasTag(t, "void")); - var wallCornerNWVoid = wallTiles.FirstOrDefault(t => HasTag(t, "corner_nw") && HasTag(t, "void")); - var wallCornerSEVoid = wallTiles.FirstOrDefault(t => HasTag(t, "corner_se") && HasTag(t, "void")); - var wallCornerSWVoid = wallTiles.FirstOrDefault(t => HasTag(t, "corner_sw") && HasTag(t, "void")); - - TileDefinition PickCorner(string cornerTag, bool preferVoid) + + // Try to get family-specific wall, fallback to any wall with that tag + TileDefinition? GetWallByTag(string tag, bool requireFamily = false) { - return cornerTag.ToLowerInvariant() switch + // First try family-specific + var familyWall = wallTiles.FirstOrDefault(t => + TileHasTag(t, tag) && TileHasTag(t, $"WallFamily_{familyId}")); + if (familyWall != null) return familyWall; + + if (requireFamily) return null; + + // Fallback to any wall with that tag + return wallTiles.FirstOrDefault(t => TileHasTag(t, tag)); + } + + // === FACE TILES (adjacent to floor) === + var wallNorthFace = GetWallByTag("wall_north") ?? GetWallByTag("north") ?? wallTiles[0]; + var wallSouthFace = GetWallByTag("wall_south") ?? GetWallByTag("south") ?? wallTiles[0]; + var wallEastFace = GetWallByTag("wall_east") ?? GetWallByTag("east") ?? wallTiles[0]; + var wallWestFace = GetWallByTag("wall_west") ?? GetWallByTag("west") ?? wallTiles[0]; + + // === TOP/CAP TILES (one tile further from floor) === + var wallNorthTop = GetWallByTag("wall_north_top") ?? wallNorthFace; + var wallSouthTop = GetWallByTag("wall_south_top") ?? wallSouthFace; + var wallEastTop = GetWallByTag("wall_east_top") ?? wallEastFace; + var wallWestTop = GetWallByTag("wall_west_top") ?? wallWestFace; + + // === OUTER CORNER FACE TILES === + var cornerNEFace = GetWallByTag("corner_ne") ?? wallTiles[0]; + var cornerNWFace = GetWallByTag("corner_nw") ?? wallTiles[0]; + var cornerSEFace = GetWallByTag("corner_se") ?? wallTiles[0]; + var cornerSWFace = GetWallByTag("corner_sw") ?? wallTiles[0]; + + // Void variants (corners that face pure void on two sides) + var cornerNEVoid = GetWallByTag("corner_ne_void") ?? wallTiles.FirstOrDefault(t => TileHasTag(t, "corner_ne") && TileHasTag(t, "void")); + var cornerNWVoid = GetWallByTag("corner_nw_void") ?? wallTiles.FirstOrDefault(t => TileHasTag(t, "corner_nw") && TileHasTag(t, "void")); + var cornerSEVoid = GetWallByTag("corner_se_void") ?? wallTiles.FirstOrDefault(t => TileHasTag(t, "corner_se") && TileHasTag(t, "void")); + var cornerSWVoid = GetWallByTag("corner_sw_void") ?? wallTiles.FirstOrDefault(t => TileHasTag(t, "corner_sw") && TileHasTag(t, "void")); + + // === OUTER CORNER TOP TILES === + var cornerNETop = GetWallByTag("corner_ne_top") ?? cornerNEFace; + var cornerNWTop = GetWallByTag("corner_nw_top") ?? cornerNWFace; + var cornerSETop = GetWallByTag("corner_se_top") ?? cornerSEFace; + var cornerSWTop = GetWallByTag("corner_sw_top") ?? cornerSWFace; + + // === INNER CORNER TILES (for L-shaped room interiors) === + var innerNEFace = GetWallByTag("inner_ne") ?? cornerNEFace; + var innerNWFace = GetWallByTag("inner_nw") ?? cornerNWFace; + var innerSEFace = GetWallByTag("inner_se") ?? cornerSEFace; + var innerSWFace = GetWallByTag("inner_sw") ?? cornerSWFace; + + var innerNETop = GetWallByTag("inner_ne_top") ?? innerNEFace; + var innerNWTop = GetWallByTag("inner_nw_top") ?? innerNWFace; + var innerSETop = GetWallByTag("inner_se_top") ?? innerSEFace; + var innerSWTop = GetWallByTag("inner_sw_top") ?? innerSWFace; + + // Helper functions + TileDefinition PickCornerFace(string corner, bool preferVoid) + { + return corner.ToLowerInvariant() switch { - "corner_ne" => (preferVoid ? wallCornerNEVoid : null) ?? wallCornerNE, - "corner_nw" => (preferVoid ? wallCornerNWVoid : null) ?? wallCornerNW, - "corner_se" => (preferVoid ? wallCornerSEVoid : null) ?? wallCornerSE, - "corner_sw" => (preferVoid ? wallCornerSWVoid : null) ?? wallCornerSW, - _ => wallCornerNW + "ne" => (preferVoid ? cornerNEVoid : null) ?? cornerNEFace, + "nw" => (preferVoid ? cornerNWVoid : null) ?? cornerNWFace, + "se" => (preferVoid ? cornerSEVoid : null) ?? cornerSEFace, + "sw" => (preferVoid ? cornerSWVoid : null) ?? cornerSWFace, + _ => cornerNWFace + }; + } + + TileDefinition PickCornerTop(string corner) + { + return corner.ToLowerInvariant() switch + { + "ne" => cornerNETop, + "nw" => cornerNWTop, + "se" => cornerSETop, + "sw" => cornerSWTop, + _ => cornerNWTop + }; + } + + TileDefinition PickInnerCornerFace(string corner) + { + return corner.ToLowerInvariant() switch + { + "ne" => innerNEFace, + "nw" => innerNWFace, + "se" => innerSEFace, + "sw" => innerSWFace, + _ => innerNWFace }; } - Console.WriteLine($"[DungeonGenV2] Wall tile mapping: N={wallNorth.Id}, S={wallSouth.Id}, E={wallEast.Id}, W={wallWest.Id}"); + Console.WriteLine($"[DungeonGenV2] Wall mapping: N={wallNorthFace.Id}, S={wallSouthFace.Id}, E={wallEastFace.Id}, W={wallWestFace.Id}"); + Console.WriteLine($"[DungeonGenV2] Wall tops: N={wallNorthTop.Id}, S={wallSouthTop.Id}, E={wallEastTop.Id}, W={wallWestTop.Id}"); - var wallPositions = new List<(int X, int Y, TileDefinition Tile)>(); + // Track placed walls for the second pass + var wallPositions = new List<(int X, int Y, TileDefinition FaceTile, TileDefinition? TopTile, int TopOffsetX, int TopOffsetY)>(); + // Helper to check tile types bool IsWallAt(int wx, int wy) { if (wx < 0 || wx >= MapWidth || wy < 0 || wy >= MapHeight) return false; @@ -1552,201 +1732,224 @@ public class DungeonGeneratorV2 return _tileDefinitions.TryGetValue(tid, out var td) && td.Type == TileType.Wall; } - bool IsOutsideAt(int wx, int wy) + bool IsFloorAt(int wx, int wy) + { + if (wx < 0 || wx >= MapWidth || wy < 0 || wy >= MapHeight) return false; + return layout.IsWalkable(wx, wy); + } + + bool IsVoidAt(int wx, int wy) { if (wx < 0 || wx >= MapWidth || wy < 0 || wy >= MapHeight) return true; if (layout.IsWalkable(wx, wy)) return false; - return !IsWallAt(wx, wy); + return !IsWallAt(wx, wy) && layout.Tiles[wx, wy] == 0; } + // === PASS 1: Place wall FACE tiles adjacent to floors === for (int x = 0; x < MapWidth; x++) { for (int y = 0; y < MapHeight; y++) { + // Skip if already has a tile if (layout.Tiles[x, y] != 0) continue; - bool hasFloorNorth = y > 0 && layout.IsWalkable(x, y - 1); - bool hasFloorSouth = y < MapHeight - 1 && layout.IsWalkable(x, y + 1); - bool hasFloorEast = x < MapWidth - 1 && layout.IsWalkable(x + 1, y); - bool hasFloorWest = x > 0 && layout.IsWalkable(x - 1, y); + bool floorN = IsFloorAt(x, y - 1); + bool floorS = IsFloorAt(x, y + 1); + bool floorE = IsFloorAt(x + 1, y); + bool floorW = IsFloorAt(x - 1, y); + + // Only place walls adjacent to floors + if (!floorN && !floorS && !floorE && !floorW) continue; - if (hasFloorNorth || hasFloorSouth || hasFloorEast || hasFloorWest) + bool voidN = IsVoidAt(x, y - 1); + bool voidS = IsVoidAt(x, y + 1); + bool voidE = IsVoidAt(x + 1, y); + bool voidW = IsVoidAt(x - 1, y); + + TileDefinition faceTile; + TileDefinition? topTile = null; + int topOffsetX = 0, topOffsetY = 0; + + // Determine wall type based on adjacent floors + if (floorN && floorW) { - TileDefinition wallTile; - - bool outsideN = IsOutsideAt(x, y - 1); - bool outsideS = IsOutsideAt(x, y + 1); - bool outsideE = IsOutsideAt(x + 1, y); - bool outsideW = IsOutsideAt(x - 1, y); - - if (hasFloorNorth && hasFloorWest) - wallTile = PickCorner("corner_nw", preferVoid: (outsideS && outsideE)); - else if (hasFloorNorth && hasFloorEast) - wallTile = PickCorner("corner_ne", preferVoid: (outsideS && outsideW)); - else if (hasFloorSouth && hasFloorWest) - wallTile = PickCorner("corner_sw", preferVoid: (outsideN && outsideE)); - else if (hasFloorSouth && hasFloorEast) - wallTile = PickCorner("corner_se", preferVoid: (outsideN && outsideW)); - else if (hasFloorSouth) - wallTile = wallNorth; - else if (hasFloorNorth) - wallTile = wallSouth; - else if (hasFloorEast) - wallTile = wallWest; - else - wallTile = wallEast; - - wallPositions.Add((x, y, wallTile)); + // Inner corner - floor to NW + faceTile = PickInnerCornerFace("se"); + topTile = innerSETop; + topOffsetY = 1; // Top is SOUTH of face (away from floor) } + else if (floorN && floorE) + { + faceTile = PickInnerCornerFace("sw"); + topTile = innerSWTop; + topOffsetY = 1; + } + else if (floorS && floorW) + { + faceTile = PickInnerCornerFace("ne"); + topTile = innerNETop; + topOffsetY = -1; // Top is NORTH of face + } + else if (floorS && floorE) + { + faceTile = PickInnerCornerFace("nw"); + topTile = innerNWTop; + topOffsetY = -1; + } + else if (floorS) + { + // Wall facing south (floor is to south) + faceTile = wallNorthFace; + topTile = wallNorthTop; + topOffsetY = -1; // Top is north of face (away from floor) + } + else if (floorN) + { + // Wall facing north (floor is to north) + faceTile = wallSouthFace; + topTile = wallSouthTop; + topOffsetY = 1; // Top is south of face + } + else if (floorE) + { + // Wall facing east + faceTile = wallWestFace; + topTile = wallWestTop; + topOffsetX = -1; + } + else // floorW + { + // Wall facing west + faceTile = wallEastFace; + topTile = wallEastTop; + topOffsetX = 1; + } + + wallPositions.Add((x, y, faceTile, topTile, topOffsetX, topOffsetY)); } } - foreach (var (x, y, tile) in wallPositions) + // === PASS 2: Place outer corners (diagonal floor adjacency) === + for (int x = 1; x < MapWidth - 1; x++) { - layout.Tiles[x, y] = tile.Id; - - if (layout.Walkable != null) + for (int y = 1; y < MapHeight - 1; y++) { - layout.Walkable[x, y] = false; + if (layout.Tiles[x, y] != 0) continue; + if (IsFloorAt(x, y)) continue; + + bool floorNE = IsFloorAt(x + 1, y - 1); + bool floorNW = IsFloorAt(x - 1, y - 1); + bool floorSE = IsFloorAt(x + 1, y + 1); + bool floorSW = IsFloorAt(x - 1, y + 1); + + // Skip if no diagonal floor + if (!floorNE && !floorNW && !floorSE && !floorSW) continue; + + // Skip if already handled by cardinal adjacency + bool floorN = IsFloorAt(x, y - 1); + bool floorS = IsFloorAt(x, y + 1); + bool floorE = IsFloorAt(x + 1, y); + bool floorW = IsFloorAt(x - 1, y); + if (floorN || floorS || floorE || floorW) continue; + + bool voidN = IsVoidAt(x, y - 1); + bool voidS = IsVoidAt(x, y + 1); + bool voidE = IsVoidAt(x + 1, y); + bool voidW = IsVoidAt(x - 1, y); + + TileDefinition faceTile; + TileDefinition? topTile = null; + int topOffsetX = 0, topOffsetY = 0; + + if (floorSE) + { + faceTile = PickCornerFace("nw", preferVoid: voidN && voidW); + topTile = cornerNWTop; + topOffsetX = -1; topOffsetY = -1; + } + else if (floorSW) + { + faceTile = PickCornerFace("ne", preferVoid: voidN && voidE); + topTile = cornerNETop; + topOffsetX = 1; topOffsetY = -1; + } + else if (floorNE) + { + faceTile = PickCornerFace("sw", preferVoid: voidS && voidW); + topTile = cornerSWTop; + topOffsetX = -1; topOffsetY = 1; + } + else // floorNW + { + faceTile = PickCornerFace("se", preferVoid: voidS && voidE); + topTile = cornerSETop; + topOffsetX = 1; topOffsetY = 1; + } + + wallPositions.Add((x, y, faceTile, topTile, topOffsetX, topOffsetY)); } - - layout.TileDetails.Add(new PlacedTile - { - X = x, - Y = y, - TileDefinitionId = tile.Id, - SheetId = tile.TileMapSheetId, - FrameIndex = tile.FrameIndex, - Layer = 2 - }); } - var wallDetailIndex = new Dictionary<(int X, int Y), int>(); - for (int i = 0; i < layout.TileDetails.Count; i++) - { - var d = layout.TileDetails[i]; - if (d.Layer == 2) - wallDetailIndex[(d.X, d.Y)] = i; - } + // === PASS 3: Actually place all wall tiles === + var placedWalls = new HashSet<(int, int)>(); + int faceCount = 0, topCount = 0; - void PlaceWall(int wx, int wy, TileDefinition tdef) + foreach (var (x, y, faceTile, topTile, topOffsetX, topOffsetY) in wallPositions) { - layout.Tiles[wx, wy] = tdef.Id; - if (layout.Walkable != null) layout.Walkable[wx, wy] = false; + // Place face tile + if (!placedWalls.Contains((x, y))) + { + layout.Tiles[x, y] = faceTile.Id; + if (layout.Walkable != null) + layout.Walkable[x, y] = false; - if (wallDetailIndex.TryGetValue((wx, wy), out var existingIdx)) - { - var d = layout.TileDetails[existingIdx]; - d.TileDefinitionId = tdef.Id; - d.SheetId = tdef.TileMapSheetId; - d.FrameIndex = tdef.FrameIndex; - layout.TileDetails[existingIdx] = d; - } - else - { - wallDetailIndex[(wx, wy)] = layout.TileDetails.Count; layout.TileDetails.Add(new PlacedTile { - X = wx, - Y = wy, - TileDefinitionId = tdef.Id, - SheetId = tdef.TileMapSheetId, - FrameIndex = tdef.FrameIndex, + X = x, + Y = y, + TileDefinitionId = faceTile.Id, + SheetId = faceTile.TileMapSheetId, + FrameIndex = faceTile.FrameIndex, Layer = 2 }); + + placedWalls.Add((x, y)); + faceCount++; } - } - for (int x = 1; x < MapWidth - 1; x++) - { - for (int y = 1; y < MapHeight - 1; y++) + // Place top tile (if we have one and the position is valid) + if (topTile != null) { - if (layout.Tiles[x, y] != 0) continue; - if (layout.IsWalkable(x, y)) continue; + int topX = x + topOffsetX; + int topY = y + topOffsetY; - bool floorNE = layout.IsWalkable(x + 1, y - 1); - bool floorNW = layout.IsWalkable(x - 1, y - 1); - bool floorSE = layout.IsWalkable(x + 1, y + 1); - bool floorSW = layout.IsWalkable(x - 1, y + 1); - - bool wallN = IsWallAt(x, y - 1); - bool wallS = IsWallAt(x, y + 1); - bool wallE = IsWallAt(x + 1, y); - bool wallW = IsWallAt(x - 1, y); - - bool vN = IsOutsideAt(x, y - 1); - bool vS = IsOutsideAt(x, y + 1); - bool vE = IsOutsideAt(x + 1, y); - bool vW = IsOutsideAt(x - 1, y); - - if (floorSE && (wallS || wallE)) PlaceWall(x, y, PickCorner("corner_se", preferVoid: (vN && vW))); - else if (floorSW && (wallS || wallW)) PlaceWall(x, y, PickCorner("corner_sw", preferVoid: (vN && vE))); - else if (floorNE && (wallN || wallE)) PlaceWall(x, y, PickCorner("corner_ne", preferVoid: (vS && vW))); - else if (floorNW && (wallN || wallW)) PlaceWall(x, y, PickCorner("corner_nw", preferVoid: (vS && vE))); - } - } - - for (int x = 1; x < MapWidth - 1; x++) - { - for (int y = 1; y < MapHeight - 1; y++) - { - int id = layout.Tiles[x, y]; - if (id == 0) continue; - if (!_tileDefinitions.TryGetValue(id, out var def)) continue; - if (def.Type != TileType.Wall) continue; - - bool floorN = layout.IsWalkable(x, y - 1); - bool floorS = layout.IsWalkable(x, y + 1); - bool floorE = layout.IsWalkable(x + 1, y); - bool floorW = layout.IsWalkable(x - 1, y); - - bool floorNE = layout.IsWalkable(x + 1, y - 1); - bool floorNW = layout.IsWalkable(x - 1, y - 1); - bool floorSE = layout.IsWalkable(x + 1, y + 1); - bool floorSW = layout.IsWalkable(x - 1, y + 1); - - TileDefinition? replace = null; - - bool vN2 = IsOutsideAt(x, y - 1); - bool vS2 = IsOutsideAt(x, y + 1); - bool vE2 = IsOutsideAt(x + 1, y); - bool vW2 = IsOutsideAt(x - 1, y); - - if (floorSE && !floorS && !floorE) replace = PickCorner("corner_se", preferVoid: (vN2 && vW2)); - else if (floorSW && !floorS && !floorW) replace = PickCorner("corner_sw", preferVoid: (vN2 && vE2)); - else if (floorNE && !floorN && !floorE) replace = PickCorner("corner_ne", preferVoid: (vS2 && vW2)); - else if (floorNW && !floorN && !floorW) replace = PickCorner("corner_nw", preferVoid: (vS2 && vE2)); - - if (replace == null) continue; - if (replace.Id == id) continue; - - layout.Tiles[x, y] = replace.Id; - if (layout.Walkable != null) layout.Walkable[x, y] = false; - - if (wallDetailIndex.TryGetValue((x, y), out var idx)) + if (topX >= 0 && topX < MapWidth && topY >= 0 && topY < MapHeight) { - var d = layout.TileDetails[idx]; - d.TileDefinitionId = replace.Id; - d.SheetId = replace.TileMapSheetId; - d.FrameIndex = replace.FrameIndex; - layout.TileDetails[idx] = d; - } - else - { - layout.TileDetails.Add(new PlacedTile + // Only place if the position is empty (void) + if (layout.Tiles[topX, topY] == 0 && !placedWalls.Contains((topX, topY))) { - X = x, - Y = y, - TileDefinitionId = replace.Id, - SheetId = replace.TileMapSheetId, - FrameIndex = replace.FrameIndex, - Layer = 2 - }); + layout.Tiles[topX, topY] = topTile.Id; + if (layout.Walkable != null) + layout.Walkable[topX, topY] = false; + + layout.TileDetails.Add(new PlacedTile + { + X = topX, + Y = topY, + TileDefinitionId = topTile.Id, + SheetId = topTile.TileMapSheetId, + FrameIndex = topTile.FrameIndex, + Layer = 3 // Top tiles on higher layer + }); + + placedWalls.Add((topX, topY)); + topCount++; + } } } } - Console.WriteLine($"[DungeonGenV2] Generated {wallPositions.Count} auto-walls"); + Console.WriteLine($"[DungeonGenV2] Generated {faceCount} wall faces, {topCount} wall tops"); } @@ -1777,6 +1980,55 @@ public class DungeonGeneratorV2 private void GenerateSpawns(List rooms, DungeonLayoutV2 layout) { + // Helper to check if a position is valid for spawning (must be walkable floor) + bool IsValidSpawnPosition(int x, int y) + { + if (x < 0 || x >= MapWidth || y < 0 || y >= MapHeight) + return false; + + // Must be walkable + if (!layout.IsWalkable(x, y)) + return false; + + // Must have a floor tile (not wall, not empty) + int tileId = layout.Tiles[x, y]; + if (tileId == 0) + return false; + + if (_tileDefinitions.TryGetValue(tileId, out var tileDef)) + { + // Only spawn on Floor or FloorDecor tiles + return tileDef.Type == TileType.Floor || tileDef.Type == TileType.FloorDecor; + } + + return false; + } + + // Find a valid spawn position within a room, with retries + (int x, int y)? FindValidSpawnPosition(DungeonRoomV2 room, int maxAttempts = 20) + { + for (int attempt = 0; attempt < maxAttempts; attempt++) + { + int x = room.X + 1 + _rng.Next(Math.Max(1, room.Width - 2)); + int y = room.Y + 1 + _rng.Next(Math.Max(1, room.Height - 2)); + + if (IsValidSpawnPosition(x, y)) + return (x, y); + } + + // Fallback: scan the room for any valid position + for (int x = room.X; x < room.X + room.Width; x++) + { + for (int y = room.Y; y < room.Y + room.Height; y++) + { + if (IsValidSpawnPosition(x, y)) + return (x, y); + } + } + + return null; + } + foreach (var room in rooms) { if (room.Type == RoomType.Entrance) continue; @@ -1790,14 +2042,18 @@ public class DungeonGeneratorV2 for (int i = 0; i < mobCount; i++) { - int x = room.X + 1 + _rng.Next(Math.Max(1, room.Width - 2)); - int y = room.Y + 1 + _rng.Next(Math.Max(1, room.Height - 2)); + var pos = FindValidSpawnPosition(room); + if (pos == null) + { + Console.WriteLine($"[DungeonGenV2] WARNING: Could not find valid spawn position in room at ({room.X},{room.Y})"); + continue; + } layout.MobSpawns.Add(new DungeonMobSpawn { Id = layout.MobSpawns.Count + 1, - X = x, - Y = y, + X = pos.Value.x, + Y = pos.Value.y, MobType = room.Type == RoomType.Boss ? DungeonMobSpawnType.Boss : DungeonMobSpawnType.Normal, RoomIndex = rooms.IndexOf(room) }); @@ -1812,14 +2068,18 @@ public class DungeonGeneratorV2 for (int i = 0; i < chestCount; i++) { - int x = room.X + 1 + _rng.Next(Math.Max(1, room.Width - 2)); - int y = room.Y + 1 + _rng.Next(Math.Max(1, room.Height - 2)); + var pos = FindValidSpawnPosition(room); + if (pos == null) + { + Console.WriteLine($"[DungeonGenV2] WARNING: Could not find valid chest position in room at ({room.X},{room.Y})"); + continue; + } layout.ChestSpawns.Add(new DungeonChestSpawn { Id = layout.ChestSpawns.Count + 1, - X = x, - Y = y, + X = pos.Value.x, + Y = pos.Value.y, ChestType = room.Type == RoomType.Boss ? DungeonChestType.Boss : DungeonChestType.Normal, RoomIndex = rooms.IndexOf(room) }); @@ -1828,6 +2088,7 @@ public class DungeonGeneratorV2 layout.TotalMobs = layout.MobSpawns.Count; layout.TotalChests = layout.ChestSpawns.Count; + Console.WriteLine($"[DungeonGenV2] Generated {layout.TotalMobs} mob spawns, {layout.TotalChests} chest spawns"); } private static Dictionary> ParseSocketTypes(HashSet tags)