From fe10c8f21991e7361c1241572183143ea43b0c23 Mon Sep 17 00:00:00 2001 From: dingo Date: Mon, 29 Dec 2025 10:24:52 -0500 Subject: [PATCH] Dungeon Revision --- Game/Dungeon/DungeonGeneratorV2.cs | 551 ++++++++++++++++++++--------- 1 file changed, 391 insertions(+), 160 deletions(-) diff --git a/Game/Dungeon/DungeonGeneratorV2.cs b/Game/Dungeon/DungeonGeneratorV2.cs index f33beab..c8862e5 100644 --- a/Game/Dungeon/DungeonGeneratorV2.cs +++ b/Game/Dungeon/DungeonGeneratorV2.cs @@ -16,13 +16,17 @@ public class DungeonGeneratorV2 private readonly int _seed; private readonly int _tier; private readonly int _tileSize = 32; - + + // Corridor sizing (in tiles) + private const int MinCorridorWidth = 4; + private const int MaxCorridorWidth = 8; + // Tier-based scaling private int MinRooms => 5 + (_tier * 2); private int MaxRooms => 8 + (_tier * 3); private int MapWidth => 60 + (_tier * 15); // In tiles private int MapHeight => 60 + (_tier * 15); - + // Cached templates private List _entranceTemplates = new(); private List _exitTemplates = new(); @@ -30,11 +34,199 @@ public class DungeonGeneratorV2 private List _treasureTemplates = new(); private List _normalTemplates = new(); private List _hallwayTemplates = new(); - + // Tile definitions cache private Dictionary _tileDefinitions = new(); private TileMapSheet? _defaultSheet; - + + private static HashSet ParseTags(string? tags) + { + if (string.IsNullOrWhiteSpace(tags)) return new HashSet(StringComparer.OrdinalIgnoreCase); + return tags + .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Where(s => !string.IsNullOrWhiteSpace(s)) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + } + + private static int CountOverlap(HashSet a, HashSet b) + { + if (a.Count == 0 || b.Count == 0) return 0; + int c = 0; + foreach (var t in a) + if (b.Contains(t)) c++; + return c; + } + + private TileDefinition? SelectBestFloorTileForTags(HashSet requiredTags) + { + var floors = _tileDefinitions.Values.Where(t => t.Type == TileType.Floor).ToList(); + if (floors.Count == 0) return null; + + if (requiredTags.Count == 0) + return floors[0]; + + TileDefinition best = floors[0]; + int bestScore = -1; + foreach (var f in floors) + { + var tags = ParseTags(f.Tags); + int score = CountOverlap(requiredTags, tags); + if (score > bestScore) + { + best = f; + bestScore = score; + } + } + return best; + } + + private RoomTemplate? SelectHallwayTemplate(HashSet requiredTags, string direction) + { + if (_hallwayTemplates.Count == 0) return null; + + // Require a hallway to support the travel direction (and its opposite) via connection points. + // If template JSON is missing, we still allow it as a fallback. + static string Opp(string dir) => dir.ToLower() switch + { + "north" => "south", + "south" => "north", + "east" => "west", + "west" => "east", + _ => dir + }; + + var needA = direction.ToLower(); + var needB = Opp(needA); + + RoomTemplate? best = null; + int bestScore = -1; + + foreach (var t in _hallwayTemplates) + { + int score = CountOverlap(requiredTags, ParseTags(t.Tags)); + + bool supports = true; + if (!string.IsNullOrEmpty(t.ConnectionPointsJson)) + { + try + { + var cps = JsonSerializer.Deserialize>(t.ConnectionPointsJson); + if (cps != null) + { + supports = cps.Any(c => c.Direction.Equals(needA, StringComparison.OrdinalIgnoreCase)) + && cps.Any(c => c.Direction.Equals(needB, StringComparison.OrdinalIgnoreCase)); + } + } + catch + { + // ignore parse failures + } + } + + if (!supports) continue; + + if (score > bestScore) + { + best = t; + bestScore = score; + } + } + + return best; + } + + private bool TryStampHallwayRun( + DungeonLayoutV2 layout, + RoomTemplate hallway, + int x1, + int y1, + int x2, + int y2, + int fallbackFloorId, + int fallbackSheetId, + int fallbackFrameIndex) + { + // Only supports straight runs. + bool horizontal = y1 == y2; + bool vertical = x1 == x2; + if (!horizontal && !vertical) return false; + + if (string.IsNullOrEmpty(hallway.TileDataJson)) return false; + + List? placements; + try + { + placements = JsonSerializer.Deserialize>(hallway.TileDataJson); + } + catch + { + return false; + } + if (placements == null || placements.Count == 0) return false; + + int step = horizontal ? Math.Max(1, hallway.Width) : Math.Max(1, hallway.Height); + int dir = horizontal ? Math.Sign(x2 - x1) : Math.Sign(y2 - y1); + if (dir == 0) dir = 1; + + // Align hallway chunk to the corridor centerline. + int baseX = horizontal ? Math.Min(x1, x2) : x1 - (hallway.Width / 2); + int baseY = vertical ? Math.Min(y1, y2) : y1 - (hallway.Height / 2); + + int end = horizontal ? Math.Max(x1, x2) : Math.Max(y1, y2); + + for (int pos = horizontal ? Math.Min(x1, x2) : Math.Min(y1, y2); + pos <= end; + pos += step) + { + int originX = horizontal ? pos : baseX; + int originY = vertical ? pos : baseY; + + foreach (var p in placements) + { + int wx = originX + p.X; + int wy = originY + p.Y; + if (wx < 0 || wx >= MapWidth || wy < 0 || wy >= MapHeight) continue; + + // Stop stamping once we collide with an existing walkable area (usually a room). + if (layout.IsWalkable(wx, wy)) continue; + + int tileId = p.TileDefinitionId; + var tileDef = _tileDefinitions.GetValueOrDefault(tileId); + if (tileDef == null) + { + tileId = fallbackFloorId; + tileDef = _tileDefinitions.GetValueOrDefault(tileId); + } + + // Remove any previous visuals at this location. + layout.TileDetails.RemoveAll(t => t.X == wx && t.Y == wy); + + layout.Tiles[wx, wy] = tileId; + if (layout.Walkable != null) + layout.Walkable[wx, wy] = tileDef?.IsWalkable ?? true; + + // Add visual + if (tileId > 0) + { + layout.TileDetails.Add(new PlacedTile + { + X = wx, + Y = wy, + TileDefinitionId = tileId, + SheetId = tileDef?.TileMapSheetId ?? fallbackSheetId, + FrameIndex = tileDef?.FrameIndex ?? fallbackFrameIndex, + Layer = p.Layer, + Rotation = p.Rotation, + FlipX = p.FlipX, + FlipY = p.FlipY + }); + } + } + } + + return true; + } + public DungeonGeneratorV2(GameDbContext db, int seed, int tier) { _db = db; @@ -42,12 +234,12 @@ public class DungeonGeneratorV2 _tier = Math.Max(1, tier); _rng = new Random(seed); } - + public async Task GenerateAsync() { // Load templates from database await LoadTemplatesAsync(); - + var layout = new DungeonLayoutV2 { Seed = _seed, @@ -56,42 +248,42 @@ public class DungeonGeneratorV2 Height = MapHeight, TileSize = _tileSize }; - + // Initialize tile map with detailed tile info // 0 = void/wall, positive = tile definition ID layout.Tiles = new int[MapWidth, MapHeight]; layout.Walkable = new bool[MapWidth, MapHeight]; // All false by default layout.TileDetails = new List(); - + // Generate rooms int roomCount = _rng.Next(MinRooms, MaxRooms + 1); var rooms = new List(); int attempts = 0; int maxAttempts = roomCount * 30; - + // Always place entrance first var entrance = await PlaceRoomAsync(layout, rooms, RoomType.Entrance, 5, 5); - if (entrance != null) + if (entrance != null) { rooms.Add(entrance); Console.WriteLine($"[DungeonGenV2] Placed entrance room: {entrance.TemplateName ?? "fallback"} at ({entrance.X},{entrance.Y})"); } - + // Place other rooms while (rooms.Count < roomCount && attempts < maxAttempts) { attempts++; - + // Determine room type based on current room count RoomType type = DetermineNextRoomType(rooms, roomCount); - + // Try to place near existing room (for connectivity) var baseRoom = rooms[_rng.Next(rooms.Count)]; int offsetX = _rng.Next(-20, 21); int offsetY = _rng.Next(-20, 21); int x = Math.Clamp(baseRoom.X + baseRoom.Width / 2 + offsetX, 2, MapWidth - 15); int y = Math.Clamp(baseRoom.Y + baseRoom.Height / 2 + offsetY, 2, MapHeight - 15); - + var newRoom = await PlaceRoomAsync(layout, rooms, type, x, y); if (newRoom != null) { @@ -99,9 +291,9 @@ public class DungeonGeneratorV2 Console.WriteLine($"[DungeonGenV2] Placed {type} room: {newRoom.TemplateName ?? "fallback"} at ({newRoom.X},{newRoom.Y})"); } } - + Console.WriteLine($"[DungeonGenV2] Placed {rooms.Count}/{roomCount} rooms after {attempts} attempts"); - + // Ensure we have an exit/boss room var bossRoom = rooms.FirstOrDefault(r => r.Type == RoomType.Boss); if (bossRoom == null && rooms.Count > 1) @@ -109,15 +301,15 @@ public class DungeonGeneratorV2 // Convert last room to boss rooms[^1].Type = RoomType.Boss; } - + // Sort rooms by distance from entrance for corridor generation var entranceRoom = rooms.FirstOrDefault(r => r.Type == RoomType.Entrance) ?? rooms[0]; rooms = rooms.OrderBy(r => Distance(entranceRoom, r)).ToList(); - + // Connect rooms with corridors - entrance MUST be connected var connected = new HashSet { 0 }; Console.WriteLine($"[DungeonGenV2] Connecting {rooms.Count} rooms..."); - + for (int i = 1; i < rooms.Count; i++) { // Find closest connected room @@ -126,7 +318,7 @@ public class DungeonGeneratorV2 connected.Add(i); Console.WriteLine($"[DungeonGenV2] Connected room {i} ({rooms[i].Type}) to room {closestIdx}"); } - + // Add some extra connections for loops for (int i = 0; i < rooms.Count / 4; i++) { @@ -137,74 +329,76 @@ public class DungeonGeneratorV2 await ConnectRoomsAsync(layout, rooms[a], rooms[b]); } } - + // Set spawn point layout.SpawnPoint = new DungeonPoint(entranceRoom.CenterX, entranceRoom.CenterY); - + // Generate mob and chest spawns based on room templates GenerateSpawns(rooms, layout); - + // Store rooms layout.Rooms = rooms.Cast().ToList(); - + // Auto-generate walls around floor tiles GenerateAutoWalls(layout); - + // Build tile data for client layout.BuildClientTileData(_tileDefinitions, _defaultSheet); - + Console.WriteLine($"[DungeonGenV2] Generation complete: {rooms.Count} rooms, {layout.TileDetails.Count} visual tiles, {layout.TileMapSheets.Count} sheets"); - + return layout; } - + private async Task LoadTemplatesAsync() { var templates = await _db.RoomTemplates .Where(r => r.IsEnabled) .Where(r => r.MinTier <= _tier && (r.MaxTier == 0 || r.MaxTier >= _tier)) .ToListAsync(); - + _entranceTemplates = templates.Where(t => t.Type == RoomType.Entrance).ToList(); _exitTemplates = templates.Where(t => t.Type == RoomType.Exit).ToList(); _bossTemplates = templates.Where(t => t.Type == RoomType.Boss).ToList(); _treasureTemplates = templates.Where(t => t.Type == RoomType.Treasure).ToList(); _normalTemplates = templates.Where(t => t.Type == RoomType.Normal).ToList(); _hallwayTemplates = templates.Where(t => t.Type == RoomType.Hallway).ToList(); - + Console.WriteLine($"[DungeonGenV2] Loaded templates for tier {_tier}: Entrance={_entranceTemplates.Count}, Exit={_exitTemplates.Count}, Boss={_bossTemplates.Count}, Treasure={_treasureTemplates.Count}, Normal={_normalTemplates.Count}"); - + // Load tile definitions from templates var tileIds = templates .Where(t => !string.IsNullOrEmpty(t.TileDataJson)) .SelectMany(t => { - try { + try + { var placements = JsonSerializer.Deserialize>(t.TileDataJson!); return placements?.Select(p => p.TileDefinitionId) ?? Enumerable.Empty(); - } catch { return Enumerable.Empty(); } + } + catch { return Enumerable.Empty(); } }) .Distinct() .ToList(); - + if (tileIds.Any()) { var tiles = await _db.TileDefinitions .Include(t => t.TileMapSheet) .Where(t => tileIds.Contains(t.Id)) .ToListAsync(); - + _tileDefinitions = tiles.ToDictionary(t => t.Id); _defaultSheet = tiles.FirstOrDefault()?.TileMapSheet; Console.WriteLine($"[DungeonGenV2] Loaded {tiles.Count} tile definitions from templates"); } - + // Always load a default sheet for fallback generation if (_defaultSheet == null) { _defaultSheet = await _db.TileMapSheets .Include(s => s.Tiles) .FirstOrDefaultAsync(s => s.IsEnabled); - + if (_defaultSheet?.Tiles != null) { foreach (var tile in _defaultSheet.Tiles) @@ -219,30 +413,30 @@ public class DungeonGeneratorV2 Console.WriteLine($"[DungeonGenV2] WARNING: No tilemap sheets found in database!"); } } - + Console.WriteLine($"[DungeonGenV2] Total tile definitions: {_tileDefinitions.Count}"); } - + private RoomType DetermineNextRoomType(List existing, int targetCount) { // Ensure we have at least one of certain types bool hasBoss = existing.Any(r => r.Type == RoomType.Boss); bool hasTreasure = existing.Any(r => r.Type == RoomType.Treasure); - + // If near the end and no boss, force boss if (!hasBoss && existing.Count >= targetCount - 2) return RoomType.Boss; - + // Weighted random selection int roll = _rng.Next(100); - + if (roll < 5 && !hasBoss) return RoomType.Boss; if (roll < 15 && !hasTreasure) return RoomType.Treasure; if (roll < 25) return RoomType.Treasure; - + return RoomType.Normal; } - + private async Task PlaceRoomAsync(DungeonLayoutV2 layout, List existing, RoomType type, int preferX, int preferY) { // Get templates for this type @@ -253,31 +447,32 @@ public class DungeonGeneratorV2 RoomType.Treasure => _treasureTemplates, _ => _normalTemplates }; - + // If no templates, use fallback generation if (templates.Count == 0) { return PlaceFallbackRoom(layout, existing, type, preferX, preferY); } - + // Weighted random selection var template = SelectWeightedTemplate(templates); if (template == null) { return PlaceFallbackRoom(layout, existing, type, preferX, preferY); } - + // Try to place at preferred position int x = Math.Clamp(preferX - template.Width / 2, 2, MapWidth - template.Width - 2); int y = Math.Clamp(preferY - template.Height / 2, 2, MapHeight - template.Height - 2); - + var room = new DungeonRoomV2(x, y, template.Width, template.Height) { Type = type, TemplateId = template.Id, - TemplateName = template.Name + TemplateName = template.Name, + TemplateTags = ParseTags(template.Tags) }; - + // Check overlap if (existing.Any(r => room.Intersects(r, padding: 3))) { @@ -290,17 +485,18 @@ public class DungeonGeneratorV2 { Type = type, TemplateId = template.Id, - TemplateName = template.Name + TemplateName = template.Name, + TemplateTags = ParseTags(template.Tags) }; - + if (!existing.Any(r => room.Intersects(r, padding: 3))) break; } - + if (existing.Any(r => room.Intersects(r, padding: 3))) return null; } - + // Place tiles from template if (!string.IsNullOrEmpty(template.TileDataJson)) { @@ -313,20 +509,20 @@ public class DungeonGeneratorV2 { int worldX = x + p.X; int worldY = y + p.Y; - + if (worldX >= 0 && worldX < MapWidth && worldY >= 0 && worldY < MapHeight) { layout.Tiles[worldX, worldY] = p.TileDefinitionId; - + // Look up tile definition for sheet info and walkability var tileDef = _tileDefinitions.GetValueOrDefault(p.TileDefinitionId); - + // Set walkability based on tile definition if (layout.Walkable != null && tileDef != null) { layout.Walkable[worldX, worldY] = tileDef.IsWalkable; } - + layout.TileDetails.Add(new PlacedTile { X = worldX, @@ -345,7 +541,7 @@ public class DungeonGeneratorV2 } catch { /* Invalid JSON, fall through to basic carve */ } } - + // Parse connection points from template if (!string.IsNullOrEmpty(template.ConnectionPointsJson)) { @@ -359,7 +555,7 @@ public class DungeonGeneratorV2 } catch { /* Invalid JSON */ } } - + // If no connection points defined, create default ones on each edge // These are positioned AT the room edge (not inside) if (room.ConnectionPoints.Count == 0) @@ -385,25 +581,25 @@ public class DungeonGeneratorV2 Console.WriteLine($" - ({cp.X},{cp.Y}) direction={cp.Direction} width={cp.Width}"); } } - + // If no tiles were placed, do basic carve if (!layout.TileDetails.Any(t => t.X >= x && t.X < x + room.Width && t.Y >= y && t.Y < y + room.Height)) { CarveBasicRoom(layout, room); } - + return room; } - + private DungeonRoomV2? PlaceFallbackRoom(DungeonLayoutV2 layout, List existing, RoomType type, int preferX, int preferY) { int w = _rng.Next(6, 12); int h = _rng.Next(6, 12); int x = Math.Clamp(preferX - w / 2, 2, MapWidth - w - 2); int y = Math.Clamp(preferY - h / 2, 2, MapHeight - h - 2); - - var room = new DungeonRoomV2(x, y, w, h) { Type = type }; - + + var room = new DungeonRoomV2(x, y, w, h) { Type = type, TemplateTags = new HashSet(StringComparer.OrdinalIgnoreCase) }; + if (existing.Any(r => room.Intersects(r, padding: 3))) { // Try random positions @@ -411,26 +607,26 @@ public class DungeonGeneratorV2 { x = _rng.Next(2, MapWidth - w - 2); y = _rng.Next(2, MapHeight - h - 2); - room = new DungeonRoomV2(x, y, w, h) { Type = type }; - + room = new DungeonRoomV2(x, y, w, h) { Type = type, TemplateTags = new HashSet(StringComparer.OrdinalIgnoreCase) }; + if (!existing.Any(r => room.Intersects(r, padding: 3))) break; } - + if (existing.Any(r => room.Intersects(r, padding: 3))) return null; } - + CarveBasicRoom(layout, room); return room; } - + private void CarveBasicRoom(DungeonLayoutV2 layout, DungeonRoomV2 room) { // Find floor tile from default sheet - var floorTile = _tileDefinitions.Values.FirstOrDefault(t => t.Type == TileType.Floor); + var floorTile = SelectBestFloorTileForTags(room.TemplateTags) ?? _tileDefinitions.Values.FirstOrDefault(t => t.Type == TileType.Floor); int floorId = floorTile?.Id ?? -1; // -1 means no visual tile, just walkable - + for (int x = room.X; x < room.X + room.Width; x++) { for (int y = room.Y; y < room.Y + room.Height; y++) @@ -438,18 +634,19 @@ public class DungeonGeneratorV2 if (x >= 0 && x < MapWidth && y >= 0 && y < MapHeight) { layout.Tiles[x, y] = floorId > 0 ? floorId : 1; // 1 = walkable but no visual - + // Set walkability - basic carved rooms are always walkable if (layout.Walkable != null) { layout.Walkable[x, y] = true; } - + if (floorId > 0 && floorTile != null) { layout.TileDetails.Add(new PlacedTile { - X = x, Y = y, + X = x, + Y = y, TileDefinitionId = floorId, SheetId = floorTile.TileMapSheetId, FrameIndex = floorTile.FrameIndex, @@ -460,19 +657,28 @@ public class DungeonGeneratorV2 } } } - + private async Task ConnectRoomsAsync(DungeonLayoutV2 layout, DungeonRoomV2 a, DungeonRoomV2 b) { - var floorTile = _tileDefinitions.Values.FirstOrDefault(t => t.Type == TileType.Floor); + // Determine tag requirements for this connection. + var requiredTags = new HashSet(a.TemplateTags ?? new HashSet(StringComparer.OrdinalIgnoreCase), StringComparer.OrdinalIgnoreCase); + requiredTags.IntersectWith(b.TemplateTags ?? new HashSet(StringComparer.OrdinalIgnoreCase)); + if (requiredTags.Count == 0) + { + requiredTags = new HashSet(a.TemplateTags ?? new HashSet(StringComparer.OrdinalIgnoreCase), StringComparer.OrdinalIgnoreCase); + requiredTags.UnionWith(b.TemplateTags ?? new HashSet(StringComparer.OrdinalIgnoreCase)); + } + + var floorTile = SelectBestFloorTileForTags(requiredTags) ?? _tileDefinitions.Values.FirstOrDefault(t => t.Type == TileType.Floor); int floorId = floorTile?.Id ?? 1; int sheetId = floorTile?.TileMapSheetId ?? 0; int frameIndex = floorTile?.FrameIndex ?? 0; - + // Determine best connection points based on relative positions string aDirection, bDirection; int deltaX = b.CenterX - a.CenterX; int deltaY = b.CenterY - a.CenterY; - + // Choose connection directions based on which room is where if (Math.Abs(deltaX) > Math.Abs(deltaY)) { @@ -486,25 +692,25 @@ public class DungeonGeneratorV2 aDirection = deltaY > 0 ? "south" : "north"; bDirection = deltaY > 0 ? "north" : "south"; } - + // Get connection points (or fall back to edge center) var cpA = a.GetConnectionPoint(aDirection); var cpB = b.GetConnectionPoint(bDirection); - + Console.WriteLine($"[DungeonGenV2] Connecting {a.TemplateName ?? "room"} to {b.TemplateName ?? "room"}"); Console.WriteLine($" A wants {aDirection}, got cp: {(cpA != null ? $"({cpA.X},{cpA.Y}) dir={cpA.Direction}" : "null")}"); Console.WriteLine($" B wants {bDirection}, got cp: {(cpB != null ? $"({cpB.X},{cpB.Y}) dir={cpB.Direction}" : "null")}"); - + int startX, startY, endX, endY; - int corridorWidth = 2; - + int corridorWidth = _rng.Next(MinCorridorWidth, MaxCorridorWidth + 1); + if (cpA != null) { var (wx, wy) = a.GetConnectionWorldPos(cpA); startX = wx; startY = wy; corridorWidth = Math.Max(corridorWidth, cpA.Width); - + // Clear the connection point area (carve through template walls) ClearConnectionPoint(layout, wx, wy, cpA.Width, aDirection, floorId, sheetId, frameIndex); } @@ -513,14 +719,14 @@ public class DungeonGeneratorV2 startX = a.CenterX; startY = a.CenterY; } - + if (cpB != null) { var (wx, wy) = b.GetConnectionWorldPos(cpB); endX = wx; endY = wy; corridorWidth = Math.Max(corridorWidth, cpB.Width); - + // Clear the connection point area (carve through template walls) ClearConnectionPoint(layout, wx, wy, cpB.Width, bDirection, floorId, sheetId, frameIndex); } @@ -529,20 +735,34 @@ public class DungeonGeneratorV2 endX = b.CenterX; endY = b.CenterY; } - + // L-shaped corridor from connection point to connection point if (_rng.Next(2) == 0) { - CarveHorizontalCorridor(layout, startX, endX, startY, floorId, sheetId, frameIndex, corridorWidth); - CarveVerticalCorridor(layout, startY, endY, endX, floorId, sheetId, frameIndex, corridorWidth); + // Horizontal segment + var hallH = SelectHallwayTemplate(requiredTags, startX <= endX ? "east" : "west"); + if (hallH == null || !TryStampHallwayRun(layout, hallH, startX, startY, endX, startY, floorId, sheetId, frameIndex)) + CarveHorizontalCorridor(layout, startX, endX, startY, floorId, sheetId, frameIndex, corridorWidth); + + // Vertical segment + var hallV = SelectHallwayTemplate(requiredTags, startY <= endY ? "south" : "north"); + if (hallV == null || !TryStampHallwayRun(layout, hallV, endX, startY, endX, endY, floorId, sheetId, frameIndex)) + CarveVerticalCorridor(layout, startY, endY, endX, floorId, sheetId, frameIndex, corridorWidth); } else { - CarveVerticalCorridor(layout, startY, endY, startX, floorId, sheetId, frameIndex, corridorWidth); - CarveHorizontalCorridor(layout, startX, endX, endY, floorId, sheetId, frameIndex, corridorWidth); + // Vertical segment + var hallV = SelectHallwayTemplate(requiredTags, startY <= endY ? "south" : "north"); + if (hallV == null || !TryStampHallwayRun(layout, hallV, startX, startY, startX, endY, floorId, sheetId, frameIndex)) + CarveVerticalCorridor(layout, startY, endY, startX, floorId, sheetId, frameIndex, corridorWidth); + + // Horizontal segment + var hallH = SelectHallwayTemplate(requiredTags, startX <= endX ? "east" : "west"); + if (hallH == null || !TryStampHallwayRun(layout, hallH, startX, endY, endX, endY, floorId, sheetId, frameIndex)) + CarveHorizontalCorridor(layout, startX, endX, endY, floorId, sheetId, frameIndex, corridorWidth); } } - + /// /// Clear tiles at a connection point to allow corridor entry /// This aggressively clears walls in both directions to ensure passage @@ -551,10 +771,10 @@ public class DungeonGeneratorV2 { int depth = 5; // How far to clear in each direction int halfWidth = Math.Max(width, 2); - + Console.WriteLine($"[DungeonGenV2] Clearing connection at ({x},{y}) direction={direction} width={width}"); int clearedCount = 0; - + // Clear in a cross/plus pattern centered on the connection point // This ensures we punch through walls regardless of direction for (int d = -depth; d <= depth; d++) @@ -562,7 +782,7 @@ public class DungeonGeneratorV2 for (int w = -halfWidth; w <= halfWidth; w++) { int cx, cy; - + switch (direction.ToLower()) { case "north": @@ -579,117 +799,124 @@ public class DungeonGeneratorV2 cy = y + w; break; } - + if (cx >= 0 && cx < MapWidth && cy >= 0 && cy < MapHeight) { // Track if we're actually changing something bool hadTile = layout.Tiles[cx, cy] != 0; bool wasBlocked = layout.Walkable != null && !layout.Walkable[cx, cy]; - + // Remove existing tile visuals layout.TileDetails.RemoveAll(t => t.X == cx && t.Y == cy); - + // Set as walkable floor layout.Tiles[cx, cy] = floorId; if (layout.Walkable != null) { layout.Walkable[cx, cy] = true; } - + // Add floor tile visual if (floorId > 0 && sheetId > 0) { layout.TileDetails.Add(new PlacedTile { - X = cx, Y = cy, + X = cx, + Y = cy, TileDefinitionId = floorId, SheetId = sheetId, FrameIndex = frameIndex, Layer = 0 }); } - + if (hadTile && wasBlocked) clearedCount++; } } } - + Console.WriteLine($"[DungeonGenV2] Cleared {clearedCount} wall tiles at connection"); } - + private void CarveHorizontalCorridor(DungeonLayoutV2 layout, int x1, int x2, int y, int floorId, int sheetId, int frameIndex, int width = 2) { int minX = Math.Min(x1, x2); int maxX = Math.Max(x1, x2); - + for (int x = minX; x <= maxX; x++) { for (int dy = 0; dy < width; dy++) { int ty = y + dy - width / 2; // Center the corridor - if (x >= 0 && x < MapWidth && ty >= 0 && ty < MapHeight && layout.Tiles[x, ty] == 0) + if (x >= 0 && x < MapWidth && ty >= 0 && ty < MapHeight && !layout.IsWalkable(x, ty)) { + // Remove any existing visual (walls, void decorations, etc.) + layout.TileDetails.RemoveAll(t => t.X == x && t.Y == ty); layout.Tiles[x, ty] = floorId; - + // Set walkability for corridors if (layout.Walkable != null) { layout.Walkable[x, ty] = true; } - + if (floorId > 0 && sheetId > 0) { - layout.TileDetails.Add(new PlacedTile - { - X = x, Y = ty, - TileDefinitionId = floorId, + layout.TileDetails.Add(new PlacedTile + { + X = x, + Y = ty, + TileDefinitionId = floorId, SheetId = sheetId, FrameIndex = frameIndex, - Layer = 0 + Layer = 0 }); } } } } } - + private void CarveVerticalCorridor(DungeonLayoutV2 layout, int y1, int y2, int x, int floorId, int sheetId, int frameIndex, int width = 2) { int minY = Math.Min(y1, y2); int maxY = Math.Max(y1, y2); - + for (int y = minY; y <= maxY; y++) { for (int dx = 0; dx < width; dx++) { int tx = x + dx - width / 2; // Center the corridor - if (tx >= 0 && tx < MapWidth && y >= 0 && y < MapHeight && layout.Tiles[tx, y] == 0) + if (tx >= 0 && tx < MapWidth && y >= 0 && y < MapHeight && !layout.IsWalkable(tx, y)) { + // Remove any existing visual (walls, void decorations, etc.) + layout.TileDetails.RemoveAll(t => t.X == tx && t.Y == y); layout.Tiles[tx, y] = floorId; - + // Set walkability for corridors if (layout.Walkable != null) { layout.Walkable[tx, y] = true; } - + if (floorId > 0 && sheetId > 0) { - layout.TileDetails.Add(new PlacedTile - { - X = tx, Y = y, + layout.TileDetails.Add(new PlacedTile + { + X = tx, + Y = y, TileDefinitionId = floorId, SheetId = sheetId, FrameIndex = frameIndex, - Layer = 0 + Layer = 0 }); } } } } } - + /// /// Automatically generate wall tiles around floor tiles that border void /// @@ -702,20 +929,20 @@ public class DungeonGeneratorV2 Console.WriteLine("[DungeonGenV2] No wall tiles found - skipping auto-wall generation"); return; } - + Console.WriteLine($"[DungeonGenV2] Found {wallTiles.Count} wall tiles for auto-wall generation"); foreach (var wt in wallTiles) { Console.WriteLine($" - {wt.Id}: {wt.Name} (tags: {wt.Tags ?? "none"})"); } - + // Helper to match tags (checks for exact tag match in comma-separated list) - bool HasTag(TileDefinition t, string tag) + bool HasTag(TileDefinition t, string tag) { if (string.IsNullOrEmpty(t.Tags)) return false; return t.Tags.Split(',').Any(s => s.Trim().Equals(tag, StringComparison.OrdinalIgnoreCase)); } - + // Try to find directional walls by tags, fall back to first wall var wallNorth = wallTiles.FirstOrDefault(t => HasTag(t, "north")) ?? wallTiles[0]; var wallSouth = wallTiles.FirstOrDefault(t => HasTag(t, "south")) ?? wallTiles[0]; @@ -725,12 +952,12 @@ public class DungeonGeneratorV2 var wallCornerNW = wallTiles.FirstOrDefault(t => HasTag(t, "corner_nw")) ?? wallTiles[0]; var wallCornerSE = wallTiles.FirstOrDefault(t => HasTag(t, "corner_se")) ?? wallTiles[0]; var wallCornerSW = wallTiles.FirstOrDefault(t => HasTag(t, "corner_sw")) ?? wallTiles[0]; - + Console.WriteLine($"[DungeonGenV2] Wall tile mapping: N={wallNorth.Id}, S={wallSouth.Id}, E={wallEast.Id}, W={wallWest.Id}"); - + // Track positions that need walls var wallPositions = new List<(int X, int Y, TileDefinition Tile)>(); - + // Check each void tile to see if it borders a floor for (int x = 0; x < MapWidth; x++) { @@ -738,19 +965,19 @@ public class DungeonGeneratorV2 { // Skip if not void if (layout.Tiles[x, y] != 0) continue; - + // Check neighbors for floor tiles (walkable) 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); - + // If any adjacent tile is floor, this should be a wall if (hasFloorNorth || hasFloorSouth || hasFloorEast || hasFloorWest) { // Determine wall type based on which direction has floor TileDefinition wallTile; - + // Check for corners first if (hasFloorSouth && hasFloorEast) wallTile = wallCornerNW; @@ -768,67 +995,68 @@ public class DungeonGeneratorV2 wallTile = wallWest; else wallTile = wallEast; - + wallPositions.Add((x, y, wallTile)); } } } - + // Place wall tiles foreach (var (x, y, tile) in wallPositions) { layout.Tiles[x, y] = tile.Id; - + // Walls are not walkable if (layout.Walkable != null) { layout.Walkable[x, y] = false; } - + layout.TileDetails.Add(new PlacedTile { - X = x, Y = y, + X = x, + Y = y, TileDefinitionId = tile.Id, SheetId = tile.TileMapSheetId, FrameIndex = tile.FrameIndex, Layer = 2 // Walls on layer 2 }); } - + Console.WriteLine($"[DungeonGenV2] Generated {wallPositions.Count} auto-walls"); } - + private RoomTemplate? SelectWeightedTemplate(List templates) { if (templates.Count == 0) return null; - + int totalWeight = templates.Sum(t => t.Weight); int roll = _rng.Next(totalWeight); int cumulative = 0; - + foreach (var t in templates) { cumulative += t.Weight; if (roll < cumulative) return t; } - + return templates[0]; } - + private float Distance(DungeonRoom a, DungeonRoom b) { float dx = a.CenterX - b.CenterX; float dy = a.CenterY - b.CenterY; return MathF.Sqrt(dx * dx + dy * dy); } - + private void GenerateSpawns(List rooms, DungeonLayoutV2 layout) { foreach (var room in rooms) { if (room.Type == RoomType.Entrance) continue; - + // Mob spawns int mobCount = room.Type switch { @@ -836,21 +1064,22 @@ public class DungeonGeneratorV2 RoomType.Treasure => _rng.Next(1, 3), _ => _rng.Next(2, 5 + _tier) }; - + 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)); - + layout.MobSpawns.Add(new DungeonMobSpawn { Id = layout.MobSpawns.Count + 1, - X = x, Y = y, + X = x, + Y = y, MobType = room.Type == RoomType.Boss ? DungeonMobSpawnType.Boss : DungeonMobSpawnType.Normal, RoomIndex = rooms.IndexOf(room) }); } - + // Chest spawns int chestCount = room.Type switch { @@ -858,22 +1087,23 @@ public class DungeonGeneratorV2 RoomType.Boss => 1, _ => _rng.NextDouble() < 0.2 ? 1 : 0 }; - + 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)); - + layout.ChestSpawns.Add(new DungeonChestSpawn { Id = layout.ChestSpawns.Count + 1, - X = x, Y = y, + X = x, + Y = y, ChestType = room.Type == RoomType.Boss ? DungeonChestType.Boss : DungeonChestType.Normal, RoomIndex = rooms.IndexOf(room) }); } } - + layout.TotalMobs = layout.MobSpawns.Count; layout.TotalChests = layout.ChestSpawns.Count; } @@ -886,20 +1116,21 @@ public class DungeonRoomV2 : DungeonRoom { public int? TemplateId { get; set; } public string? TemplateName { get; set; } + public HashSet TemplateTags { get; set; } = new(StringComparer.OrdinalIgnoreCase); public new RoomType Type { get; set; } = RoomType.Normal; - + /// Connection points parsed from template public List ConnectionPoints { get; set; } = new(); - + public DungeonRoomV2(int x, int y, int width, int height) : base(x, y, width, height) { } - + /// Get the best connection point for a given direction public ConnectionPoint? GetConnectionPoint(string direction) { // First try exact match var exact = ConnectionPoints.FirstOrDefault(c => c.Direction.Equals(direction, StringComparison.OrdinalIgnoreCase)); if (exact != null) return exact; - + // No exact match - create a default one for this direction rather than using wrong direction // This ensures the connection point is actually on the correct edge return direction.ToLower() switch @@ -911,7 +1142,7 @@ public class DungeonRoomV2 : DungeonRoom _ => ConnectionPoints.FirstOrDefault() // Last resort fallback }; } - + /// Get world position of a connection point public (int X, int Y) GetConnectionWorldPos(ConnectionPoint cp) {