Files
systemrevivalserver/Game/Dungeon/DungeonGeneratorVNext.cs
T
dingo b99d5fce7f Prioritize corner buckets over broad cardinal wall matches
- Defer cardinal-pass placement when an 8-direction corner/diagonal bucket match exists in the active palette

- Prevent corner cells from being flattened into top/side walls during first pass

- Keep two-pass flow intact: cardinal fallback first, unresolved cells resolved by 8-direction masks
2026-02-09 15:52:23 -05:00

927 lines
32 KiB
C#

using DataServer.Data;
using DataServer.Data.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Text.Json;
namespace GameServer.Dungeon;
/// <summary>
/// Dungeon Generator VNext (first-pass implementation):
/// - BSP room partitioning for macro structure
/// - Random-walk corridor carving (2-4 tile width)
/// - Tier-scaled size/room count and multi-boss support for tier 6+
/// </summary>
public class DungeonGeneratorVNext
{
private readonly GameDbContext _db;
private readonly int _seed;
private readonly int _tier;
private readonly Random _rng;
private readonly ILogger<DungeonGeneratorVNext>? _logger;
public DungeonGeneratorVNext(GameDbContext db, int seed, int tier = 1, ILogger<DungeonGeneratorVNext>? logger = null)
{
_db = db;
_seed = seed;
_tier = Math.Max(1, tier);
_rng = new Random(seed);
_logger = logger;
}
private readonly record struct PartitionRect(int X, int Y, int Width, int Height)
{
public int CenterX => X + Width / 2;
public int CenterY => Y + Height / 2;
}
public async Task<DungeonLayoutV2> GenerateAsync()
{
int size = 72 + (_tier * 8);
if (_tier >= 6) size += (_tier - 5) * 12;
int mapWidth = Math.Clamp(size, 64, 220);
int mapHeight = Math.Clamp(size, 64, 220);
int targetRooms = 10 + (_tier * 2);
if (_tier >= 6) targetRooms += _tier;
targetRooms = Math.Clamp(targetRooms, 12, 80);
int minExpectedRooms = Math.Max(8, targetRooms / 2);
var layout = new DungeonLayoutV2(mapWidth, mapHeight)
{
Seed = _seed,
Tier = _tier,
TileSize = 32
};
for (int x = 0; x < mapWidth; x++)
{
for (int y = 0; y < mapHeight; y++)
{
layout.Tiles[x, y] = 0;
layout.Walkable![x, y] = false;
}
}
var rooms = GenerateRooms(mapWidth, mapHeight, targetRooms);
if (rooms.Count < minExpectedRooms)
{
rooms = GenerateFallbackRooms(mapWidth, mapHeight, targetRooms);
}
foreach (var room in rooms)
{
CarveRoom(layout, room);
}
ConnectRoomsWithRandomWalk(layout, rooms);
AddLoopConnections(layout, rooms, Math.Max(2, rooms.Count / 4));
AssignRoomTypes(rooms);
GenerateSpawnsAndChests(layout, rooms);
await BuildPaletteDrivenTileDetailsAsync(layout);
layout.Rooms = rooms;
var entrance = rooms.FirstOrDefault(r => r.Type == DungeonRoomType.Entrance) ?? rooms[0];
layout.SpawnPoint = new DungeonPoint(entrance.CenterX, entrance.CenterY);
layout.PlayerSpawnX = entrance.CenterX;
layout.PlayerSpawnY = entrance.CenterY;
layout.TotalMobs = layout.MobSpawns.Count;
layout.TotalChests = layout.ChestSpawns.Count;
_logger?.LogInformation(
"VNext generated seed {Seed}, tier {Tier}: {Width}x{Height}, rooms={RoomCount}, mobs={MobCount}, chests={ChestCount}, bosses={BossCount}",
_seed,
_tier,
mapWidth,
mapHeight,
rooms.Count,
layout.TotalMobs,
layout.TotalChests,
layout.MobSpawns.Count(m => m.MobType == DungeonMobSpawnType.Boss));
return layout;
}
private List<DungeonRoom> GenerateRooms(int mapWidth, int mapHeight, int targetRooms)
{
var leaves = new List<PartitionRect> { new(2, 2, mapWidth - 4, mapHeight - 4) };
int minLeafSize = 16;
int splitGuard = 0;
while (leaves.Count < targetRooms * 2 && splitGuard++ < 4000)
{
int index = _rng.Next(leaves.Count);
var leaf = leaves[index];
bool splitVertical = leaf.Width > leaf.Height;
if (_rng.NextDouble() < 0.35) splitVertical = !splitVertical;
if (splitVertical)
{
if (leaf.Width < minLeafSize * 2) continue;
int splitX = _rng.Next(leaf.X + minLeafSize, leaf.X + leaf.Width - minLeafSize);
var left = new PartitionRect(leaf.X, leaf.Y, splitX - leaf.X, leaf.Height);
var right = new PartitionRect(splitX, leaf.Y, leaf.X + leaf.Width - splitX, leaf.Height);
leaves[index] = left;
leaves.Add(right);
}
else
{
if (leaf.Height < minLeafSize * 2) continue;
int splitY = _rng.Next(leaf.Y + minLeafSize, leaf.Y + leaf.Height - minLeafSize);
var top = new PartitionRect(leaf.X, leaf.Y, leaf.Width, splitY - leaf.Y);
var bottom = new PartitionRect(leaf.X, splitY, leaf.Width, leaf.Y + leaf.Height - splitY);
leaves[index] = top;
leaves.Add(bottom);
}
}
var rooms = new List<DungeonRoom>();
int minRoom = 8;
int maxRoom = 20;
foreach (var leaf in leaves.OrderBy(_ => _rng.Next()))
{
if (rooms.Count >= targetRooms) break;
int margin = 2;
int maxW = Math.Max(minRoom, leaf.Width - margin * 2);
int maxH = Math.Max(minRoom, leaf.Height - margin * 2);
if (maxW < minRoom || maxH < minRoom) continue;
int width = _rng.Next(minRoom, Math.Min(maxRoom, maxW) + 1);
int height = _rng.Next(minRoom, Math.Min(maxRoom, maxH) + 1);
int x = _rng.Next(leaf.X + 1, leaf.X + leaf.Width - width);
int y = _rng.Next(leaf.Y + 1, leaf.Y + leaf.Height - height);
var room = new DungeonRoom(x, y, width, height);
if (rooms.Any(r => room.Intersects(r, 1))) continue;
rooms.Add(room);
}
return rooms
.OrderBy(r => r.X + r.Y)
.ToList();
}
private List<DungeonRoom> GenerateFallbackRooms(int mapWidth, int mapHeight, int desiredCount)
{
var rooms = new List<DungeonRoom>();
int count = Math.Clamp(desiredCount, 12, 80);
int attempts = 0;
while (rooms.Count < count && attempts++ < count * 60)
{
int maxRoom = Math.Min(24, 10 + _tier);
int width = _rng.Next(8, maxRoom + 1);
int height = _rng.Next(8, maxRoom + 1);
if (width >= mapWidth - 4 || height >= mapHeight - 4) continue;
int x = _rng.Next(2, mapWidth - width - 2);
int y = _rng.Next(2, mapHeight - height - 2);
var room = new DungeonRoom(x, y, width, height);
if (rooms.Any(r => room.Intersects(r, 2))) continue;
rooms.Add(room);
}
return rooms.OrderBy(r => r.X + r.Y).ToList();
}
private void CarveRoom(DungeonLayoutV2 layout, DungeonRoom room)
{
for (int x = room.X; x < room.X + room.Width; x++)
{
for (int y = room.Y; y < room.Y + room.Height; y++)
{
SetFloor(layout, x, y);
}
}
}
private void ConnectRoomsWithRandomWalk(DungeonLayoutV2 layout, List<DungeonRoom> rooms)
{
if (rooms.Count < 2) return;
var connected = new List<DungeonRoom> { rooms[0] };
var unconnected = new HashSet<DungeonRoom>(rooms.Skip(1));
while (unconnected.Count > 0)
{
DungeonRoom? bestFrom = null;
DungeonRoom? bestTo = null;
float bestDist = float.MaxValue;
foreach (var from in connected)
{
foreach (var to in unconnected)
{
float dist = Distance(from.CenterX, from.CenterY, to.CenterX, to.CenterY);
if (dist < bestDist)
{
bestDist = dist;
bestFrom = from;
bestTo = to;
}
}
}
if (bestFrom == null || bestTo == null) break;
int width = _rng.Next(2, 5);
CarveRandomWalkCorridor(layout, bestFrom.CenterX, bestFrom.CenterY, bestTo.CenterX, bestTo.CenterY, width);
connected.Add(bestTo);
unconnected.Remove(bestTo);
}
}
private void AddLoopConnections(DungeonLayoutV2 layout, List<DungeonRoom> rooms, int loopCount)
{
if (rooms.Count < 3) return;
for (int i = 0; i < loopCount; i++)
{
var a = rooms[_rng.Next(rooms.Count)];
var b = rooms[_rng.Next(rooms.Count)];
if (ReferenceEquals(a, b)) continue;
int width = _rng.Next(2, 5);
CarveRandomWalkCorridor(layout, a.CenterX, a.CenterY, b.CenterX, b.CenterY, width);
}
}
private void CarveRandomWalkCorridor(DungeonLayoutV2 layout, int startX, int startY, int endX, int endY, int width)
{
int x = startX;
int y = startY;
int guard = layout.Width * layout.Height * 2;
while ((x != endX || y != endY) && guard-- > 0)
{
CarveBrush(layout, x, y, width);
int dx = Math.Sign(endX - x);
int dy = Math.Sign(endY - y);
int stepX = 0;
int stepY = 0;
if (_rng.NextDouble() < 0.7)
{
if (Math.Abs(endX - x) >= Math.Abs(endY - y))
stepX = dx;
else
stepY = dy;
}
else
{
int roll = _rng.Next(4);
if (roll == 0) stepX = 1;
if (roll == 1) stepX = -1;
if (roll == 2) stepY = 1;
if (roll == 3) stepY = -1;
}
if (stepX == 0 && stepY == 0)
{
if (dx != 0) stepX = dx;
else if (dy != 0) stepY = dy;
}
x = Math.Clamp(x + stepX, 1, layout.Width - 2);
y = Math.Clamp(y + stepY, 1, layout.Height - 2);
}
CarveBrush(layout, endX, endY, width);
}
private void CarveBrush(DungeonLayoutV2 layout, int cx, int cy, int width)
{
int half = width / 2;
for (int x = cx - half; x <= cx + half; x++)
{
for (int y = cy - half; y <= cy + half; y++)
{
SetFloor(layout, x, y);
}
}
}
private void SetFloor(DungeonLayoutV2 layout, int x, int y)
{
if (x < 1 || y < 1 || x >= layout.Width - 1 || y >= layout.Height - 1) return;
layout.Tiles[x, y] = 1;
layout.Walkable![x, y] = true;
}
private void AssignRoomTypes(List<DungeonRoom> rooms)
{
if (rooms.Count == 0) return;
int entranceIndex = rooms
.Select((r, i) => (idx: i, score: r.X + r.Y))
.OrderBy(p => p.score)
.Select(p => p.idx)
.First();
rooms[entranceIndex].Type = DungeonRoomType.Entrance;
int bossCount = GetRequiredBossCount();
var candidates = rooms
.Select((r, i) => (room: r, idx: i))
.Where(p => p.idx != entranceIndex)
.OrderByDescending(p => Distance(rooms[entranceIndex].CenterX, rooms[entranceIndex].CenterY, p.room.CenterX, p.room.CenterY))
.ToList();
if (candidates.Count == 0)
{
rooms[entranceIndex].Type = DungeonRoomType.Boss;
return;
}
foreach (var room in rooms.Where(r => r.Type != DungeonRoomType.Entrance))
{
room.Type = DungeonRoomType.Combat;
}
for (int i = 0; i < Math.Min(bossCount, candidates.Count); i++)
{
candidates[i].room.Type = DungeonRoomType.Boss;
}
int treasureCount = Math.Max(1, rooms.Count / 8);
var treasureCandidates = rooms
.Where(r => r.Type == DungeonRoomType.Combat)
.OrderBy(_ => _rng.Next())
.Take(treasureCount);
foreach (var room in treasureCandidates)
{
room.Type = DungeonRoomType.Treasure;
}
}
private void GenerateSpawnsAndChests(DungeonLayoutV2 layout, List<DungeonRoom> rooms)
{
layout.MobSpawns.Clear();
layout.ChestSpawns.Clear();
int mobId = 1;
int chestId = 1;
for (int i = 0; i < rooms.Count; i++)
{
var room = rooms[i];
if (room.Type == DungeonRoomType.Entrance) continue;
int mobCount = room.Type switch
{
DungeonRoomType.Boss => 1,
DungeonRoomType.Treasure => _rng.Next(1, 3),
_ => _rng.Next(2, 5 + Math.Max(0, _tier / 2))
};
for (int m = 0; m < mobCount; m++)
{
var pos = RandomPointInRoom(room);
layout.MobSpawns.Add(new DungeonMobSpawn
{
Id = mobId++,
X = pos.x,
Y = pos.y,
MobType = room.Type == DungeonRoomType.Boss ? DungeonMobSpawnType.Boss : DungeonMobSpawnType.Normal,
RoomIndex = i
});
}
int chestCount = room.Type switch
{
DungeonRoomType.Boss => 1,
DungeonRoomType.Treasure => _rng.Next(1, 3),
_ => _rng.NextDouble() < 0.25 ? 1 : 0
};
for (int c = 0; c < chestCount; c++)
{
var pos = RandomPointInRoom(room);
layout.ChestSpawns.Add(new DungeonChestSpawn
{
Id = chestId++,
X = pos.x,
Y = pos.y,
ChestType = room.Type == DungeonRoomType.Boss ? DungeonChestType.Boss : DungeonChestType.Normal,
RoomIndex = i
});
}
}
int requiredBossCount = Math.Min(GetRequiredBossCount(), Math.Max(1, rooms.Count - 1));
int bossSpawnCount = layout.MobSpawns.Count(m => m.MobType == DungeonMobSpawnType.Boss);
if (bossSpawnCount < requiredBossCount && rooms.Count > 1)
{
var entranceRoom = rooms.FirstOrDefault(r => r.Type == DungeonRoomType.Entrance) ?? rooms[0];
var candidateRooms = rooms
.Select((room, idx) => (room, idx))
.Where(p => p.room.Type != DungeonRoomType.Entrance)
.OrderByDescending(p => Distance(entranceRoom.CenterX, entranceRoom.CenterY, p.room.CenterX, p.room.CenterY))
.ToList();
foreach (var candidate in candidateRooms)
{
if (bossSpawnCount >= requiredBossCount) break;
bool roomAlreadyHasBoss = layout.MobSpawns.Any(m => m.RoomIndex == candidate.idx && m.MobType == DungeonMobSpawnType.Boss);
if (roomAlreadyHasBoss) continue;
var pos = RandomPointInRoom(candidate.room);
layout.MobSpawns.Add(new DungeonMobSpawn
{
Id = mobId++,
X = pos.x,
Y = pos.y,
MobType = DungeonMobSpawnType.Boss,
RoomIndex = candidate.idx
});
candidate.room.Type = DungeonRoomType.Boss;
bossSpawnCount++;
}
}
if (bossSpawnCount == 0 && rooms.Count > 0)
{
int fallbackRoomIndex = rooms.FindIndex(r => r.Type != DungeonRoomType.Entrance);
if (fallbackRoomIndex < 0) fallbackRoomIndex = 0;
var pos = RandomPointInRoom(rooms[fallbackRoomIndex]);
layout.MobSpawns.Add(new DungeonMobSpawn
{
Id = mobId,
X = pos.x,
Y = pos.y,
MobType = DungeonMobSpawnType.Boss,
RoomIndex = fallbackRoomIndex
});
rooms[fallbackRoomIndex].Type = DungeonRoomType.Boss;
}
}
private int GetRequiredBossCount()
{
if (_tier < 6) return 1;
return Math.Clamp(1 + (_tier / 4), 2, 4);
}
private (int x, int y) RandomPointInRoom(DungeonRoom room)
{
int x = _rng.Next(room.X + 1, room.X + room.Width - 1);
int y = _rng.Next(room.Y + 1, room.Y + room.Height - 1);
return (x, y);
}
private async Task BuildPaletteDrivenTileDetailsAsync(DungeonLayoutV2 layout)
{
layout.TileDetails.Clear();
layout.TileMapSheets.Clear();
var tileContext = await BuildTileContextAsync();
if (tileContext.FloorCandidates.Count == 0 && tileContext.WallCandidates.Count == 0)
{
_logger?.LogWarning("VNext tile context had no palette candidates; using fallback tile placeholders.");
BuildFallbackTileDetails(layout);
return;
}
var usedSheetIds = new HashSet<int>();
for (int y = 0; y < layout.Height; y++)
{
for (int x = 0; x < layout.Width; x++)
{
if (!layout.Walkable![x, y]) continue;
var floorDef = SelectFloorDefinition(tileContext);
if (floorDef == null) continue;
layout.Tiles[x, y] = floorDef.Id;
usedSheetIds.Add(floorDef.TileMapSheetId);
layout.TileDetails.Add(new PlacedTile
{
X = x,
Y = y,
TileDefinitionId = floorDef.Id,
SheetId = floorDef.TileMapSheetId,
FrameIndex = floorDef.FrameIndex,
Layer = floorDef.RenderLayer,
Rotation = 0,
FlipX = false,
FlipY = false
});
}
}
var wallCells = new List<(int X, int Y)>();
for (int y = 0; y < layout.Height; y++)
{
for (int x = 0; x < layout.Width; x++)
{
if (layout.Walkable![x, y]) continue;
if (!HasAdjacentWalkable(layout, x, y)) continue;
wallCells.Add((x, y));
}
}
var unresolved = new List<(int X, int Y)>();
// Pass 1: cardinal-direction masks first.
foreach (var cell in wallCells)
{
int mask4 = ComputeCardinalMask(layout, cell.X, cell.Y);
string? bucketName = ResolveCardinalBucketName(mask4);
if (string.IsNullOrEmpty(bucketName))
{
unresolved.Add(cell);
continue;
}
// If this cell has a specific 8-direction corner/diagonal match that exists in the
// current palette, defer to pass 2 so corners do not get flattened by broad cardinal buckets.
int mask8 = ComputeEightDirectionMask(layout, cell.X, cell.Y);
string? specific8Bucket = ResolveEightDirectionBucketName(mask8);
if (!string.IsNullOrEmpty(specific8Bucket) &&
tileContext.WallDefinitionsByCanonicalBucket.TryGetValue(specific8Bucket, out var defs8) &&
defs8.Count > 0)
{
unresolved.Add(cell);
continue;
}
var wallDef = SelectWallDefinitionForBucket(tileContext, bucketName);
if (wallDef == null)
{
unresolved.Add(cell);
continue;
}
PlaceWallTile(layout, cell.X, cell.Y, wallDef);
usedSheetIds.Add(wallDef.TileMapSheetId);
}
// Pass 2: only fill unresolved cells with 8-direction masks.
foreach (var cell in unresolved)
{
int mask8 = ComputeEightDirectionMask(layout, cell.X, cell.Y);
string? bucketName = ResolveEightDirectionBucketName(mask8);
var wallDef = !string.IsNullOrEmpty(bucketName)
? SelectWallDefinitionForBucket(tileContext, bucketName)
: null;
wallDef ??= SelectFallbackWallDefinition(tileContext);
if (wallDef == null) continue;
PlaceWallTile(layout, cell.X, cell.Y, wallDef);
usedSheetIds.Add(wallDef.TileMapSheetId);
}
foreach (int sheetId in usedSheetIds)
{
if (!tileContext.SheetsById.TryGetValue(sheetId, out var sheet)) continue;
layout.TileMapSheets.Add(new TileMapSheetInfo
{
Id = sheet.Id,
CdnPath = sheet.CdnPath,
TileWidth = sheet.TileWidth,
TileHeight = sheet.TileHeight,
SheetWidth = sheet.SheetWidth,
SheetHeight = sheet.SheetHeight,
Columns = sheet.Columns,
Rows = sheet.Rows
});
}
}
private void BuildFallbackTileDetails(DungeonLayoutV2 layout)
{
for (int y = 0; y < layout.Height; y++)
{
for (int x = 0; x < layout.Width; x++)
{
if (!layout.Walkable![x, y]) continue;
layout.TileDetails.Add(new PlacedTile
{
X = x,
Y = y,
TileDefinitionId = 0,
SheetId = 0,
FrameIndex = 0,
Layer = 0,
Rotation = 0,
FlipX = false,
FlipY = false
});
}
}
}
private async Task<TileBuildContext> BuildTileContextAsync()
{
var sheets = await _db.TileMapSheets
.Where(s => s.IsEnabled)
.ToListAsync();
var sheetsById = sheets.ToDictionary(s => s.Id);
var palette = await SelectPaletteAsync();
var allowedBucketIds = ParseIds(palette?.AllowedBucketIdsJson).ToHashSet();
var allTiles = await _db.TileDefinitions
.Where(t => t.IsEnabled)
.ToListAsync();
var links = await _db.TileDefinitionBuckets.ToListAsync();
var tileBuckets = new Dictionary<int, HashSet<int>>();
foreach (var link in links)
{
if (!tileBuckets.TryGetValue(link.TileDefinitionId, out var set))
{
set = new HashSet<int>();
tileBuckets[link.TileDefinitionId] = set;
}
set.Add(link.TileBucketId);
}
var buckets = await _db.TileBuckets
.Where(b => b.IsEnabled)
.ToListAsync();
var bucketNamesById = buckets.ToDictionary(b => b.Id, b => b.Name);
var bucketIdsByName = buckets
.GroupBy(b => b.Name.Trim().ToLowerInvariant())
.ToDictionary(g => g.Key, g => g.First().Id);
bool TileAllowedByPalette(TileDefinition t)
{
if (allowedBucketIds.Count == 0) return true;
if (!tileBuckets.TryGetValue(t.Id, out var ids) || ids.Count == 0) return false;
return ids.Overlaps(allowedBucketIds);
}
var floorCandidates = allTiles
.Where(t => t.IsWalkable && t.Type != TileType.Wall && t.Type != TileType.WallDecor)
.Where(TileAllowedByPalette)
.ToList();
var wallCandidates = allTiles
.Where(t => !t.IsWalkable || t.Type == TileType.Wall || t.Type == TileType.WallDecor)
.Where(TileAllowedByPalette)
.ToList();
var canonicalWallBucketIds = ResolveCanonicalWallBucketIds(bucketIdsByName, allowedBucketIds);
var wallDefsByCanonicalBucket = new Dictionary<string, List<TileDefinition>>(StringComparer.OrdinalIgnoreCase);
foreach (var wallDef in wallCandidates)
{
if (!tileBuckets.TryGetValue(wallDef.Id, out var defBuckets) || defBuckets.Count == 0) continue;
var canonicalMatches = new List<string>();
foreach (var kvp in canonicalWallBucketIds)
{
if (defBuckets.Contains(kvp.Value))
{
canonicalMatches.Add(kvp.Key);
}
}
// Enforce "wall tiles belong to one wall bucket" for placement selection.
if (canonicalMatches.Count != 1) continue;
string canonical = canonicalMatches[0];
if (!wallDefsByCanonicalBucket.TryGetValue(canonical, out var defs))
{
defs = new List<TileDefinition>();
wallDefsByCanonicalBucket[canonical] = defs;
}
defs.Add(wallDef);
}
_logger?.LogInformation(
"VNext tile context: palette={PaletteId}, allowedBuckets={AllowedBuckets}, floorDefs={FloorDefs}, wallDefs={WallDefs}, resolvedWallBuckets={ResolvedBuckets}",
palette?.Id ?? 0,
allowedBucketIds.Count,
floorCandidates.Count,
wallCandidates.Count,
wallDefsByCanonicalBucket.Count);
return new TileBuildContext(
sheetsById,
floorCandidates,
wallCandidates,
wallDefsByCanonicalBucket,
bucketNamesById);
}
private async Task<DungeonPalette?> SelectPaletteAsync()
{
var palettes = await _db.DungeonPalettes
.Where(p => p.IsEnabled)
.OrderBy(p => p.Id)
.ToListAsync();
if (palettes.Count == 0) return null;
return palettes[_rng.Next(palettes.Count)];
}
private static List<int> ParseIds(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return new List<int>();
try
{
return JsonSerializer.Deserialize<List<int>>(json) ?? new List<int>();
}
catch
{
return new List<int>();
}
}
private static Dictionary<string, int> ResolveCanonicalWallBucketIds(
Dictionary<string, int> bucketIdsByName,
HashSet<int> allowedBucketIds)
{
var resolved = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
foreach (var alias in WallBucketAliases)
{
foreach (var name in alias.Value)
{
if (!bucketIdsByName.TryGetValue(name, out int id)) continue;
if (allowedBucketIds.Count > 0 && !allowedBucketIds.Contains(id)) continue;
resolved[alias.Key] = id;
break;
}
}
return resolved;
}
private TileDefinition? SelectFloorDefinition(TileBuildContext context)
{
if (context.FloorCandidates.Count == 0) return null;
return context.FloorCandidates[_rng.Next(context.FloorCandidates.Count)];
}
private TileDefinition? SelectWallDefinitionForBucket(TileBuildContext context, string canonicalBucketName)
{
if (!context.WallDefinitionsByCanonicalBucket.TryGetValue(canonicalBucketName, out var defs) || defs.Count == 0)
{
return null;
}
return defs[_rng.Next(defs.Count)];
}
private TileDefinition? SelectFallbackWallDefinition(TileBuildContext context)
{
if (context.WallCandidates.Count == 0) return null;
return context.WallCandidates[_rng.Next(context.WallCandidates.Count)];
}
private static void PlaceWallTile(DungeonLayoutV2 layout, int x, int y, TileDefinition def)
{
layout.Tiles[x, y] = def.Id;
layout.TileDetails.Add(new PlacedTile
{
X = x,
Y = y,
TileDefinitionId = def.Id,
SheetId = def.TileMapSheetId,
FrameIndex = def.FrameIndex,
Layer = def.RenderLayer,
Rotation = 0,
FlipX = false,
FlipY = false
});
}
private static bool HasAdjacentWalkable(DungeonLayoutV2 layout, int x, int y)
{
for (int oy = -1; oy <= 1; oy++)
{
for (int ox = -1; ox <= 1; ox++)
{
if (ox == 0 && oy == 0) continue;
int nx = x + ox;
int ny = y + oy;
if (nx < 0 || ny < 0 || nx >= layout.Width || ny >= layout.Height) continue;
if (layout.Walkable![nx, ny]) return true;
}
}
return false;
}
private static int ComputeCardinalMask(DungeonLayoutV2 layout, int x, int y)
{
// Bit order N, E, S, W (MSB -> LSB).
int n = IsWalkable(layout, x, y - 1) ? 1 : 0;
int e = IsWalkable(layout, x + 1, y) ? 1 : 0;
int s = IsWalkable(layout, x, y + 1) ? 1 : 0;
int w = IsWalkable(layout, x - 1, y) ? 1 : 0;
return (n << 3) | (e << 2) | (s << 1) | w;
}
private static int ComputeEightDirectionMask(DungeonLayoutV2 layout, int x, int y)
{
// Bit order N, NE, E, SE, S, SW, W, NW (MSB -> LSB).
int n = IsWalkable(layout, x, y - 1) ? 1 : 0;
int ne = IsWalkable(layout, x + 1, y - 1) ? 1 : 0;
int e = IsWalkable(layout, x + 1, y) ? 1 : 0;
int se = IsWalkable(layout, x + 1, y + 1) ? 1 : 0;
int s = IsWalkable(layout, x, y + 1) ? 1 : 0;
int sw = IsWalkable(layout, x - 1, y + 1) ? 1 : 0;
int w = IsWalkable(layout, x - 1, y) ? 1 : 0;
int nw = IsWalkable(layout, x - 1, y - 1) ? 1 : 0;
return (n << 7) | (ne << 6) | (e << 5) | (se << 4) | (s << 3) | (sw << 2) | (w << 1) | nw;
}
private static bool IsWalkable(DungeonLayoutV2 layout, int x, int y)
{
if (x < 0 || y < 0 || x >= layout.Width || y >= layout.Height) return false;
return layout.Walkable![x, y];
}
private static string? ResolveCardinalBucketName(int mask4)
{
foreach (var mapping in CardinalBucketMasks)
{
if (mapping.Value.Contains(mask4))
{
return mapping.Key;
}
}
return null;
}
private static string? ResolveEightDirectionBucketName(int mask8)
{
foreach (var mapping in EightDirectionBucketMasks)
{
if (mapping.Value.Contains(mask8))
{
return mapping.Key;
}
}
return null;
}
private sealed record TileBuildContext(
Dictionary<int, TileMapSheet> SheetsById,
List<TileDefinition> FloorCandidates,
List<TileDefinition> WallCandidates,
Dictionary<string, List<TileDefinition>> WallDefinitionsByCanonicalBucket,
Dictionary<int, string> BucketNamesById);
private static readonly Dictionary<string, string[]> WallBucketAliases = new(StringComparer.OrdinalIgnoreCase)
{
["WallTop"] = new[] { "walltop" },
["WallSideLeft"] = new[] { "wallsideleft" },
["WallSideRight"] = new[] { "wallsideright" },
["WallBottom"] = new[] { "wallbottom", "wallbottm" },
["WallInnerCornerDownLeft"] = new[] { "wallinnercornerdownleft" },
["WallInnerCornerDownRight"] = new[] { "wallinnercornerdownright" },
["WallDiagonalCornerDownLeft"] = new[] { "walldiagonalcornerdownleft" },
["WallDiagonalCornerDownRight"] = new[] { "walldiagonalcornerdownright" },
["WallDiagonalCornerUpLeft"] = new[] { "walldiagonalcornerupleft" },
["WallDiagonalCornerUpRight"] = new[] { "walldiagonalcornerupright" },
["WallFull"] = new[] { "wallfull" },
["WallFullEightDirections"] = new[] { "wallfulleightdirections" },
["WallBottomEightDirections"] = new[] { "wallbottmeightdirections", "wallbottomeightdirections" }
};
private static readonly KeyValuePair<string, HashSet<int>>[] CardinalBucketMasks =
{
new("WallTop", new HashSet<int> { 15, 6, 3, 2, 10, 12, 14, 11, 7 }),
new("WallSideLeft", new HashSet<int> { 4 }),
new("WallSideRight", new HashSet<int> { 1 }),
new("WallBottom", new HashSet<int> { 8 }),
new("WallFull", new HashSet<int> { 13, 5, 9 })
};
private static readonly KeyValuePair<string, HashSet<int>>[] EightDirectionBucketMasks =
{
new("WallInnerCornerDownLeft", new HashSet<int> { 241, 224, 240, 225, 160, 81, 209, 97, 208, 113, 17, 177, 161, 144, 49, 176, 33, 145 }),
new("WallInnerCornerDownRight", new HashSet<int> { 199, 195, 131, 135, 130, 69, 197, 67, 133, 71, 68, 198, 194, 132, 70, 134, 196, 66 }),
new("WallDiagonalCornerDownLeft", new HashSet<int> { 64 }),
new("WallDiagonalCornerDownRight", new HashSet<int> { 1 }),
new("WallDiagonalCornerUpLeft", new HashSet<int> { 16, 80 }),
new("WallDiagonalCornerUpRight", new HashSet<int> { 4, 5 }),
new("WallBottomEightDirections", new HashSet<int> { 65 }),
new("WallFullEightDirections", new HashSet<int> { 20, 228, 147, 116, 23, 22, 52, 21, 84, 18, 36, 19, 100, 151, 244, 150, 180, 229, 211, 245, 215, 117, 87, 101, 83, 82, 37, 53, 86, 213, 212, 149 })
};
private static float Distance(int x1, int y1, int x2, int y2)
{
int dx = x2 - x1;
int dy = y2 - y1;
return MathF.Sqrt(dx * dx + dy * dy);
}
}