feat: Implement Story 1.6 - Move Shared Defs Resources to the Dedicated Host

- Added documentation for Story 1.6 outlining the requirements and acceptance criteria for migrating shared defs-backed resources to a dedicated host.
- Updated sprint status to reflect the readiness of Story 1.6 for development.
- Created epics document detailing the breakdown of the Fantasy-Map-Generator project, including functional and non-functional requirements.
- Added implementation readiness report assessing the current state of documentation and readiness for the project.
- Introduced end-to-end tests for scene bootstrap to ensure runtime hosts are created and reused correctly.
This commit is contained in:
Azgaar 2026-03-13 00:22:23 +01:00
parent df18f69516
commit 125403b82f
10 changed files with 1522 additions and 0 deletions

View file

@ -0,0 +1,99 @@
# Story 1.1: Bootstrap Scene Container and Defs Host
Status: ready-for-dev
<!-- Note: Validation is optional. Run validate-create-story for quality check before dev-story. -->
## Story
As a map maintainer,
I want runtime initialization to create a dedicated scene container and defs host,
so that split layer surfaces can share resources without depending on one map SVG root.
## Acceptance Criteria
1. Given the current runtime starts from one canonical map host, when the layered runtime bootstrap runs, then it creates or reuses a dedicated scene container for layer surfaces and a dedicated defs host outside individual layer surfaces, and the visible map loads without user-facing regressions at startup.
2. Given existing code expects the map to initialize once, when the new bootstrap path is enabled, then the scene container and defs host are available through stable runtime references, and initialization does not require changing user-facing layer controls.
## Tasks / Subtasks
- [ ] Audit the current bootstrap ownership before changing runtime structure.
- [ ] Confirm which DOM nodes already exist in the HTML shell and which are still assumed to be canonical at runtime.
- [ ] Inventory the startup and load paths that currently rebind `svg`, `defs`, and `viewbox` globals.
- [ ] Create or reuse the layered runtime hosts.
- [ ] Establish one scene container under the map host for layer surfaces.
- [ ] Establish one dedicated runtime defs host outside individual layer surfaces.
- [ ] Preserve the existing WebGL canvas mount so current relief rendering does not regress during the bootstrap change.
- [ ] Publish stable references for the new hosts.
- [ ] Expose bootstrap references through one runtime owner instead of scattering raw DOM lookups.
- [ ] Keep legacy globals working during the transition without making them the new source of truth.
- [ ] Update startup and saved-map reload to reuse the new hosts instead of assuming the initial DOM is always present.
- [ ] Keep existing layer controls and initial draw order unchanged.
- [ ] Ensure load-from-file can rebuild host references after replacing the map SVG.
- [ ] Perform manual smoke verification.
- [ ] Fresh page load renders normally.
- [ ] Loading an existing map still rebinds all required runtime references.
- [ ] Relief canvas and fixed UI elements remain correctly mounted.
## Dev Notes
### Context Summary
- The HTML shell already contains a positioned `#map-container`, the main `#map` SVG, and a sibling `#webgl-canvas`. Do not duplicate those elements if they can be reused as the scene bootstrap root.
- The current runtime still treats the map SVG as canonical: `public/main.js` binds `svg = d3.select("#map")`, `defs = svg.select("#deftemp")`, and `viewbox = svg.select("#viewbox")` during startup.
- The saved-map load path tears out and reinserts the SVG, then rebinds all global layer selections in `public/modules/io/load.js`. Any new scene bootstrap must survive that path.
- There is already a second hidden SVG asset host at `#defElements` in the HTML shell. Treat that as a static asset library, not automatically as the new runtime defs host.
### Technical Requirements
- Reuse existing DOM nodes when practical. The acceptance criteria require stable runtime references, not a full DOM redesign in this story.
- Keep the runtime compatible with the current global-variable model. New TypeScript code must use ambient globals directly, not `window` or `globalThis` wrappers.
- New TypeScript modules must follow the project Global Module Pattern: declare global, implement a class, then assign `window.ModuleName = new ModuleClass()`.
- Avoid grouped SVG buckets or speculative abstractions here. The goal is bootstrap ownership only.
### Architecture Compliance
- This story is the Phase 1 foundation from the layered-map architecture: create one scene container, one defs host, and stable references before any layer split begins.
- `svg` and `viewbox` remain compatibility-era globals after this story. They must stop being the architectural source of truth, but they are not removed yet.
- The runtime defs host must live outside individual layer surfaces so later split SVG shells can reference shared resources by stable ID.
### Project Structure Notes
- Expected touch points:
- `src/index.html`
- `public/main.js`
- `public/modules/io/load.js`
- `src/types/global.ts`
- Expected new module if needed:
- `src/modules/scene.ts` or a similarly narrow runtime bootstrap owner
- Do not add a separate helper file unless multiple call sites genuinely need it.
- Keep new foundation code in `src/`; do not add new runtime architecture code to `public/modules/`.
### Testing Notes
- The architecture document explicitly defers formal test work for this tranche.
- Do manual verification for fresh load, saved-map load, and relief visibility.
- If a pure helper is extracted while implementing bootstrap ownership, keep it testable, but do not expand scope into a new test suite in this story.
### References
- [Source: _bmad-output/planning-artifacts/epics.md, Epic 1, Story 1.1]
- [Source: _bmad-output/planning-artifacts/architecture-layered-map-dom-split.md, Core Decisions, Runtime Structure, Migration Plan]
- [Source: docs/architecture-globals.md, main.js globals and module loading order]
- [Source: src/index.html, `#map-container`, `#map`, `#webgl-canvas`, `#defElements`]
- [Source: public/main.js, bootstrap globals and initial layer append order]
- [Source: public/modules/io/load.js, saved-map SVG replacement and global rebinding]
## Dev Agent Record
### Agent Model Used
TBD
### Debug Log References
### Completion Notes List
- Story context prepared on 2026-03-13.
### File List

