# Dungeon Build System Review (Admin/DungeonBuilder) ## Goal Document the current dungeon build/generation system, explain why it works today, and define a practical plan to make it more reliable and easier to operate from `/admin/dungeonbuilder`. ## Current Architecture ### Runtime generation entry points - Active dungeon creation uses fallback chain: 1. `Game/Dungeon/DungeonHandler.Dungeons.cs` tries `DungeonGeneratorV3` first. 2. If V3 produces no tiles or throws, it falls back to `DungeonGeneratorV2`. 3. If V2 fails, it falls back to `DungeonGenerator` (V1). - `DungeonHandler` has a duplicated create/join flow in `Game/Dungeon/DungeonHandler.cs` with the same fallback behavior. ### Layout models - `DungeonLayout` (`Game/Dungeon/DungeonLayout.cs`): - Core grid + walkability + spawn lists. - Supports RLE serialization for transport. - `DungeonLayoutV2` (`Game/Dungeon/DungeonLayoutV2.cs`): - Adds `TileDetails`, `TileMapSheets`, and placed objects for visual rendering. - Keeps compatibility with `DungeonLayout`. ### Generator versions - V1: `Game/Dungeon/DungeonGenerator.cs` - Pure procedural rooms + L-corridors. - No DungeonBuilder template pipeline. - V2: `Game/Dungeon/DungeonGeneratorV2.cs` - Uses legacy `RoomTemplate` + tile definitions + socket/tag logic. - Includes strict socket support and tag-driven fallback (`Game/Dungeon/TagDrivenTiles.cs`). - V3: `Game/Dungeon/DungeonGeneratorV3.cs` - Uses DungeonBuilder entities (`BuilderRoomTemplate`, `TileTemplate`, `ObjectTemplate`, `DungeonPalette`, buckets/rules). - Pipeline: 1. Load palette and template sets. 2. Load tile definitions/sheets and bucket rules. 3. Place rooms (template stamp or procedural fallback). 4. Connect rooms (MST-like nearest linking + L corridors). 5. Fill floor tiles. 6. Place wall tiles. 7. Place objects. 8. Build spawn points. ### Admin DungeonBuilder data model - Main entities are defined in: - `Data/entities/DungeonBuilder.cs` - `Data/entities/TileMap.cs` - `Data/entities/TileBuckets.cs` - Editing pages: - Rooms: `Services/Admin/Pages/DungeonBuilder/Rooms.cshtml.cs`, `RoomEdit.cshtml.cs` - Tiles: `Services/Admin/Pages/DungeonBuilder/Tiles.cshtml.cs`, `TileEdit.cshtml.cs` - Palettes: `Services/Admin/Pages/DungeonBuilder/PaletteEdit.cshtml.cs` - Buckets: `Services/Admin/Pages/DungeonBuilder/Buckets/Edit.cshtml.cs` - Stamps: `Services/Admin/Pages/DungeonBuilder/Stamps/Edit.cshtml.cs` ## Why the system works today ### 1) Defensive fallback chain prevents total outage - Even if V3 content is misconfigured, dungeon creation still succeeds via V2/V1 fallback. ### 2) Deterministic seed-based generation - All generators initialize `Random` with seed, so reproducing map behavior is possible when using the same pipeline and data. ### 3) Separation between logic grid and render tiles - `Walkable` + tile ids drive simulation; `TileDetails` + `TileMapSheets` drive rendering. - This supports live gameplay without requiring renderer-specific assumptions in sim code. ### 4) Content-first generation in V3 - V3 consumes palette and template assets from admin-managed DB content, enabling non-code content iteration. ## Main issues (current gaps) ### A) Generator fragmentation and duplicate orchestration - V1/V2/V3 coexist with overlapping responsibilities. - Dungeon creation logic is duplicated in both `DungeonHandler.Dungeons.cs` and `DungeonHandler.cs`. - This increases drift risk and makes fixes easy to miss. ### B) Restore path drops V2/V3 visual fidelity - `RestoreDungeonFromPersistenceAsync` rebuilds with V1 (`DungeonGenerator.Generate(...)`) in `Game/Dungeon/DungeonHandler.Dungeons.cs`. - Result: restored dungeons do not preserve V2/V3 visual layout/object output. ### C) Test tool does not test real runtime generator - `/admin/dungeonbuilder/testgen` (`TestGen.cshtml.cs`) uses an internal simplified generator, not V3. - This makes admin preview results diverge from real dungeon runtime behavior. ### D) Heavy silent-failure behavior in V3 parsing - Multiple broad `catch { }` paths in `DungeonGeneratorV3` suppress parse/content errors. - Invalid JSON or bad references degrade quality silently instead of failing fast with diagnostics. ### E) Runtime DB access inside stamp/object loops - `DungeonGeneratorV3` calls DB lookups inside generation loops (example: object template lookup during room stamping). - This increases generation latency and variability under load. ### F) Live tile edit broadcasting can become expensive - Tile updates in `DungeonHandler` can fall back to full tile payload broadcast when diff data is missing. - `HasPendingTileUpdates` and `_changedTiles` coordination is workable but fragile under concurrent edits. ### G) Inconsistent template lineage - V2 relies on `RoomTemplate` while V3 uses `BuilderRoomTemplate`. - Admin UX is centered on Builder entities, but runtime still keeps legacy paths active. ## Viable solution to improve system ## Direction Keep V3 as the primary pipeline and make admin tools validate against the same runtime code path. Retain V2/V1 only as controlled feature-flagged emergency fallback, not normal operation. ## Phase 1: Stabilize and align tooling 1. Make `/admin/dungeonbuilder/testgen` call `DungeonGeneratorV3.GenerateAsync` directly. 2. Add a structured generation report object (rooms placed, fallbacks used, parse errors, missing refs, timing). 3. Surface this report in the TestGen UI and store last N reports for troubleshooting. ## Phase 2: Add content validation/compile step 1. Add “Validate Palette” action in admin: - checks JSON parse for room/tile/object blobs, - verifies referenced IDs exist and are enabled, - checks connection points and spawn points are in-bounds, - checks sockets/buckets consistency. 2. Add “Compile Palette Snapshot”: - pre-resolve template references into normalized DTOs, - cache by palette id + updated timestamp. 3. Generator consumes compiled snapshot (single load) instead of many ad-hoc DB lookups. ## Phase 3: Runtime consistency and persistence 1. Persist enough V2/V3 layout data to restore exact walkability + visual state (or persisted layout seed+palette+version with deterministic replay). 2. Remove V1 restore path for dungeons created with V2/V3. 3. Keep one generator orchestration path in `DungeonHandler` (single method used by both partial files). ## Phase 4: Live editing robustness 1. Replace boolean `HasPendingTileUpdates` with monotonic change version. 2. Store tile delta batches (position/layer/op/version) per dungeon for replay-safe client sync. 3. Keep “full snapshot” path only for explicit resync, not as implicit fallback. ## Concrete acceptance criteria 1. TestGen output matches runtime generation for same `seed/tier/palette`. 2. Invalid Builder content produces actionable validation errors before runtime. 3. Restored dungeons preserve V3 visual/walkability integrity. 4. Generation no longer does N+1 DB fetches in stamp/object loops. 5. Tile edit sync remains differential under normal operation. ## Recommended immediate next steps 1. Implement TestGen -> V3 integration first (highest ROI for admin trust). 2. Add validation endpoint + UI report next (prevents silent bad content). 3. Refactor dungeon creation into one shared internal method in `DungeonHandler`.