Dungeon Builder Changes

This commit is contained in:
dingo
2026-01-09 07:35:24 -05:00
parent e803dafaea
commit fd4d31e5e6
+301 -19
View File
@@ -26,6 +26,12 @@ public class DungeonGeneratorV3
/// </summary>
public static bool LogEveryTile { get; set; } = true;
/// <summary>
/// Enable socket-based tile matching. When true, tiles are selected based on
/// compatibility with neighboring tiles' sockets.
/// </summary>
public static bool UseSocketMatching { get; set; } = true;
// ============================================================
// DEPENDENCIES
// ============================================================
@@ -46,6 +52,22 @@ public class DungeonGeneratorV3
PropertyNameCaseInsensitive = true
};
// ============================================================
// SOCKET MATCHING DATA
// ============================================================
/// <summary>
/// Cache of parsed socket configurations for each TileTemplate.
/// Key = TileTemplate.Id, Value = parsed SocketConfiguration
/// </summary>
private Dictionary<int, SocketConfiguration> _templateSocketConfigs = new();
/// <summary>
/// Track which template was placed at each position for socket matching.
/// Key = "x,y", Value = TileTemplate.Id
/// </summary>
private Dictionary<string, int> _placedTemplates = new();
// ============================================================
// PALETTE & TEMPLATES
// ============================================================
@@ -367,6 +389,7 @@ public class DungeonGeneratorV3
CategorizeRoomTemplates();
LogTemplateStats();
ParseSocketConfigurations();
}
private async Task LoadAllTemplatesAsync()
@@ -408,6 +431,7 @@ public class DungeonGeneratorV3
CategorizeRoomTemplates();
LogTemplateStats();
ParseSocketConfigurations();
}
private void CategorizeRoomTemplates()
@@ -1176,13 +1200,17 @@ public class DungeonGeneratorV3
/// Fill all walkable cells with floor tiles.
///
/// For each walkable cell without a tile:
/// 1. Call SelectFloorTile to get appropriate tile
/// 1. Call SelectFloorTile to get appropriate tile (with socket matching)
/// 2. Set layout.Tiles and add to TileDetails
/// </summary>
private void FillFloorTiles(DungeonLayoutV2 layout)
{
Log($"--- Filling Floor Tiles ---");
Log($"Floor templates available: {_floorTemplates.Count}");
Log($"Socket matching: {(UseSocketMatching ? "ENABLED" : "DISABLED")}");
// Clear placement tracking for socket matching
_placedTemplates.Clear();
// Log detailed template info for debugging
foreach (var t in _floorTemplates)
@@ -1201,7 +1229,7 @@ public class DungeonGeneratorV3
// Only fill walkable cells that don't have tiles yet
if (layout.Walkable[x, y] && layout.Tiles[x, y] == 0)
{
var tile = SelectFloorTile(x, y, out bool usedFallback);
var tile = SelectFloorTile(x, y, layout, out bool usedFallback);
if (tile != null)
{
if (firstSelectedTile == null)
@@ -1238,27 +1266,29 @@ public class DungeonGeneratorV3
/// <summary>
/// Select a floor tile for the given position.
///
/// SELECTION PROCESS:
/// SELECTION PROCESS (with socket matching):
/// 1. If _floorTemplates has templates:
/// a. Select one via weighted random (higher Weight = more likely)
/// b. Try template.PrimaryTileDefinitionId first - if set, look up that TileDefinition
/// c. If no PrimaryTileDefinitionId, parse template.TilesJson
/// d. TilesJson format: [{"x":0,"y":0,"sheetId":3,"frameIndex":273}]
/// e. Take first tile's sheetId and frameIndex
/// f. Search _tileDefinitions for match: TileMapSheetId==sheetId AND FrameIndex==frameIndex
/// a. Filter to socket-compatible templates (if UseSocketMatching)
/// b. Select one via weighted random from compatible list
/// c. Try template.PrimaryTileDefinitionId first
/// d. If no PrimaryTileDefinitionId, parse template.TilesJson
/// e. Track placed template for future socket matching
/// 2. FALLBACK: Return first walkable TileDefinition (ordered by ID)
/// </summary>
private TileDefinition? SelectFloorTile(int x, int y, out bool usedFallback)
private TileDefinition? SelectFloorTile(int x, int y, DungeonLayoutV2 layout, out bool usedFallback)
{
usedFallback = false;
// First try to use floor templates
if (_floorTemplates.Count > 0)
{
var template = SelectWeightedTemplate(_floorTemplates);
// Get socket-compatible templates
var compatibleTemplates = GetCompatibleTemplates(_floorTemplates, x, y, layout);
var template = SelectWeightedTemplate(compatibleTemplates);
if (template != null)
{
LogVerbose($"SelectFloorTile({x},{y}): Template '{template.Name}' (ID={template.Id})");
LogVerbose($"SelectFloorTile({x},{y}): Template '{template.Name}' (ID={template.Id}) [Compatible: {compatibleTemplates.Count}/{_floorTemplates.Count}]");
// Method 1: Try PrimaryTileDefinitionId first
if (template.PrimaryTileDefinitionId.HasValue)
@@ -1269,6 +1299,10 @@ public class DungeonGeneratorV3
if (!UsedFloorTemplates.Contains(template.Name))
UsedFloorTemplates.Add(template.Name);
LogVerbose($" -> Found TileDef {tileDef.Id} '{tileDef.Name}'");
// Track placement for socket matching
_placedTemplates[$"{x},{y}"] = template.Id;
return tileDef;
}
LogVerbose($" -> NOT FOUND in _tileDefinitions!");
@@ -1302,6 +1336,10 @@ public class DungeonGeneratorV3
if (!UsedFloorTemplates.Contains(template.Name))
UsedFloorTemplates.Add(template.Name);
LogVerbose($" -> Match: TileDef {match.Id} '{match.Name}'");
// Track placement for socket matching
_placedTemplates[$"{x},{y}"] = template.Id;
return match;
}
else
@@ -1340,6 +1378,55 @@ public class DungeonGeneratorV3
return _tileDefinitions.Values.FirstOrDefault();
}
// Overload for backward compatibility (without layout parameter)
private TileDefinition? SelectFloorTile(int x, int y, out bool usedFallback)
{
// Create a minimal layout for compatibility
usedFallback = false;
if (_floorTemplates.Count > 0)
{
var template = SelectWeightedTemplate(_floorTemplates);
if (template != null)
{
if (template.PrimaryTileDefinitionId.HasValue)
{
if (_tileDefinitions.TryGetValue(template.PrimaryTileDefinitionId.Value, out var tileDef))
{
if (!UsedFloorTemplates.Contains(template.Name))
UsedFloorTemplates.Add(template.Name);
return tileDef;
}
}
if (!string.IsNullOrEmpty(template.TilesJson))
{
try
{
var tiles = JsonSerializer.Deserialize<List<TemplateTilePlacement>>(template.TilesJson, _jsonOptions);
if (tiles?.Count > 0)
{
var first = tiles[0];
var match = _tileDefinitions.Values
.FirstOrDefault(t => t.TileMapSheetId == first.SheetId && t.FrameIndex == first.FrameIndex);
if (match != null)
{
if (!UsedFloorTemplates.Contains(template.Name))
UsedFloorTemplates.Add(template.Name);
return match;
}
}
}
catch { }
}
}
}
usedFallback = true;
var walkableTiles = _tileDefinitions.Values.Where(t => t.IsWalkable).OrderBy(t => t.Id).ToList();
return walkableTiles.FirstOrDefault() ?? _tileDefinitions.Values.FirstOrDefault();
}
/// <summary>
/// Place wall tiles around walkable areas.
/// Walls are placed on non-walkable cells adjacent to walkable cells.
@@ -1405,22 +1492,26 @@ public class DungeonGeneratorV3
/// <summary>
/// Select a wall tile for the given position.
///
/// SELECTION PROCESS:
/// SELECTION PROCESS (with socket matching):
/// 1. If _wallTemplates has templates:
/// a. Select one via weighted random
/// b. Try template.PrimaryTileDefinitionId first
/// c. If no PrimaryTileDefinitionId, parse template.TilesJson
/// d. Look up TileDefinition by SheetId + FrameIndex
/// a. Filter to socket-compatible templates (if UseSocketMatching)
/// b. Select one via weighted random
/// c. Try template.PrimaryTileDefinitionId first
/// d. If no PrimaryTileDefinitionId, parse template.TilesJson
/// e. Track placed template for future socket matching
/// 2. FALLBACK: Return first non-walkable TileDefinition
/// </summary>
private TileDefinition? SelectWallTile(int x, int y, DungeonLayoutV2 layout)
{
if (_wallTemplates.Count > 0)
{
var template = SelectWeightedTemplate(_wallTemplates);
// Get socket-compatible templates
var compatibleTemplates = GetCompatibleTemplates(_wallTemplates, x, y, layout);
var template = SelectWeightedTemplate(compatibleTemplates);
if (template != null)
{
LogVerbose($"SelectWallTile({x},{y}): Template '{template.Name}' (ID={template.Id})");
LogVerbose($"SelectWallTile({x},{y}): Template '{template.Name}' (ID={template.Id}) [Compatible: {compatibleTemplates.Count}/{_wallTemplates.Count}]");
// Method 1: Try PrimaryTileDefinitionId first
if (template.PrimaryTileDefinitionId.HasValue)
@@ -1431,6 +1522,10 @@ public class DungeonGeneratorV3
if (!UsedWallTemplates.Contains(template.Name))
UsedWallTemplates.Add(template.Name);
LogVerbose($" -> Found TileDef {tileDef.Id} '{tileDef.Name}'");
// Track placement for socket matching
_placedTemplates[$"{x},{y}"] = template.Id;
return tileDef;
}
LogVerbose($" -> NOT FOUND in _tileDefinitions!");
@@ -1463,6 +1558,10 @@ public class DungeonGeneratorV3
if (!UsedWallTemplates.Contains(template.Name))
UsedWallTemplates.Add(template.Name);
LogVerbose($" -> Match: TileDef {match.Id} '{match.Name}'");
// Track placement for socket matching
_placedTemplates[$"{x},{y}"] = template.Id;
return match;
}
else
@@ -1500,6 +1599,189 @@ public class DungeonGeneratorV3
return null;
}
// ============================================================
// SOCKET MATCHING METHODS
// ============================================================
/// <summary>
/// Parse and cache socket configurations for all loaded templates.
/// Call this after loading templates.
/// </summary>
private void ParseSocketConfigurations()
{
_templateSocketConfigs.Clear();
var allTemplates = _floorTemplates
.Concat(_wallTemplates)
.Concat(_doorTemplates);
int parsed = 0;
foreach (var template in allTemplates)
{
var config = ParseSocketConfig(template);
if (config != null)
{
_templateSocketConfigs[template.Id] = config;
parsed++;
}
}
Log($"Parsed socket configurations for {parsed} templates");
}
/// <summary>
/// Parse a template's socket configuration from JSON or legacy fields.
/// </summary>
private SocketConfiguration? ParseSocketConfig(TileTemplate template)
{
// Try new JSON format first
if (!string.IsNullOrEmpty(template.SocketConfigJson))
{
try
{
var config = JsonSerializer.Deserialize<SocketConfiguration>(template.SocketConfigJson, _jsonOptions);
if (config != null)
{
LogVerbose($" Template {template.Id} '{template.Name}': Parsed SocketConfigJson");
return config;
}
}
catch (Exception ex)
{
Log($" WARNING: Failed to parse SocketConfigJson for template {template.Id}: {ex.Message}");
}
}
// Fall back to legacy socket fields
var legacyConfig = SocketConfiguration.CreateDefault(template.Width, template.Height);
// Set first socket of each edge from legacy fields
if (legacyConfig.North.Count > 0)
{
legacyConfig.North[0].Type = template.SocketN;
if (template.SocketN == SocketType.Custom)
legacyConfig.North[0].CustomName = template.SocketCustom?.ToLower();
}
if (legacyConfig.East.Count > 0)
{
legacyConfig.East[0].Type = template.SocketE;
if (template.SocketE == SocketType.Custom)
legacyConfig.East[0].CustomName = template.SocketCustom?.ToLower();
}
if (legacyConfig.South.Count > 0)
{
legacyConfig.South[0].Type = template.SocketS;
if (template.SocketS == SocketType.Custom)
legacyConfig.South[0].CustomName = template.SocketCustom?.ToLower();
}
if (legacyConfig.West.Count > 0)
{
legacyConfig.West[0].Type = template.SocketW;
if (template.SocketW == SocketType.Custom)
legacyConfig.West[0].CustomName = template.SocketCustom?.ToLower();
}
return legacyConfig;
}
/// <summary>
/// Check if a template can be placed at (x,y) based on neighboring tiles' sockets.
///
/// For a 1x1 template at (x,y):
/// - Check North socket against South socket of template at (x, y-1)
/// - Check East socket against West socket of template at (x+1, y)
/// - Check South socket against North socket of template at (x, y+1)
/// - Check West socket against East socket of template at (x-1, y)
///
/// Returns true if all present neighbors have compatible sockets.
/// </summary>
private bool IsSocketCompatible(TileTemplate template, int x, int y, DungeonLayoutV2 layout)
{
if (!UseSocketMatching) return true;
if (!_templateSocketConfigs.TryGetValue(template.Id, out var config)) return true;
// Check North neighbor (our North socket vs their South socket)
if (y > 0 && _placedTemplates.TryGetValue($"{x},{y-1}", out var northTemplateId))
{
if (_templateSocketConfigs.TryGetValue(northTemplateId, out var northConfig))
{
var ourSocket = config.North.FirstOrDefault();
var theirSocket = northConfig.South.FirstOrDefault();
if (ourSocket != null && theirSocket != null && !SocketConfiguration.CanConnect(ourSocket, theirSocket))
{
return false;
}
}
}
// Check South neighbor (our South socket vs their North socket)
if (y < layout.Height - 1 && _placedTemplates.TryGetValue($"{x},{y+1}", out var southTemplateId))
{
if (_templateSocketConfigs.TryGetValue(southTemplateId, out var southConfig))
{
var ourSocket = config.South.FirstOrDefault();
var theirSocket = southConfig.North.FirstOrDefault();
if (ourSocket != null && theirSocket != null && !SocketConfiguration.CanConnect(ourSocket, theirSocket))
{
return false;
}
}
}
// Check East neighbor (our East socket vs their West socket)
if (x < layout.Width - 1 && _placedTemplates.TryGetValue($"{x+1},{y}", out var eastTemplateId))
{
if (_templateSocketConfigs.TryGetValue(eastTemplateId, out var eastConfig))
{
var ourSocket = config.East.FirstOrDefault();
var theirSocket = eastConfig.West.FirstOrDefault();
if (ourSocket != null && theirSocket != null && !SocketConfiguration.CanConnect(ourSocket, theirSocket))
{
return false;
}
}
}
// Check West neighbor (our West socket vs their East socket)
if (x > 0 && _placedTemplates.TryGetValue($"{x-1},{y}", out var westTemplateId))
{
if (_templateSocketConfigs.TryGetValue(westTemplateId, out var westConfig))
{
var ourSocket = config.West.FirstOrDefault();
var theirSocket = westConfig.East.FirstOrDefault();
if (ourSocket != null && theirSocket != null && !SocketConfiguration.CanConnect(ourSocket, theirSocket))
{
return false;
}
}
}
return true;
}
/// <summary>
/// Get all templates from a list that are socket-compatible at position (x,y).
/// </summary>
private List<TileTemplate> GetCompatibleTemplates(List<TileTemplate> templates, int x, int y, DungeonLayoutV2 layout)
{
if (!UseSocketMatching) return templates;
var compatible = templates.Where(t => IsSocketCompatible(t, x, y, layout)).ToList();
if (compatible.Count == 0)
{
LogVerbose($" No socket-compatible templates at ({x},{y}), using all {templates.Count} templates");
return templates; // Fallback to all if none match
}
LogVerbose($" Socket-compatible: {compatible.Count}/{templates.Count} templates at ({x},{y})");
return compatible;
}
// ============================================================
// LOGGING HELPERS
// ============================================================