View file

@ -0,0 +1,103 @@
# Story 1.2: Add Scene Module for Shared Camera State
Status: ready-for-dev
<!-- Note: Validation is optional. Run validate-create-story for quality check before dev-story. -->
## Story
As a map maintainer,
I want a Scene module to own shared camera and viewport state,
so that all layer surfaces consume one authoritative transform contract.
## Acceptance Criteria
1. Given shared globals such as `scale`, `viewX`, `viewY`, `graphWidth`, and `graphHeight` already exist, when the Scene module is introduced, then it exposes a single runtime contract for camera and viewport state, and existing global values remain authoritative and usable during migration.
2. Given multiple surfaces will render the same map, when camera state changes, then the Scene module provides one consistent state source for all registered surfaces, and no feature code needs to read transforms from DOM structure directly.
## Tasks / Subtasks
- [ ] Create a narrow Scene runtime module.
- [ ] Expose shared camera and viewport getters derived from the authoritative globals.
- [ ] Expose scene-host references established in Story 1.1 through the same contract.
- [ ] Centralize transform ownership.
- [ ] Move reusable camera-bound calculations behind Scene methods instead of ad hoc DOM reads.
- [ ] Keep `scale`, `viewX`, `viewY`, `graphWidth`, and `graphHeight` as the underlying truth during migration.
- [ ] Update runtime consumers that already operate across surfaces.
- [ ] Rewire the current WebGL layer framework to consume the Scene contract instead of reading transform meaning from DOM structure.
- [ ] Ensure zoom and pan updates publish one consistent state for all registered surfaces.
- [ ] Keep compatibility intact.
- [ ] Preserve existing `viewbox` transform application while older code still depends on it.
- [ ] Do not break callers that still read the existing globals directly.
- [ ] Perform manual smoke verification.
- [ ] Zoom and pan keep SVG and WebGL content aligned.
- [ ] Startup and resize continue to use the correct viewport bounds.
## Dev Notes
### Context Summary
- `public/main.js` owns the current zoom flow: `onZoom` updates `scale`, `viewX`, and `viewY`, then `handleZoom` applies `viewbox.attr("transform", ...)` and triggers `WebGLLayer.rerender()`.
- `src/modules/webgl-layer.ts` already has `syncTransform()` logic that computes camera bounds from those globals. That logic is the best initial candidate to move behind a shared Scene contract instead of duplicating it elsewhere.
- The architecture requires Scene to own shared transform meaning while keeping the global values authoritative. This story should centralize interpretation, not rename the underlying globals.
### Technical Requirements
- Implement the Scene module in `src/` as a TypeScript global module and register it through `src/modules/index.ts`.
- Use bare ambient globals declared in `src/types/global.ts`. Do not introduce `window.scale` or `globalThis.viewX` usage.
- Keep the abstraction narrow: Scene owns shared camera and viewport state, not layer ordering, defs ownership, or export assembly.
- Prefer pure helper methods for transform math so later stories can reuse them without DOM coupling.
### Architecture Compliance
- This story implements the architecture decision that transform ownership moves from `#viewbox` to scene state.
- `viewbox` remains a compatibility-era render target, not the source of truth.
- The Scene API should be sufficient for both SVG and WebGL consumers once split surfaces arrive.
### Previous Story Intelligence
- Story 1.1 should leave the runtime with stable scene-host and defs-host references. Reuse those references here instead of letting Scene rediscover DOM nodes on every call.
- Do not fold bootstrap ownership and camera ownership into one large module. Story 1.1 is about host setup; this story is about transform semantics.
### Project Structure Notes
- Expected touch points:
- `src/modules/scene.ts`
- `src/modules/index.ts`
- `src/modules/webgl-layer.ts`
- `public/main.js`
- `src/types/global.ts`
- Keep any math helpers inside the Scene module unless there are multiple concrete callers that justify extraction.
- Keep the scene contract in `src/`; legacy `public/main.js` should consume it, not own a second parallel source of truth.
### Testing Notes
- Formal automated test work is out of scope for this tranche.
- Keep transform calculation logic pure enough for later coverage.
- Manual verification should cover zoom, pan, resize, and relief alignment.
### Dependencies
- Build on the runtime references introduced in Story 1.1.
### References
- [Source: _bmad-output/planning-artifacts/epics.md, Epic 1, Story 1.2]
- [Source: _bmad-output/planning-artifacts/architecture-layered-map-dom-split.md, Decision 3, Runtime Structure, Migration Plan]
- [Source: docs/architecture-globals.md, `scale`, `viewX`, `viewY`, `graphWidth`, `graphHeight` globals]
- [Source: public/main.js, zoom pipeline and `handleZoom`]
- [Source: src/modules/webgl-layer.ts, `syncTransform()` and current camera ownership]
## Dev Agent Record
### Agent Model Used
TBD
### Debug Log References
### Completion Notes List
- Story context prepared on 2026-03-13.
### File List

