Dungeon Revision

This commit is contained in:
dingo
2025-12-29 10:24:52 -05:00
parent 9806ce5940
commit fe10c8f219
+253 -22
View File
@@ -17,6 +17,10 @@ public class DungeonGeneratorV2
private readonly int _tier; private readonly int _tier;
private readonly int _tileSize = 32; private readonly int _tileSize = 32;
// Corridor sizing (in tiles)
private const int MinCorridorWidth = 4;
private const int MaxCorridorWidth = 8;
// Tier-based scaling // Tier-based scaling
private int MinRooms => 5 + (_tier * 2); private int MinRooms => 5 + (_tier * 2);
private int MaxRooms => 8 + (_tier * 3); private int MaxRooms => 8 + (_tier * 3);
@@ -35,6 +39,194 @@ public class DungeonGeneratorV2
private Dictionary<int, TileDefinition> _tileDefinitions = new(); private Dictionary<int, TileDefinition> _tileDefinitions = new();
private TileMapSheet? _defaultSheet; private TileMapSheet? _defaultSheet;
private static HashSet<string> ParseTags(string? tags)
{
if (string.IsNullOrWhiteSpace(tags)) return new HashSet<string>(StringComparer.OrdinalIgnoreCase);
return tags
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Where(s => !string.IsNullOrWhiteSpace(s))
.ToHashSet(StringComparer.OrdinalIgnoreCase);
}
private static int CountOverlap(HashSet<string> a, HashSet<string> 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<string> 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<string> 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<List<ConnectionPoint>>(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<TilePlacement>? placements;
try
{
placements = JsonSerializer.Deserialize<List<TilePlacement>>(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) public DungeonGeneratorV2(GameDbContext db, int seed, int tier)
{ {
_db = db; _db = db;
@@ -178,10 +370,12 @@ public class DungeonGeneratorV2
var tileIds = templates var tileIds = templates
.Where(t => !string.IsNullOrEmpty(t.TileDataJson)) .Where(t => !string.IsNullOrEmpty(t.TileDataJson))
.SelectMany(t => { .SelectMany(t => {
try { try
{
var placements = JsonSerializer.Deserialize<List<TilePlacement>>(t.TileDataJson!); var placements = JsonSerializer.Deserialize<List<TilePlacement>>(t.TileDataJson!);
return placements?.Select(p => p.TileDefinitionId) ?? Enumerable.Empty<int>(); return placements?.Select(p => p.TileDefinitionId) ?? Enumerable.Empty<int>();
} catch { return Enumerable.Empty<int>(); } }
catch { return Enumerable.Empty<int>(); }
}) })
.Distinct() .Distinct()
.ToList(); .ToList();
@@ -275,7 +469,8 @@ public class DungeonGeneratorV2
{ {
Type = type, Type = type,
TemplateId = template.Id, TemplateId = template.Id,
TemplateName = template.Name TemplateName = template.Name,
TemplateTags = ParseTags(template.Tags)
}; };
// Check overlap // Check overlap
@@ -290,7 +485,8 @@ public class DungeonGeneratorV2
{ {
Type = type, Type = type,
TemplateId = template.Id, TemplateId = template.Id,
TemplateName = template.Name TemplateName = template.Name,
TemplateTags = ParseTags(template.Tags)
}; };
if (!existing.Any(r => room.Intersects(r, padding: 3))) if (!existing.Any(r => room.Intersects(r, padding: 3)))
@@ -402,7 +598,7 @@ public class DungeonGeneratorV2
int x = Math.Clamp(preferX - w / 2, 2, MapWidth - w - 2); int x = Math.Clamp(preferX - w / 2, 2, MapWidth - w - 2);
int y = Math.Clamp(preferY - h / 2, 2, MapHeight - h - 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<string>(StringComparer.OrdinalIgnoreCase) };
if (existing.Any(r => room.Intersects(r, padding: 3))) if (existing.Any(r => room.Intersects(r, padding: 3)))
{ {
@@ -411,7 +607,7 @@ public class DungeonGeneratorV2
{ {
x = _rng.Next(2, MapWidth - w - 2); x = _rng.Next(2, MapWidth - w - 2);
y = _rng.Next(2, MapHeight - h - 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<string>(StringComparer.OrdinalIgnoreCase) };
if (!existing.Any(r => room.Intersects(r, padding: 3))) if (!existing.Any(r => room.Intersects(r, padding: 3)))
break; break;
@@ -428,7 +624,7 @@ public class DungeonGeneratorV2
private void CarveBasicRoom(DungeonLayoutV2 layout, DungeonRoomV2 room) private void CarveBasicRoom(DungeonLayoutV2 layout, DungeonRoomV2 room)
{ {
// Find floor tile from default sheet // 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 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 x = room.X; x < room.X + room.Width; x++)
@@ -449,7 +645,8 @@ public class DungeonGeneratorV2
{ {
layout.TileDetails.Add(new PlacedTile layout.TileDetails.Add(new PlacedTile
{ {
X = x, Y = y, X = x,
Y = y,
TileDefinitionId = floorId, TileDefinitionId = floorId,
SheetId = floorTile.TileMapSheetId, SheetId = floorTile.TileMapSheetId,
FrameIndex = floorTile.FrameIndex, FrameIndex = floorTile.FrameIndex,
@@ -463,7 +660,16 @@ public class DungeonGeneratorV2
private async Task ConnectRoomsAsync(DungeonLayoutV2 layout, DungeonRoomV2 a, DungeonRoomV2 b) 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<string>(a.TemplateTags ?? new HashSet<string>(StringComparer.OrdinalIgnoreCase), StringComparer.OrdinalIgnoreCase);
requiredTags.IntersectWith(b.TemplateTags ?? new HashSet<string>(StringComparer.OrdinalIgnoreCase));
if (requiredTags.Count == 0)
{
requiredTags = new HashSet<string>(a.TemplateTags ?? new HashSet<string>(StringComparer.OrdinalIgnoreCase), StringComparer.OrdinalIgnoreCase);
requiredTags.UnionWith(b.TemplateTags ?? new HashSet<string>(StringComparer.OrdinalIgnoreCase));
}
var floorTile = SelectBestFloorTileForTags(requiredTags) ?? _tileDefinitions.Values.FirstOrDefault(t => t.Type == TileType.Floor);
int floorId = floorTile?.Id ?? 1; int floorId = floorTile?.Id ?? 1;
int sheetId = floorTile?.TileMapSheetId ?? 0; int sheetId = floorTile?.TileMapSheetId ?? 0;
int frameIndex = floorTile?.FrameIndex ?? 0; int frameIndex = floorTile?.FrameIndex ?? 0;
@@ -496,7 +702,7 @@ public class DungeonGeneratorV2
Console.WriteLine($" B wants {bDirection}, got cp: {(cpB != null ? $"({cpB.X},{cpB.Y}) dir={cpB.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 startX, startY, endX, endY;
int corridorWidth = 2; int corridorWidth = _rng.Next(MinCorridorWidth, MaxCorridorWidth + 1);
if (cpA != null) if (cpA != null)
{ {
@@ -533,13 +739,27 @@ public class DungeonGeneratorV2
// L-shaped corridor from connection point to connection point // L-shaped corridor from connection point to connection point
if (_rng.Next(2) == 0) if (_rng.Next(2) == 0)
{ {
CarveHorizontalCorridor(layout, startX, endX, startY, floorId, sheetId, frameIndex, corridorWidth); // Horizontal segment
CarveVerticalCorridor(layout, startY, endY, endX, floorId, sheetId, frameIndex, corridorWidth); 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 else
{ {
CarveVerticalCorridor(layout, startY, endY, startX, floorId, sheetId, frameIndex, corridorWidth); // Vertical segment
CarveHorizontalCorridor(layout, startX, endX, endY, floorId, sheetId, frameIndex, corridorWidth); 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);
} }
} }
@@ -601,7 +821,8 @@ public class DungeonGeneratorV2
{ {
layout.TileDetails.Add(new PlacedTile layout.TileDetails.Add(new PlacedTile
{ {
X = cx, Y = cy, X = cx,
Y = cy,
TileDefinitionId = floorId, TileDefinitionId = floorId,
SheetId = sheetId, SheetId = sheetId,
FrameIndex = frameIndex, FrameIndex = frameIndex,
@@ -628,8 +849,10 @@ public class DungeonGeneratorV2
for (int dy = 0; dy < width; dy++) for (int dy = 0; dy < width; dy++)
{ {
int ty = y + dy - width / 2; // Center the corridor 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; layout.Tiles[x, ty] = floorId;
// Set walkability for corridors // Set walkability for corridors
@@ -642,7 +865,8 @@ public class DungeonGeneratorV2
{ {
layout.TileDetails.Add(new PlacedTile layout.TileDetails.Add(new PlacedTile
{ {
X = x, Y = ty, X = x,
Y = ty,
TileDefinitionId = floorId, TileDefinitionId = floorId,
SheetId = sheetId, SheetId = sheetId,
FrameIndex = frameIndex, FrameIndex = frameIndex,
@@ -664,8 +888,10 @@ public class DungeonGeneratorV2
for (int dx = 0; dx < width; dx++) for (int dx = 0; dx < width; dx++)
{ {
int tx = x + dx - width / 2; // Center the corridor 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; layout.Tiles[tx, y] = floorId;
// Set walkability for corridors // Set walkability for corridors
@@ -678,7 +904,8 @@ public class DungeonGeneratorV2
{ {
layout.TileDetails.Add(new PlacedTile layout.TileDetails.Add(new PlacedTile
{ {
X = tx, Y = y, X = tx,
Y = y,
TileDefinitionId = floorId, TileDefinitionId = floorId,
SheetId = sheetId, SheetId = sheetId,
FrameIndex = frameIndex, FrameIndex = frameIndex,
@@ -787,7 +1014,8 @@ public class DungeonGeneratorV2
layout.TileDetails.Add(new PlacedTile layout.TileDetails.Add(new PlacedTile
{ {
X = x, Y = y, X = x,
Y = y,
TileDefinitionId = tile.Id, TileDefinitionId = tile.Id,
SheetId = tile.TileMapSheetId, SheetId = tile.TileMapSheetId,
FrameIndex = tile.FrameIndex, FrameIndex = tile.FrameIndex,
@@ -845,7 +1073,8 @@ public class DungeonGeneratorV2
layout.MobSpawns.Add(new DungeonMobSpawn layout.MobSpawns.Add(new DungeonMobSpawn
{ {
Id = layout.MobSpawns.Count + 1, Id = layout.MobSpawns.Count + 1,
X = x, Y = y, X = x,
Y = y,
MobType = room.Type == RoomType.Boss ? DungeonMobSpawnType.Boss : DungeonMobSpawnType.Normal, MobType = room.Type == RoomType.Boss ? DungeonMobSpawnType.Boss : DungeonMobSpawnType.Normal,
RoomIndex = rooms.IndexOf(room) RoomIndex = rooms.IndexOf(room)
}); });
@@ -867,7 +1096,8 @@ public class DungeonGeneratorV2
layout.ChestSpawns.Add(new DungeonChestSpawn layout.ChestSpawns.Add(new DungeonChestSpawn
{ {
Id = layout.ChestSpawns.Count + 1, Id = layout.ChestSpawns.Count + 1,
X = x, Y = y, X = x,
Y = y,
ChestType = room.Type == RoomType.Boss ? DungeonChestType.Boss : DungeonChestType.Normal, ChestType = room.Type == RoomType.Boss ? DungeonChestType.Boss : DungeonChestType.Normal,
RoomIndex = rooms.IndexOf(room) RoomIndex = rooms.IndexOf(room)
}); });
@@ -886,6 +1116,7 @@ public class DungeonRoomV2 : DungeonRoom
{ {
public int? TemplateId { get; set; } public int? TemplateId { get; set; }
public string? TemplateName { get; set; } public string? TemplateName { get; set; }
public HashSet<string> TemplateTags { get; set; } = new(StringComparer.OrdinalIgnoreCase);
public new RoomType Type { get; set; } = RoomType.Normal; public new RoomType Type { get; set; } = RoomType.Normal;
/// <summary>Connection points parsed from template</summary> /// <summary>Connection points parsed from template</summary>