View file

@ -0,0 +1,106 @@
# Story 1.3: Add Layers Registry as the Ordering Source of Truth
Status: ready-for-dev
<!-- Note: Validation is optional. Run validate-create-story for quality check before dev-story. -->
## Story
As a map maintainer,
I want a centralized Layers registry,
so that visibility, order, and surface ownership are managed consistently instead of inferred from DOM position.
## Acceptance Criteria
1. Given logical map layers currently rely on DOM placement and ad hoc lookups, when a layer is registered, then the registry stores its `id`, `kind`, `order`, `visible` state, and surface handle, and callers can query layer state without inferring it from DOM order.
2. Given runtime layer order changes, when reorder operations are applied through the registry, then all registered layer surfaces receive the updated ordering atomically, and the registry remains the single source of truth for visibility and order.
## Tasks / Subtasks
- [ ] Create the Layers registry module.
- [ ] Define the minimum record shape: `id`, `kind`, `order`, `visible`, `surface`.
- [ ] Expose lookup and mutation APIs that are narrow enough to become the single ordering contract.
- [ ] Bootstrap the current layer stack into the registry.
- [ ] Register the existing logical SVG layers in their current order.
- [ ] Register the current WebGL surface path so mixed rendering already has a place in the model.
- [ ] Move order and visibility mutations behind the registry.
- [ ] Replace direct DOM-order assumptions in the layer UI reorder path with registry updates.
- [ ] Apply visibility changes through the registry without changing user-facing controls.
- [ ] Ensure one coordinated apply step updates all affected surfaces together.
- [ ] Preserve compatibility for migration-era callers.
- [ ] Keep existing layer IDs and toggle IDs stable.
- [ ] Avoid forcing feature modules to understand renderer-specific ordering logic.
- [ ] Perform manual smoke verification.
- [ ] Reordering through the existing Layers UI still changes the visible stack correctly.
- [ ] Visibility toggles still map to the correct runtime surface.
## Dev Notes
### Context Summary
- The current reorder path is still DOM-driven. `public/modules/ui/layers.js` maps toggle IDs to concrete DOM groups in `getLayer(id)` and then calls `insertAfter` or `insertBefore` directly in `moveLayer`.
- The initial stack order is created in `public/main.js` by appending groups to `viewbox` in sequence. Older-map migration code in `public/modules/dynamic/auto-update.js` also inserts groups relative to concrete siblings such as `#terrain` and `#borders`.
- The registry has to become the source of truth without breaking those legacy IDs immediately. This story is about authoritative state ownership, not yet about fully removing all DOM-based insertion helpers.
### Technical Requirements
- Implement the registry in `src/` as a global module, likely `src/modules/layers.ts`.
- Keep the public contract minimal. Do not add export metadata yet; that belongs to Epic 4.
- Store actual surface handles, not just selectors, so later stories can mount independent SVG shells and WebGL surfaces under one contract.
- Ensure reorder application is atomic from the user perspective. Avoid partial states where one surface has moved and another has not.
### Architecture Compliance
- This story implements Decision 1 from the architecture: the Layers registry is the single source of truth for ordering and visibility.
- The runtime must support arbitrary future ordering of SVG and WebGL layers. Do not hard-code separate ordering buckets.
- The registry should own state; individual layer modules should not infer state from the DOM.
### Previous Story Intelligence
- Story 1.1 introduces stable runtime hosts; the registry should refer to those hosts rather than embedding DOM queries in each layer record.
- Story 1.2 centralizes shared transform state; do not mix camera ownership into the registry API.
- The current sortable UI already maps toggle IDs to concrete layer IDs in `getLayer(id)`. Preserve those IDs so Story 1.5 can bridge legacy callers cleanly.
### Project Structure Notes
- Expected touch points:
- `src/modules/layers.ts`
- `src/modules/index.ts`
- `src/types/global.ts`
- `public/modules/ui/layers.js`
- `public/main.js`
- `public/modules/dynamic/auto-update.js`
- Keep migration focused. Do not rewrite every legacy caller in this story.
- Keep the registry implementation in `src/` and expose only the smallest legacy-facing hooks needed in `public/modules/ui/layers.js`.
### Testing Notes
- Manual verification is sufficient for this tranche.
- Verify the existing sortable Layers UI still works and that no layer disappears from the visible stack after a reorder.
### Dependencies
- Story 1.1 provides runtime host references.
- Story 1.2 provides the shared Scene contract that registry-managed surfaces will consume.
### References
- [Source: _bmad-output/planning-artifacts/epics.md, Epic 1, Story 1.3]
- [Source: _bmad-output/planning-artifacts/architecture-layered-map-dom-split.md, Decision 1, Decision 2, Migration Plan]
- [Source: public/modules/ui/layers.js, `moveLayer` and `getLayer`]
- [Source: public/main.js, layer append order]
- [Source: public/modules/dynamic/auto-update.js, compatibility inserts relative to existing siblings]
## Dev Agent Record
### Agent Model Used
TBD
### Debug Log References
### Completion Notes List
- Story context prepared on 2026-03-13.
### File List

View file

@ -0,0 +1,103 @@
# Story 1.4: Add Layer Surface Lifecycle Ownership
Status: ready-for-dev
<!-- Note: Validation is optional. Run validate-create-story for quality check before dev-story. -->
## Story
As a map maintainer,
I want a Layer abstraction to own each surface lifecycle,
so that individual layers can be created, mounted, updated, and disposed without leaking renderer-specific details.
## Acceptance Criteria
1. Given the runtime needs one surface per logical layer, when a layer is instantiated, then the Layer abstraction owns creation, mount, update, and teardown for that surface, and caller code interacts with the layer through a stable contract rather than direct DOM assumptions.
2. Given both SVG and WebGL layers will exist, when a surface is registered with the Layer abstraction, then surface lifecycle handling works without exposing renderer-specific branching to feature modules, and layer modules remain responsible only for drawing their own surface.
## Tasks / Subtasks
- [ ] Introduce the Layer lifecycle contract.
- [ ] Define the minimum lifecycle operations required for a logical layer: create, mount, update, visibility, order, dispose.
- [ ] Ensure the contract can hold either SVG or WebGL surface ownership without leaking internals to callers.
- [ ] Integrate the lifecycle contract with the Layers registry.
- [ ] Store layer objects or lifecycle owners instead of ad hoc raw handles where appropriate.
- [ ] Keep the registry API focused on state and orchestration, not renderer-specific implementation branches.
- [ ] Adapt current surfaces to the new ownership model.
- [ ] Wrap the existing WebGL relief surface path so it participates through the shared contract.
- [ ] Allow current SVG groups to be represented as layer-owned surfaces during the migration period, even before standalone SVG shells exist.
- [ ] Preserve module boundaries.
- [ ] Keep feature renderers responsible for drawing content only.
- [ ] Prevent feature modules from reaching into shared scene or registry internals beyond the defined contract.
- [ ] Perform manual smoke verification.
- [ ] Relief rendering still mounts and clears correctly.
- [ ] Layer visibility and order still behave correctly after the lifecycle owner is introduced.
## Dev Notes
### Context Summary
- `src/modules/webgl-layer.ts` already owns one shared Three.js scene and keeps a `Map<string, RegisteredLayer>` of WebGL groups. Reuse that work. Do not create a second parallel WebGL ownership model.
- `src/renderers/draw-relief-icons.ts` currently delegates to `TextureAtlasLayer`, which triggers `WebGLLayer.rerender()` directly. That is a concrete example of a feature module that should eventually talk only to its own surface owner.
- Current SVG layers are still raw D3 groups under `viewbox`. During Epic 1 the lifecycle abstraction can wrap those existing groups first; standalone SVG shells belong to Epic 2.
### Technical Requirements
- Keep the abstraction narrow and named after the architecture: `Layer` or similarly direct terminology.
- Avoid generic factories or strategy trees. One lifecycle owner with SVG and WebGL-capable implementations is enough for this phase.
- Do not force feature modules to pass renderer flags around. If two surface kinds need separate logic, isolate that inside the lifecycle owner.
- Preserve the current `WebGLLayer` canvas and shared context budget.
### Architecture Compliance
- This story implements the architecture requirement that each logical layer owns one surface lifecycle and that layer modules own only their own drawing surface.
- The abstraction must support incremental migration. Existing SVG groups can be wrapped now; split SVG shells come later.
### Previous Story Intelligence
- Story 1.3 should already establish the registry as the single ordering authority. Plug lifecycle ownership into that registry instead of storing a second map of surfaces.
- The existing `WebGLLayer` module already manages per-layer groups and a shared renderer. Extend that ownership model rather than replacing it.
- Story 1.2 should already own shared camera meaning. The lifecycle contract should consume Scene state, not recreate transform helpers.
### Project Structure Notes
- Expected touch points:
- `src/modules/layer.ts`
- `src/modules/layers.ts`
- `src/modules/webgl-layer.ts`
- `src/modules/texture-atlas-layer.ts`
- `src/renderers/draw-relief-icons.ts`
- `src/types/global.ts`
- Keep renderer-specific logic close to the existing modules rather than introducing extra indirection files.
- Avoid adding separate generic adapter directories or pattern-heavy wrappers for only one WebGL and one SVG path.
### Testing Notes
- Manual validation is sufficient.
- Focus on mount, redraw, hide/show, and cleanup behavior for relief because that is the current live mixed-render surface.
### Dependencies
- Story 1.3 should land first so the lifecycle owner plugs into the registry instead of inventing a second source of truth.
### References
- [Source: _bmad-output/planning-artifacts/epics.md, Epic 1, Story 1.4]
- [Source: _bmad-output/planning-artifacts/architecture-layered-map-dom-split.md, Decision 2, Decision 4, Clean Code Rules, Migration Plan]
- [Source: src/modules/webgl-layer.ts, shared renderer and per-layer group ownership]
- [Source: src/renderers/draw-relief-icons.ts, current feature-to-WebGL integration]
- [Source: src/modules/texture-atlas-layer.ts, current WebGL rerender trigger]
## Dev Agent Record
### Agent Model Used
TBD
### Debug Log References
### Completion Notes List
- Story context prepared on 2026-03-13.
### File List

View file

@ -0,0 +1,108 @@
# Story 1.5: Add Compatibility Lookups for Legacy Single-SVG Callers
Status: ready-for-dev
<!-- Note: Validation is optional. Run validate-create-story for quality check before dev-story. -->
## Story
As a map maintainer,
I want compatibility helpers for legacy single-SVG access patterns,
so that existing workflows keep working while code migrates to the new scene and layer contracts.
## Acceptance Criteria
1. Given legacy code still expects `svg`, `viewbox`, or one shared selector scope, when compatibility helpers are introduced, then the runtime provides `getLayerSvg(id)`, `getLayerSurface(id)`, and `queryMap(selector)`, and callers can continue to function during migration without depending on one canonical map SVG.
2. Given new code is added after the compatibility layer exists, when it needs layer or scene access, then it can use the new layer and scene contracts directly, and the compatibility layer remains a migration bridge rather than the new source of truth.
## Tasks / Subtasks
- [ ] Add the compatibility bridge API.
- [ ] Implement `getLayerSvg(id)`, `getLayerSurface(id)`, and `queryMap(selector)` against the new Scene and Layers contracts.
- [ ] Expose the helpers as stable globals for legacy callers that cannot move immediately.
- [ ] Type and document the bridge.
- [ ] Add ambient global declarations for the new helpers.
- [ ] Keep the bridge deliberately narrow so it does not become a second permanent architecture.
- [ ] Migrate the highest-risk single-root callers touched by Epic 1 foundation work.
- [ ] Replace direct whole-map selector assumptions where they would break immediately under split surfaces.
- [ ] Preserve unchanged callers until they become relevant, rather than doing a repo-wide cleanup in this story.
- [ ] Verify legacy workflows still function.
- [ ] Saved-map load and export paths still find required map elements.
- [ ] Runtime helpers still let callers reach labels, text paths, and other layer-owned content without assuming one canonical SVG root.
## Dev Notes
### Context Summary
- The codebase has many single-SVG assumptions. Current hotspots include:
- `public/main.js` and `public/modules/io/load.js` rebinding `svg`, `defs`, and `viewbox`
- `public/modules/io/save.js` and `public/modules/io/export.js` operating on `svg.node()` and `#viewbox`
- `src/modules/fonts.ts`, where `getUsedFonts(svg)` queries `#labels` and `#legend` inside a single SVG root
- `src/renderers/draw-state-labels.ts`, which appends text paths to `defs > g#deftemp > g#textPaths`
- `public/modules/dynamic/auto-update.js`, which uses selectors such as `#viewbox > #routes > g`
- This story is a bridge. New code written for the layered runtime should use Scene and Layers directly.
### Technical Requirements
- Implement the compatibility API in `src/` so it is typed and globally available to both TypeScript and legacy JS.
- Return real layer surfaces or layer-local SVG roots where available. Do not fake a new canonical SVG document.
- `queryMap(selector)` should be controlled and predictable. It must not silently reintroduce global DOM coupling as a hidden permanent pattern.
- Preserve current IDs and selectors where possible so callers can migrate incrementally.
### Architecture Compliance
- This story implements Decision 4 from the architecture: a thin compatibility layer for migration-era callers.
- The compatibility API must not become the new source of truth. Scene and Layers remain authoritative.
- The goal is operational continuity for legacy workflows while the map DOM is being split.
### Previous Story Intelligence
- Story 1.3 should already provide registry-backed layer lookup. Build `getLayerSurface(id)` on that instead of re-querying the DOM.
- Story 1.4 should already wrap surfaces in lifecycle ownership. Compatibility helpers should return current owned surfaces, not bypass the lifecycle layer.
- Story 1.1 should already provide stable host references after load and reload. Reuse those references for `queryMap(selector)` resolution order.
### Project Structure Notes
- Expected touch points:
- `src/modules` or `src/utils` compatibility bridge module
- `src/types/global.ts`
- `src/modules/fonts.ts`
- `src/renderers/draw-state-labels.ts`
- `public/modules/io/save.js`
- `public/modules/io/export.js`
- `public/modules/io/load.js`
- Only migrate the callers that the new foundation stories would otherwise break.
- Keep the bridge in one place in `src/`; do not sprinkle ad hoc fallback selector logic across legacy files.
### Testing Notes
- Manual verification is sufficient.
- Validate save/export, labels/text paths, and at least one legacy selector-heavy workflow after the helpers are introduced.
### Dependencies
- Requires Scene and Layers to exist first so the compatibility helpers can delegate to the real runtime contracts.
### References
- [Source: _bmad-output/planning-artifacts/epics.md, Epic 1, Story 1.5]
- [Source: _bmad-output/planning-artifacts/architecture-layered-map-dom-split.md, Decision 3, Decision 4]
- [Source: public/modules/io/load.js, global rebinding after map replacement]
- [Source: public/modules/io/export.js, single-SVG export assumptions]
- [Source: public/modules/io/save.js, `getUsedFonts(svg.node())` and `#viewbox` assumptions]
- [Source: src/modules/fonts.ts, single-SVG font collection]
- [Source: src/renderers/draw-state-labels.ts, defs and text path assumptions]
## Dev Agent Record
### Agent Model Used
TBD
### Debug Log References
### Completion Notes List
- Story context prepared on 2026-03-13.
### File List

View file

@ -0,0 +1,115 @@
# Story 1.6: Move Shared Defs Resources to the Dedicated Host
Status: ready-for-dev
<!-- Note: Validation is optional. Run validate-create-story for quality check before dev-story. -->
## Story
As a map maintainer,
I want shared defs-backed resources to be registered in one dedicated host,
so that split surfaces can keep using stable IDs for filters, masks, symbols, markers, patterns, and text paths.
## Acceptance Criteria
1. Given runtime resources currently live under one shared SVG structure, when defs registration is migrated, then shared resources are created under the dedicated defs host with stable identifiers, and layer surfaces can reference those resources without duplicating them per layer.
2. Given a split surface uses a filter, mask, symbol, marker, pattern, or text path, when the layer renders, then the resource reference resolves from the dedicated defs host, and existing visual behavior remains unchanged for supported runtime features.
## Tasks / Subtasks
- [ ] Establish one runtime defs owner.
- [ ] Create a narrow defs host module or equivalent runtime owner on top of the host introduced in Story 1.1.
- [ ] Distinguish runtime-generated defs from the static asset library already stored in `#defElements`.
- [ ] Migrate the current runtime writers for shared defs-backed resources.
- [ ] Move feature paths and masks now written through `defs.select(...)` to the dedicated host.
- [ ] Move text path registration used by state labels to the dedicated host.
- [ ] Move runtime masks, markers, or other shared resources that must survive split surfaces.
- [ ] Preserve stable IDs and references.
- [ ] Keep existing IDs intact wherever possible so current `url(#id)` and `href="#id"` references continue to resolve.
- [ ] Avoid duplicating identical resources into per-layer surfaces.
- [ ] Keep export work out of scope for this story.
- [ ] Do not redesign the export assembler here.
- [ ] Only make the runtime defs placement compatible with later export assembly.
- [ ] Perform manual smoke verification.
- [ ] Filters, masks, symbols, markers, patterns, and text-path-backed labels still render.
- [ ] Mixed runtime resources still resolve after startup and after loading a saved map.
## Dev Notes
### Context Summary
- The current runtime writes shared resources into the main map defs tree. `public/main.js` binds `defs = svg.select("#deftemp")`.
- Current high-risk shared defs writers include:
- `src/renderers/draw-features.ts` writing `#featurePaths`, `#land`, and `#water`
- `src/renderers/draw-state-labels.ts` writing text paths under `defs > g#deftemp > g#textPaths`
- `public/modules/dynamic/auto-update.js` appending masks such as `#fog`
- `src/modules/emblem/renderer.ts` and export code that rely on stable symbol/pattern IDs
- The HTML shell also contains `#defElements`, a hidden SVG used as a static resource library for markers, relief symbols, and similar assets. Do not collapse static asset storage and runtime-generated shared defs into one accidental abstraction.
### Technical Requirements
- Keep resource IDs stable. The migration should change ownership, not the externally referenced names.
- The dedicated defs host must be reachable by all layer surfaces after the map DOM is split.
- Prefer one focused defs owner module over scattered DOM writes.
- Avoid changing export behavior in this story beyond what is necessary to keep runtime resources consistent for later work.
### Architecture Compliance
- This story implements the architecture decision that runtime shared defs live in a dedicated host separate from layer surfaces.
- Shared defs are a first-class requirement for later split layers and export assembly.
- Runtime and export are separate pipelines; this story only handles runtime ownership.
### Previous Story Intelligence
- Story 1.1 should already establish the dedicated runtime defs host. Reuse that host instead of creating another hidden SVG container.
- Story 1.5 should already provide compatibility lookups for legacy defs consumers. Use that bridge for remaining migration-era callers rather than leaving direct `svg.select("#deftemp")` assumptions behind.
- Story 1.3 and Story 1.4 should already make surface ownership explicit. Keep defs ownership separate from layer lifecycle ownership.
### Project Structure Notes
- Expected touch points:
- `src/modules/defs.ts` or equivalent narrow owner
- `src/modules/index.ts`
- `src/types/global.ts`
- `public/main.js`
- `src/renderers/draw-features.ts`
- `src/renderers/draw-state-labels.ts`
- `public/modules/dynamic/auto-update.js`
- `public/modules/io/export.js`
- Keep changes focused on shared defs ownership. Do not start split-layer rendering in this story.
- Keep static resource assets in the existing HTML asset library and move only runtime-generated shared defs into the new owner.
### Testing Notes
- Manual validation is sufficient.
- Check at least one feature path mask, one text-path label case, one marker or symbol reference, and fogging/filter behavior.
### Dependencies
- Story 1.1 must establish the dedicated runtime defs host first.
- Story 1.5 should land before or alongside this story if compatibility callers still search the old defs tree.
### References
- [Source: _bmad-output/planning-artifacts/epics.md, Epic 1, Story 1.6]
- [Source: _bmad-output/planning-artifacts/architecture-layered-map-dom-split.md, Decision 2, Decision 4, Shared Resource Strategy, Migration Plan]
- [Source: public/main.js, current `defs = svg.select("#deftemp")` binding]
- [Source: src/renderers/draw-features.ts, feature paths and masks in defs]
- [Source: src/renderers/draw-state-labels.ts, text paths in defs]
- [Source: public/modules/dynamic/auto-update.js, runtime mask creation]
- [Source: src/index.html, `#deftemp` and `#defElements`]
- [Source: public/modules/io/export.js, current defs cloning and cleanup]
## Dev Agent Record
### Agent Model Used
TBD
### Debug Log References
### Completion Notes List
- Story context prepared on 2026-03-13.
### File List

View file

@ -0,0 +1,72 @@
# generated: 2026-03-13
# project: Fantasy-Map-Generator
# project_key: NOKEY
# tracking_system: file-system
# story_location: /Users/azgaar/Fantasy-Map-Generator/_bmad-output/implementation-artifacts
# STATUS DEFINITIONS:
# ==================
# Epic Status:
# - backlog: Epic not yet started
# - in-progress: Epic actively being worked on
# - done: All stories in epic completed
#
# Epic Status Transitions:
# - backlog -> in-progress: Automatically when first story is created (via create-story)
# - in-progress -> done: Manually when all stories reach 'done' status
#
# Story Status:
# - backlog: Story only exists in epic file
# - ready-for-dev: Story file created in stories folder
# - in-progress: Developer actively working on implementation
# - review: Ready for code review (via Dev's code-review workflow)
# - done: Story completed
#
# Retrospective Status:
# - optional: Can be completed but not required
# - done: Retrospective has been completed
#
# WORKFLOW NOTES:
# ===============
# - Epic transitions to 'in-progress' automatically when first story is created
# - Stories can be worked in parallel if team capacity allows
# - SM typically creates next story after previous one is 'done' to incorporate learnings
# - Dev moves story to 'review', then runs code-review (fresh context, different LLM recommended)
generated: 2026-03-13
project: Fantasy-Map-Generator
project_key: NOKEY
tracking_system: file-system
story_location: /Users/azgaar/Fantasy-Map-Generator/_bmad-output/implementation-artifacts
development_status:
epic-1: in-progress
1-1-bootstrap-scene-container-and-defs-host: in-progress
1-2-add-scene-module-for-shared-camera-state: ready-for-dev
1-3-add-layers-registry-as-the-ordering-source-of-truth: ready-for-dev
1-4-add-layer-surface-lifecycle-ownership: ready-for-dev
1-5-add-compatibility-lookups-for-legacy-single-svg-callers: ready-for-dev
1-6-move-shared-defs-resources-to-the-dedicated-host: ready-for-dev
epic-1-retrospective: optional
epic-2: backlog
2-1-create-reusable-standalone-svg-shell-mounting: backlog
2-2-migrate-a-representative-low-risk-svg-layer-to-a-dedicated-shell: backlog
2-3-migrate-remaining-approved-low-risk-svg-layers: backlog
2-4-drive-reorder-and-visibility-for-split-svg-layers-from-the-registry: backlog
2-5-preserve-pointer-and-editing-workflows-for-split-svg-layers: backlog
epic-2-retrospective: optional
epic-3: backlog
3-1-register-webgl-surfaces-in-the-shared-layer-model: backlog
3-2-unify-mixed-layer-ordering-and-visibility-controls: backlog
3-3-keep-scene-transforms-and-interaction-correct-in-mixed-rendering: backlog
3-4-preserve-atomic-updates-and-no-regressions-guardrails-in-mixed-mode: backlog
epic-3-retrospective: optional
epic-4: backlog
4-1-add-export-participation-metadata-to-the-layer-registry: backlog
4-2-assemble-unified-svg-export-from-registry-order: backlog
4-3-clone-only-required-defs-resources-into-export: backlog
4-4-preserve-text-paths-masks-and-filtered-layers-in-export: backlog
epic-4-retrospective: optional