@forgeax/engine-scene 0.1.20 → 0.1.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -9
- package/dist/__tests__/flat-propagation.contract.test.d.ts +2 -0
- package/dist/__tests__/flat-propagation.contract.test.d.ts.map +1 -0
- package/dist/__tests__/flat-propagation.derived-writer.contract.test.d.ts +2 -0
- package/dist/__tests__/flat-propagation.derived-writer.contract.test.d.ts.map +1 -0
- package/dist/__tests__/flat-propagation.perf.test.d.ts +2 -0
- package/dist/__tests__/flat-propagation.perf.test.d.ts.map +1 -0
- package/dist/__tests__/scene-binding.integration.test.d.ts +2 -0
- package/dist/__tests__/scene-binding.integration.test.d.ts.map +1 -0
- package/dist/__tests__/schedule-order.contract.test.d.ts +2 -0
- package/dist/__tests__/schedule-order.contract.test.d.ts.map +1 -0
- package/dist/__tests__/structural.test.d.ts +2 -0
- package/dist/__tests__/structural.test.d.ts.map +1 -0
- package/dist/__tests__/transform-carrier-consumers.test-d.d.ts +2 -0
- package/dist/__tests__/transform-carrier-consumers.test-d.d.ts.map +1 -0
- package/dist/__tests__/transform-carrier-prototype.bench.d.ts +39 -0
- package/dist/__tests__/transform-carrier-prototype.bench.d.ts.map +1 -0
- package/dist/__tests__/transform-carrier-prototype.test-d.d.ts +2 -0
- package/dist/__tests__/transform-carrier-prototype.test-d.d.ts.map +1 -0
- package/dist/__tests__/transform-carrier-prototype.test.d.ts +2 -0
- package/dist/__tests__/transform-carrier-prototype.test.d.ts.map +1 -0
- package/dist/__tests__/transform-component-version.unit.test.d.ts +2 -0
- package/dist/__tests__/transform-component-version.unit.test.d.ts.map +1 -0
- package/dist/assets/scene-decoder.d.ts.map +1 -1
- package/dist/components/child-of.d.ts +15 -8
- package/dist/components/child-of.d.ts.map +1 -1
- package/dist/components/children.d.ts.map +1 -1
- package/dist/components/transform.d.ts +7 -43
- package/dist/components/transform.d.ts.map +1 -1
- package/dist/errors.d.ts +23 -2
- package/dist/errors.d.ts.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +616 -372
- package/dist/index.mjs.map +1 -1
- package/dist/instances/binding.d.ts +29 -0
- package/dist/instances/binding.d.ts.map +1 -0
- package/dist/instances/externalization.d.ts.map +1 -1
- package/dist/instances/scene-instances.d.ts +5 -17
- package/dist/instances/scene-instances.d.ts.map +1 -1
- package/dist/instances/state.d.ts +28 -0
- package/dist/instances/state.d.ts.map +1 -0
- package/dist/plugin.d.ts.map +1 -1
- package/dist/systems/hierarchy-projection.d.ts.map +1 -1
- package/dist/systems/index.d.ts +1 -1
- package/dist/systems/index.d.ts.map +1 -1
- package/dist/systems/propagate-transforms.d.ts +1 -2
- package/dist/systems/propagate-transforms.d.ts.map +1 -1
- package/package.json +5 -5
- package/src/__tests__/components.unit.test.ts +34 -2
- package/src/__tests__/flat-propagation.contract.test.ts +128 -0
- package/src/__tests__/flat-propagation.derived-writer.contract.test.ts +39 -0
- package/src/__tests__/flat-propagation.perf.test.ts +336 -0
- package/src/__tests__/plugin.integration.test.ts +2 -2
- package/src/__tests__/propagation.unit.test.ts +207 -91
- package/src/__tests__/scene-binding.integration.test.ts +124 -0
- package/src/__tests__/schedule-order.contract.test.ts +43 -0
- package/src/__tests__/structural.test.ts +23 -0
- package/src/__tests__/transform-carrier-consumers.test-d.ts +156 -0
- package/src/__tests__/transform-carrier-prototype.bench.ts +168 -0
- package/src/__tests__/transform-carrier-prototype.test-d.ts +71 -0
- package/src/__tests__/transform-carrier-prototype.test.ts +170 -0
- package/src/__tests__/{transform-change-journal.unit.test.ts → transform-component-version.unit.test.ts} +32 -39
- package/src/assets/scene-decoder.ts +6 -1
- package/src/components/child-of.ts +15 -8
- package/src/components/children.ts +6 -0
- package/src/components/transform.ts +23 -81
- package/src/errors.ts +26 -2
- package/src/index.ts +10 -1
- package/src/instances/binding.ts +77 -0
- package/src/instances/externalization.ts +7 -1
- package/src/instances/scene-instances.ts +47 -76
- package/src/instances/state.ts +62 -0
- package/src/plugin.ts +9 -2
- package/src/systems/hierarchy-projection.ts +25 -8
- package/src/systems/index.ts +3 -0
- package/src/systems/propagate-transforms.ts +376 -245
- package/dist/.tsbuildinfo +0 -1
- package/dist/__tests__/transform-change-journal.unit.test.d.ts +0 -2
- package/dist/__tests__/transform-change-journal.unit.test.d.ts.map +0 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/assets/scene-decoder.ts","../src/components/children.ts","../src/collect-subtree.ts","../src/components/morph-weights.ts","../src/components/name.ts","../src/components/transform.ts","../src/errors.ts","../src/instances/collect-profile.ts","../src/instances/externalization.ts","../src/instances/scene-instances.ts","../src/systems/propagate-transforms.ts","../src/systems/hierarchy-projection.ts","../src/plugin.ts"],"sourcesContent":["import {\n type AssetDecoder,\n type AssetDecoderContribution,\n type AssetKind,\n type AssetLoadError,\n err,\n ok,\n type Result,\n type SceneAsset,\n type SceneEntity,\n type SceneInstanceMount,\n} from '@forgeax/engine-types';\n\nexport const sceneAssetKind: AssetKind<SceneAsset, 'scene'> = {\n kind: 'scene',\n} as AssetKind<SceneAsset, 'scene'>;\n\nfunction invalidScene(guid: string, reason: string): Result<SceneAsset, AssetLoadError> {\n return err({\n code: 'asset-package-invalid',\n expected: 'a scene payload with an entities array',\n hint: 'recook the SceneAsset and publish its complete envelope',\n detail: { guid, reason },\n });\n}\n\ntype SceneWireRefResult =\n | { readonly ok: true; readonly value: SceneAsset }\n | { readonly ok: false; readonly reason: string };\n\n// The Pack envelope owns refs[] while the decoded SceneAsset remains the\n// portable payload. Keep that wire-only fact beside the decoded object so the\n// World-local projection can interpret shared-field indices without putting a\n// component registry or World into the decoder contract.\nconst sceneWireRefs = new WeakMap<object, readonly string[]>();\n\n/** @internal Read the Pack refs[] retained for a decoded SceneAsset payload. */\nexport function sceneAssetWireRefs(asset: SceneAsset): readonly string[] | undefined {\n return sceneWireRefs.get(asset);\n}\n\nfunction resolveWireRef(\n refs: readonly string[],\n value: number,\n location: string,\n): { readonly ok: true; readonly value: string } | { readonly ok: false; readonly reason: string } {\n const guid = refs[value];\n if (!Number.isInteger(value) || value < 0 || guid === undefined) {\n return {\n ok: false,\n reason: `${location} references refs[${value}], but refs contains ${refs.length} entries`,\n };\n }\n return { ok: true, value: guid };\n}\n\nfunction resolveMounts(\n mounts: readonly SceneInstanceMount[] | undefined,\n refs: readonly string[],\n):\n | { readonly ok: true; readonly value: readonly SceneInstanceMount[] | undefined }\n | { readonly ok: false; readonly reason: string } {\n if (mounts === undefined) return { ok: true, value: undefined };\n const resolved: SceneInstanceMount[] = [];\n for (const mount of mounts) {\n if (typeof mount.source !== 'number' || !Number.isInteger(mount.source)) {\n resolved.push(mount);\n continue;\n }\n const ref = resolveWireRef(refs, mount.source, `mount ${mount.localId} source`);\n if (!ref.ok) return ref;\n resolved.push({ ...mount, source: ref.value });\n }\n return { ok: true, value: resolved };\n}\n\nfunction resolveSkinGuids(\n skinGuids: readonly (number | string)[] | undefined,\n refs: readonly string[],\n):\n | { readonly ok: true; readonly value: readonly string[] | undefined }\n | { readonly ok: false; readonly reason: string } {\n if (skinGuids === undefined) return { ok: true, value: undefined };\n const resolved: string[] = [];\n for (let index = 0; index < skinGuids.length; index += 1) {\n const value = skinGuids[index];\n if (typeof value === 'string') {\n resolved.push(value);\n continue;\n }\n if (typeof value !== 'number' || !Number.isInteger(value)) {\n return { ok: false, reason: `skinGuids[${index}] is not a GUID or refs index` };\n }\n const ref = resolveWireRef(refs, value, `skinGuids[${index}]`);\n if (!ref.ok) return ref;\n resolved.push(ref.value);\n }\n return { ok: true, value: resolved };\n}\n\nfunction resolveSceneWireRefs(payload: SceneAsset, refs: readonly string[]): SceneWireRefResult {\n const entities: SceneEntity[] = [];\n for (const entity of payload.entities) {\n const components: Record<string, Record<string, unknown>> = {};\n for (const [componentName, rawFields] of Object.entries(entity.components)) {\n // Component schema lookup is World-local after the ECS core reduction.\n // The runtime projection owns the World-local schema and converts\n // authored GUID fields into World.sharedRefs handles. Keep this loader\n // boundary POD-only instead of consulting a removed process-global ECS\n // component registry.\n components[componentName] = { ...(rawFields as Record<string, unknown>) };\n }\n entities.push({ localId: entity.localId, components });\n }\n\n const mounts = resolveMounts(payload.mounts, refs);\n if (!mounts.ok) return mounts;\n const skinGuids = resolveSkinGuids(\n payload.skinGuids as readonly (number | string)[] | undefined,\n refs,\n );\n if (!skinGuids.ok) return skinGuids;\n\n return {\n ok: true,\n value: {\n kind: 'scene',\n entities,\n ...(mounts.value === undefined ? {} : { mounts: mounts.value }),\n ...(skinGuids.value === undefined ? {} : { skinGuids: skinGuids.value }),\n },\n };\n}\n\n/** Scene owns structural validation; World-local projection resolves shared refs. */\nexport const sceneAssetDecoder: AssetDecoder<SceneAsset> = {\n async decode({ envelope }): Promise<Result<SceneAsset, AssetLoadError>> {\n const payload = envelope.payload;\n if (payload.kind !== 'scene' || !Array.isArray(payload.entities)) {\n return invalidScene(envelope.guid, 'scene payload is missing entities');\n }\n const resolved = resolveSceneWireRefs(payload, envelope.refs);\n if (!resolved.ok) return invalidScene(envelope.guid, resolved.reason);\n sceneWireRefs.set(resolved.value, Object.freeze([...envelope.refs]));\n return ok(resolved.value);\n },\n};\n\nexport const sceneAssetContribution: AssetDecoderContribution<SceneAsset, 'scene'> = {\n kind: sceneAssetKind,\n decoder: sceneAssetDecoder,\n consumer: 'Scene',\n};\n","// @forgeax/engine-runtime - Children (forward-list of child entities).\n//\n// Schema: 1 array<entity> field `entities` (variable-length, ECS-managed via\n// the BufferPool slot column + sidecar count column allocated by the ECS M2\n// `world.push` / `world.pop` / `world.capacity` command surface).\n//\n// feat-20260515-buffer-array-vocab-collapse M3 / w17:\n// the legacy `VarArrayView<Entity>` value-shape wrapper was retired in\n// favour of a direct `TypedArray` snapshot returned by `world.get` plus the\n// three `world` commands. AI users mutate the list through:\n//\n// world.push(parent, Children, 'entities', child).unwrap();\n// world.pop(parent, Children, 'entities').unwrap();\n// world.capacity(parent, Children, 'entities').unwrap();\n//\n// And read through the read-only `Uint32Array` snapshot:\n//\n// const snap = world.get(parent, Children).unwrap().entities;\n// const liveCount = snap.length;\n// for (let i = 0; i < liveCount; i++) { const child = snap[i]; ... }\n//\n// Snapshot length equals the live element count (sidecar count column owned\n// by the ECS layer); the snapshot is rematerialised on every `world.get`\n// (D-4 no-cache); writes routed through the snapshot are undefined behaviour\n// (the contract is read-only, plan-strategy §2.2 D-R3).\n//\n// feat-20260531-ecs-relationship-abstraction-bidirectional-sync M4 / t20:\n// Children is the MIRROR side of the ChildOf relationship. Its schema is\n// unchanged (the `entities: 'array<entity>'` shape is exactly what the\n// relationship mirror contract requires), but the engine now maintains this\n// list automatically whenever ChildOf is added / removed / reparented on a\n// child entity (M2 bidirectional-sync hook on ChildOf). The prior OOS-10\n// \"AI users keep the two sides consistent themselves\" contract is retired:\n// `world.addComponent(child, ChildOf{parent})` appends `child` to\n// `parent.Children.entities`, `world.removeComponent` / reparent prunes it.\n// AI users still MAY push/pop the list manually (the three `world` commands\n// below remain valid for non-ChildOf forward-lists), but for the ChildOf\n// hierarchy the engine owns consistency.\n//\n// feat-20260514-ecs-children-instances-managed-buffer-array M3 / w13 (kept\n// for context): migrated from the legacy `{ count: 'u32' }` advisory marker\n// to the real variable-length entity-array storage path.\n// - OOS-09 (prior loop): no `addChild` / `removeChild` / `removeChildren`\n// Commands API. Retired this feat: `world.addChild` / `world.removeChild`\n// / `world.reparent` ship in M3, plus the relationship hook above.\n// - OOS-01 (prior loop): no dangling-entity sweep on `array<entity>`. If a\n// child entity has been despawned, the stored u32 still occupies the\n// slot; AI users explicitly call the engine's entity-liveness check\n// before consuming a child id (see `world.get(child, ChildOf)` returns\n// `Result.err(...)` for a despawned entity --- the stored u32 surfaces\n// as a dead handle, not a silent zero). Charter proposition 4\n// (explicit failure): the engine does not silently drop dangling\n// entries.\n//\n// charter mapping: proposition 2 (Bevy ChildOf+Children pair, holder\n// perspective) + proposition 3 (machine-readable schema:\n// `componentSchema(Children).entities === 'array<entity>'`) + proposition 4 (explicit\n// failure: dangling entries surface to the AI user via `world.get(parent, Entity)` liveness probe,\n// not silent drop) + proposition 5 (consistent abstraction: Children is the\n// generic relationship-mirror shape, not a ChildOf special case).\n\nimport { defineRelationship } from '@forgeax/engine-ecs';\n\n/**\n * Hierarchy forward-list of child entities.\n *\n * `entities` is a variable-length `array<entity>` field; each element is\n * an `Entity` u32 the AI user pushed via\n * `world.push(parent, Children, 'entities', child)`. The value returned by\n * `world.get(parent, Children).unwrap().entities` is a read-only\n * `Uint32Array` snapshot rematerialised fresh on every read (D-4 no-cache);\n * the snapshot's `length` equals the live element count.\n *\n * Invariants:\n * - Children is NOT consumed by `propagateTransforms` (which walks ChildOf\n * upward, D-P2). The forward list is for AI-user traversal / debug /\n * inspection.\n * - Children <-> ChildOf consistency is maintained by the engine via the\n * ChildOf `relationship` mirror hook (see ./child-of.ts): adding /\n * removing / reparenting ChildOf on a child auto-updates the parent's\n * `entities` list. AI users do not hand-sync the two sides for the\n * hierarchy.\n * - Stored entity u32s are NOT auto-cleared when the referenced entity is\n * despawned (OOS-01 above); a `world.get(despawnedChild, ...)` call\n * returns `Result.err(...)` so AI users discover the dangling state\n * through the engine's structured-error channel.\n *\n * @example Spawn a parent and two children via ChildOf (engine maintains Children):\n * const parent = world.spawn({ component: Transform, data: identityXf() }).unwrap();\n * const a = world.spawn(\n * { component: Transform, data: identityXf() },\n * { component: ChildOf, data: { parent } },\n * ).unwrap();\n * const b = world.spawn(\n * { component: Transform, data: identityXf() },\n * { component: ChildOf, data: { parent } },\n * ).unwrap();\n * // Read back via the read-only snapshot - engine appended a, b:\n * const snap = world.get(parent, Children).unwrap().entities;\n * for (let i = 0; i < snap.length; i++) {\n * const child = snap[i];\n * // ... consume; world.get(child, ...) surfaces a structured error\n * // if the child has been despawned (OOS-01 dangling-entity surface).\n * }\n */\nexport const { source: ChildOf, target: Children } = defineRelationship({\n sourceName: 'ChildOf',\n sourceField: 'parent',\n targetName: 'Children',\n targetField: 'entities',\n exclusive: true,\n linkedSpawn: true,\n});\n","// Scene-owned hierarchy traversal shared by scene collection and render hooks.\n\nimport type { EntityHandle, World } from '@forgeax/engine-ecs';\n\nimport { Children } from './components/children';\n\n/** Walk a Children hierarchy breadth-first, reusing an optional visited set. */\nexport function collectSubtree(\n world: World,\n spawnRoot: EntityHandle,\n visited?: Set<number>,\n): Set<number> {\n if (visited === undefined) visited = new Set<number>();\n if (visited.has(spawnRoot as number)) return visited;\n const queue: number[] = [spawnRoot as number];\n visited.add(spawnRoot as number);\n while (queue.length > 0) {\n const current = queue.shift() as number;\n const children = world.get(current as EntityHandle, Children);\n if (!children.ok) continue;\n const entities = children.value.entities as ArrayLike<number>;\n for (let index = 0; index < entities.length; index += 1) {\n const child = entities[index] as number;\n if (visited.has(child)) continue;\n visited.add(child);\n queue.push(child);\n }\n }\n return visited;\n}\n","import { defineComponent } from '@forgeax/engine-ecs';\n\n/** Per-entity morph weights; length is validated against the mesh target count. */\nexport const MorphWeights = defineComponent('MorphWeights', {\n weights: { type: 'array<f32>' },\n});\n","// @forgeax/engine-runtime --- Name component (built-in identifier).\n//\n// Single-field minimal skeleton: { value: 'string' }. Bare 'string' schema\n// vocab keyword routes through ECS UniqueRefStore (D-R3 single-arm managed\n// dispatch); the read shape is a native JS string.\n//\n// Lives in `runtime` rather than `ecs` because Name is a built-in *component*,\n// not part of the ECS framework itself (it does not participate in archetype /\n// query / world mechanics like the essential `Entity` component does). Mirrors\n// Bevy's split: `Entity` lives in `bevy_ecs`; `Name` lives in `bevy_core`.\n//\n// Migrated from packages/ecs/src/name.ts by tweak-20260612-ecs-concept-compression\n// (architecture-principles.md §1 SSOT: Name's authoritative location is the\n// runtime built-in components surface, not the ECS framework barrel).\n//\n// Naming follows the Bevy-aligned convention locked by feat-20260513:\n// single-semantic component drops the 'Component' suffix (Transform / Camera\n// / DirectionalLight / Name).\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\nexport const Name = defineComponent('Name', { value: { type: 'string' } });\n","// @forgeax/engine-runtime - Transform (local TRS + world mat4).\n//\n// Schema: three local array<f32, N> columns -- pos (3-vec position), quat\n// (4-quat rotation, component order [x, y, z, w]), scale (3-vec scale) --\n// plus one `world: array<f32, 16>` field carrying the resolved world-space\n// mat4 (column-major 16 floats, written by the propagate kernel each frame).\n// Inline stride-N array columns (feat-20260602) store each row's N floats\n// contiguously, so per-row xyz locality is native to the column layout; the\n// former per-axis scalar decomposition (10 f32 columns) predates\n// inline array columns and was retired in feat-20260709 M2.\n//\n// The world column is the SSOT for the resolved world transform: a root's\n// world equals its local mat4; a child's world equals parent.world x local.\n// AI users author the local TRS arrays and read the derived world mat4 via\n// the ECS column-level array view (`world.get(e, Transform).world` -> live\n// Float32Array of 16 column-major floats). They MUST NOT hand-write the\n// world column -- it is overwritten by propagate.\n//\n// charter mapping: P1 (progressive disclosure via defaults map -- AI users\n// spawn with data: {} and get identity local TRS + identity world mat4),\n// F1 (context-limited: single-import barrel; 3 array keys replace 10 scalar\n// keys at every spawn call-site), P4 (consistent abstraction: pos / quat /\n// scale array columns follow the same access pattern as `world` -- learn\n// the flat column form once, apply it to every array<f32, N> field),\n// P3 (machine-readable schema > prose).\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\n// Column-major identity mat4 (16 floats) used as the world-column default so\n// `spawn({ component: Transform, data: {} })` lands an identity world view\n// before the first propagate pass writes the resolved transform.\nconst IDENTITY_MAT4 = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);\n\n/**\n * Transform: local position `pos` (xyz), rotation `quat` (quaternion,\n * component order [x, y, z, w]), scale `scale` (xyz), plus the resolved\n * `world` mat4 (column-major 16 floats).\n *\n * Local TRS is stored as three inline stride-N array<f32, N> columns. The\n * propagate kernel composes each entity's local TRS into a mat4 and writes it\n * into the `world` column (root: world = local; child: world = parent.world x\n * local) using `@forgeax/engine-math` mat4 / vec3 / quat APIs (charter P4: do\n * not reinvent math). MVP recomposes every frame; dirty-flag optimization is\n * owned by feat-future-render-world.\n *\n * The `world` column is a fixed-capacity `array<f32, 16>` (feat-20260602):\n * the 16 contiguous floats live inline in a stride-16 column -- no BufferPool\n * slot. Read it via `world.get(e, Transform).world` which returns a live\n * `Float32Array` aliasing the column buffer. The view is transient: it aliases\n * the archetype column buffer and is valid only until the next structural\n * change (spawn / despawn / addComponent / removeComponent). Re-fetch the view\n * on every access; holding a view across a structural change is undefined\n * behaviour (the backing `ArrayBuffer` is detached on column growth, and\n * swap-remove at the same row index points to the wrong entity). All existing\n * hot paths (propagate / render-extract / pick) already comply -- see\n * `packages/ecs/README.md` Transient view contract section.\n *\n * All three local columns carry explicit layer-2 defaults (identity\n * transform): `pos: [0, 0, 0]`, `quat: [0, 0, 0, 1]` (identity quaternion,\n * [x, y, z, w]), `scale: [1, 1, 1]`. quat and scale MUST stay explicit: the\n * layer-3 fallback for array<f32, N> is all-zero, which would land an invalid\n * zero quaternion / zero scale. The `world` field defaults to the identity\n * mat4. AI users spawn with `data: {}` or with only the fields they need to\n * override.\n *\n * @example Minimal spawn (local defaulted to identity, world = identity mat4):\n * world.spawn({ component: Transform, data: {} });\n *\n * @example Override only the position, leaving rotation/scale at identity:\n * world.spawn({ component: Transform, data: { pos: [0, 6, 0] } });\n *\n * @example Full explicit local form (defaults are opt-in):\n * world.spawn({ component: Transform, data: {\n * pos: [1, 2, 3],\n * quat: [0, 0, 0, 1], // [x, y, z, w]\n * scale: [1, 1, 1],\n * } });\n */\nexport const Transform = defineComponent('Transform', {\n pos: { type: 'array<f32, 3>', default: new Float32Array([0, 0, 0]) },\n // Component order [x, y, z, w] end to end (glTF-aligned; E6).\n quat: { type: 'array<f32, 4>', default: new Float32Array([0, 0, 0, 1]) },\n scale: { type: 'array<f32, 3>', default: new Float32Array([1, 1, 1]) },\n // `world` is field-level transient (D-5): scene collect skips it. The resolved\n // world mat4 is derived by the propagate kernel from the persisted local TRS\n // each frame, so serializing it would store reconstructable data (SSOT: local\n // TRS). Round-trip re-derives an equivalent world on the first propagate pass.\n world: { type: 'array<f32, 16>', default: IDENTITY_MAT4, transient: true },\n});\n","import type { EntityHandle } from '@forgeax/engine-ecs';\n\nexport type SceneErrorCode = 'hierarchy-broken' | 'hierarchy-cycle';\n\n/** Scene-instantiation failures owned by the scene package. */\nexport type SceneInstanceErrorCode = 'component-not-defined' | 'scene-override-type-mismatch';\n\nexport { ComponentNotDefinedError } from '@forgeax/engine-ecs/projection';\n\nexport interface SceneErrorDetail {\n readonly entity: EntityHandle;\n readonly parent: EntityHandle;\n}\n\nexport class SceneError extends Error {\n readonly code: SceneErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: SceneErrorDetail | undefined;\n\n constructor(args: {\n code: SceneErrorCode;\n expected: string;\n hint: string;\n detail?: SceneErrorDetail;\n }) {\n super(`[SceneError ${args.code}] expected: ${args.expected}; hint: ${args.hint}`);\n this.name = 'SceneError';\n this.code = args.code;\n this.expected = args.expected;\n this.hint = args.hint;\n this.detail = args.detail;\n }\n}\n","/** Immutable Scene collection policy shared by runtime collectors. */\nexport interface SceneCollectProfile {\n readonly includeComponent: (componentName: string, transient: boolean) => boolean;\n readonly includeField: (componentName: string, fieldName: string, transient: boolean) => boolean;\n}\n\nexport const SCENE_COLLECT_PROFILE: SceneCollectProfile = Object.freeze({\n includeComponent: (_componentName: string, transient: boolean) => !transient,\n includeField: (_componentName: string, _fieldName: string, transient: boolean) => !transient,\n});\n","import type { AssetRef, MountOverride, SceneAsset } from '@forgeax/engine-types';\nimport { err, ok, type Result } from '@forgeax/engine-types';\n\nexport type SceneComponentSchemaResolver = (\n componentName: string,\n) => Readonly<Record<string, string>> | undefined;\n\nexport interface SceneExternalizationError {\n readonly field: string;\n readonly value: unknown;\n}\n\nexport interface ExternalizedSceneAsset {\n readonly payload: Record<string, unknown>;\n readonly refs: readonly AssetRef[];\n}\n\nfunction sharedKind(type: string | undefined): 'one' | 'many' | undefined {\n if (type?.startsWith('shared<')) return 'one';\n if (type?.startsWith('array<shared<')) return 'many';\n return undefined;\n}\n\nfunction overrideGuids(\n override: MountOverride,\n resolveSchema: SceneComponentSchemaResolver,\n): readonly { field: string; guid: string }[] {\n const schema = resolveSchema(override.comp);\n const values =\n override.field !== undefined\n ? [[override.field, override.value] as const]\n : override.value !== null &&\n typeof override.value === 'object' &&\n !Array.isArray(override.value)\n ? Object.entries(override.value as Record<string, unknown>)\n : [];\n return values.flatMap(([field, value]) => {\n const kind = sharedKind(schema?.[field]);\n if (kind === 'one' && typeof value === 'string') return [{ field, guid: value }];\n if (kind === 'many' && Array.isArray(value)) {\n return value.flatMap((item) => (typeof item === 'string' ? [{ field, guid: item }] : []));\n }\n return [];\n });\n}\n\n/** Project a SceneAsset's shared asset fields into a payload plus indexed refs. */\nexport function externalizeSceneAsset(\n scene: SceneAsset,\n resolveSchema: SceneComponentSchemaResolver,\n): Result<ExternalizedSceneAsset, SceneExternalizationError> {\n const refs: AssetRef[] = [];\n const indexByGuid = new Map<string, number>();\n const addRef = (\n guid: string,\n sourceField: NonNullable<AssetRef['sourceField']>,\n sceneEntityId?: number,\n ): number => {\n const prior = indexByGuid.get(guid);\n if (prior !== undefined) return prior;\n const index = refs.length;\n refs.push({ guid, sourceField, ...(sceneEntityId === undefined ? {} : { sceneEntityId }) });\n indexByGuid.set(guid, index);\n return index;\n };\n\n const entities = scene.entities.map((entity) => {\n const components: Record<string, Record<string, unknown>> = {};\n for (const componentName of Object.keys(entity.components)) {\n const schema = resolveSchema(componentName);\n const source = entity.components[componentName] as Record<string, unknown> | undefined;\n if (source === undefined) continue;\n const fields: Record<string, unknown> = {};\n for (const fieldName of Object.keys(source)) {\n const value = source[fieldName];\n if (value === undefined) continue;\n const kind = sharedKind(schema?.[fieldName]);\n if (kind === 'one' && typeof value === 'string') {\n fields[fieldName] = addRef(value, { componentName, fieldName }, entity.localId as number);\n } else if (kind === 'many' && Array.isArray(value)) {\n fields[fieldName] = value.map((item, arrayIndex) =>\n typeof item === 'string'\n ? addRef(item, { componentName, fieldName, arrayIndex }, entity.localId as number)\n : item,\n );\n } else {\n fields[fieldName] = value;\n }\n }\n if (Object.keys(fields).length > 0 || Object.keys(schema ?? {}).length === 0) {\n components[componentName] = fields;\n }\n }\n return { localId: entity.localId as number, components };\n });\n\n const mounts = scene.mounts?.map((mount) => {\n const source =\n typeof mount.source === 'string'\n ? addRef(\n mount.source,\n { componentName: 'SceneInstance', fieldName: 'source' },\n mount.localId as number,\n )\n : (mount.source as number);\n for (const { field, guid } of (mount.overrides ?? []).flatMap((override) =>\n overrideGuids(override, resolveSchema),\n )) {\n addRef(guid, { componentName: 'SceneInstance', fieldName: `overrides.${field}` });\n }\n return {\n localId: mount.localId as number,\n source,\n memberFirst: mount.memberFirst as number,\n memberCount: mount.memberCount,\n ...(mount.parent === undefined ? {} : { parent: mount.parent as number }),\n ...(mount.publicationFence === undefined ? {} : { publicationFence: mount.publicationFence }),\n ...(mount.overrides === undefined\n ? {}\n : { overrides: mount.overrides.map((item) => ({ ...item })) }),\n };\n });\n for (const [arrayIndex, guid] of (scene.skinGuids ?? []).entries()) {\n if (typeof guid !== 'string') return err({ field: 'skinGuids', value: guid });\n addRef(guid, { componentName: '<scene>', fieldName: 'skinGuids', arrayIndex });\n }\n return ok({\n payload: {\n entities,\n ...(mounts === undefined || mounts.length === 0 ? {} : { mounts }),\n ...(scene.skinGuids === undefined\n ? {}\n : { skinGuids: scene.skinGuids.map((guid) => indexByGuid.get(guid) as number) }),\n },\n refs,\n });\n}\n","// @forgeax/engine-scene — scene instantiation and instance-state subsystem.\n\nimport {\n type Component,\n type ComponentData,\n type ComponentSchema,\n type EcsError,\n ENTITY_NULL_RAW,\n type EntityHandle,\n type InputShapeOf,\n type ShapeOf,\n type World,\n} from '@forgeax/engine-ecs';\nimport { classifyEntityField, remapEntityFieldValue } from '@forgeax/engine-ecs/externalization';\nimport { componentSchema } from '@forgeax/engine-ecs/internal';\nimport { fillComponentDefaults, StaleEntityError } from '@forgeax/engine-ecs/projection';\nimport type {\n Handle,\n LocalEntityId,\n MountOverride,\n PackErrorCode,\n PackErrorDetail,\n SceneAsset,\n SceneInstanceMount,\n} from '@forgeax/engine-types';\nimport {\n err,\n ok,\n PACK_ERROR_HINTS,\n type Result,\n toUnique,\n unwrapHandle,\n} from '@forgeax/engine-types';\nimport { ComponentNotDefinedError } from '../errors';\n\nconst entityIndex = (entity: EntityHandle): number => (entity as number) & 0x00ffffff;\nconst entityGeneration = (entity: EntityHandle): number => ((entity as number) >>> 24) & 0xff;\n\n/**\n * C-R2 (feat-20260622-s5 / studio-issues): one structured, non-fatal record of\n * a SceneAsset payload field that did NOT match the target component's schema.\n *\n * Scene data is loader-fed and may carry a stale / deprecated / typo'd field\n * (an editor renames a field, an old `.pack.json` lags). `worldInstantiateScene`\n * does NOT blank the whole scene over one such field (#478 lesson: a\n * prod-silent strip re-introduced an invisible-entity class) and does NOT abort\n * fatally. Instead it skips the unknown key (no write, no input mutation) and\n * surfaces this record on the success value's `diagnostics[]` — observable in\n * production (NOT NODE_ENV-gated), consumed by property access (no string parse):\n *\n * const r = worldInstantiateScene(world, handle);\n * if (r.ok) for (const d of r.value.diagnostics)\n * console.warn(`unknown field ${d.component}.${d.field} on localId ${d.localId}`);\n *\n * Direct `world.spawn` / `world.addComponent` / `Commands.spawn` stay fail-fast\n * with `SpawnDataUnknownFieldError` — those are explicit API calls where a typo\n * is a programming error, not loader-fed data.\n */\nexport type SceneInstantiateDiagnostic = {\n /** Component name (schema key) the unknown field appeared under. */\n readonly component: string;\n /** The offending field name not declared in the component schema. */\n readonly field: string;\n /** LocalEntityId (within its owning SceneAsset) of the carrying entity. */\n readonly localId: number;\n};\n\n/**\n * Success value of `worldInstantiateScene`. `root` is the synthetic scene-root\n * EntityHandle (carries `SceneInstance`); `diagnostics` is the (possibly empty)\n * list of non-fatal unknown-field records aggregated across this scene and every\n * recursively mounted sub-scene (C-R2). Empty array = no diagnostics.\n */\nexport type SceneInstantiateOk = {\n readonly root: EntityHandle;\n readonly diagnostics: readonly SceneInstantiateDiagnostic[];\n};\n\n/**\n * Success value of `worldInstantiateSceneFlat` — the \"edit the scene itself\"\n * primitive. Unlike `instantiateScene`, NO synthetic SceneInstance root is\n * minted and NO `ChildOf` is forced onto top-level members: the scene's own\n * entities become plain top-level world entities whose hierarchy is exactly\n * their authored `ChildOf` (an entity with no `ChildOf` stays a root). `roots`\n * is the set of those top-level handles (own rootless entities + top-level\n * mount carriers). Nested prefabs inside the scene STILL materialise as their\n * own SceneInstance anchors (charter P4: instance == entity-with-SceneInstance)\n * — only THIS scene is flat.\n */\nexport type SceneInstantiateFlatOk = {\n readonly roots: EntityHandle[];\n /**\n * All mount carrier entities spawned while flattening this scene. These are\n * separate from `roots`: carriers with an authored parent are not roots,\n * but still delimit a nested prefab subtree for post-spawn hooks.\n */\n readonly mountEntities: EntityHandle[];\n readonly diagnostics: readonly SceneInstantiateDiagnostic[];\n};\n\n/**\n * @internal Intermediate produced by `_spawnSceneMembers` and consumed by both\n * the anchor finisher (`_instantiateSceneAsset`) and the flat finisher\n * (`_instantiateSceneAssetFlat`). Holds everything the shared member-spawn\n * (mounts recursion + own-entity spawn + deferred owned-parent wiring) computes,\n * before either finisher decides whether to wrap the members in a synthetic\n * SceneInstance root.\n */\nexport interface SceneMembersSpawn {\n /** LocalEntityId → live Entity u32 (ENTITY_NULL_RAW for unspawned slots). */\n readonly mapping: Uint32Array;\n /** Reverse map live Entity → LocalEntityId for override / detach bookkeeping. */\n readonly entityToLocalId: Map<EntityHandle, LocalEntityId>;\n /** Own entities that carried no `ChildOf` — the scene's authored top-level roots. */\n readonly rootEntities: EntityHandle[];\n /** Mount carriers whose `mount.parent === undefined` (default-parented). */\n readonly mountEntitiesNeedingRootParent: EntityHandle[];\n /** Every mount carrier spawned by this scene, including explicitly parented carriers. */\n readonly mountEntities: EntityHandle[];\n /**\n * The child anchor and mapping for each mount. Flat scene opening has no\n * outer SceneInstance state to own parent-namespace mount overrides, so it\n * records those overrides on this child anchor after the shared spawn pass.\n */\n readonly mountInstances: readonly {\n readonly mount: SceneInstanceMount;\n readonly root: EntityHandle;\n readonly mapping: Uint32Array;\n }[];\n /** `entities.length + mounts + Σ memberCount`, captured at instantiate-time. */\n readonly totalSlots: number;\n}\n\nexport type SceneAssetResolver = (\n source: number | string,\n parentHandle: Handle<'SceneAsset', 'shared'>,\n) => Result<Handle<'SceneAsset', 'shared'>, unknown>;\n\ninterface SceneWorldState {\n resolver: SceneAssetResolver | null;\n readonly statePayloads: Map<number, unknown>;\n}\n\nconst sceneWorldStates = new WeakMap<World, SceneWorldState>();\n\nfunction sceneWorldState(world: World): SceneWorldState {\n const current = sceneWorldStates.get(world);\n if (current !== undefined) return current;\n const created = { resolver: null, statePayloads: new Map<number, unknown>() };\n sceneWorldStates.set(world, created);\n return created;\n}\n\n/** @internal */\nexport function worldSetSceneAssetResolver(world: World, resolver: SceneAssetResolver): void {\n sceneWorldState(world).resolver = resolver;\n}\n\n/** @internal */\nexport function worldGetSceneAssetResolver(world: World): SceneAssetResolver | null {\n return sceneWorldState(world).resolver;\n}\n\n/**\n * Materialise a SceneAsset (and any nested SceneAsset references via\n * `mounts[]`) into live entities. Returns the synthetic root Entity that\n * carries the `SceneInstance` ECS component (charter P4: instance ==\n * entity-with-SceneInstance).\n *\n * Recursion path is closed inside `_instantiateSceneRec(handle, parent,\n * stack)` (D-3); cycle detection is fail-fast `pack-cyclic-reference +\n * detail.kind:'mount-asset'` (D-1 mirror, plan-strategy §D-3). The\n * caller-supplied `parent` flows to the synthetic root's `ChildOf` so the\n * full sub-tree attaches under the AI user's host entity.\n *\n * @example\n * const r = worldInstantiateScene(world, handle);\n * if (!r.ok) return r;\n * const { root, diagnostics } = r.value;\n * for (const d of diagnostics) // C-R2: unknown-field records, non-fatal\n * console.warn(`unknown field ${d.component}.${d.field} on localId ${d.localId}`);\n * const inst = world.get(root, SceneInstance).value;\n * const member = inst.mapping[0]; // first member entity\n */\nexport function worldInstantiateScene(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n parent?: EntityHandle,\n): Result<SceneInstantiateOk, EcsError> {\n const stack = new Set<number>();\n // C-R2: collect non-fatal unknown-field diagnostics across this scene and\n // every recursively mounted sub-scene. The internal recursion writes into\n // this accumulator; only the public entry packages it onto the success value.\n const diagnostics: SceneInstantiateDiagnostic[] = [];\n const r = worldInstantiateSceneRec(world, handle, parent, stack, diagnostics);\n if (!r.ok) return r;\n return ok({ root: r.value, diagnostics });\n}\n\n/**\n * Materialise a projected `SceneAsset` payload without exposing the temporary\n * shared-ref handle to the caller. The World remains the owner of both the\n * handle and the instantiated SceneInstance: the producer grant is released\n * after the SceneInstance retains its source, including when instantiation\n * fails. This is the payload-shaped counterpart to `worldInstantiateScene` for\n * hosts that load a SceneAsset directly from the Engine AssetRegistry.\n */\nexport function worldInstantiateScenePayload(\n world: World,\n asset: SceneAsset,\n parent?: EntityHandle,\n): Result<SceneInstantiateOk, EcsError> {\n const handle = world.allocSharedRef('SceneAsset', asset);\n try {\n return worldInstantiateScene(world, handle, parent);\n } finally {\n // The SceneInstance source column retains the handle on success. On a\n // failed materialisation there should be no remaining holder; either way\n // release the producer grant owned by this convenience entrypoint.\n world.sharedRefs.release(handle);\n }\n}\n\n/**\n * Materialise a SceneAsset FLAT — the \"edit the scene itself\" primitive.\n * Unlike `instantiateScene`, this mints NO synthetic SceneInstance root and\n * forces NO `ChildOf` onto top-level members: the scene's own entities become\n * plain top-level world entities whose hierarchy is exactly their authored\n * `ChildOf` (an entity with no `ChildOf` is a root). Use this to OPEN a scene\n * for editing; use `instantiateScene` (anchor) at runtime / for nested\n * prefabs where an instance boundary + override isolation is wanted.\n *\n * Nested prefabs referenced via `mounts[]` STILL materialise as their own\n * SceneInstance anchors (charter P4 preserved) — only THIS top scene is flat.\n *\n * @example\n * const r = worldInstantiateSceneFlat(world, handle);\n * if (!r.ok) return r;\n * const { roots, diagnostics } = r.value; // roots = top-level handles\n */\nexport function worldInstantiateSceneFlat(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n): Result<SceneInstantiateFlatOk, EcsError> {\n const stack = new Set<number>();\n const diagnostics: SceneInstantiateDiagnostic[] = [];\n const handleKey = unwrapHandle(handle);\n const resolved = worldResolveSceneAsset(world, handle);\n if (!resolved.ok) return resolved;\n stack.add(handleKey);\n let r: Result<{ roots: EntityHandle[]; mountEntities: EntityHandle[] }, EcsError>;\n try {\n r = worldInstantiateSceneAssetFlat(world, handle, resolved.value, stack, diagnostics);\n } finally {\n stack.delete(handleKey);\n }\n if (!r.ok) return r;\n return ok({ ...r.value, diagnostics });\n}\n/**\n * @internal Recursive helper carrying the cycle-detection stack. Sugar /\n * other public callers must not see this mechanic — use `instantiateScene`\n * (D-3 / charter P1).\n */\nexport function worldInstantiateSceneRec(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n parent: EntityHandle | undefined,\n stack: Set<number>,\n diagnostics: SceneInstantiateDiagnostic[],\n): Result<EntityHandle, EcsError> {\n const handleKey = unwrapHandle(handle);\n if (stack.has(handleKey)) {\n const cycleArr: string[] = [];\n for (const k of stack) cycleArr.push(String(k));\n cycleArr.push(String(handleKey));\n const detail: PackErrorDetail = {\n code: 'pack-cyclic-reference',\n kind: 'mount-asset',\n cycle: cycleArr,\n };\n return err({\n code: 'pack-cyclic-reference' as PackErrorCode,\n expected: 'acyclic SceneAsset mount graph',\n hint: PACK_ERROR_HINTS['pack-cyclic-reference'],\n detail,\n } as unknown as EcsError);\n }\n const resolved = worldResolveSceneAsset(world, handle);\n if (!resolved.ok) return resolved;\n const asset = resolved.value;\n stack.add(handleKey);\n try {\n return worldInstantiateSceneAsset(world, handle, asset, parent, stack, diagnostics);\n } finally {\n stack.delete(handleKey);\n }\n}\n/**\n * @internal Resolve a SceneAsset handle through the SharedRefStore.\n * The handle u32 is the SharedRefStore slot id (`world.allocSharedRef\n * ('SceneAsset', asset)` is the producer; rc starts at 1, the SceneInstance\n * spawn retains to rc=2 in M4 / w13). Errors propagate as EcsError so the\n * instantiateScene chain returns a single closed union.\n */\nexport function worldResolveSceneAsset(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n): Result<SceneAsset, EcsError> {\n const r = world.sharedRefs.resolve(handle);\n if (!r.ok) {\n return err(r.error as unknown as EcsError);\n }\n return ok(r.value as SceneAsset);\n}\n/**\n * @internal Spawn one SceneAsset's members — the shared body of both scene\n * finishers. Recurses into `mounts[]` (each nested prefab becomes its own\n * SceneInstance anchor), spawns `entities[]` honouring their authored\n * `ChildOf`, and wires deferred owned-parent mount edges. Does NOT create a\n * synthetic root or force any `ChildOf` — that is the caller's (finisher's)\n * job. `_instantiateSceneRec` owns cycle bookkeeping.\n */\nexport function worldSpawnSceneMembers(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n asset: SceneAsset,\n stack: Set<number>,\n diagnostics: SceneInstantiateDiagnostic[],\n): Result<SceneMembersSpawn, EcsError> {\n const sceneInstanceToken = world.components.resolve('SceneInstance');\n if (sceneInstanceToken === undefined) {\n return err(new ComponentNotDefinedError('SceneInstance'));\n }\n const childOfToken = world.components.resolve('ChildOf');\n // ChildOf is optional — only needed if the asset declares ChildOf or a\n // caller-supplied parent must be wired. If absent and we need it, we\n // fail-fast at the wiring site below.\n\n const ownEntities = asset.entities;\n const ownMounts = asset.mounts ?? [];\n const memberSum = ownMounts.reduce((s, m) => s + m.memberCount, 0);\n const countBaseline = ownEntities.length + ownMounts.length + memberSum;\n // C-R1 (studio-issues #6): mapping table must be sized to maxLocalId+1,\n // not to the entity count. An editor scene may have non-contiguous\n // localIds (deleted entities leave gaps); sizing to count means any\n // localId >= count is a silent Uint32Array OOB no-op -> entity spawns\n // but is unreachable by localId -> users report \"character can't move\".\n // Take the max of count-baseline and id-range so both packed and\n // sparse scenes work without over-allocation in the common case.\n let maxLocalId = ownEntities.reduce((m, e) => Math.max(m, e.localId as unknown as number), -1);\n for (const mount of ownMounts) {\n maxLocalId = Math.max(maxLocalId, mount.localId as unknown as number);\n const last = (mount.memberFirst as unknown as number) + mount.memberCount - 1;\n maxLocalId = Math.max(maxLocalId, last);\n }\n const totalSlots = Math.max(countBaseline, maxLocalId + 1);\n\n // R2/Bonus: namespace-overlap fail-fast (AC-05 /\n // pack-mount-localid-overlap). Each LocalEntityId in\n // [0, totalSlots) must be claimed by exactly one of:\n // - entities[i].localId\n // - mounts[i].localId\n // - mounts[i] window slot (memberFirst .. memberFirst+memberCount-1)\n // Overlap or duplicate claim => fail-fast with the offending localIds\n // and human-readable origin labels.\n {\n const claims = new Map<number, string>();\n const overlapLids = new Set<number>();\n const overlapSources: string[] = [];\n const claim = (lid: number, src: string): void => {\n const prior = claims.get(lid);\n if (prior !== undefined) {\n if (!overlapLids.has(lid)) {\n overlapLids.add(lid);\n overlapSources.push(prior);\n overlapSources.push(src);\n } else {\n overlapSources.push(src);\n }\n return;\n }\n claims.set(lid, src);\n };\n for (const ent of ownEntities) {\n claim(ent.localId as unknown as number, `entities[${ent.localId as unknown as number}]`);\n }\n for (const mount of ownMounts) {\n const mLid = mount.localId as unknown as number;\n claim(mLid, `mount[${mLid}]`);\n const first = mount.memberFirst as unknown as number;\n for (let k = 0; k < mount.memberCount; k += 1) {\n claim(first + k, `mount[${mLid}].member[${k}]`);\n }\n }\n if (overlapLids.size > 0) {\n const overlapping = Array.from(overlapLids).sort((a, b) => a - b);\n return err({\n code: 'pack-mount-localid-overlap' as PackErrorCode,\n expected: 'each LocalEntityId claimed by exactly one entity or mount slot',\n hint: PACK_ERROR_HINTS['pack-mount-localid-overlap'],\n detail: {\n code: 'pack-mount-localid-overlap',\n overlapping,\n sources: overlapSources,\n } as PackErrorDetail,\n } as unknown as EcsError);\n }\n }\n\n // Slot table: indexed by LocalEntityId; populated as entities / mounts /\n // members are spawned. mapping[localId] = encoded Entity u32. Unspawned\n // slots hold ENTITY_NULL_RAW (0xffffffff) — NOT 0, because a fresh World's\n // first spawn encodes to gen=0+idx=0=raw 0, which is a valid Entity. The\n // remap path in `_buildSceneEntityComponentDatas` distinguishes the two\n // (live=ENTITY_NULL_RAW => parent unspawned at remap time => surface as\n // null sentinel; live=any other u32 => valid live Entity, including 0).\n const mapping = new Uint32Array(totalSlots).fill(ENTITY_NULL_RAW);\n const entityToLocalId = new Map<EntityHandle, LocalEntityId>();\n const rootEntities: EntityHandle[] = [];\n const mountEntities: EntityHandle[] = [];\n // R2/B-1: mount entities whose `mount.parent === undefined` need their\n // ChildOf wired to the outer synthetic root (this scene's root). Step 5\n // does the wiring once the synthetic root entity is materialised; we\n // collect them here in step 1.\n const mountEntitiesNeedingRootParent: EntityHandle[] = [];\n // D-8 (feat-20260707): mount entities whose `mount.parent` points at an\n // OWNED entity slot are wired AFTER step 2 spawns the owned entities —\n // mounts are processed first (step 1), so the owned parent slot is still\n // ENTITY_NULL_RAW at mount-processing time. Same deferred-wiring shape as\n // mountEntitiesNeedingRootParent: register [mountEntity, parentSlot] here,\n // wire ChildOf once the slot is live. Without this the edge was silently\n // dropped, and the mount carrier stayed unreachable from its owned parent.\n const mountEntitiesNeedingDeferredParent: Array<[EntityHandle, number]> = [];\n const mountInstances: Array<{\n readonly mount: SceneInstanceMount;\n readonly root: EntityHandle;\n readonly mapping: Uint32Array;\n }> = [];\n\n // 1. Recurse into mounts[] FIRST so the mount-window slots\n // (`mount.localId` + `[memberFirst, memberFirst+memberCount)`) are\n // populated before any owned entity tries to remap a LocalEntityId\n // pointing into the mount window (AC-24 cross-boundary reference).\n for (const mount of ownMounts) {\n // R2/B-3 + R2/B-4: validate overrides BEFORE child resolution so a\n // malformed override fails fast without observable side-effects.\n const overrideValidationRes = worldValidateMountOverrides(world, mount);\n if (!overrideValidationRes.ok) {\n return overrideValidationRes;\n }\n\n // Spawn the mount entity (carries mount.components).\n const mountLid = mount.localId as unknown as number;\n const mountSpawnRes = worldSpawnMountEntity(world, mount, mapping, diagnostics);\n if (!mountSpawnRes.ok) return mountSpawnRes;\n const mountEntity = mountSpawnRes.value;\n mountEntities.push(mountEntity);\n mapping[mountLid] = mountEntity as unknown as number;\n\n // Resolve mount.source -> child SceneAsset handle.\n const childHandleRes = worldResolveMountSource(world, mount.source, handle);\n if (!childHandleRes.ok) return childHandleRes;\n const childHandle = childHandleRes.value;\n\n // Recursively instantiate the child. Its synthetic root attaches as a\n // child of the mount entity. The child writes its own unknown-field\n // diagnostics into the SAME accumulator, so they bubble to the top-level\n // instantiateScene result (C-R2 recursive aggregation).\n const childRes = worldInstantiateSceneRec(world, childHandle, mountEntity, stack, diagnostics);\n if (!childRes.ok) return childRes;\n\n // R2/B-2: cross-check mount.memberCount === child.totalSlots BEFORE\n // copying the mount window. The child SceneInstance.mapping length is\n // the authoritative `totalSlots` of the child. AC-04 / requirements\n // S-5 mandate fail-fast at runtime for this disagreement.\n const childInstRes = world.get(childRes.value, sceneInstanceToken);\n if (!childInstRes.ok) return childInstRes;\n const childMapping = (childInstRes.value as unknown as { mapping: Uint32Array }).mapping;\n mountInstances.push({ mount, root: childRes.value, mapping: childMapping });\n if (childMapping.length !== mount.memberCount) {\n return err({\n code: 'pack-mount-count-mismatch' as PackErrorCode,\n expected: 'mount.memberCount === child SceneAsset totalSlots',\n hint: PACK_ERROR_HINTS['pack-mount-count-mismatch'],\n detail: {\n code: 'pack-mount-count-mismatch',\n mountLocalId: mountLid,\n declared: mount.memberCount,\n actual: childMapping.length,\n } as PackErrorDetail,\n } as unknown as EcsError);\n }\n\n // Pull the child's mapping into our parent window. Default unset slots\n // to ENTITY_NULL_RAW so downstream \"live\" checks distinguish them from\n // the first Entity (gen=0+idx=0 encodes to raw u32 0).\n const window = mount.memberCount;\n for (let k = 0; k < window; k += 1) {\n mapping[(mount.memberFirst as unknown as number) + k] = childMapping[k] ?? ENTITY_NULL_RAW;\n }\n\n // Apply mount.overrides at instantiate-time (AC-19).\n // Each override.localId addresses a slot in *this* (parent) namespace\n // (R2/F-8 cement: parent-namespace + memberFirst+offset addressing).\n // The state map will be populated below with these overrides — but we\n // must also write the value through to the live entity column so the\n // readback invariant holds.\n // Mount-entity itself never has children attached by the caller other\n // than via the recursive child; nothing else to wire here.\n if (childOfToken !== undefined) {\n if (mount.parent !== undefined) {\n // Reparent the mount-entity ChildOf to the caller-specified parent.\n const parentSlot = mount.parent as unknown as number;\n const parentEntity = mapping[parentSlot];\n if (parentEntity !== undefined && parentEntity !== ENTITY_NULL_RAW) {\n const r = world.addComponent(mountEntity, {\n component: childOfToken,\n data: { parent: parentEntity } as never,\n });\n if (!r.ok) {\n // ChildOf may already be present from layer-1; reparent via set.\n const set = world.set(mountEntity, childOfToken, {\n parent: parentEntity,\n } as never);\n if (!set.ok) return set as Result<SceneMembersSpawn, EcsError>;\n }\n } else {\n // D-8: the owned parent slot is not spawned yet (owned entities\n // spawn in step 2, after this mount loop). Defer the ChildOf wire\n // to step 2's tail once mapping[parentSlot] is live.\n mountEntitiesNeedingDeferredParent.push([mountEntity, parentSlot]);\n }\n } else {\n // R2/B-1: default semantic — mount.parent === undefined wires the\n // mount entity ChildOf to *this* scene's synthetic root (created\n // in step 3 below). Defer the actual wire to step 5 after the\n // synthetic root spawn; record the mount entity here.\n mountEntitiesNeedingRootParent.push(mountEntity);\n }\n }\n }\n\n // 2. Spawn entities[] entities. Topo-sort by ChildOf so parents are\n // spawned before children (so localId remap can read mapping live).\n // This runs AFTER mount processing (step 1) so cross-boundary\n // `ChildOf {parent: <mount-window-localId>}` references resolve\n // correctly (AC-24).\n const order = sceneTopoSort(ownEntities);\n for (const idx of order) {\n const node = ownEntities[idx];\n if (node === undefined) continue;\n const lid = node.localId as unknown as number;\n const compDataRes = worldBuildSceneEntityComponentDatas(world, node, mapping, diagnostics);\n if (!compDataRes.ok) return compDataRes;\n const sp = (world.spawn as (...c: ComponentData[]) => Result<EntityHandle, EcsError>)(\n ...compDataRes.value,\n );\n if (!sp.ok) return sp as Result<SceneMembersSpawn, EcsError>;\n const e = sp.value;\n mapping[lid] = e as unknown as number;\n entityToLocalId.set(e, lid as unknown as LocalEntityId);\n if (node.components.ChildOf === undefined) {\n rootEntities.push(e);\n }\n }\n\n // 2b. D-8 (feat-20260707): wire deferred owned-parent mount ChildOf edges.\n // Owned entities are now live (step 2 above), so mapping[parentSlot]\n // resolves. Same shape as the mountEntitiesNeedingRootParent wiring in\n // step 5. The relationship mirror hook (relationshipOnInsert) pushes the\n // carrier into the owned parent's Children mirror automatically.\n if (childOfToken !== undefined) {\n for (const [mountEntity, parentSlot] of mountEntitiesNeedingDeferredParent) {\n const parentEntity = mapping[parentSlot];\n if (parentEntity === undefined || parentEntity === ENTITY_NULL_RAW) continue;\n const set = world.set(mountEntity, childOfToken, { parent: parentEntity } as never);\n if (!set.ok) {\n const r = world.addComponent(mountEntity, {\n component: childOfToken,\n data: { parent: parentEntity } as never,\n });\n if (!r.ok) return r as Result<SceneMembersSpawn, EcsError>;\n }\n }\n }\n\n return ok({\n mapping,\n entityToLocalId,\n rootEntities,\n mountEntitiesNeedingRootParent,\n mountEntities,\n mountInstances,\n totalSlots,\n });\n}\n/**\n * @internal Spawn one SceneAsset's entities + apply mounts recursively, then\n * wrap them in a synthetic SceneInstance root (the anchor). This is the\n * runtime / Play / nested-mount finisher (charter P4: instance ==\n * entity-with-SceneInstance). Caller (`_instantiateSceneRec`) owns cycle\n * bookkeeping.\n */\nexport function worldInstantiateSceneAsset(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n asset: SceneAsset,\n parent: EntityHandle | undefined,\n stack: Set<number>,\n diagnostics: SceneInstantiateDiagnostic[],\n): Result<EntityHandle, EcsError> {\n const sceneInstanceToken = world.components.resolve('SceneInstance');\n if (sceneInstanceToken === undefined) {\n return err(new ComponentNotDefinedError('SceneInstance'));\n }\n const childOfToken = world.components.resolve('ChildOf');\n\n const membersRes = worldSpawnSceneMembers(world, handle, asset, stack, diagnostics);\n if (!membersRes.ok) return membersRes;\n const { mapping, entityToLocalId, rootEntities, mountEntitiesNeedingRootParent, totalSlots } =\n membersRes.value;\n const { mountInstances } = membersRes.value;\n const ownMounts = asset.mounts ?? [];\n\n // 3. Spawn the synthetic root entity carrying SceneInstance.\n // First alloc the state ref so the SceneInstance.state column has a\n // live u32; then attach SceneInstance to a fresh entity.\n let stateRef: Handle<'SceneInstanceState', 'unique'>;\n stateRef = world.allocUniqueRef('SceneInstanceState', null, () => {\n sceneWorldState(world).statePayloads.delete(Number(stateRef));\n });\n // Spawn the root with SceneInstance component, mapping snapshot, and\n // state ref. The mapping is a Uint32Array (array<entity> field shape).\n // Convert mapping Uint32Array to plain number[] for spawn write — the\n // ECS array<entity> arm copies element-by-element and accepts both, but\n // the plain-array form sidesteps a Uint32Array.length=0 corner case\n // observed during M2 testing where a non-empty Uint32Array was written\n // as if empty (suspect: archetype write-array dispatch on instanceof\n // Array vs TypedArray).\n const mappingPlain: number[] = Array.from(mapping);\n // The synthetic root is the ChildOf parent of every owned root entity\n // (step 5 below) and may itself become a ChildOf parent of a caller-\n // supplied `parent` chain. propagateTransforms walks ChildOf parents\n // through the Transform liveMap and treats a parent missing Transform\n // as `hierarchy-broken`, so the synthetic root must carry Transform\n // (identity TRS via layer-2 defaults) when Transform is defined.\n const rootComponents: ComponentData[] = [\n {\n component: sceneInstanceToken,\n data: {\n source: handle,\n mapping: mappingPlain,\n state: stateRef,\n } as never,\n },\n ];\n const transformToken = world.components.resolve('Transform');\n if (transformToken !== undefined) {\n rootComponents.push({\n component: transformToken,\n data: {} as never,\n });\n }\n const rootSpawn = (world.spawn as (...c: ComponentData[]) => Result<EntityHandle, EcsError>)(\n ...rootComponents,\n );\n if (!rootSpawn.ok) {\n return rootSpawn;\n }\n const rootEntity = rootSpawn.value;\n\n // 4. Build SceneInstanceState payload + register it in the UniqueRefStore\n // under the same handle. We use the public `_setUniqueRefPayload`\n // helper (added below) so the alloc -> populate sequence stays atomic.\n const overrides = new Map<LocalEntityId, Map<string, MountOverride>>();\n for (const mount of ownMounts) {\n for (const ov of mount.overrides ?? []) {\n // feat-20260713 M2 / w8: `MountOverride.field` is optional (add-or-patch\n // discriminant carried by the shape itself). Record the override into\n // the SceneInstanceState map keyed by comp (no field) or comp:field\n // (field-patch), then apply it to the live member column via the shared\n // add-or-patch helper.\n const lid = ov.localId as unknown as LocalEntityId;\n let fieldMap = overrides.get(lid);\n if (fieldMap === undefined) {\n fieldMap = new Map();\n overrides.set(lid, fieldMap);\n }\n fieldMap.set(mountOverrideStateKey(ov), ov);\n // Apply override to the live member entity column.\n const memberEntityRaw = mapping[lid as unknown as number];\n if (memberEntityRaw !== undefined && memberEntityRaw !== ENTITY_NULL_RAW) {\n const memberEntity = memberEntityRaw as unknown as EntityHandle;\n const applyRes = worldApplyMountOverride(world, memberEntity, ov);\n if (!applyRes.ok) {\n return applyRes as Result<EntityHandle, EcsError>;\n }\n }\n }\n }\n\n const detached = new Set<LocalEntityId>();\n const state: Record<string, unknown> = {\n source: handle,\n entityToLocalId,\n detachedLocalIds: detached,\n // Convert overrides Map<LocalEntityId, Map<string, MountOverride>>\n // into Map<LocalEntityId, Map<string, SceneInstanceOverrideRecord>>\n overrides: worldMountOverridesToStateMap(overrides),\n rootEntities,\n mountRoots: mountInstances.map(({ root }) => root),\n totalSlots,\n mountTimeOverrides: ownMounts.flatMap((m) => m.overrides ?? []),\n };\n // Stuff the state into the UniqueRefStore under the existing slot. We\n // re-use the slot we allocated above by writing directly into the\n // payloads map via a `_setUniqueRefPayload` shim.\n worldSetUniqueRefPayload(world, stateRef, state);\n\n // 5. Wire ChildOf for every owned root entity (no ChildOf at layer-1)\n // to the synthetic root.\n if (childOfToken !== undefined) {\n for (const rootE of rootEntities) {\n const has = world.get(rootE, childOfToken);\n if (!has.ok) {\n // No ChildOf yet — attach to synthetic root.\n const r = world.addComponent(rootE, {\n component: childOfToken,\n data: { parent: rootEntity } as never,\n });\n if (!r.ok) return r as Result<EntityHandle, EcsError>;\n }\n }\n // R2/B-1: wire mount entities with default `mount.parent === undefined`\n // to this scene's synthetic root. _spawnMountEntity may have attached a\n // placeholder ChildOf {parent: ENTITY_NULL_RAW} when mount.components\n // was empty; overwrite via set so the ChildOf chain meshRenderer ->\n // childSyntheticRoot -> mountEntity -> outerSyntheticRoot resolves\n // through Transform-bearing parents (AC-16 / requirements S-7).\n for (const mountE of mountEntitiesNeedingRootParent) {\n const set = world.set(mountE, childOfToken, { parent: rootEntity } as never);\n if (!set.ok) {\n const r = world.addComponent(mountE, {\n component: childOfToken,\n data: { parent: rootEntity } as never,\n });\n if (!r.ok) return r as Result<EntityHandle, EcsError>;\n }\n }\n // Caller-supplied parent: synthetic root's ChildOf -> parent.\n if (parent !== undefined) {\n const r = world.addComponent(rootEntity, {\n component: childOfToken,\n data: { parent } as never,\n });\n if (!r.ok) return r as Result<EntityHandle, EcsError>;\n }\n }\n\n return ok(rootEntity);\n}\n/**\n * @internal Flat finisher — spawn one SceneAsset's members WITHOUT wrapping\n * them in a synthetic SceneInstance root and WITHOUT forcing `ChildOf` onto\n * top-level members. Used for \"opening a scene to edit\": the scene's own\n * entities become plain top-level world entities whose hierarchy is exactly\n * their authored `ChildOf`. Nested prefabs inside still materialise as their\n * own SceneInstance anchors (the mount recursion in `_spawnSceneMembers` is\n * always anchored). Returns the top-level handles (own rootless entities +\n * top-level mount carriers).\n */\nexport function worldInstantiateSceneAssetFlat(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n asset: SceneAsset,\n stack: Set<number>,\n diagnostics: SceneInstantiateDiagnostic[],\n): Result<{ roots: EntityHandle[]; mountEntities: EntityHandle[] }, EcsError> {\n const membersRes = worldSpawnSceneMembers(world, handle, asset, stack, diagnostics);\n if (!membersRes.ok) return membersRes;\n const { rootEntities, mountEntitiesNeedingRootParent, mountEntities, mountInstances } =\n membersRes.value;\n const childOfToken = world.components.resolve('ChildOf');\n\n // Apply parent mount overrides to the live columns and record them on the\n // nested child anchor. Flat mode has no outer SceneInstance state; without\n // this hand-authored mounts[].overrides affect the live value but disappear\n // from the child state, so Gateway re-open cannot discover or revert them.\n for (const { mount, root, mapping: childMapping } of mountInstances) {\n const childStateRes = worldGetSceneInstanceState(world, root);\n if (!childStateRes.ok) return childStateRes;\n for (const ov of mount.overrides ?? []) {\n const childLocalId =\n (ov.localId as unknown as number) - (mount.memberFirst as unknown as number);\n const memberEntityRaw = childMapping[childLocalId];\n if (memberEntityRaw === undefined || memberEntityRaw === ENTITY_NULL_RAW) continue;\n const memberEntity = memberEntityRaw as unknown as EntityHandle;\n const applyRes = worldApplyMountOverride(world, memberEntity, ov);\n if (!applyRes.ok) {\n return applyRes as Result<\n { roots: EntityHandle[]; mountEntities: EntityHandle[] },\n EcsError\n >;\n }\n let fieldMap = childStateRes.value.overrides.get(childLocalId as LocalEntityId);\n if (fieldMap === undefined) {\n fieldMap = new Map();\n childStateRes.value.overrides.set(childLocalId as LocalEntityId, fieldMap);\n }\n fieldMap.set(mountOverrideStateKey(ov), {\n comp: ov.comp,\n ...(ov.field === undefined ? {} : { field: ov.field }),\n value: ov.value,\n });\n }\n }\n\n // Default-parented mount carriers (`mount.parent === undefined`) would, in\n // anchor mode, attach to the synthetic root. Flat mode has none, so they\n // stay top-level. `_spawnMountEntity` may have left a placeholder\n // `ChildOf {parent: ENTITY_NULL_RAW}` (rare: mount with no components AND\n // Transform unregistered) — strip it so the carrier is a genuine root.\n if (childOfToken !== undefined) {\n for (const mountE of mountEntitiesNeedingRootParent) {\n const co = world.get(mountE, childOfToken);\n if (co.ok && (co.value as { parent: number }).parent === ENTITY_NULL_RAW) {\n world.removeComponent(mountE, childOfToken);\n }\n }\n }\n\n return ok({ roots: [...rootEntities, ...mountEntitiesNeedingRootParent], mountEntities });\n}\n/** @internal Build ComponentData[] for one SceneEntity, remapping localIds.\n *\n * C-R2 (feat-20260622-s5 M6): unknown fields on a SceneAsset payload are NOT\n * fatal. Unlike `world.spawn` (an explicit API call where a typo is a\n * programming error -> `SpawnDataUnknownFieldError`), scene data is loader-fed\n * and may carry a stale / deprecated / typo'd field. The remap below builds a\n * fresh `remappedRaw` and simply SKIPS keys absent from the schema (no input\n * mutation — the source `raw` is never deleted-from), recording each skipped\n * key as a non-fatal `SceneInstantiateDiagnostic` into the passed accumulator.\n * All known fields still write through, so one bad field cannot blank the\n * entity or the scene (C-AC-02/03/04).\n */\nexport function worldBuildSceneEntityComponentDatas(\n world: World,\n node: import('@forgeax/engine-types').SceneEntity,\n mapping: Uint32Array,\n diagnostics: SceneInstantiateDiagnostic[],\n): Result<ComponentData[], EcsError> {\n const out: ComponentData[] = [];\n const nodeLocalId = node.localId as unknown as number;\n for (const compName of Object.keys(node.components)) {\n const token = world.components.resolve(compName);\n if (token === undefined) {\n return err(new ComponentNotDefinedError(compName));\n }\n const raw = node.components[compName] ?? {};\n const schema = componentSchema(token) as Record<string, string>;\n const remappedRaw: Record<string, unknown> = {};\n for (const fieldName of Object.keys(raw)) {\n const fieldType = schema[fieldName];\n // C-R2: unknown key -> skip (do not copy into remappedRaw, do not\n // mutate the source `raw`) and record a structured diagnostic. The\n // downstream `spawn` only sees schema-valid keys, so its own\n // validateComponentDataKeys gate stays green.\n if (fieldType === undefined) {\n diagnostics.push({ component: compName, field: fieldName, localId: nodeLocalId });\n continue;\n }\n const value = (raw as Record<string, unknown>)[fieldName];\n const kind = classifyEntityField(token, fieldName);\n if (kind !== null) {\n // Entity / array<entity> field — remap through the shared kernel.\n // localId -> live Entity. Slots not yet spawned hold ENTITY_NULL_RAW.\n const sceneRemap = (localId: number): number => {\n if (localId < 0 || localId >= mapping.length) return ENTITY_NULL_RAW;\n const live = mapping[localId];\n return live === undefined || live === ENTITY_NULL_RAW ? ENTITY_NULL_RAW : live;\n };\n remappedRaw[fieldName] = remapEntityFieldValue(value, kind, sceneRemap);\n } else {\n remappedRaw[fieldName] = value;\n }\n }\n const filled = fillComponentDefaults(token, remappedRaw);\n out.push({ component: token, data: filled as never });\n }\n return ok(out);\n}\n/**\n * @internal feat-20260713 M2 / w8: apply one MountOverride to a live member\n * entity column. The `field?` shape is the add-or-patch discriminant:\n *\n * - `field` present -> PATCH one field: `world.set(member, comp, {[field]:\n * value})`. Omitted fields keep their authored / existing values.\n * - `field` absent -> ADD/UPSERT the whole component: `value` is the\n * per-field value map for `comp`. When the member already carries `comp`\n * it is upserted (set-over each supplied field + schema defaults for the\n * omitted ones — the whole component is rewritten from the value map +\n * defaults, never a `component-already-present` error). When absent it is\n * added fresh via `addComponent` (fillComponentDefaults fills omitted\n * fields). The value-map is fed through `fillComponentDefaults` so the\n * add and upsert paths write byte-identical rows.\n *\n * Component registration + value-key validation happened at\n * `_validateMountOverrides` (fail-fast before any spawn); by this point the\n * comp resolves through the World-local catalog and the value keys are schema-valid.\n * still guards defensively (an unregistered comp is a no-op skip, matching\n * the prior field-patch behaviour). Returns the underlying set / addComponent\n * Result so a shared-field value gate (D-4) or any other write error\n * propagates unchanged.\n */\nexport function worldApplyMountOverride(\n world: World,\n member: EntityHandle,\n ov: MountOverride,\n): Result<void, EcsError> {\n const ovToken = world.components.resolve(ov.comp);\n if (ovToken === undefined) return ok(undefined);\n if (ov.field !== undefined) {\n // PATCH one field.\n return world.set(member, ovToken, { [ov.field]: ov.value } as never);\n }\n // ADD/UPSERT the whole component. Fill omitted fields from the schema so\n // add and upsert produce identical rows (upsert = full rewrite from the\n // value map + defaults).\n const rawValue = (ov.value ?? {}) as Record<string, unknown>;\n const filled = fillComponentDefaults(ovToken as Component, rawValue);\n const has = world.get(member, ovToken);\n if (has.ok) {\n // Already present -> upsert (set every filled field, no duplicate error).\n return world.set(member, ovToken, filled as never);\n }\n return world.addComponent(member, { component: ovToken, data: filled as never });\n}\n/**\n * @internal R2/B-3 + R2/B-4: validate `mount.overrides[]` BEFORE any\n * spawn so a malformed override fails fast with no observable side\n * effects (charter P3 explicit-failure). Two checks:\n *\n * 1. `override.localId` must address a slot inside the parent-namespace\n * member window `[memberFirst, memberFirst + memberCount)` (AC-06).\n * 2. `override.field` must exist in the resolved component schema\n * (AC-07). When the component is unregistered we cannot validate the\n * field shape; let the existing fall-through path proceed (the\n * catalog guard inside the override-application loop\n * will skip the write).\n */\nexport function worldValidateMountOverrides(\n world: World,\n mount: SceneInstanceMount,\n): Result<void, EcsError> {\n const overrides = mount.overrides;\n if (overrides === undefined) return ok(undefined);\n const memberFirst = mount.memberFirst as unknown as number;\n const memberCount = mount.memberCount;\n const memberLast = memberFirst + memberCount;\n const mountLid = mount.localId as unknown as number;\n for (const ov of overrides) {\n const ovLid = ov.localId as unknown as number;\n // R2/B-3: parent-namespace check — override.localId must lie in the\n // member window [memberFirst, memberFirst + memberCount).\n if (ovLid < memberFirst || ovLid >= memberLast) {\n return err({\n code: 'pack-mount-override-localid-out-of-range' as PackErrorCode,\n expected: `override.localId in [${memberFirst}, ${memberLast})`,\n hint: PACK_ERROR_HINTS['pack-mount-override-localid-out-of-range'],\n detail: {\n code: 'pack-mount-override-localid-out-of-range',\n overrideLocalId: ovLid,\n mountLocalId: mountLid,\n memberCount,\n } as PackErrorDetail,\n } as unknown as EcsError);\n }\n // feat-20260713 M2 / w8: double-branch schema check.\n // - field-patch form (field present): the component (when registered)\n // must declare `override.field` in its schema (R2/B-4, unchanged).\n // - component-add form (field absent): the component MUST be registered\n // (component-not-defined otherwise) AND every key in the value map\n // must be a schema field (pack-mount-override-unknown-field).\n const ovToken = world.components.resolve(ov.comp);\n if (ov.field !== undefined) {\n if (ovToken !== undefined) {\n const schema = componentSchema(ovToken) as Record<string, unknown>;\n if (!(ov.field in schema)) {\n return err({\n code: 'pack-mount-override-unknown-field' as PackErrorCode,\n expected: `override.field defined on component '${ov.comp}'`,\n hint: PACK_ERROR_HINTS['pack-mount-override-unknown-field'],\n detail: {\n code: 'pack-mount-override-unknown-field',\n comp: ov.comp,\n field: ov.field,\n mountLocalId: mountLid,\n } as PackErrorDetail,\n } as unknown as EcsError);\n }\n }\n } else {\n // component-add form: comp must be registered so we can validate + apply\n // the whole component (add/upsert needs the schema).\n if (ovToken === undefined) {\n return err(new ComponentNotDefinedError(ov.comp));\n }\n const schema = componentSchema(ovToken) as Record<string, unknown>;\n const valueMap = (ov.value ?? {}) as Record<string, unknown>;\n for (const key of Object.keys(valueMap)) {\n if (!(key in schema)) {\n return err({\n code: 'pack-mount-override-unknown-field' as PackErrorCode,\n expected: `override.value keys defined on component '${ov.comp}'`,\n hint: PACK_ERROR_HINTS['pack-mount-override-unknown-field'],\n detail: {\n code: 'pack-mount-override-unknown-field',\n comp: ov.comp,\n field: key,\n mountLocalId: mountLid,\n } as PackErrorDetail,\n } as unknown as EcsError);\n }\n }\n }\n }\n return ok(undefined);\n}\n/** @internal Spawn the mount-entity slot carrying mount.components (if any).\n *\n * R2/B-1: the mount entity is a structural intermediate in the ChildOf\n * chain `cube -> innerSyntheticRoot -> mountEntity -> outerSyntheticRoot`,\n * so it MUST carry Transform whenever Transform is registered (mirrors\n * the D-V-0 synthetic-root invariant). Otherwise propagateTransforms\n * walking the chain hits a Transform-less parent and emits per-frame\n * `RhiError(hierarchy-broken)` (verify R1 root cause of the\n * hello-scene-nesting demo black frames).\n */\nexport function worldSpawnMountEntity(\n world: World,\n mount: SceneInstanceMount,\n mapping: Uint32Array,\n diagnostics: SceneInstantiateDiagnostic[],\n): Result<EntityHandle, EcsError> {\n const fakeNode: import('@forgeax/engine-types').SceneEntity = {\n localId: mount.localId,\n components: mount.components ?? {},\n };\n const cdRes = worldBuildSceneEntityComponentDatas(world, fakeNode, mapping, diagnostics);\n if (!cdRes.ok) return cdRes;\n // R2/B-1: ensure Transform is attached so propagateTransforms can walk\n // through this entity. Layer-2 defaults supply identity TRS; the\n // mount.components overlay (when present and including Transform) takes\n // precedence and is already in cdRes.value.\n const transformToken = world.components.resolve('Transform');\n if (transformToken !== undefined) {\n const hasTransform = cdRes.value.some((c) => c.component === transformToken);\n if (!hasTransform) {\n cdRes.value.push({ component: transformToken, data: {} as never });\n }\n }\n if (cdRes.value.length === 0) {\n // Mount has no components AND Transform is unregistered (rare unit-\n // test path). Fall back to the placeholder ChildOf so the spawn has\n // a real archetype. Step 5 overwrites this placeholder.\n const childOfToken = world.components.resolve('ChildOf');\n if (childOfToken === undefined) {\n return err(new ComponentNotDefinedError('ChildOf'));\n }\n cdRes.value.push({\n component: childOfToken,\n data: { parent: ENTITY_NULL_RAW } as never,\n });\n }\n return (world.spawn as (...c: ComponentData[]) => Result<EntityHandle, EcsError>)(...cdRes.value);\n}\n/** @internal Resolve mount.source through the wired SceneAssetResolver. */\nexport function worldResolveMountSource(\n world: World,\n source: number | string,\n parentHandle: Handle<'SceneAsset', 'shared'>,\n): Result<Handle<'SceneAsset', 'shared'>, EcsError> {\n const resolver = worldGetSceneAssetResolver(world);\n if (resolver === null) {\n return err({\n code: 'stale-entity' as const,\n expected: 'wired SceneAssetResolver (auto-wired by engine.assets.instantiate)',\n hint:\n 'engine.assets.instantiate sugar wires this for you; ' +\n 'call worldSetSceneAssetResolver before nested scene expansion.',\n detail: { entity: 0, slot: 0, generation: 0 },\n } as unknown as EcsError);\n }\n const r = resolver(source, parentHandle);\n if (!r.ok) {\n // Resolver carries `unknown` err (loose contract — engine-runtime may\n // wire any shape); narrow back to EcsError here at the boundary.\n return err(r.error as EcsError);\n }\n return ok(r.value);\n}\n/** @internal Convert mount.overrides Map shape to the SceneInstanceState shape.\n *\n * feat-20260713 M1 / w4: `field` is optional (add-or-patch discriminant). In\n * M1 only the field-patch form reaches this builder (the component-add form\n * fails fast in the apply loops); the record type stays `field?: string` so\n * the M2 add path can flow through untouched. `exactOptionalPropertyTypes`\n * forbids writing an explicit `field: undefined`, so omit the key when absent.\n */\nexport function worldMountOverridesToStateMap(\n src: Map<LocalEntityId, Map<string, MountOverride>>,\n): Map<LocalEntityId, Map<string, { comp: string; field?: string; value: unknown }>> {\n const out = new Map<\n LocalEntityId,\n Map<string, { comp: string; field?: string; value: unknown }>\n >();\n for (const [lid, fields] of src) {\n const m = new Map<string, { comp: string; field?: string; value: unknown }>();\n for (const [k, v] of fields) {\n m.set(k, {\n comp: v.comp,\n value: v.value,\n ...(v.field !== undefined ? { field: v.field } : {}),\n });\n }\n out.set(lid, m);\n }\n return out;\n}\n/** @internal Set the payload of an already-allocated SceneInstance state ref. */\nexport function worldSetUniqueRefPayload<T>(\n world: World,\n handle: Handle<string, 'unique'>,\n payload: T,\n): void {\n sceneWorldState(world).statePayloads.set(Number(handle), payload);\n}\n\n/**\n * @internal Resolve the SceneInstanceState payload behind the\n * `SceneInstance.state` ref column on `root`. Returns Err when `root`\n * does not carry SceneInstance or the ref slot is dead.\n */\nexport function worldResolveSceneInstanceStatePayload(\n world: World,\n root: EntityHandle,\n): Result<SceneInstanceStatePayload, EcsError> {\n const sceneInstanceToken = world.components.resolve('SceneInstance');\n if (sceneInstanceToken === undefined) {\n return err(new ComponentNotDefinedError('SceneInstance'));\n }\n const r = world.get(root, sceneInstanceToken);\n if (!r.ok) return r;\n const stateRefRaw = (r.value as unknown as { state: number }).state;\n const stateRefHandle = toUnique<'SceneInstanceState'>(stateRefRaw);\n const payload = sceneWorldState(world).statePayloads.get(Number(stateRefHandle));\n if (payload === undefined) {\n return err(\n new StaleEntityError(root as unknown as number, entityIndex(root), entityGeneration(root), {\n operation: 'resolveSceneInstanceState',\n component: 'SceneInstance',\n expectedGeneration: entityGeneration(root),\n actualGeneration: entityGeneration(root),\n }),\n );\n }\n return ok(payload as SceneInstanceStatePayload);\n}\n/**\n * Public sugar — get the SceneInstanceState payload (Map / Set view) for\n * `root`. Equivalent to `world.get(root, SceneInstance)` followed by a\n * managed-ref resolution; provided so AI users do not have to learn the\n * `ref<T>` slot resolution mechanic for the common read path.\n */\nexport function worldGetSceneInstanceState(\n world: World,\n root: EntityHandle,\n): Result<SceneInstanceStatePayload, EcsError> {\n return worldResolveSceneInstanceStatePayload(world, root);\n}\n/**\n * Despawn a SceneInstance root + all its members. `opts.keepDetached`\n * preserves members marked via `worldDetachSceneMember` (plan-strategy\n * §D-5). Returns the count of entities actually despawned (root + each\n * non-detached member).\n *\n * For a plain entity (no SceneInstance), behaviour matches\n * `world.despawn(entity)` followed by `despawnDescendants(entity)` — i.e.\n * `keepDetached` is a no-op.\n */\nexport function worldDespawnScene(\n world: World,\n root: EntityHandle,\n opts?: { keepDetached?: boolean },\n): Result<number, EcsError> {\n const dRes = worldDespawnDescendants(world, root, opts);\n if (!dRes.ok) return dRes;\n const drop = world.despawn(root);\n if (!drop.ok) return drop;\n return ok(dRes.value + 1);\n}\n/**\n * Despawn every descendant of `root` reachable through Children mirror /\n * SceneInstance.mapping. `opts.keepDetached` is honoured only when `root`\n * carries a SceneInstance (otherwise the option is ignored — there is no\n * detached set on a plain entity).\n *\n * Returns the count of entities despawned. The `root` itself is NOT\n * despawned (that is `despawnScene`'s extra step).\n */\nexport function worldDespawnDescendants(\n world: World,\n root: EntityHandle,\n opts?: { keepDetached?: boolean },\n): Result<number, EcsError> {\n let detached: Set<LocalEntityId> | null = null;\n let entityToLocalId: Map<EntityHandle, LocalEntityId> | null = null;\n if (opts?.keepDetached === true) {\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (stateRes.ok) {\n detached = stateRes.value.detachedLocalIds;\n entityToLocalId = stateRes.value.entityToLocalId;\n }\n }\n let count = 0;\n // Collect descendants first (DFS via iterDescendants) to avoid mutating\n // while iterating. SceneInstance.mapping also owns members that may not be\n // reachable through a Children mirror in a partially registered host. The\n // nested anchor list closes that same ownership boundary for mounted scenes.\n const list: EntityHandle[] = [];\n const seen = new Set<number>();\n const collect = (anchor: EntityHandle): void => {\n for (const e of world.iterDescendants(anchor)) {\n const raw = e as unknown as number;\n if (!seen.has(raw)) {\n seen.add(raw);\n list.push(e);\n }\n }\n const stateRes = worldResolveSceneInstanceStatePayload(world, anchor);\n if (!stateRes.ok) return;\n for (const e of stateRes.value.entityToLocalId.keys()) {\n const raw = e as unknown as number;\n if (!seen.has(raw)) {\n seen.add(raw);\n list.push(e);\n }\n }\n for (const nestedRoot of stateRes.value.mountRoots) {\n const raw = nestedRoot as unknown as number;\n if (seen.has(raw)) continue;\n seen.add(raw);\n list.push(nestedRoot);\n collect(nestedRoot);\n }\n };\n collect(root);\n const childOfToken = world.components.resolve('ChildOf');\n // ChildOf uses linkedSpawn, so a parent-first pass would recursively retire\n // its children before this function can count them. Sort the ownership set\n // by its live ChildOf depth instead of relying on mirror traversal order;\n // nested SceneInstance roots are siblings of their mount carrier in the\n // flattened traversal but parents of the mounted members.\n const owned = new Set(list.map((entity) => Number(entity)));\n const ownedDepth = (entity: EntityHandle): number => {\n if (childOfToken === undefined) return 0;\n let current = entity;\n let depth = 0;\n const visited = new Set<number>();\n while (!visited.has(Number(current))) {\n visited.add(Number(current));\n const parentRes = world.get(current, childOfToken);\n if (!parentRes.ok) break;\n const parent = (parentRes.value as { parent: EntityHandle }).parent;\n if (!owned.has(Number(parent))) break;\n depth += 1;\n current = parent;\n }\n return depth;\n };\n list.sort((a, b) => ownedDepth(b) - ownedDepth(a));\n for (const e of list) {\n if (detached !== null) {\n const lid = entityToLocalId?.get(e);\n if (lid !== undefined && detached.has(lid)) {\n if (childOfToken !== undefined) {\n world.removeComponent(e, childOfToken);\n }\n continue;\n }\n }\n const r = world.despawn(e);\n if (!r.ok) {\n if (r.error.code === 'stale-entity') continue;\n return r;\n }\n count += 1;\n }\n return ok(count);\n}\n/**\n * Write a runtime override to a member entity belonging to `root`. Routes\n * through `world.set(member, comp, { [field]: value })` after an entity-\n * scope guard so cross-instance writes fail-fast. Type-mismatch surfaces\n * `EcsErrorCode = 'scene-override-type-mismatch'` (D-9).\n */\nexport function worldSetSceneOverride<S extends ComponentSchema>(\n world: World,\n root: EntityHandle,\n member: EntityHandle,\n component: Component<string, S>,\n field: keyof ShapeOf<S> & string,\n value: unknown,\n): Result<void, EcsError> {\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (!stateRes.ok) return stateRes;\n const state = stateRes.value;\n const lid = state.entityToLocalId.get(member);\n if (lid === undefined) {\n return err(\n new StaleEntityError(\n member as unknown as number,\n entityIndex(member),\n entityGeneration(member),\n {\n operation: 'setSceneOverride',\n component: component.name,\n expectedGeneration: entityGeneration(member),\n actualGeneration: entityGeneration(member),\n },\n ),\n );\n }\n // Type guard: only check primitive scalar field types where we can\n // narrow `typeof`; ref / handle / entity / array / buffer fields skip\n // (write would surface a deeper error from set).\n const schemaType = (componentSchema(component) as Record<string, string>)[field];\n if (schemaType !== undefined && isPrimitiveScalarFieldType(schemaType)) {\n const expectJsType = primitiveJsType(schemaType);\n const actualJsType = typeof value;\n if (expectJsType !== actualJsType) {\n return err({\n code: 'scene-override-type-mismatch' as const,\n expected: `value typeof === ${expectJsType}`,\n hint:\n `setSceneOverride(${component.name}.${field}) expected ${expectJsType}, ` +\n `got ${actualJsType}; coerce or pick a different override path.`,\n detail: {\n code: 'scene-override-type-mismatch' as const,\n comp: component.name,\n field: field as string,\n expectedType: schemaType,\n actualType: actualJsType,\n },\n } as unknown as EcsError);\n }\n }\n const setRes = world.set(member, component, { [field]: value } as Partial<InputShapeOf<S>>);\n if (!setRes.ok) return setRes;\n // Record into state.overrides\n let fieldMap = state.overrides.get(lid);\n if (fieldMap === undefined) {\n fieldMap = new Map();\n state.overrides.set(lid, fieldMap);\n }\n fieldMap.set(`${component.name}:${field}`, {\n comp: component.name,\n field: field as string,\n value,\n });\n return ok(undefined);\n}\n/**\n * Drop a runtime override (and any mount-time override for the same\n * (member, comp, field) triple); roll the live column value back to the\n * source SceneAsset's layer-1 explicit value (M2 v1 — M3+ widens to layer\n * 2/3 defaults via fillComponentDefaults).\n */\nexport function worldRemoveSceneOverride<S extends ComponentSchema>(\n world: World,\n root: EntityHandle,\n member: EntityHandle,\n component: Component<string, S>,\n field: keyof ShapeOf<S> & string,\n): Result<void, EcsError> {\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (!stateRes.ok) return stateRes;\n const state = stateRes.value;\n const lid = state.entityToLocalId.get(member);\n if (lid === undefined) return ok(undefined);\n const fieldMap = state.overrides.get(lid);\n if (fieldMap !== undefined) {\n fieldMap.delete(`${component.name}:${field}`);\n if (fieldMap.size === 0) state.overrides.delete(lid);\n }\n // Look up the source SceneAsset layer-1 value.\n const assetRes = worldResolveSceneAsset(world, state.source);\n if (!assetRes.ok) return assetRes;\n const node = assetRes.value.entities.find(\n (n) => (n.localId as unknown as number) === (lid as unknown as number),\n );\n const layer1 = node?.components[component.name] as Record<string, unknown> | undefined;\n if (layer1 !== undefined && field in layer1) {\n const r = world.set(member, component, { [field]: layer1[field] } as Partial<InputShapeOf<S>>);\n if (!r.ok) return r;\n }\n return ok(undefined);\n}\n/** Mark a member entity detached. Idempotent (set semantics). */\nexport function worldDetachSceneMember(\n world: World,\n root: EntityHandle,\n member: EntityHandle,\n): Result<void, EcsError> {\n const sceneInstanceToken = world.components.resolve('SceneInstance');\n if (sceneInstanceToken === undefined) {\n return err(new ComponentNotDefinedError('SceneInstance'));\n }\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (!stateRes.ok) return stateRes;\n const state = stateRes.value;\n const lid = state.entityToLocalId.get(member);\n if (lid === undefined) return ok(undefined);\n state.detachedLocalIds.add(lid);\n return ok(undefined);\n}\n/** Clear a detached mark. Idempotent (set semantics). */\nexport function worldReattachSceneMember(\n world: World,\n root: EntityHandle,\n member: EntityHandle,\n): Result<void, EcsError> {\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (!stateRes.ok) return stateRes;\n const state = stateRes.value;\n const lid = state.entityToLocalId.get(member);\n if (lid === undefined) return ok(undefined);\n state.detachedLocalIds.delete(lid);\n return ok(undefined);\n}\n/**\n * Get the SceneAsset handle a SceneInstance root was instantiated from.\n * Returns Err on a plain entity (no SceneInstance component).\n */\nexport function worldGetSceneAssetForInstance(\n world: World,\n root: EntityHandle,\n): Result<Handle<'SceneAsset', 'shared'>, EcsError> {\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (!stateRes.ok) return stateRes;\n return ok(stateRes.value.source);\n}\n\n// SceneInstanceStatePayload — internal echo of the runtime\n// `SceneInstanceState` interface for ECS-side consumption (engine-ecs cannot\n// value-import engine-runtime by AC-29; structural shape only).\n// ────────────────────────────────────────────────────────────────────────────\n\n/** @internal Structural payload behind `SceneInstance.state` ref column. */\nexport interface SceneInstanceStatePayload {\n readonly source: Handle<'SceneAsset', 'shared'>;\n readonly entityToLocalId: Map<EntityHandle, LocalEntityId>;\n readonly detachedLocalIds: Set<LocalEntityId>;\n readonly overrides: Map<\n LocalEntityId,\n Map<string, { readonly comp: string; readonly field?: string; readonly value: unknown }>\n >;\n readonly rootEntities: EntityHandle[];\n /** Synthetic roots of recursively mounted SceneAssets owned by this instance. */\n readonly mountRoots: EntityHandle[];\n readonly totalSlots: number;\n readonly mountTimeOverrides: readonly MountOverride[];\n}\n\n/**\n * Topological sort over the implicit ChildOf graph (parents before children).\n * Cycle-free input always covers all n nodes; cyclic input emits whatever was\n * reachable from indegree-0 (the fallback caller handles cycle reporting via\n * `pack-cyclic-reference` at the upstream scanner / runtime path).\n */\nfunction sceneTopoSort(\n nodes: readonly import('@forgeax/engine-types').SceneEntity[],\n): readonly number[] {\n const n = nodes.length;\n const childrenOf: number[][] = Array.from({ length: n }, () => []);\n const indeg = new Uint32Array(n);\n const localIdToIdx = new Map<number, number>();\n for (let i = 0; i < n; i += 1) {\n const node = nodes[i];\n if (node === undefined) continue;\n localIdToIdx.set(node.localId as unknown as number, i);\n }\n for (let i = 0; i < n; i += 1) {\n const node = nodes[i];\n if (node === undefined) continue;\n const child = node.components.ChildOf;\n if (child === undefined) continue;\n const p = (child as Record<string, unknown>).parent;\n if (typeof p === 'number') {\n const parentIdx = localIdToIdx.get(p);\n if (parentIdx !== undefined && parentIdx !== i) {\n childrenOf[parentIdx]?.push(i);\n indeg[i] = (indeg[i] ?? 0) + 1;\n }\n }\n }\n const order: number[] = [];\n const queue: number[] = [];\n for (let i = 0; i < n; i += 1) if ((indeg[i] ?? 0) === 0) queue.push(i);\n while (queue.length > 0) {\n const head = queue.shift();\n if (head === undefined) break;\n order.push(head);\n for (const c of childrenOf[head] ?? []) {\n indeg[c] = (indeg[c] ?? 0) - 1;\n if ((indeg[c] ?? 0) === 0) queue.push(c);\n }\n }\n // Append any nodes left unvisited (defensive — cycle would surface here).\n for (let i = 0; i < n; i += 1) {\n if (!order.includes(i) && nodes[i] !== undefined) order.push(i);\n }\n return order;\n}\n\n/**\n * @internal feat-20260713 M2 / w8: SceneInstanceState map key for a\n * MountOverride. Field-patch form keys by `comp:field` (one entry per patched\n * field); component-add form keys by `comp` (one entry per added component). The\n * two key shapes cannot collide because a field-patch always carries a `:field`\n * suffix. Later array entries for the same key overwrite earlier ones, matching\n * the array-order apply semantics.\n */\nfunction mountOverrideStateKey(ov: MountOverride): string {\n return ov.field !== undefined ? `${ov.comp}:${ov.field}` : ov.comp;\n}\n\n/** Schema field types that are JS primitives (typeof checkable). */\nfunction isPrimitiveScalarFieldType(fieldType: string): boolean {\n if (\n fieldType === 'f32' ||\n fieldType === 'f64' ||\n fieldType === 'u32' ||\n fieldType === 'i32' ||\n fieldType === 'u8' ||\n fieldType === 'i8' ||\n fieldType === 'u16' ||\n fieldType === 'i16' ||\n fieldType === 'bool' ||\n fieldType === 'string'\n ) {\n return true;\n }\n if (fieldType.startsWith('enum<')) return true;\n return false;\n}\n\n/** Map a primitive scalar field type to the runtime `typeof` it should narrow to. */\nfunction primitiveJsType(fieldType: string): string {\n if (fieldType === 'bool') return 'boolean';\n if (fieldType === 'string') return 'string';\n return 'number';\n}\n","import {\n defineSystem,\n defineSystemSet,\n type EntityHandle,\n FixedUpdate,\n type SystemHandle,\n Update,\n type World,\n} from '@forgeax/engine-ecs';\nimport {\n createWorldProjection,\n setDerivedComponent,\n type WorldProjection,\n} from '@forgeax/engine-ecs/projection';\nimport { type Mat4, mat4 } from '@forgeax/engine-math';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { ChildOf } from '../components/child-of';\nimport { Transform } from '../components/transform';\nimport { SceneError } from '../errors';\nimport { projectHierarchy, type SceneHierarchySnapshot } from './hierarchy-projection';\n\nexport const PROPAGATE_TRANSFORMS_SYSTEM = 'propagateTransforms' as const;\nexport const PROPAGATE_TRANSFORMS_FIXED_SYSTEM = 'propagateTransformsFixed' as const;\nexport const TransformSet = defineSystemSet({ name: 'transform' });\nexport const TransformFixedSet = defineSystemSet({ name: 'transform-fixed' });\n\ninterface LocalState {\n readonly pos: Float32Array;\n readonly quat: Float32Array;\n readonly scale: Float32Array;\n}\n\ninterface PropagationCache {\n readonly projection: WorldProjection;\n readonly hierarchy: SceneHierarchySnapshot;\n readonly parentOf: ReadonlyMap<EntityHandle, EntityHandle>;\n readonly childrenOf: ReadonlyMap<EntityHandle, readonly EntityHandle[]>;\n readonly entities: ReadonlySet<EntityHandle>;\n readonly locals: Map<EntityHandle, LocalState>;\n readonly derived: Map<EntityHandle, Float32Array>;\n result: Result<void, SceneError>;\n}\n\nconst CACHE = new WeakMap<World, PropagationCache>();\n\ninterface TransformRegistrationLease {\n refs: number;\n}\n\n// A World can be consumed by more than one renderer/view. Keep the schedule\n// registration leased per World so one owner disposing cannot remove the\n// shared transform system from another owner. This is lifecycle bookkeeping,\n// not a second component/system authority; the World schedule remains the\n// source of truth.\nconst REGISTRATION_LEASES = new WeakMap<World, TransformRegistrationLease>();\n\nfunction copyState(value: {\n readonly pos: ArrayLike<number>;\n readonly quat: ArrayLike<number>;\n readonly scale: ArrayLike<number>;\n}): LocalState {\n return {\n pos: new Float32Array(value.pos),\n quat: new Float32Array(value.quat),\n scale: new Float32Array(value.scale),\n };\n}\n\nfunction sameArray(left: ArrayLike<number>, right: ArrayLike<number>): boolean {\n if (left.length !== right.length) return false;\n for (let index = 0; index < left.length; index += 1) {\n if (left[index] !== right[index]) return false;\n }\n return true;\n}\n\nfunction sameState(left: LocalState | undefined, right: LocalState): boolean {\n return (\n left !== undefined &&\n sameArray(left.pos, right.pos) &&\n sameArray(left.quat, right.quat) &&\n sameArray(left.scale, right.scale)\n );\n}\n\nfunction compose(state: LocalState, out: Mat4): void {\n mat4.compose(out, state.pos, state.quat, state.scale);\n}\n\nfunction indexChildren(\n hierarchy: SceneHierarchySnapshot,\n): ReadonlyMap<EntityHandle, readonly EntityHandle[]> {\n const childrenOf = new Map<EntityHandle, EntityHandle[]>();\n for (const [child, parent] of hierarchy.parentOf) {\n const children = childrenOf.get(parent);\n if (children === undefined) childrenOf.set(parent, [child]);\n else children.push(child);\n }\n return childrenOf;\n}\n\nfunction descendants(\n childrenOf: ReadonlyMap<EntityHandle, readonly EntityHandle[]>,\n roots: ReadonlySet<EntityHandle>,\n): Set<EntityHandle> {\n const affected = new Set(roots);\n const pending = [...roots];\n for (let index = 0; index < pending.length; index += 1) {\n const parent = pending[index];\n if (parent === undefined) continue;\n for (const child of childrenOf.get(parent) ?? []) {\n if (affected.has(child)) continue;\n affected.add(child);\n pending.push(child);\n }\n }\n return affected;\n}\n\nfunction hierarchyError(hierarchy: SceneHierarchySnapshot): Result<void, SceneError> {\n const first = hierarchy.diagnostics[0];\n if (first === undefined) return ok(undefined);\n return err(\n new SceneError({\n code: first.code,\n expected: first.expected,\n hint: first.hint,\n detail: first.detail,\n }),\n );\n}\n\nfunction buildCache(world: World, projection: WorldProjection): PropagationCache {\n const hierarchy = projectHierarchy(world);\n const locals = new Map<EntityHandle, LocalState>();\n const entities = new Set<EntityHandle>();\n const query = world.query({ read: [Transform], optional: [ChildOf] });\n if (query.ok) {\n for (const row of query.value) {\n const transform = row.get(Transform);\n if (transform === undefined) continue;\n entities.add(row.entity);\n locals.set(row.entity, copyState(transform));\n }\n }\n return {\n projection,\n hierarchy,\n parentOf: hierarchy.parentOf,\n childrenOf: indexChildren(hierarchy),\n entities,\n locals,\n derived: new Map(),\n result: ok(undefined),\n };\n}\n\nfunction deriveEntity(\n world: World,\n entity: EntityHandle,\n cache: PropagationCache,\n affected: ReadonlySet<EntityHandle>,\n visiting: Set<EntityHandle>,\n published: Set<EntityHandle>,\n): Result<void, SceneError> {\n if (!affected.has(entity) || cache.derived.has(entity)) return ok(undefined);\n if (visiting.has(entity)) return ok(undefined);\n visiting.add(entity);\n const local = cache.locals.get(entity);\n if (local === undefined) {\n visiting.delete(entity);\n return ok(undefined);\n }\n const parent = cache.parentOf.get(entity);\n if (parent !== undefined && cache.entities.has(parent)) {\n const parentResult = deriveEntity(world, parent, cache, affected, visiting, published);\n if (!parentResult.ok) return parentResult;\n }\n const localWorld = mat4.create();\n compose(local, localWorld);\n const parentWorld = parent === undefined ? undefined : cache.derived.get(parent);\n const resolved = mat4.create();\n if (parentWorld === undefined) resolved.set(localWorld);\n else mat4.multiply(resolved, parentWorld, localWorld);\n const write = setDerivedComponent(world, entity, Transform, { world: resolved });\n if (!write.ok) {\n visiting.delete(entity);\n return err(\n new SceneError({\n code: 'hierarchy-broken',\n expected: 'the derived Transform.world write to succeed',\n hint: 'inspect the ECS mutation error before retrying transform propagation',\n detail: { entity, parent: entity },\n }),\n );\n }\n cache.derived.set(entity, resolved);\n published.add(entity);\n visiting.delete(entity);\n return ok(undefined);\n}\n\nfunction drainPublishedChanges(\n cache: PropagationCache,\n published: ReadonlySet<EntityHandle>,\n): boolean {\n const drained = cache.projection.poll();\n if (drained.status === 'rebuild') return true;\n return drained.changes.every(\n (change) =>\n change.kind === 'derived-component-changed' &&\n change.component === Transform &&\n published.has(change.entity),\n );\n}\n\nexport function propagateTransforms(\n world: World,\n _hierarchy?: SceneHierarchySnapshot,\n): Result<void, SceneError> {\n let cache = CACHE.get(world);\n if (cache === undefined) {\n cache = buildCache(world, createWorldProjection(world, { components: [Transform, ChildOf] }));\n CACHE.set(world, cache);\n const initial = new Set(cache.entities);\n const published = new Set<EntityHandle>();\n for (const entity of initial) {\n const result = deriveEntity(world, entity, cache, initial, new Set(), published);\n if (!result.ok) return result;\n }\n if (!drainPublishedChanges(cache, published)) {\n CACHE.delete(world);\n return propagateTransforms(world);\n }\n cache.result = hierarchyError(cache.hierarchy);\n return cache.result;\n }\n\n const evidence = cache.projection.poll();\n if (evidence.status === 'rebuild') {\n cache = buildCache(world, cache.projection);\n CACHE.set(world, cache);\n const all = new Set(cache.entities);\n const published = new Set<EntityHandle>();\n for (const entity of all) {\n const result = deriveEntity(world, entity, cache, all, new Set(), published);\n if (!result.ok) return result;\n }\n if (!drainPublishedChanges(cache, published)) {\n CACHE.delete(world);\n return propagateTransforms(world);\n }\n cache.result = hierarchyError(cache.hierarchy);\n return cache.result;\n }\n if (evidence.changes.length === 0) return cache.result;\n\n const transformSeeds = new Set<EntityHandle>();\n let rebuild = false;\n for (const change of evidence.changes) {\n if (\n change.kind === 'entity-removed' ||\n change.kind === 'component-added' ||\n change.kind === 'component-removed'\n ) {\n rebuild = true;\n break;\n }\n if (change.kind !== 'component-changed') continue;\n if (change.component === ChildOf) {\n rebuild = true;\n break;\n }\n // Derived Transform publications are deliberately not dirty seeds. Only\n // authored component-changed records can invalidate local TRS state.\n if (change.component === Transform) transformSeeds.add(change.entity);\n }\n if (rebuild) {\n CACHE.delete(world);\n return propagateTransforms(world);\n }\n\n // A World can record several authored writes before this pass. Read each\n // seed once so the final local state decides whether propagation is needed.\n const changed = new Set<EntityHandle>();\n for (const entity of transformSeeds) {\n const current = world.get(entity, Transform);\n if (!current.ok) {\n CACHE.delete(world);\n return propagateTransforms(world);\n }\n const next = copyState(current.value);\n if (!sameState(cache.locals.get(entity), next)) changed.add(entity);\n cache.locals.set(entity, next);\n }\n if (changed.size === 0) return cache.result;\n\n const affected = descendants(cache.childrenOf, changed);\n const published = new Set<EntityHandle>();\n for (const entity of affected) cache.derived.delete(entity);\n for (const entity of affected) {\n const result = deriveEntity(world, entity, cache, affected, new Set(), published);\n if (!result.ok) return result;\n }\n if (!drainPublishedChanges(cache, published)) {\n CACHE.delete(world);\n return propagateTransforms(world);\n }\n cache.result = hierarchyError(cache.hierarchy);\n return cache.result;\n}\n\nexport const PropagateTransforms: SystemHandle<readonly []> = defineSystem({\n name: PROPAGATE_TRANSFORMS_SYSTEM,\n queries: [],\n fn: (world) => {\n const result = propagateTransforms(world);\n if (!result.ok) throw result.error;\n },\n});\n\nexport const PropagateTransformsFixed: SystemHandle<readonly []> = defineSystem({\n name: PROPAGATE_TRANSFORMS_FIXED_SYSTEM,\n queries: [],\n fn: PropagateTransforms.fn,\n});\n\nexport function registerPropagateTransforms(\n world: World,\n options: { beforeSystemName?: string } = {},\n): () => void {\n const existing = REGISTRATION_LEASES.get(world);\n if (existing !== undefined) {\n existing.refs += 1;\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n existing.refs -= 1;\n if (existing.refs === 0) {\n world.removeSystem(FixedUpdate, PROPAGATE_TRANSFORMS_FIXED_SYSTEM);\n world.removeSystem(Update, PROPAGATE_TRANSFORMS_SYSTEM);\n REGISTRATION_LEASES.delete(world);\n CACHE.delete(world);\n }\n };\n }\n if (options.beforeSystemName === undefined) {\n world.addSystems(Update, TransformSet, [PropagateTransforms]).unwrap();\n } else {\n world\n .addSystems(Update, TransformSet, [\n {\n name: PROPAGATE_TRANSFORMS_SYSTEM,\n queries: [],\n fn: PropagateTransforms.fn,\n before: [options.beforeSystemName],\n },\n ])\n .unwrap();\n }\n world.addSystems(FixedUpdate, TransformFixedSet, [PropagateTransformsFixed]).unwrap();\n const lease: TransformRegistrationLease = { refs: 1 };\n REGISTRATION_LEASES.set(world, lease);\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n lease.refs -= 1;\n if (lease.refs !== 0) return;\n world.removeSystem(FixedUpdate, PROPAGATE_TRANSFORMS_FIXED_SYSTEM);\n world.removeSystem(Update, PROPAGATE_TRANSFORMS_SYSTEM);\n REGISTRATION_LEASES.delete(world);\n CACHE.delete(world);\n };\n}\n","import { Entity, type EntityHandle, type World } from '@forgeax/engine-ecs';\nimport { createWorldProjection } from '@forgeax/engine-ecs/projection';\nimport { ChildOf } from '../components/child-of';\nimport type { SceneErrorCode, SceneErrorDetail } from '../errors';\n\nexport interface SceneHierarchyDiagnostic {\n readonly code: SceneErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: SceneErrorDetail;\n}\n\nexport interface SceneHierarchySnapshot {\n readonly parentOf: ReadonlyMap<EntityHandle, EntityHandle>;\n readonly diagnostics: readonly SceneHierarchyDiagnostic[];\n getParent(entity: EntityHandle): EntityHandle | undefined;\n}\n\ninterface HierarchyProjectionCacheEntry {\n readonly changes: ReturnType<typeof createWorldProjection>;\n readonly snapshot: SceneHierarchySnapshot;\n}\n\n// A World can be observed by the transform system, renderer visibility, and\n// editor projections in the same frame. Keep one World-local projection so\n// those consumers do not each rescan every archetype. Structure changes and\n// the ChildOf component's own mutation token are the invalidation keys; the\n// global mutation epoch is intentionally too broad because animation and\n// runtime-only component writes may advance it every frame. Direct table\n// writes are internal-only and must not mutate authored hierarchy state.\nconst HIERARCHY_PROJECTION_CACHE = new WeakMap<World, HierarchyProjectionCacheEntry>();\n\nfunction diagnostic(\n code: SceneErrorCode,\n entity: EntityHandle,\n parent: EntityHandle,\n): SceneHierarchyDiagnostic {\n if (code === 'hierarchy-cycle') {\n return {\n code,\n expected: 'ChildOf parent edges form an acyclic live hierarchy',\n hint: 'remove one ChildOf edge from the reported cycle, then re-run the extract',\n detail: { entity, parent },\n };\n }\n return {\n code,\n expected: 'ChildOf.parent references a live entity in the same World',\n hint: 'remove the stale ChildOf component or restore the referenced parent in this World',\n detail: { entity, parent },\n };\n}\n\n/** Build the only World-local projection of ChildOf parent facts. */\nexport function projectHierarchy(world: World): SceneHierarchySnapshot {\n const cached = HIERARCHY_PROJECTION_CACHE.get(world);\n const changes = cached?.changes ?? createWorldProjection(world, { components: [ChildOf] });\n if (cached !== undefined) {\n const evidence = changes.poll();\n if (evidence.status === 'delta' && evidence.changes.length === 0) return cached.snapshot;\n }\n const liveEntities = new Set<EntityHandle>();\n const authoredParents = new Map<EntityHandle, EntityHandle>();\n\n const query = world.query({ read: [Entity], optional: [ChildOf] });\n if (query.ok) {\n for (const row of query.value) {\n liveEntities.add(row.entity);\n const parent = row.get(ChildOf)?.parent;\n if (parent !== undefined && parent !== null) authoredParents.set(row.entity, parent);\n }\n }\n\n const parentOf = new Map<EntityHandle, EntityHandle>();\n const diagnostics: SceneHierarchyDiagnostic[] = [];\n for (const [entity, parent] of authoredParents) {\n if (liveEntities.has(parent)) {\n parentOf.set(entity, parent);\n } else {\n diagnostics.push(diagnostic('hierarchy-broken', entity, parent));\n }\n }\n\n const state = new Map<EntityHandle, 0 | 1 | 2>();\n const stack: EntityHandle[] = [];\n const cycleMembers = new Set<EntityHandle>();\n const visit = (entity: EntityHandle): void => {\n const currentState = state.get(entity) ?? 0;\n if (currentState === 2) return;\n if (currentState === 1) {\n const cycleStart = stack.indexOf(entity);\n for (let index = cycleStart; index >= 0 && index < stack.length; index++) {\n const member = stack[index];\n if (member !== undefined) cycleMembers.add(member);\n }\n return;\n }\n\n state.set(entity, 1);\n stack.push(entity);\n const parent = parentOf.get(entity);\n if (parent !== undefined) visit(parent);\n stack.pop();\n state.set(entity, 2);\n };\n\n for (const entity of liveEntities) visit(entity);\n for (const entity of cycleMembers) {\n const parent = authoredParents.get(entity);\n if (parent !== undefined) diagnostics.push(diagnostic('hierarchy-cycle', entity, parent));\n parentOf.delete(entity);\n }\n\n diagnostics.sort((left, right) => {\n const entityDelta = (left.detail.entity as number) - (right.detail.entity as number);\n if (entityDelta !== 0) return entityDelta;\n return left.code.localeCompare(right.code);\n });\n\n const stableParentOf = new Map(parentOf);\n const stableDiagnostics = Object.freeze(diagnostics.slice());\n const snapshot: SceneHierarchySnapshot = {\n parentOf: stableParentOf,\n diagnostics: stableDiagnostics,\n getParent(entity: EntityHandle): EntityHandle | undefined {\n return stableParentOf.get(entity);\n },\n };\n HIERARCHY_PROJECTION_CACHE.set(world, {\n changes,\n snapshot,\n });\n return snapshot;\n}\n","import type { Component, World } from '@forgeax/engine-ecs';\nimport type { Plugin } from '@forgeax/engine-plugin';\nimport { ChildOf } from './components/child-of';\nimport { Children } from './components/children';\nimport { MorphWeights } from './components/morph-weights';\nimport { Name } from './components/name';\nimport { Transform } from './components/transform';\nimport { registerPropagateTransforms } from './systems/propagate-transforms';\n\nconst SCENE_COMPONENTS: readonly Component[] = [ChildOf, Children, MorphWeights, Name, Transform];\n\nfunction registerSceneComponents(world: World): () => void {\n const leases = SCENE_COMPONENTS.map((component) => world.components.register(component).unwrap());\n return () => {\n for (let index = leases.length - 1; index >= 0; index -= 1) leases[index]?.dispose();\n };\n}\n\nexport function scenePlugin(): Plugin {\n return {\n name: 'scene',\n inject: ['world'],\n apply(ctx) {\n ctx.effect(() => registerSceneComponents(ctx.world), 'scene/components');\n ctx.effect(() => registerPropagateTransforms(ctx.world), 'scene/propagate-transforms');\n },\n };\n}\n"],"mappings":";AAAA;AAAA,EAKE;AAAA,EACA;AAAA,OAKK;AAEA,IAAM,iBAAiD;AAAA,EAC5D,MAAM;AACR;AAEA,SAAS,aAAa,MAAc,QAAoD;AACtF,SAAO,IAAI;AAAA,IACT,MAAM;AAAA,IACN,UAAU;AAAA,IACV,MAAM;AAAA,IACN,QAAQ,EAAE,MAAM,OAAO;AAAA,EACzB,CAAC;AACH;AAUA,IAAM,gBAAgB,oBAAI,QAAmC;AAO7D,SAAS,eACP,MACA,OACA,UACiG;AACjG,QAAM,OAAO,KAAK,KAAK;AACvB,MAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,KAAK,SAAS,QAAW;AAC/D,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,QAAQ,GAAG,QAAQ,oBAAoB,KAAK,wBAAwB,KAAK,MAAM;AAAA,IACjF;AAAA,EACF;AACA,SAAO,EAAE,IAAI,MAAM,OAAO,KAAK;AACjC;AAEA,SAAS,cACP,QACA,MAGkD;AAClD,MAAI,WAAW,OAAW,QAAO,EAAE,IAAI,MAAM,OAAO,OAAU;AAC9D,QAAM,WAAiC,CAAC;AACxC,aAAW,SAAS,QAAQ;AAC1B,QAAI,OAAO,MAAM,WAAW,YAAY,CAAC,OAAO,UAAU,MAAM,MAAM,GAAG;AACvE,eAAS,KAAK,KAAK;AACnB;AAAA,IACF;AACA,UAAM,MAAM,eAAe,MAAM,MAAM,QAAQ,SAAS,MAAM,OAAO,SAAS;AAC9E,QAAI,CAAC,IAAI,GAAI,QAAO;AACpB,aAAS,KAAK,EAAE,GA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B,OAAO,KAAK;AAChC,UAAM,OAAO,KAAK;AAAA,EACpB;AACF;;;AE9WA,IAAM,mBAAyC,CAAC,SAAS,UAAU,cAAc,MAAM,SAAS;AAEhG,SAAS,wBAAwB,OAA0B;AACzD,QAAM,SAAS,iBAAiB,IAAI,CAAC,cAAc,MAAM,WAAW,SAAS,SAAS,EAAE,OAAO,CAAC;AAChG,SAAO,MAAM;AACX,aAAS,QAAQ,OAAO,SAAS,GAAG,SAAS,GAAG,SAAS,EAAG,QAAO,KAAK,GAAG,QAAQ;AAAA,EACrF;AACF;AAEO,SAAS,cAAsB;AACpC,SAAO;AAAA,IACL,MAAM;AAAA,IACN,QAAQ,CAAC,OAAO;AAAA,IAChB,MAAM,KAAK;AACT,UAAI,OAAO,MAAM,wBAAwB,IAAI,KAAK,GAAG,kBAAkB;AACvE,UAAI,OAAO,MAAM,4BAA4B,IAAI,KAAK,GAAG,4BAA4B;AAAA,IACvF;AAAA,EACF;AACF;","names":["defineComponent","defineComponent","err","ok","err","ok","ok","err","createWorldProjection","err","ok","ok","err","createWorldProjection","published","active"]}
|
|
1
|
+
{"version":3,"sources":["../src/assets/scene-decoder.ts","../src/components/children.ts","../src/components/transform.ts","../src/collect-subtree.ts","../src/components/morph-weights.ts","../src/components/name.ts","../src/errors.ts","../src/instances/binding.ts","../src/instances/collect-profile.ts","../src/instances/externalization.ts","../src/instances/scene-instances.ts","../src/instances/state.ts","../src/systems/propagate-transforms.ts","../src/plugin.ts","../src/systems/hierarchy-projection.ts"],"sourcesContent":["import {\n type AssetDecoder,\n type AssetDecoderContribution,\n type AssetKind,\n type AssetLoadError,\n err,\n ok,\n type Result,\n type SceneAsset,\n type SceneEntity,\n type SceneInstanceMount,\n} from '@forgeax/engine-types';\n\nexport const sceneAssetKind: AssetKind<SceneAsset, 'scene'> = {\n kind: 'scene',\n} as AssetKind<SceneAsset, 'scene'>;\n\nfunction invalidScene(guid: string, reason: string): Result<SceneAsset, AssetLoadError> {\n return err({\n code: 'asset-package-invalid',\n expected: 'a scene payload with an entities array',\n hint: 'recook the SceneAsset and publish its complete envelope',\n detail: { guid, reason },\n });\n}\n\ntype SceneWireRefResult =\n | { readonly ok: true; readonly value: SceneAsset }\n | { readonly ok: false; readonly reason: string };\n\n// The Pack envelope owns refs[] while the decoded SceneAsset remains the\n// portable payload. Keep that wire-only fact beside the decoded object so the\n// World-local projection can interpret shared-field indices without putting a\n// component registry or World into the decoder contract.\nconst sceneWireRefs = new WeakMap<object, readonly string[]>();\n\n/** @internal Read the Pack refs[] retained for a decoded SceneAsset payload. */\nexport function sceneAssetWireRefs(asset: SceneAsset): readonly string[] | undefined {\n return sceneWireRefs.get(asset);\n}\n\nfunction resolveWireRef(\n refs: readonly string[],\n value: number,\n location: string,\n): { readonly ok: true; readonly value: string } | { readonly ok: false; readonly reason: string } {\n const guid = refs[value];\n if (!Number.isInteger(value) || value < 0 || guid === undefined) {\n return {\n ok: false,\n reason: `${location} references refs[${value}], but refs contains ${refs.length} entries`,\n };\n }\n return { ok: true, value: guid };\n}\n\nfunction resolveMounts(\n mounts: readonly SceneInstanceMount[] | undefined,\n refs: readonly string[],\n):\n | { readonly ok: true; readonly value: readonly SceneInstanceMount[] | undefined }\n | { readonly ok: false; readonly reason: string } {\n if (mounts === undefined) return { ok: true, value: undefined };\n const resolved: SceneInstanceMount[] = [];\n for (const mount of mounts) {\n if (typeof mount.source !== 'number' || !Number.isInteger(mount.source)) {\n resolved.push(mount);\n continue;\n }\n const ref = resolveWireRef(refs, mount.source, `mount ${mount.localId} source`);\n if (!ref.ok) return ref;\n resolved.push({ ...mount, source: ref.value });\n }\n return { ok: true, value: resolved };\n}\n\nfunction resolveSkinGuids(\n skinGuids: readonly (number | string)[] | undefined,\n refs: readonly string[],\n):\n | { readonly ok: true; readonly value: readonly string[] | undefined }\n | { readonly ok: false; readonly reason: string } {\n if (skinGuids === undefined) return { ok: true, value: undefined };\n const resolved: string[] = [];\n for (let index = 0; index < skinGuids.length; index += 1) {\n const value = skinGuids[index];\n if (typeof value === 'string') {\n resolved.push(value);\n continue;\n }\n if (typeof value !== 'number' || !Number.isInteger(value)) {\n return { ok: false, reason: `skinGuids[${index}] is not a GUID or refs index` };\n }\n const ref = resolveWireRef(refs, value, `skinGuids[${index}]`);\n if (!ref.ok) return ref;\n resolved.push(ref.value);\n }\n return { ok: true, value: resolved };\n}\n\nfunction resolveSceneWireRefs(payload: SceneAsset, refs: readonly string[]): SceneWireRefResult {\n const entities: SceneEntity[] = [];\n for (const entity of payload.entities) {\n const components: Record<string, Record<string, unknown>> = {};\n for (const [componentName, rawFields] of Object.entries(entity.components)) {\n // Component schema lookup is World-local after the ECS core reduction.\n // The runtime projection owns the World-local schema and converts\n // authored GUID fields into World.sharedRefs handles. Keep this loader\n // boundary POD-only instead of consulting a removed process-global ECS\n // component registry.\n components[componentName] = { ...(rawFields as Record<string, unknown>) };\n }\n entities.push({\n localId: entity.localId,\n ...(entity.bindingKey === undefined ? {} : { bindingKey: entity.bindingKey }),\n components,\n });\n }\n\n const mounts = resolveMounts(payload.mounts, refs);\n if (!mounts.ok) return mounts;\n const skinGuids = resolveSkinGuids(\n payload.skinGuids as readonly (number | string)[] | undefined,\n refs,\n );\n if (!skinGuids.ok) return skinGuids;\n\n return {\n ok: true,\n value: {\n kind: 'scene',\n ...(payload.sourceKey === undefined ? {} : { sourceKey: payload.sourceKey }),\n entities,\n ...(mounts.value === undefined ? {} : { mounts: mounts.value }),\n ...(skinGuids.value === undefined ? {} : { skinGuids: skinGuids.value }),\n },\n };\n}\n\n/** Scene owns structural validation; World-local projection resolves shared refs. */\nexport const sceneAssetDecoder: AssetDecoder<SceneAsset> = {\n async decode({ envelope }): Promise<Result<SceneAsset, AssetLoadError>> {\n const payload = envelope.payload;\n if (payload.kind !== 'scene' || !Array.isArray(payload.entities)) {\n return invalidScene(envelope.guid, 'scene payload is missing entities');\n }\n const resolved = resolveSceneWireRefs(payload, envelope.refs);\n if (!resolved.ok) return invalidScene(envelope.guid, resolved.reason);\n sceneWireRefs.set(resolved.value, Object.freeze([...envelope.refs]));\n return ok(resolved.value);\n },\n};\n\nexport const sceneAssetContribution: AssetDecoderContribution<SceneAsset, 'scene'> = {\n kind: sceneAssetKind,\n decoder: sceneAssetDecoder,\n consumer: 'Scene',\n};\n","// @forgeax/engine-runtime - Children (forward-list of child entities).\n//\n// Schema: 1 array<entity> field `entities` (variable-length, ECS-managed via\n// the BufferPool slot column + sidecar count column allocated by the ECS M2\n// `world.push` / `world.pop` / `world.capacity` command surface).\n//\n// feat-20260515-buffer-array-vocab-collapse M3 / w17:\n// the legacy `VarArrayView<Entity>` value-shape wrapper was retired in\n// favour of a direct `TypedArray` snapshot returned by `world.get` plus the\n// three `world` commands. AI users mutate the list through:\n//\n// world.push(parent, Children, 'entities', child).unwrap();\n// world.pop(parent, Children, 'entities').unwrap();\n// world.capacity(parent, Children, 'entities').unwrap();\n//\n// And read through the read-only `Uint32Array` snapshot:\n//\n// const snap = world.get(parent, Children).unwrap().entities;\n// const liveCount = snap.length;\n// for (let i = 0; i < liveCount; i++) { const child = snap[i]; ... }\n//\n// Snapshot length equals the live element count (sidecar count column owned\n// by the ECS layer); the snapshot is rematerialised on every `world.get`\n// (D-4 no-cache); writes routed through the snapshot are undefined behaviour\n// (the contract is read-only, plan-strategy §2.2 D-R3).\n//\n// feat-20260531-ecs-relationship-abstraction-bidirectional-sync M4 / t20:\n// Children is the MIRROR side of the ChildOf relationship. Its schema is\n// unchanged (the `entities: 'array<entity>'` shape is exactly what the\n// relationship mirror contract requires), but the engine now maintains this\n// list automatically whenever ChildOf is added / removed / reparented on a\n// child entity (M2 bidirectional-sync hook on ChildOf). The prior OOS-10\n// \"AI users keep the two sides consistent themselves\" contract is retired:\n// `world.addComponent(child, ChildOf{parent})` appends `child` to\n// `parent.Children.entities`, `world.removeComponent` / reparent prunes it.\n// AI users still MAY push/pop the list manually (the three `world` commands\n// below remain valid for non-ChildOf forward-lists), but for the ChildOf\n// hierarchy the engine owns consistency.\n//\n// feat-20260514-ecs-children-instances-managed-buffer-array M3 / w13 (kept\n// for context): migrated from the legacy `{ count: 'u32' }` advisory marker\n// to the real variable-length entity-array storage path.\n// - OOS-09 (prior loop): no `addChild` / `removeChild` / `removeChildren`\n// Commands API. Retired this feat: `world.addChild` / `world.removeChild`\n// / `world.reparent` ship in M3, plus the relationship hook above.\n// - OOS-01 (prior loop): no dangling-entity sweep on `array<entity>`. If a\n// child entity has been despawned, the stored u32 still occupies the\n// slot; AI users explicitly call the engine's entity-liveness check\n// before consuming a child id (see `world.get(child, ChildOf)` returns\n// `Result.err(...)` for a despawned entity --- the stored u32 surfaces\n// as a dead handle, not a silent zero). Charter proposition 4\n// (explicit failure): the engine does not silently drop dangling\n// entries.\n//\n// charter mapping: proposition 2 (Bevy ChildOf+Children pair, holder\n// perspective) + proposition 3 (machine-readable schema:\n// `componentSchema(Children).entities === 'array<entity>'`) + proposition 4 (explicit\n// failure: dangling entries surface to the AI user via `world.get(parent, Entity)` liveness probe,\n// not silent drop) + proposition 5 (consistent abstraction: Children is the\n// generic relationship-mirror shape, not a ChildOf special case).\n\nimport { defineRelationship } from '@forgeax/engine-ecs';\nimport { Transform } from './transform';\n\n/**\n * Hierarchy forward-list of child entities.\n *\n * `entities` is a variable-length `array<entity>` field; each element is\n * an `Entity` u32 the AI user pushed via\n * `world.push(parent, Children, 'entities', child)`. The value returned by\n * `world.get(parent, Children).unwrap().entities` is a read-only\n * `Uint32Array` snapshot rematerialised fresh on every read (D-4 no-cache);\n * the snapshot's `length` equals the live element count.\n *\n * Invariants:\n * - Children is NOT consumed by `propagateTransforms` (which walks ChildOf\n * upward, D-P2). The forward list is for AI-user traversal / debug /\n * inspection.\n * - Children <-> ChildOf consistency is maintained by the engine via the\n * ChildOf `relationship` mirror hook (see ./child-of.ts): adding /\n * removing / reparenting ChildOf on a child auto-updates the parent's\n * `entities` list. AI users do not hand-sync the two sides for the\n * hierarchy.\n * - Stored entity u32s are NOT auto-cleared when the referenced entity is\n * despawned (OOS-01 above); a `world.get(despawnedChild, ...)` call\n * returns `Result.err(...)` so AI users discover the dangling state\n * through the engine's structured-error channel.\n *\n * @example Spawn a parent and two children via ChildOf (engine maintains Children):\n * const parent = world.spawn({ component: Transform, data: identityXf() }).unwrap();\n * const a = world.spawn(\n * { component: Transform, data: identityXf() },\n * { component: ChildOf, data: { parent } },\n * ).unwrap();\n * const b = world.spawn(\n * { component: Transform, data: identityXf() },\n * { component: ChildOf, data: { parent } },\n * ).unwrap();\n * // Read back via the read-only snapshot - engine appended a, b:\n * const snap = world.get(parent, Children).unwrap().entities;\n * for (let i = 0; i < snap.length; i++) {\n * const child = snap[i];\n * // ... consume; world.get(child, ...) surfaces a structured error\n * // if the child has been despawned (OOS-01 dangling-entity surface).\n * }\n */\nexport const { source: ChildOf, target: Children } = defineRelationship({\n sourceName: 'ChildOf',\n sourceField: 'parent',\n targetName: 'Children',\n targetField: 'entities',\n // Every scene hierarchy node is spatial. Adding ChildOf therefore\n // materializes the local/derived transform pair at the same structural\n // boundary, so render- and scene-authored children cannot enter a frame\n // with an incomplete hierarchy node.\n sourceRequires: [Transform],\n exclusive: true,\n linkedSpawn: true,\n});\n","// @forgeax/engine-runtime - authored local transform and derived world output.\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\nconst IDENTITY_MAT4 = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);\n\n/** Scene-owned derived world transform. Only TransformPropagation writes it. */\nexport const GlobalTransform = defineComponent(\n 'GlobalTransform',\n {\n world: { type: 'array<f32, 16>', default: IDENTITY_MAT4 },\n },\n { transient: true },\n);\n\n/**\n * Authored local position, rotation and scale columns.\n *\n * The ECS `requires` declaration is the generic structural invariant: callers\n * add `Transform`, while `GlobalTransform` is materialized once at spawn/add.\n */\nexport const Transform = defineComponent(\n 'Transform',\n {\n pos: { type: 'array<f32, 3>', default: new Float32Array([0, 0, 0]) },\n // Component order [x, y, z, w] is shared with glTF.\n quat: { type: 'array<f32, 4>', default: new Float32Array([0, 0, 0, 1]) },\n scale: { type: 'array<f32, 3>', default: new Float32Array([1, 1, 1]) },\n },\n { requires: [GlobalTransform] },\n);\n","// Scene-owned hierarchy traversal shared by scene collection and render hooks.\n\nimport type { EntityHandle, World } from '@forgeax/engine-ecs';\n\nimport { Children } from './components/children';\n\n/** Walk a Children hierarchy breadth-first, reusing an optional visited set. */\nexport function collectSubtree(\n world: World,\n spawnRoot: EntityHandle,\n visited?: Set<number>,\n): Set<number> {\n if (visited === undefined) visited = new Set<number>();\n if (visited.has(spawnRoot as number)) return visited;\n const queue: number[] = [spawnRoot as number];\n visited.add(spawnRoot as number);\n while (queue.length > 0) {\n const current = queue.shift() as number;\n const children = world.get(current as EntityHandle, Children);\n if (!children.ok) continue;\n const entities = children.value.entities as ArrayLike<number>;\n for (let index = 0; index < entities.length; index += 1) {\n const child = entities[index] as number;\n if (visited.has(child)) continue;\n visited.add(child);\n queue.push(child);\n }\n }\n return visited;\n}\n","import { defineComponent } from '@forgeax/engine-ecs';\n\n/** Per-entity morph weights; length is validated against the mesh target count. */\nexport const MorphWeights = defineComponent('MorphWeights', {\n weights: { type: 'array<f32>' },\n});\n","// @forgeax/engine-runtime --- Name component (built-in identifier).\n//\n// Single-field minimal skeleton: { value: 'string' }. Bare 'string' schema\n// vocab keyword routes through ECS UniqueRefStore (D-R3 single-arm managed\n// dispatch); the read shape is a native JS string.\n//\n// Lives in `runtime` rather than `ecs` because Name is a built-in *component*,\n// not part of the ECS framework itself (it does not participate in archetype /\n// query / world mechanics like the essential `Entity` component does). Mirrors\n// Bevy's split: `Entity` lives in `bevy_ecs`; `Name` lives in `bevy_core`.\n//\n// Migrated from packages/ecs/src/name.ts by tweak-20260612-ecs-concept-compression\n// (architecture-principles.md §1 SSOT: Name's authoritative location is the\n// runtime built-in components surface, not the ECS framework barrel).\n//\n// Naming follows the Bevy-aligned convention locked by feat-20260513:\n// single-semantic component drops the 'Component' suffix (Transform / Camera\n// / DirectionalLight / Name).\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\nexport const Name = defineComponent('Name', { value: { type: 'string' } });\n","import type { EcsError, EntityHandle } from '@forgeax/engine-ecs';\n\nexport type SceneErrorCode = 'hierarchy-broken' | 'hierarchy-cycle';\n\n/** Scene-instantiation failures owned by the scene package. */\nexport type SceneInstanceErrorCode = 'component-not-defined' | 'scene-override-type-mismatch';\n\nexport { ComponentNotDefinedError } from '@forgeax/engine-ecs/projection';\n\n/** The structured ECS failure retained by a Scene derived-write diagnostic. */\nexport interface SceneErrorCause {\n readonly code: EcsError['code'];\n readonly expected?: string;\n readonly hint?: string;\n readonly detail?: unknown;\n}\n\n/** Location detail shared by hierarchy diagnostics and derived-write errors. */\nexport interface SceneHierarchyErrorDetail {\n readonly kind?: 'hierarchy';\n readonly entity: EntityHandle;\n readonly parent: EntityHandle;\n}\n\n/** A flat derived publication failure with its original ECS error intact. */\nexport interface SceneDerivedWriteErrorDetail {\n readonly kind: 'derived-write';\n readonly entity: EntityHandle;\n readonly parent: EntityHandle;\n readonly bindingIndex: number;\n readonly base: number;\n readonly start: number;\n readonly count: number;\n readonly cause: SceneErrorCause;\n}\n\nexport type SceneErrorDetail = SceneHierarchyErrorDetail | SceneDerivedWriteErrorDetail;\n\nexport class SceneError extends Error {\n readonly code: SceneErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: SceneErrorDetail | undefined;\n\n constructor(args: {\n code: SceneErrorCode;\n expected: string;\n hint: string;\n detail?: SceneErrorDetail;\n }) {\n super(`[SceneError ${args.code}] expected: ${args.expected}; hint: ${args.hint}`);\n this.name = 'SceneError';\n this.code = args.code;\n this.expected = args.expected;\n this.hint = args.hint;\n this.detail = args.detail;\n }\n}\n","import type { EntityHandle } from '@forgeax/engine-ecs';\nimport type { SceneEntityRef } from '@forgeax/engine-types';\nimport { err, ok, type Result } from '@forgeax/engine-types';\n\nexport type { SceneEntityRef } from '@forgeax/engine-types';\n\nexport type SceneBindingError = {\n readonly code: 'scene-binding-missing' | 'scene-binding-wrong-instance';\n readonly expected: string;\n readonly hint: string;\n readonly detail: { readonly sceneSourceKey: string; readonly bindingKey: string };\n};\n\nexport type SceneBindingDeclarationError = {\n readonly code: 'scene-binding-duplicate' | 'scene-binding-source-missing';\n readonly expected: string;\n readonly hint: string;\n readonly detail: { readonly sceneSourceKey?: string; readonly bindingKey?: string };\n};\n\nexport function validateSceneBindings(\n sceneSourceKey: string,\n bindingKeys: readonly string[],\n): Result<readonly string[], SceneBindingDeclarationError> {\n if (sceneSourceKey.length === 0) {\n return err({\n code: 'scene-binding-source-missing',\n expected: 'a non-empty scene sourceKey',\n hint: 'declare the scene sourceKey in the author inventory',\n detail: {},\n });\n }\n const seen = new Set<string>();\n for (const bindingKey of bindingKeys) {\n if (bindingKey.length === 0 || seen.has(bindingKey)) {\n return err({\n code: 'scene-binding-duplicate',\n expected: 'unique non-empty bindingKey values within one scene',\n hint: 'rename the duplicate bindingKey in the scene producer',\n detail: { sceneSourceKey, bindingKey },\n });\n }\n seen.add(bindingKey);\n }\n return ok([...bindingKeys]);\n}\n\nexport function sceneEntity(sceneSourceKey: string, bindingKey: string): SceneEntityRef {\n return { sceneSourceKey, bindingKey };\n}\n\nexport function resolveSceneEntity(\n ref: SceneEntityRef,\n instance: {\n readonly sceneSourceKey: string;\n readonly bindings: ReadonlyMap<string, EntityHandle | number>;\n },\n): Result<EntityHandle | number, SceneBindingError> {\n if (ref.sceneSourceKey !== instance.sceneSourceKey) {\n return err({\n code: 'scene-binding-wrong-instance',\n expected: `scene instance ${ref.sceneSourceKey}`,\n hint: 'resolve the SceneEntityRef against its owning SceneInstance',\n detail: { sceneSourceKey: ref.sceneSourceKey, bindingKey: ref.bindingKey },\n });\n }\n const value = instance.bindings.get(ref.bindingKey);\n if (value === undefined) {\n return err({\n code: 'scene-binding-missing',\n expected: 'bindingKey declared by the scene producer',\n hint: 'declare the bindingKey in the scene producer before consuming it',\n detail: { sceneSourceKey: ref.sceneSourceKey, bindingKey: ref.bindingKey },\n });\n }\n return ok(value);\n}\n","/** Immutable Scene collection policy shared by runtime collectors. */\nexport interface SceneCollectProfile {\n readonly includeComponent: (componentName: string, transient: boolean) => boolean;\n readonly includeField: (componentName: string, fieldName: string, transient: boolean) => boolean;\n}\n\nexport const SCENE_COLLECT_PROFILE: SceneCollectProfile = Object.freeze({\n includeComponent: (_componentName: string, transient: boolean) => !transient,\n includeField: (_componentName: string, _fieldName: string, transient: boolean) => !transient,\n});\n","import type { AssetRef, MountOverride, SceneAsset } from '@forgeax/engine-types';\nimport { err, ok, type Result } from '@forgeax/engine-types';\n\nexport type SceneComponentSchemaResolver = (\n componentName: string,\n) => Readonly<Record<string, string>> | undefined;\n\nexport interface SceneExternalizationError {\n readonly field: string;\n readonly value: unknown;\n}\n\nexport interface ExternalizedSceneAsset {\n readonly payload: Record<string, unknown>;\n readonly refs: readonly AssetRef[];\n}\n\nfunction sharedKind(type: string | undefined): 'one' | 'many' | undefined {\n if (type?.startsWith('shared<')) return 'one';\n if (type?.startsWith('array<shared<')) return 'many';\n return undefined;\n}\n\nfunction overrideGuids(\n override: MountOverride,\n resolveSchema: SceneComponentSchemaResolver,\n): readonly { field: string; guid: string }[] {\n const schema = resolveSchema(override.comp);\n const values =\n override.field !== undefined\n ? [[override.field, override.value] as const]\n : override.value !== null &&\n typeof override.value === 'object' &&\n !Array.isArray(override.value)\n ? Object.entries(override.value as Record<string, unknown>)\n : [];\n return values.flatMap(([field, value]) => {\n const kind = sharedKind(schema?.[field]);\n if (kind === 'one' && typeof value === 'string') return [{ field, guid: value }];\n if (kind === 'many' && Array.isArray(value)) {\n return value.flatMap((item) => (typeof item === 'string' ? [{ field, guid: item }] : []));\n }\n return [];\n });\n}\n\n/** Project a SceneAsset's shared asset fields into a payload plus indexed refs. */\nexport function externalizeSceneAsset(\n scene: SceneAsset,\n resolveSchema: SceneComponentSchemaResolver,\n): Result<ExternalizedSceneAsset, SceneExternalizationError> {\n const refs: AssetRef[] = [];\n const indexByGuid = new Map<string, number>();\n const addRef = (\n guid: string,\n sourceField: NonNullable<AssetRef['sourceField']>,\n sceneEntityId?: number,\n ): number => {\n const prior = indexByGuid.get(guid);\n if (prior !== undefined) return prior;\n const index = refs.length;\n refs.push({ guid, sourceField, ...(sceneEntityId === undefined ? {} : { sceneEntityId }) });\n indexByGuid.set(guid, index);\n return index;\n };\n\n const entities = scene.entities.map((entity) => {\n const components: Record<string, Record<string, unknown>> = {};\n for (const componentName of Object.keys(entity.components)) {\n const schema = resolveSchema(componentName);\n const source = entity.components[componentName] as Record<string, unknown> | undefined;\n if (source === undefined) continue;\n const fields: Record<string, unknown> = {};\n for (const fieldName of Object.keys(source)) {\n const value = source[fieldName];\n if (value === undefined) continue;\n const kind = sharedKind(schema?.[fieldName]);\n if (kind === 'one' && typeof value === 'string') {\n fields[fieldName] = addRef(value, { componentName, fieldName }, entity.localId as number);\n } else if (kind === 'many' && Array.isArray(value)) {\n fields[fieldName] = value.map((item, arrayIndex) =>\n typeof item === 'string'\n ? addRef(item, { componentName, fieldName, arrayIndex }, entity.localId as number)\n : item,\n );\n } else {\n fields[fieldName] = value;\n }\n }\n if (Object.keys(fields).length > 0 || Object.keys(schema ?? {}).length === 0) {\n components[componentName] = fields;\n }\n }\n return {\n localId: entity.localId as number,\n ...(entity.bindingKey === undefined ? {} : { bindingKey: entity.bindingKey }),\n components,\n };\n });\n\n const mounts = scene.mounts?.map((mount) => {\n const source =\n typeof mount.source === 'string'\n ? addRef(\n mount.source,\n { componentName: 'SceneInstance', fieldName: 'source' },\n mount.localId as number,\n )\n : (mount.source as number);\n for (const { field, guid } of (mount.overrides ?? []).flatMap((override) =>\n overrideGuids(override, resolveSchema),\n )) {\n addRef(guid, { componentName: 'SceneInstance', fieldName: `overrides.${field}` });\n }\n return {\n localId: mount.localId as number,\n source,\n memberFirst: mount.memberFirst as number,\n memberCount: mount.memberCount,\n ...(mount.parent === undefined ? {} : { parent: mount.parent as number }),\n ...(mount.publicationFence === undefined ? {} : { publicationFence: mount.publicationFence }),\n ...(mount.overrides === undefined\n ? {}\n : { overrides: mount.overrides.map((item) => ({ ...item })) }),\n };\n });\n for (const [arrayIndex, guid] of (scene.skinGuids ?? []).entries()) {\n if (typeof guid !== 'string') return err({ field: 'skinGuids', value: guid });\n addRef(guid, { componentName: '<scene>', fieldName: 'skinGuids', arrayIndex });\n }\n return ok({\n payload: {\n kind: 'scene',\n ...(scene.sourceKey === undefined ? {} : { sourceKey: scene.sourceKey }),\n entities,\n ...(mounts === undefined || mounts.length === 0 ? {} : { mounts }),\n ...(scene.skinGuids === undefined\n ? {}\n : { skinGuids: scene.skinGuids.map((guid) => indexByGuid.get(guid) as number) }),\n },\n refs,\n });\n}\n","// @forgeax/engine-scene — scene instantiation and instance-state subsystem.\n\nimport {\n type Component,\n type ComponentData,\n type ComponentSchema,\n type EcsError,\n ENTITY_NULL_RAW,\n type EntityHandle,\n type InputShapeOf,\n type ShapeOf,\n type World,\n} from '@forgeax/engine-ecs';\nimport { classifyEntityField, remapEntityFieldValue } from '@forgeax/engine-ecs/externalization';\nimport { componentSchema } from '@forgeax/engine-ecs/internal';\nimport { fillComponentDefaults, StaleEntityError } from '@forgeax/engine-ecs/projection';\nimport type {\n Handle,\n LocalEntityId,\n MountOverride,\n PackErrorCode,\n PackErrorDetail,\n SceneAsset,\n SceneEntityRef,\n SceneInstanceMount,\n} from '@forgeax/engine-types';\nimport {\n err,\n ok,\n PACK_ERROR_HINTS,\n type Result,\n toUnique,\n unwrapHandle,\n} from '@forgeax/engine-types';\nimport { ComponentNotDefinedError } from '../errors';\nimport { resolveSceneEntity, validateSceneBindings } from './binding.js';\nimport {\n isPrimitiveScalarFieldType,\n mountOverrideStateKey,\n primitiveJsType,\n type SceneInstanceStatePayload,\n sceneWorldState,\n} from './state.js';\n\nexport type { SceneInstanceStatePayload } from './state.js';\n\nconst entityIndex = (entity: EntityHandle): number => (entity as number) & 0x00ffffff;\nconst entityGeneration = (entity: EntityHandle): number => ((entity as number) >>> 24) & 0xff;\n\n/**\n * C-R2 (feat-20260622-s5 / studio-issues): one structured, non-fatal record of\n * a SceneAsset payload field that did NOT match the target component's schema.\n *\n * Scene data is loader-fed and may carry a stale / deprecated / typo'd field\n * (an editor renames a field, an old `.pack.json` lags). `worldInstantiateScene`\n * does NOT blank the whole scene over one such field (#478 lesson: a\n * prod-silent strip re-introduced an invisible-entity class) and does NOT abort\n * fatally. Instead it skips the unknown key (no write, no input mutation) and\n * surfaces this record on the success value's `diagnostics[]` — observable in\n * production (NOT NODE_ENV-gated), consumed by property access (no string parse):\n *\n * const r = worldInstantiateScene(world, handle);\n * if (r.ok) for (const d of r.value.diagnostics)\n * console.warn(`unknown field ${d.component}.${d.field} on localId ${d.localId}`);\n *\n * Direct `world.spawn` / `world.addComponent` / `Commands.spawn` stay fail-fast\n * with `SpawnDataUnknownFieldError` — those are explicit API calls where a typo\n * is a programming error, not loader-fed data.\n */\nexport type SceneInstantiateDiagnostic = {\n /** Component name (schema key) the unknown field appeared under. */\n readonly component: string;\n /** The offending field name not declared in the component schema. */\n readonly field: string;\n /** LocalEntityId (within its owning SceneAsset) of the carrying entity. */\n readonly localId: number;\n};\n\n/**\n * Success value of `worldInstantiateScene`. `root` is the synthetic scene-root\n * EntityHandle (carries `SceneInstance`); `diagnostics` is the (possibly empty)\n * list of non-fatal unknown-field records aggregated across this scene and every\n * recursively mounted sub-scene (C-R2). Empty array = no diagnostics.\n */\nexport type SceneInstantiateOk = {\n readonly root: EntityHandle;\n readonly diagnostics: readonly SceneInstantiateDiagnostic[];\n};\n\n/**\n * Success value of `worldInstantiateSceneFlat` — the \"edit the scene itself\"\n * primitive. Unlike `instantiateScene`, NO synthetic SceneInstance root is\n * minted and NO `ChildOf` is forced onto top-level members: the scene's own\n * entities become plain top-level world entities whose hierarchy is exactly\n * their authored `ChildOf` (an entity with no `ChildOf` stays a root). `roots`\n * is the set of those top-level handles (own rootless entities + top-level\n * mount carriers). Nested prefabs inside the scene STILL materialise as their\n * own SceneInstance anchors (charter P4: instance == entity-with-SceneInstance)\n * — only THIS scene is flat.\n */\nexport type SceneInstantiateFlatOk = {\n readonly roots: EntityHandle[];\n /**\n * All mount carrier entities spawned while flattening this scene. These are\n * separate from `roots`: carriers with an authored parent are not roots,\n * but still delimit a nested prefab subtree for post-spawn hooks.\n */\n readonly mountEntities: EntityHandle[];\n readonly diagnostics: readonly SceneInstantiateDiagnostic[];\n};\n\n/**\n * @internal Intermediate produced by `_spawnSceneMembers` and consumed by both\n * the anchor finisher (`_instantiateSceneAsset`) and the flat finisher\n * (`_instantiateSceneAssetFlat`). Holds everything the shared member-spawn\n * (mounts recursion + own-entity spawn + deferred owned-parent wiring) computes,\n * before either finisher decides whether to wrap the members in a synthetic\n * SceneInstance root.\n */\nexport interface SceneMembersSpawn {\n /** LocalEntityId → live Entity u32 (ENTITY_NULL_RAW for unspawned slots). */\n readonly mapping: Uint32Array;\n /** Reverse map live Entity → LocalEntityId for override / detach bookkeeping. */\n readonly entityToLocalId: Map<EntityHandle, LocalEntityId>;\n /** Own entities that carried no `ChildOf` — the scene's authored top-level roots. */\n readonly rootEntities: EntityHandle[];\n /** Mount carriers whose `mount.parent === undefined` (default-parented). */\n readonly mountEntitiesNeedingRootParent: EntityHandle[];\n /** Every mount carrier spawned by this scene, including explicitly parented carriers. */\n readonly mountEntities: EntityHandle[];\n /**\n * The child anchor and mapping for each mount. Flat scene opening has no\n * outer SceneInstance state to own parent-namespace mount overrides, so it\n * records those overrides on this child anchor after the shared spawn pass.\n */\n readonly mountInstances: readonly {\n readonly mount: SceneInstanceMount;\n readonly root: EntityHandle;\n readonly mapping: Uint32Array;\n }[];\n /** `entities.length + mounts + Σ memberCount`, captured at instantiate-time. */\n readonly totalSlots: number;\n}\n\nexport type SceneAssetResolver = (\n source: number | string,\n parentHandle: Handle<'SceneAsset', 'shared'>,\n) => Result<Handle<'SceneAsset', 'shared'>, unknown>;\n\n/** @internal */\nexport function worldSetSceneAssetResolver(world: World, resolver: SceneAssetResolver): void {\n sceneWorldState(world).resolver = resolver;\n}\n\n/** @internal */\nexport function worldGetSceneAssetResolver(world: World): SceneAssetResolver | null {\n return sceneWorldState(world).resolver as SceneAssetResolver | null;\n}\n\n/**\n * Materialise a SceneAsset (and any nested SceneAsset references via\n * `mounts[]`) into live entities. Returns the synthetic root Entity that\n * carries the `SceneInstance` ECS component (charter P4: instance ==\n * entity-with-SceneInstance).\n *\n * Recursion path is closed inside `_instantiateSceneRec(handle, parent,\n * stack)` (D-3); cycle detection is fail-fast `pack-cyclic-reference +\n * detail.kind:'mount-asset'` (D-1 mirror, plan-strategy §D-3). The\n * caller-supplied `parent` flows to the synthetic root's `ChildOf` so the\n * full sub-tree attaches under the AI user's host entity.\n *\n * @example\n * const r = worldInstantiateScene(world, handle);\n * if (!r.ok) return r;\n * const { root, diagnostics } = r.value;\n * for (const d of diagnostics) // C-R2: unknown-field records, non-fatal\n * console.warn(`unknown field ${d.component}.${d.field} on localId ${d.localId}`);\n * const inst = world.get(root, SceneInstance).value;\n * const member = inst.mapping[0]; // first member entity\n */\nexport function worldInstantiateScene(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n parent?: EntityHandle,\n): Result<SceneInstantiateOk, EcsError> {\n const stack = new Set<number>();\n // C-R2: collect non-fatal unknown-field diagnostics across this scene and\n // every recursively mounted sub-scene. The internal recursion writes into\n // this accumulator; only the public entry packages it onto the success value.\n const diagnostics: SceneInstantiateDiagnostic[] = [];\n const r = worldInstantiateSceneRec(world, handle, parent, stack, diagnostics);\n if (!r.ok) return r;\n return ok({ root: r.value, diagnostics });\n}\n\n/**\n * Materialise a projected `SceneAsset` payload without exposing the temporary\n * shared-ref handle to the caller. The World remains the owner of both the\n * handle and the instantiated SceneInstance: the producer grant is released\n * after the SceneInstance retains its source, including when instantiation\n * fails. This is the payload-shaped counterpart to `worldInstantiateScene` for\n * hosts that load a SceneAsset directly from the Engine AssetRegistry.\n */\nexport function worldInstantiateScenePayload(\n world: World,\n asset: SceneAsset,\n parent?: EntityHandle,\n): Result<SceneInstantiateOk, EcsError> {\n const handle = world.allocSharedRef('SceneAsset', asset);\n try {\n return worldInstantiateScene(world, handle, parent);\n } finally {\n // The SceneInstance source column retains the handle on success. On a\n // failed materialisation there should be no remaining holder; either way\n // release the producer grant owned by this convenience entrypoint.\n world.sharedRefs.release(handle);\n }\n}\n\n/**\n * Materialise a SceneAsset FLAT — the \"edit the scene itself\" primitive.\n * Unlike `instantiateScene`, this mints NO synthetic SceneInstance root and\n * forces NO `ChildOf` onto top-level members: the scene's own entities become\n * plain top-level world entities whose hierarchy is exactly their authored\n * `ChildOf` (an entity with no `ChildOf` is a root). Use this to OPEN a scene\n * for editing; use `instantiateScene` (anchor) at runtime / for nested\n * prefabs where an instance boundary + override isolation is wanted.\n *\n * Nested prefabs referenced via `mounts[]` STILL materialise as their own\n * SceneInstance anchors (charter P4 preserved) — only THIS top scene is flat.\n *\n * @example\n * const r = worldInstantiateSceneFlat(world, handle);\n * if (!r.ok) return r;\n * const { roots, diagnostics } = r.value; // roots = top-level handles\n */\nexport function worldInstantiateSceneFlat(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n): Result<SceneInstantiateFlatOk, EcsError> {\n const stack = new Set<number>();\n const diagnostics: SceneInstantiateDiagnostic[] = [];\n const handleKey = unwrapHandle(handle);\n const resolved = worldResolveSceneAsset(world, handle);\n if (!resolved.ok) return resolved;\n stack.add(handleKey);\n let r: Result<{ roots: EntityHandle[]; mountEntities: EntityHandle[] }, EcsError>;\n try {\n r = worldInstantiateSceneAssetFlat(world, handle, resolved.value, stack, diagnostics);\n } finally {\n stack.delete(handleKey);\n }\n if (!r.ok) return r;\n return ok({ ...r.value, diagnostics });\n}\n/**\n * @internal Recursive helper carrying the cycle-detection stack. Sugar /\n * other public callers must not see this mechanic — use `instantiateScene`\n * (D-3 / charter P1).\n */\nexport function worldInstantiateSceneRec(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n parent: EntityHandle | undefined,\n stack: Set<number>,\n diagnostics: SceneInstantiateDiagnostic[],\n): Result<EntityHandle, EcsError> {\n const handleKey = unwrapHandle(handle);\n if (stack.has(handleKey)) {\n const cycleArr: string[] = [];\n for (const k of stack) cycleArr.push(String(k));\n cycleArr.push(String(handleKey));\n const detail: PackErrorDetail = {\n code: 'pack-cyclic-reference',\n kind: 'mount-asset',\n cycle: cycleArr,\n };\n return err({\n code: 'pack-cyclic-reference' as PackErrorCode,\n expected: 'acyclic SceneAsset mount graph',\n hint: PACK_ERROR_HINTS['pack-cyclic-reference'],\n detail,\n } as unknown as EcsError);\n }\n const resolved = worldResolveSceneAsset(world, handle);\n if (!resolved.ok) return resolved;\n const asset = resolved.value;\n stack.add(handleKey);\n try {\n return worldInstantiateSceneAsset(world, handle, asset, parent, stack, diagnostics);\n } finally {\n stack.delete(handleKey);\n }\n}\n/**\n * @internal Resolve a SceneAsset handle through the SharedRefStore.\n * The handle u32 is the SharedRefStore slot id (`world.allocSharedRef\n * ('SceneAsset', asset)` is the producer; rc starts at 1, the SceneInstance\n * spawn retains to rc=2 in M4 / w13). Errors propagate as EcsError so the\n * instantiateScene chain returns a single closed union.\n */\nexport function worldResolveSceneAsset(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n): Result<SceneAsset, EcsError> {\n const r = world.sharedRefs.resolve(handle);\n if (!r.ok) {\n return err(r.error as unknown as EcsError);\n }\n return ok(r.value as SceneAsset);\n}\n/**\n * @internal Spawn one SceneAsset's members — the shared body of both scene\n * finishers. Recurses into `mounts[]` (each nested prefab becomes its own\n * SceneInstance anchor), spawns `entities[]` honouring their authored\n * `ChildOf`, and wires deferred owned-parent mount edges. Does NOT create a\n * synthetic root or force any `ChildOf` — that is the caller's (finisher's)\n * job. `_instantiateSceneRec` owns cycle bookkeeping.\n */\nexport function worldSpawnSceneMembers(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n asset: SceneAsset,\n stack: Set<number>,\n diagnostics: SceneInstantiateDiagnostic[],\n): Result<SceneMembersSpawn, EcsError> {\n const sceneInstanceToken = world.components.resolve('SceneInstance');\n if (sceneInstanceToken === undefined) {\n return err(new ComponentNotDefinedError('SceneInstance'));\n }\n const childOfToken = world.components.resolve('ChildOf');\n // ChildOf is optional — only needed if the asset declares ChildOf or a\n // caller-supplied parent must be wired. If absent and we need it, we\n // fail-fast at the wiring site below.\n\n const ownEntities = asset.entities;\n const ownMounts = asset.mounts ?? [];\n const bindingKeys = ownEntities.flatMap((entity) =>\n entity.bindingKey === undefined ? [] : [entity.bindingKey],\n );\n if (bindingKeys.length > 0) {\n const bindingCheck = validateSceneBindings(asset.sourceKey ?? '', bindingKeys);\n if (!bindingCheck.ok) {\n return err(bindingCheck.error as unknown as EcsError);\n }\n }\n const memberSum = ownMounts.reduce((s, m) => s + m.memberCount, 0);\n const countBaseline = ownEntities.length + ownMounts.length + memberSum;\n // C-R1 (studio-issues #6): mapping table must be sized to maxLocalId+1,\n // not to the entity count. An editor scene may have non-contiguous\n // localIds (deleted entities leave gaps); sizing to count means any\n // localId >= count is a silent Uint32Array OOB no-op -> entity spawns\n // but is unreachable by localId -> users report \"character can't move\".\n // Take the max of count-baseline and id-range so both packed and\n // sparse scenes work without over-allocation in the common case.\n let maxLocalId = ownEntities.reduce((m, e) => Math.max(m, e.localId as unknown as number), -1);\n for (const mount of ownMounts) {\n maxLocalId = Math.max(maxLocalId, mount.localId as unknown as number);\n const last = (mount.memberFirst as unknown as number) + mount.memberCount - 1;\n maxLocalId = Math.max(maxLocalId, last);\n }\n const totalSlots = Math.max(countBaseline, maxLocalId + 1);\n\n // R2/Bonus: namespace-overlap fail-fast (AC-05 /\n // pack-mount-localid-overlap). Each LocalEntityId in\n // [0, totalSlots) must be claimed by exactly one of:\n // - entities[i].localId\n // - mounts[i].localId\n // - mounts[i] window slot (memberFirst .. memberFirst+memberCount-1)\n // Overlap or duplicate claim => fail-fast with the offending localIds\n // and human-readable origin labels.\n {\n const claims = new Map<number, string>();\n const overlapLids = new Set<number>();\n const overlapSources: string[] = [];\n const claim = (lid: number, src: string): void => {\n const prior = claims.get(lid);\n if (prior !== undefined) {\n if (!overlapLids.has(lid)) {\n overlapLids.add(lid);\n overlapSources.push(prior);\n overlapSources.push(src);\n } else {\n overlapSources.push(src);\n }\n return;\n }\n claims.set(lid, src);\n };\n for (const ent of ownEntities) {\n claim(ent.localId as unknown as number, `entities[${ent.localId as unknown as number}]`);\n }\n for (const mount of ownMounts) {\n const mLid = mount.localId as unknown as number;\n claim(mLid, `mount[${mLid}]`);\n const first = mount.memberFirst as unknown as number;\n for (let k = 0; k < mount.memberCount; k += 1) {\n claim(first + k, `mount[${mLid}].member[${k}]`);\n }\n }\n if (overlapLids.size > 0) {\n const overlapping = Array.from(overlapLids).sort((a, b) => a - b);\n return err({\n code: 'pack-mount-localid-overlap' as PackErrorCode,\n expected: 'each LocalEntityId claimed by exactly one entity or mount slot',\n hint: PACK_ERROR_HINTS['pack-mount-localid-overlap'],\n detail: {\n code: 'pack-mount-localid-overlap',\n overlapping,\n sources: overlapSources,\n } as PackErrorDetail,\n } as unknown as EcsError);\n }\n }\n\n // Slot table: indexed by LocalEntityId; populated as entities / mounts /\n // members are spawned. mapping[localId] = encoded Entity u32. Unspawned\n // slots hold ENTITY_NULL_RAW (0xffffffff) — NOT 0, because a fresh World's\n // first spawn encodes to gen=0+idx=0=raw 0, which is a valid Entity. The\n // remap path in `_buildSceneEntityComponentDatas` distinguishes the two\n // (live=ENTITY_NULL_RAW => parent unspawned at remap time => surface as\n // null sentinel; live=any other u32 => valid live Entity, including 0).\n const mapping = new Uint32Array(totalSlots).fill(ENTITY_NULL_RAW);\n const entityToLocalId = new Map<EntityHandle, LocalEntityId>();\n const rootEntities: EntityHandle[] = [];\n const mountEntities: EntityHandle[] = [];\n // R2/B-1: mount entities whose `mount.parent === undefined` need their\n // ChildOf wired to the outer synthetic root (this scene's root). Step 5\n // does the wiring once the synthetic root entity is materialised; we\n // collect them here in step 1.\n const mountEntitiesNeedingRootParent: EntityHandle[] = [];\n // D-8 (feat-20260707): mount entities whose `mount.parent` points at an\n // OWNED entity slot are wired AFTER step 2 spawns the owned entities —\n // mounts are processed first (step 1), so the owned parent slot is still\n // ENTITY_NULL_RAW at mount-processing time. Same deferred-wiring shape as\n // mountEntitiesNeedingRootParent: register [mountEntity, parentSlot] here,\n // wire ChildOf once the slot is live. Without this the edge was silently\n // dropped, and the mount carrier stayed unreachable from its owned parent.\n const mountEntitiesNeedingDeferredParent: Array<[EntityHandle, number]> = [];\n const mountInstances: Array<{\n readonly mount: SceneInstanceMount;\n readonly root: EntityHandle;\n readonly mapping: Uint32Array;\n }> = [];\n\n // 1. Recurse into mounts[] FIRST so the mount-window slots\n // (`mount.localId` + `[memberFirst, memberFirst+memberCount)`) are\n // populated before any owned entity tries to remap a LocalEntityId\n // pointing into the mount window (AC-24 cross-boundary reference).\n for (const mount of ownMounts) {\n // R2/B-3 + R2/B-4: validate overrides BEFORE child resolution so a\n // malformed override fails fast without observable side-effects.\n const overrideValidationRes = worldValidateMountOverrides(world, mount);\n if (!overrideValidationRes.ok) {\n return overrideValidationRes;\n }\n\n // Spawn the mount entity (carries mount.components).\n const mountLid = mount.localId as unknown as number;\n const mountSpawnRes = worldSpawnMountEntity(world, mount, mapping, diagnostics);\n if (!mountSpawnRes.ok) return mountSpawnRes;\n const mountEntity = mountSpawnRes.value;\n mountEntities.push(mountEntity);\n mapping[mountLid] = mountEntity as unknown as number;\n\n // Resolve mount.source -> child SceneAsset handle.\n const childHandleRes = worldResolveMountSource(world, mount.source, handle);\n if (!childHandleRes.ok) return childHandleRes;\n const childHandle = childHandleRes.value;\n\n // Recursively instantiate the child. Its synthetic root attaches as a\n // child of the mount entity. The child writes its own unknown-field\n // diagnostics into the SAME accumulator, so they bubble to the top-level\n // instantiateScene result (C-R2 recursive aggregation).\n const childRes = worldInstantiateSceneRec(world, childHandle, mountEntity, stack, diagnostics);\n if (!childRes.ok) return childRes;\n\n // R2/B-2: cross-check mount.memberCount === child.totalSlots BEFORE\n // copying the mount window. The child SceneInstance.mapping length is\n // the authoritative `totalSlots` of the child. AC-04 / requirements\n // S-5 mandate fail-fast at runtime for this disagreement.\n const childInstRes = world.get(childRes.value, sceneInstanceToken);\n if (!childInstRes.ok) return childInstRes;\n const childMapping = (childInstRes.value as unknown as { mapping: Uint32Array }).mapping;\n mountInstances.push({ mount, root: childRes.value, mapping: childMapping });\n if (childMapping.length !== mount.memberCount) {\n return err({\n code: 'pack-mount-count-mismatch' as PackErrorCode,\n expected: 'mount.memberCount === child SceneAsset totalSlots',\n hint: PACK_ERROR_HINTS['pack-mount-count-mismatch'],\n detail: {\n code: 'pack-mount-count-mismatch',\n mountLocalId: mountLid,\n declared: mount.memberCount,\n actual: childMapping.length,\n } as PackErrorDetail,\n } as unknown as EcsError);\n }\n\n // Pull the child's mapping into our parent window. Default unset slots\n // to ENTITY_NULL_RAW so downstream \"live\" checks distinguish them from\n // the first Entity (gen=0+idx=0 encodes to raw u32 0).\n const window = mount.memberCount;\n for (let k = 0; k < window; k += 1) {\n mapping[(mount.memberFirst as unknown as number) + k] = childMapping[k] ?? ENTITY_NULL_RAW;\n }\n\n // Apply mount.overrides at instantiate-time (AC-19).\n // Each override.localId addresses a slot in *this* (parent) namespace\n // (R2/F-8 cement: parent-namespace + memberFirst+offset addressing).\n // The state map will be populated below with these overrides — but we\n // must also write the value through to the live entity column so the\n // readback invariant holds.\n // Mount-entity itself never has children attached by the caller other\n // than via the recursive child; nothing else to wire here.\n if (childOfToken !== undefined) {\n if (mount.parent !== undefined) {\n // Reparent the mount-entity ChildOf to the caller-specified parent.\n const parentSlot = mount.parent as unknown as number;\n const parentEntity = mapping[parentSlot];\n if (parentEntity !== undefined && parentEntity !== ENTITY_NULL_RAW) {\n const r = world.addComponent(mountEntity, {\n component: childOfToken,\n data: { parent: parentEntity } as never,\n });\n if (!r.ok) {\n // ChildOf may already be present from layer-1; reparent via set.\n const set = world.set(mountEntity, childOfToken, {\n parent: parentEntity,\n } as never);\n if (!set.ok) return set as Result<SceneMembersSpawn, EcsError>;\n }\n } else {\n // D-8: the owned parent slot is not spawned yet (owned entities\n // spawn in step 2, after this mount loop). Defer the ChildOf wire\n // to step 2's tail once mapping[parentSlot] is live.\n mountEntitiesNeedingDeferredParent.push([mountEntity, parentSlot]);\n }\n } else {\n // R2/B-1: default semantic — mount.parent === undefined wires the\n // mount entity ChildOf to *this* scene's synthetic root (created\n // in step 3 below). Defer the actual wire to step 5 after the\n // synthetic root spawn; record the mount entity here.\n mountEntitiesNeedingRootParent.push(mountEntity);\n }\n }\n }\n\n // 2. Spawn entities[] entities. Topo-sort by ChildOf so parents are\n // spawned before children (so localId remap can read mapping live).\n // This runs AFTER mount processing (step 1) so cross-boundary\n // `ChildOf {parent: <mount-window-localId>}` references resolve\n // correctly (AC-24).\n const order = sceneTopoSort(ownEntities);\n for (const idx of order) {\n const node = ownEntities[idx];\n if (node === undefined) continue;\n const lid = node.localId as unknown as number;\n const compDataRes = worldBuildSceneEntityComponentDatas(world, node, mapping, diagnostics);\n if (!compDataRes.ok) return compDataRes;\n const sp = (world.spawn as (...c: ComponentData[]) => Result<EntityHandle, EcsError>)(\n ...compDataRes.value,\n );\n if (!sp.ok) return sp as Result<SceneMembersSpawn, EcsError>;\n const e = sp.value;\n mapping[lid] = e as unknown as number;\n entityToLocalId.set(e, lid as unknown as LocalEntityId);\n if (node.components.ChildOf === undefined) {\n rootEntities.push(e);\n }\n }\n\n // 2b. D-8 (feat-20260707): wire deferred owned-parent mount ChildOf edges.\n // Owned entities are now live (step 2 above), so mapping[parentSlot]\n // resolves. Same shape as the mountEntitiesNeedingRootParent wiring in\n // step 5. The relationship mirror hook (relationshipOnInsert) pushes the\n // carrier into the owned parent's Children mirror automatically.\n if (childOfToken !== undefined) {\n for (const [mountEntity, parentSlot] of mountEntitiesNeedingDeferredParent) {\n const parentEntity = mapping[parentSlot];\n if (parentEntity === undefined || parentEntity === ENTITY_NULL_RAW) continue;\n const set = world.set(mountEntity, childOfToken, { parent: parentEntity } as never);\n if (!set.ok) {\n const r = world.addComponent(mountEntity, {\n component: childOfToken,\n data: { parent: parentEntity } as never,\n });\n if (!r.ok) return r as Result<SceneMembersSpawn, EcsError>;\n }\n }\n }\n\n return ok({\n mapping,\n entityToLocalId,\n rootEntities,\n mountEntitiesNeedingRootParent,\n mountEntities,\n mountInstances,\n totalSlots,\n });\n}\n/**\n * @internal Spawn one SceneAsset's entities + apply mounts recursively, then\n * wrap them in a synthetic SceneInstance root (the anchor). This is the\n * runtime / Play / nested-mount finisher (charter P4: instance ==\n * entity-with-SceneInstance). Caller (`_instantiateSceneRec`) owns cycle\n * bookkeeping.\n */\nexport function worldInstantiateSceneAsset(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n asset: SceneAsset,\n parent: EntityHandle | undefined,\n stack: Set<number>,\n diagnostics: SceneInstantiateDiagnostic[],\n): Result<EntityHandle, EcsError> {\n const sceneInstanceToken = world.components.resolve('SceneInstance');\n if (sceneInstanceToken === undefined) {\n return err(new ComponentNotDefinedError('SceneInstance'));\n }\n const childOfToken = world.components.resolve('ChildOf');\n\n const membersRes = worldSpawnSceneMembers(world, handle, asset, stack, diagnostics);\n if (!membersRes.ok) return membersRes;\n const { mapping, entityToLocalId, rootEntities, mountEntitiesNeedingRootParent, totalSlots } =\n membersRes.value;\n const { mountInstances } = membersRes.value;\n const ownMounts = asset.mounts ?? [];\n\n // 3. Spawn the synthetic root entity carrying SceneInstance.\n // First alloc the state ref so the SceneInstance.state column has a\n // live u32; then attach SceneInstance to a fresh entity.\n let stateRef: Handle<'SceneInstanceState', 'unique'>;\n stateRef = world.allocUniqueRef('SceneInstanceState', null, () => {\n sceneWorldState(world).statePayloads.delete(Number(stateRef));\n });\n // Spawn the root with SceneInstance component, mapping snapshot, and\n // state ref. The mapping is a Uint32Array (array<entity> field shape).\n // Convert mapping Uint32Array to plain number[] for spawn write — the\n // ECS array<entity> arm copies element-by-element and accepts both, but\n // the plain-array form sidesteps a Uint32Array.length=0 corner case\n // observed during M2 testing where a non-empty Uint32Array was written\n // as if empty (suspect: archetype write-array dispatch on instanceof\n // Array vs TypedArray).\n const mappingPlain: number[] = Array.from(mapping);\n // The synthetic root is the ChildOf parent of every owned root entity\n // (step 5 below) and may itself become a ChildOf parent of a caller-\n // supplied `parent` chain. propagateTransforms walks ChildOf parents\n // through the Transform liveMap and treats a parent missing Transform\n // as `hierarchy-broken`, so the synthetic root must carry Transform\n // (identity TRS via layer-2 defaults) when Transform is defined.\n const rootComponents: ComponentData[] = [\n {\n component: sceneInstanceToken,\n data: {\n source: handle,\n mapping: mappingPlain,\n state: stateRef,\n } as never,\n },\n ];\n const transformToken = world.components.resolve('Transform');\n if (transformToken !== undefined) {\n rootComponents.push({\n component: transformToken,\n data: {} as never,\n });\n }\n const rootSpawn = (world.spawn as (...c: ComponentData[]) => Result<EntityHandle, EcsError>)(\n ...rootComponents,\n );\n if (!rootSpawn.ok) {\n return rootSpawn;\n }\n const rootEntity = rootSpawn.value;\n\n // 4. Build SceneInstanceState payload + register it in the UniqueRefStore\n // under the same handle. We use the public `_setUniqueRefPayload`\n // helper (added below) so the alloc -> populate sequence stays atomic.\n const overrides = new Map<LocalEntityId, Map<string, MountOverride>>();\n for (const mount of ownMounts) {\n for (const ov of mount.overrides ?? []) {\n // feat-20260713 M2 / w8: `MountOverride.field` is optional (add-or-patch\n // discriminant carried by the shape itself). Record the override into\n // the SceneInstanceState map keyed by comp (no field) or comp:field\n // (field-patch), then apply it to the live member column via the shared\n // add-or-patch helper.\n const lid = ov.localId as unknown as LocalEntityId;\n let fieldMap = overrides.get(lid);\n if (fieldMap === undefined) {\n fieldMap = new Map();\n overrides.set(lid, fieldMap);\n }\n fieldMap.set(mountOverrideStateKey(ov), ov);\n // Apply override to the live member entity column.\n const memberEntityRaw = mapping[lid as unknown as number];\n if (memberEntityRaw !== undefined && memberEntityRaw !== ENTITY_NULL_RAW) {\n const memberEntity = memberEntityRaw as unknown as EntityHandle;\n const applyRes = worldApplyMountOverride(world, memberEntity, ov);\n if (!applyRes.ok) {\n return applyRes as Result<EntityHandle, EcsError>;\n }\n }\n }\n }\n\n const detached = new Set<LocalEntityId>();\n const bindings = new Map<string, EntityHandle>();\n for (const entity of asset.entities) {\n if (entity.bindingKey === undefined) continue;\n const live = mapping[entity.localId as unknown as number];\n if (live !== undefined && live !== ENTITY_NULL_RAW) {\n bindings.set(entity.bindingKey, live as unknown as EntityHandle);\n }\n }\n const state: Record<string, unknown> = {\n source: handle,\n sceneSourceKey: asset.sourceKey,\n bindings,\n entityToLocalId,\n detachedLocalIds: detached,\n // Convert overrides Map<LocalEntityId, Map<string, MountOverride>>\n // into Map<LocalEntityId, Map<string, SceneInstanceOverrideRecord>>\n overrides: worldMountOverridesToStateMap(overrides),\n rootEntities,\n mountRoots: mountInstances.map(({ root }) => root),\n totalSlots,\n mountTimeOverrides: ownMounts.flatMap((m) => m.overrides ?? []),\n };\n // Stuff the state into the UniqueRefStore under the existing slot. We\n // re-use the slot we allocated above by writing directly into the\n // payloads map via a `_setUniqueRefPayload` shim.\n worldSetUniqueRefPayload(world, stateRef, state);\n\n // 5. Wire ChildOf for every owned root entity (no ChildOf at layer-1)\n // to the synthetic root.\n if (childOfToken !== undefined) {\n for (const rootE of rootEntities) {\n const has = world.get(rootE, childOfToken);\n if (!has.ok) {\n // No ChildOf yet — attach to synthetic root.\n const r = world.addComponent(rootE, {\n component: childOfToken,\n data: { parent: rootEntity } as never,\n });\n if (!r.ok) return r as Result<EntityHandle, EcsError>;\n }\n }\n // R2/B-1: wire mount entities with default `mount.parent === undefined`\n // to this scene's synthetic root. _spawnMountEntity may have attached a\n // placeholder ChildOf {parent: ENTITY_NULL_RAW} when mount.components\n // was empty; overwrite via set so the ChildOf chain meshRenderer ->\n // childSyntheticRoot -> mountEntity -> outerSyntheticRoot resolves\n // through Transform-bearing parents (AC-16 / requirements S-7).\n for (const mountE of mountEntitiesNeedingRootParent) {\n const set = world.set(mountE, childOfToken, { parent: rootEntity } as never);\n if (!set.ok) {\n const r = world.addComponent(mountE, {\n component: childOfToken,\n data: { parent: rootEntity } as never,\n });\n if (!r.ok) return r as Result<EntityHandle, EcsError>;\n }\n }\n // Caller-supplied parent: synthetic root's ChildOf -> parent.\n if (parent !== undefined) {\n const r = world.addComponent(rootEntity, {\n component: childOfToken,\n data: { parent } as never,\n });\n if (!r.ok) return r as Result<EntityHandle, EcsError>;\n }\n }\n\n return ok(rootEntity);\n}\n/**\n * @internal Flat finisher — spawn one SceneAsset's members WITHOUT wrapping\n * them in a synthetic SceneInstance root and WITHOUT forcing `ChildOf` onto\n * top-level members. Used for \"opening a scene to edit\": the scene's own\n * entities become plain top-level world entities whose hierarchy is exactly\n * their authored `ChildOf`. Nested prefabs inside still materialise as their\n * own SceneInstance anchors (the mount recursion in `_spawnSceneMembers` is\n * always anchored). Returns the top-level handles (own rootless entities +\n * top-level mount carriers).\n */\nexport function worldInstantiateSceneAssetFlat(\n world: World,\n handle: Handle<'SceneAsset', 'shared'>,\n asset: SceneAsset,\n stack: Set<number>,\n diagnostics: SceneInstantiateDiagnostic[],\n): Result<{ roots: EntityHandle[]; mountEntities: EntityHandle[] }, EcsError> {\n const membersRes = worldSpawnSceneMembers(world, handle, asset, stack, diagnostics);\n if (!membersRes.ok) return membersRes;\n const { rootEntities, mountEntitiesNeedingRootParent, mountEntities, mountInstances } =\n membersRes.value;\n const childOfToken = world.components.resolve('ChildOf');\n\n // Apply parent mount overrides to the live columns and record them on the\n // nested child anchor. Flat mode has no outer SceneInstance state; without\n // this hand-authored mounts[].overrides affect the live value but disappear\n // from the child state, so Gateway re-open cannot discover or revert them.\n for (const { mount, root, mapping: childMapping } of mountInstances) {\n const childStateRes = worldGetSceneInstanceState(world, root);\n if (!childStateRes.ok) return childStateRes;\n for (const ov of mount.overrides ?? []) {\n const childLocalId =\n (ov.localId as unknown as number) - (mount.memberFirst as unknown as number);\n const memberEntityRaw = childMapping[childLocalId];\n if (memberEntityRaw === undefined || memberEntityRaw === ENTITY_NULL_RAW) continue;\n const memberEntity = memberEntityRaw as unknown as EntityHandle;\n const applyRes = worldApplyMountOverride(world, memberEntity, ov);\n if (!applyRes.ok) {\n return applyRes as Result<\n { roots: EntityHandle[]; mountEntities: EntityHandle[] },\n EcsError\n >;\n }\n let fieldMap = childStateRes.value.overrides.get(childLocalId as LocalEntityId);\n if (fieldMap === undefined) {\n fieldMap = new Map();\n childStateRes.value.overrides.set(childLocalId as LocalEntityId, fieldMap);\n }\n fieldMap.set(mountOverrideStateKey(ov), {\n comp: ov.comp,\n ...(ov.field === undefined ? {} : { field: ov.field }),\n value: ov.value,\n });\n }\n }\n\n // Default-parented mount carriers (`mount.parent === undefined`) would, in\n // anchor mode, attach to the synthetic root. Flat mode has none, so they\n // stay top-level. `_spawnMountEntity` may have left a placeholder\n // `ChildOf {parent: ENTITY_NULL_RAW}` (rare: mount with no components AND\n // Transform unregistered) — strip it so the carrier is a genuine root.\n if (childOfToken !== undefined) {\n for (const mountE of mountEntitiesNeedingRootParent) {\n const co = world.get(mountE, childOfToken);\n if (co.ok && (co.value as { parent: number }).parent === ENTITY_NULL_RAW) {\n world.removeComponent(mountE, childOfToken);\n }\n }\n }\n\n return ok({ roots: [...rootEntities, ...mountEntitiesNeedingRootParent], mountEntities });\n}\n/** @internal Build ComponentData[] for one SceneEntity, remapping localIds.\n *\n * C-R2 (feat-20260622-s5 M6): unknown fields on a SceneAsset payload are NOT\n * fatal. Unlike `world.spawn` (an explicit API call where a typo is a\n * programming error -> `SpawnDataUnknownFieldError`), scene data is loader-fed\n * and may carry a stale / deprecated / typo'd field. The remap below builds a\n * fresh `remappedRaw` and simply SKIPS keys absent from the schema (no input\n * mutation — the source `raw` is never deleted-from), recording each skipped\n * key as a non-fatal `SceneInstantiateDiagnostic` into the passed accumulator.\n * All known fields still write through, so one bad field cannot blank the\n * entity or the scene (C-AC-02/03/04).\n */\nexport function worldBuildSceneEntityComponentDatas(\n world: World,\n node: import('@forgeax/engine-types').SceneEntity,\n mapping: Uint32Array,\n diagnostics: SceneInstantiateDiagnostic[],\n): Result<ComponentData[], EcsError> {\n const out: ComponentData[] = [];\n const nodeLocalId = node.localId as unknown as number;\n for (const compName of Object.keys(node.components)) {\n const token = world.components.resolve(compName);\n if (token === undefined) {\n return err(new ComponentNotDefinedError(compName));\n }\n const raw = node.components[compName] ?? {};\n const schema = componentSchema(token) as Record<string, string>;\n const remappedRaw: Record<string, unknown> = {};\n for (const fieldName of Object.keys(raw)) {\n const fieldType = schema[fieldName];\n // C-R2: unknown key -> skip (do not copy into remappedRaw, do not\n // mutate the source `raw`) and record a structured diagnostic. The\n // downstream `spawn` only sees schema-valid keys, so its own\n // validateComponentDataKeys gate stays green.\n if (fieldType === undefined) {\n diagnostics.push({ component: compName, field: fieldName, localId: nodeLocalId });\n continue;\n }\n const value = (raw as Record<string, unknown>)[fieldName];\n const kind = classifyEntityField(token, fieldName);\n if (kind !== null) {\n // Entity / array<entity> field — remap through the shared kernel.\n // localId -> live Entity. Slots not yet spawned hold ENTITY_NULL_RAW.\n const sceneRemap = (localId: number): number => {\n if (localId < 0 || localId >= mapping.length) return ENTITY_NULL_RAW;\n const live = mapping[localId];\n return live === undefined || live === ENTITY_NULL_RAW ? ENTITY_NULL_RAW : live;\n };\n remappedRaw[fieldName] = remapEntityFieldValue(value, kind, sceneRemap);\n } else {\n remappedRaw[fieldName] = value;\n }\n }\n const filled = fillComponentDefaults(token, remappedRaw);\n out.push({ component: token, data: filled as never });\n }\n return ok(out);\n}\n/**\n * @internal feat-20260713 M2 / w8: apply one MountOverride to a live member\n * entity column. The `field?` shape is the add-or-patch discriminant:\n *\n * - `field` present -> PATCH one field: `world.set(member, comp, {[field]:\n * value})`. Omitted fields keep their authored / existing values.\n * - `field` absent -> ADD/UPSERT the whole component: `value` is the\n * per-field value map for `comp`. When the member already carries `comp`\n * it is upserted (set-over each supplied field + schema defaults for the\n * omitted ones — the whole component is rewritten from the value map +\n * defaults, never a `component-already-present` error). When absent it is\n * added fresh via `addComponent` (fillComponentDefaults fills omitted\n * fields). The value-map is fed through `fillComponentDefaults` so the\n * add and upsert paths write byte-identical rows.\n *\n * Component registration + value-key validation happened at\n * `_validateMountOverrides` (fail-fast before any spawn); by this point the\n * comp resolves through the World-local catalog and the value keys are schema-valid.\n * still guards defensively (an unregistered comp is a no-op skip, matching\n * the prior field-patch behaviour). Returns the underlying set / addComponent\n * Result so a shared-field value gate (D-4) or any other write error\n * propagates unchanged.\n */\nexport function worldApplyMountOverride(\n world: World,\n member: EntityHandle,\n ov: MountOverride,\n): Result<void, EcsError> {\n const ovToken = world.components.resolve(ov.comp);\n if (ovToken === undefined) return ok(undefined);\n if (ov.field !== undefined) {\n // PATCH one field.\n return world.set(member, ovToken, { [ov.field]: ov.value } as never);\n }\n // ADD/UPSERT the whole component. Fill omitted fields from the schema so\n // add and upsert produce identical rows (upsert = full rewrite from the\n // value map + defaults).\n const rawValue = (ov.value ?? {}) as Record<string, unknown>;\n const filled = fillComponentDefaults(ovToken as Component, rawValue);\n const has = world.get(member, ovToken);\n if (has.ok) {\n // Already present -> upsert (set every filled field, no duplicate error).\n return world.set(member, ovToken, filled as never);\n }\n return world.addComponent(member, { component: ovToken, data: filled as never });\n}\n/**\n * @internal R2/B-3 + R2/B-4: validate `mount.overrides[]` BEFORE any\n * spawn so a malformed override fails fast with no observable side\n * effects (charter P3 explicit-failure). Two checks:\n *\n * 1. `override.localId` must address a slot inside the parent-namespace\n * member window `[memberFirst, memberFirst + memberCount)` (AC-06).\n * 2. `override.field` must exist in the resolved component schema\n * (AC-07). When the component is unregistered we cannot validate the\n * field shape; let the existing fall-through path proceed (the\n * catalog guard inside the override-application loop\n * will skip the write).\n */\nexport function worldValidateMountOverrides(\n world: World,\n mount: SceneInstanceMount,\n): Result<void, EcsError> {\n const overrides = mount.overrides;\n if (overrides === undefined) return ok(undefined);\n const memberFirst = mount.memberFirst as unknown as number;\n const memberCount = mount.memberCount;\n const memberLast = memberFirst + memberCount;\n const mountLid = mount.localId as unknown as number;\n for (const ov of overrides) {\n const ovLid = ov.localId as unknown as number;\n // R2/B-3: parent-namespace check — override.localId must lie in the\n // member window [memberFirst, memberFirst + memberCount).\n if (ovLid < memberFirst || ovLid >= memberLast) {\n return err({\n code: 'pack-mount-override-localid-out-of-range' as PackErrorCode,\n expected: `override.localId in [${memberFirst}, ${memberLast})`,\n hint: PACK_ERROR_HINTS['pack-mount-override-localid-out-of-range'],\n detail: {\n code: 'pack-mount-override-localid-out-of-range',\n overrideLocalId: ovLid,\n mountLocalId: mountLid,\n memberCount,\n } as PackErrorDetail,\n } as unknown as EcsError);\n }\n // feat-20260713 M2 / w8: double-branch schema check.\n // - field-patch form (field present): the component (when registered)\n // must declare `override.field` in its schema (R2/B-4, unchanged).\n // - component-add form (field absent): the component MUST be registered\n // (component-not-defined otherwise) AND every key in the value map\n // must be a schema field (pack-mount-override-unknown-field).\n const ovToken = world.components.resolve(ov.comp);\n if (ov.field !== undefined) {\n if (ovToken !== undefined) {\n const schema = componentSchema(ovToken) as Record<string, unknown>;\n if (!(ov.field in schema)) {\n return err({\n code: 'pack-mount-override-unknown-field' as PackErrorCode,\n expected: `override.field defined on component '${ov.comp}'`,\n hint: PACK_ERROR_HINTS['pack-mount-override-unknown-field'],\n detail: {\n code: 'pack-mount-override-unknown-field',\n comp: ov.comp,\n field: ov.field,\n mountLocalId: mountLid,\n } as PackErrorDetail,\n } as unknown as EcsError);\n }\n }\n } else {\n // component-add form: comp must be registered so we can validate + apply\n // the whole component (add/upsert needs the schema).\n if (ovToken === undefined) {\n return err(new ComponentNotDefinedError(ov.comp));\n }\n const schema = componentSchema(ovToken) as Record<string, unknown>;\n const valueMap = (ov.value ?? {}) as Record<string, unknown>;\n for (const key of Object.keys(valueMap)) {\n if (!(key in schema)) {\n return err({\n code: 'pack-mount-override-unknown-field' as PackErrorCode,\n expected: `override.value keys defined on component '${ov.comp}'`,\n hint: PACK_ERROR_HINTS['pack-mount-override-unknown-field'],\n detail: {\n code: 'pack-mount-override-unknown-field',\n comp: ov.comp,\n field: key,\n mountLocalId: mountLid,\n } as PackErrorDetail,\n } as unknown as EcsError);\n }\n }\n }\n }\n return ok(undefined);\n}\n/** @internal Spawn the mount-entity slot carrying mount.components (if any).\n *\n * R2/B-1: the mount entity is a structural intermediate in the ChildOf\n * chain `cube -> innerSyntheticRoot -> mountEntity -> outerSyntheticRoot`,\n * so it MUST carry Transform whenever Transform is registered (mirrors\n * the D-V-0 synthetic-root invariant). Otherwise propagateTransforms\n * walking the chain hits a Transform-less parent and emits per-frame\n * `RhiError(hierarchy-broken)` (verify R1 root cause of the\n * hello-scene-nesting demo black frames).\n */\nexport function worldSpawnMountEntity(\n world: World,\n mount: SceneInstanceMount,\n mapping: Uint32Array,\n diagnostics: SceneInstantiateDiagnostic[],\n): Result<EntityHandle, EcsError> {\n const fakeNode: import('@forgeax/engine-types').SceneEntity = {\n localId: mount.localId,\n components: mount.components ?? {},\n };\n const cdRes = worldBuildSceneEntityComponentDatas(world, fakeNode, mapping, diagnostics);\n if (!cdRes.ok) return cdRes;\n // R2/B-1: ensure Transform is attached so propagateTransforms can walk\n // through this entity. Layer-2 defaults supply identity TRS; the\n // mount.components overlay (when present and including Transform) takes\n // precedence and is already in cdRes.value.\n const transformToken = world.components.resolve('Transform');\n if (transformToken !== undefined) {\n const hasTransform = cdRes.value.some((c) => c.component === transformToken);\n if (!hasTransform) {\n cdRes.value.push({ component: transformToken, data: {} as never });\n }\n }\n if (cdRes.value.length === 0) {\n // Mount has no components AND Transform is unregistered (rare unit-\n // test path). Fall back to the placeholder ChildOf so the spawn has\n // a real archetype. Step 5 overwrites this placeholder.\n const childOfToken = world.components.resolve('ChildOf');\n if (childOfToken === undefined) {\n return err(new ComponentNotDefinedError('ChildOf'));\n }\n cdRes.value.push({\n component: childOfToken,\n data: { parent: ENTITY_NULL_RAW } as never,\n });\n }\n return (world.spawn as (...c: ComponentData[]) => Result<EntityHandle, EcsError>)(...cdRes.value);\n}\n/** @internal Resolve mount.source through the wired SceneAssetResolver. */\nexport function worldResolveMountSource(\n world: World,\n source: number | string,\n parentHandle: Handle<'SceneAsset', 'shared'>,\n): Result<Handle<'SceneAsset', 'shared'>, EcsError> {\n const resolver = worldGetSceneAssetResolver(world);\n if (resolver === null) {\n return err({\n code: 'stale-entity' as const,\n expected: 'wired SceneAssetResolver (auto-wired by engine.assets.instantiate)',\n hint:\n 'engine.assets.instantiate sugar wires this for you; ' +\n 'call worldSetSceneAssetResolver before nested scene expansion.',\n detail: { entity: 0, slot: 0, generation: 0 },\n } as unknown as EcsError);\n }\n const r = resolver(source, parentHandle);\n if (!r.ok) {\n // Resolver carries `unknown` err (loose contract — engine-runtime may\n // wire any shape); narrow back to EcsError here at the boundary.\n return err(r.error as EcsError);\n }\n return ok(r.value);\n}\n/** @internal Convert mount.overrides Map shape to the SceneInstanceState shape.\n *\n * feat-20260713 M1 / w4: `field` is optional (add-or-patch discriminant). In\n * M1 only the field-patch form reaches this builder (the component-add form\n * fails fast in the apply loops); the record type stays `field?: string` so\n * the M2 add path can flow through untouched. `exactOptionalPropertyTypes`\n * forbids writing an explicit `field: undefined`, so omit the key when absent.\n */\nexport function worldMountOverridesToStateMap(\n src: Map<LocalEntityId, Map<string, MountOverride>>,\n): Map<LocalEntityId, Map<string, { comp: string; field?: string; value: unknown }>> {\n const out = new Map<\n LocalEntityId,\n Map<string, { comp: string; field?: string; value: unknown }>\n >();\n for (const [lid, fields] of src) {\n const m = new Map<string, { comp: string; field?: string; value: unknown }>();\n for (const [k, v] of fields) {\n m.set(k, {\n comp: v.comp,\n value: v.value,\n ...(v.field !== undefined ? { field: v.field } : {}),\n });\n }\n out.set(lid, m);\n }\n return out;\n}\n/** @internal Set the payload of an already-allocated SceneInstance state ref. */\nexport function worldSetUniqueRefPayload<T>(\n world: World,\n handle: Handle<string, 'unique'>,\n payload: T,\n): void {\n sceneWorldState(world).statePayloads.set(Number(handle), payload);\n}\n\n/**\n * @internal Resolve the SceneInstanceState payload behind the\n * `SceneInstance.state` ref column on `root`. Returns Err when `root`\n * does not carry SceneInstance or the ref slot is dead.\n */\nexport function worldResolveSceneInstanceStatePayload(\n world: World,\n root: EntityHandle,\n): Result<SceneInstanceStatePayload, EcsError> {\n const sceneInstanceToken = world.components.resolve('SceneInstance');\n if (sceneInstanceToken === undefined) {\n return err(new ComponentNotDefinedError('SceneInstance'));\n }\n const r = world.get(root, sceneInstanceToken);\n if (!r.ok) return r;\n const stateRefRaw = (r.value as unknown as { state: number }).state;\n const stateRefHandle = toUnique<'SceneInstanceState'>(stateRefRaw);\n const payload = sceneWorldState(world).statePayloads.get(Number(stateRefHandle));\n if (payload === undefined) {\n return err(\n new StaleEntityError(root as unknown as number, entityIndex(root), entityGeneration(root), {\n operation: 'resolveSceneInstanceState',\n component: 'SceneInstance',\n expectedGeneration: entityGeneration(root),\n actualGeneration: entityGeneration(root),\n }),\n );\n }\n return ok(payload as SceneInstanceStatePayload);\n}\n/**\n * Public sugar — get the SceneInstanceState payload (Map / Set view) for\n * `root`. Equivalent to `world.get(root, SceneInstance)` followed by a\n * managed-ref resolution; provided so AI users do not have to learn the\n * `ref<T>` slot resolution mechanic for the common read path.\n */\nexport function worldGetSceneInstanceState(\n world: World,\n root: EntityHandle,\n): Result<SceneInstanceStatePayload, EcsError> {\n return worldResolveSceneInstanceStatePayload(world, root);\n}\n\n/** Resolve a generated SceneEntityRef against one concrete SceneInstance. */\nexport function worldResolveSceneEntity(\n world: World,\n root: EntityHandle,\n ref: SceneEntityRef,\n): Result<EntityHandle, EcsError> {\n const state = worldResolveSceneInstanceStatePayload(world, root);\n if (!state.ok) return state;\n const resolved = resolveSceneEntity(ref, {\n sceneSourceKey: state.value.sceneSourceKey ?? ref.sceneSourceKey,\n bindings: state.value.bindings,\n });\n if (!resolved.ok) return err(resolved.error as unknown as EcsError);\n return ok(resolved.value as EntityHandle);\n}\n/**\n * Despawn a SceneInstance root + all its members. `opts.keepDetached`\n * preserves members marked via `worldDetachSceneMember` (plan-strategy\n * §D-5). Returns the count of entities actually despawned (root + each\n * non-detached member).\n *\n * For a plain entity (no SceneInstance), behaviour matches\n * `world.despawn(entity)` followed by `despawnDescendants(entity)` — i.e.\n * `keepDetached` is a no-op.\n */\nexport function worldDespawnScene(\n world: World,\n root: EntityHandle,\n opts?: { keepDetached?: boolean },\n): Result<number, EcsError> {\n const dRes = worldDespawnDescendants(world, root, opts);\n if (!dRes.ok) return dRes;\n const drop = world.despawn(root);\n if (!drop.ok) return drop;\n return ok(dRes.value + 1);\n}\n/**\n * Despawn every descendant of `root` reachable through Children mirror /\n * SceneInstance.mapping. `opts.keepDetached` is honoured only when `root`\n * carries a SceneInstance (otherwise the option is ignored — there is no\n * detached set on a plain entity).\n *\n * Returns the count of entities despawned. The `root` itself is NOT\n * despawned (that is `despawnScene`'s extra step).\n */\nexport function worldDespawnDescendants(\n world: World,\n root: EntityHandle,\n opts?: { keepDetached?: boolean },\n): Result<number, EcsError> {\n let detached: Set<LocalEntityId> | null = null;\n let entityToLocalId: Map<EntityHandle, LocalEntityId> | null = null;\n if (opts?.keepDetached === true) {\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (stateRes.ok) {\n detached = stateRes.value.detachedLocalIds;\n entityToLocalId = stateRes.value.entityToLocalId;\n }\n }\n let count = 0;\n // Collect descendants first (DFS via iterDescendants) to avoid mutating\n // while iterating. SceneInstance.mapping also owns members that may not be\n // reachable through a Children mirror in a partially registered host. The\n // nested anchor list closes that same ownership boundary for mounted scenes.\n const list: EntityHandle[] = [];\n const seen = new Set<number>();\n const collect = (anchor: EntityHandle): void => {\n for (const e of world.iterDescendants(anchor)) {\n const raw = e as unknown as number;\n if (!seen.has(raw)) {\n seen.add(raw);\n list.push(e);\n }\n }\n const stateRes = worldResolveSceneInstanceStatePayload(world, anchor);\n if (!stateRes.ok) return;\n for (const e of stateRes.value.entityToLocalId.keys()) {\n const raw = e as unknown as number;\n if (!seen.has(raw)) {\n seen.add(raw);\n list.push(e);\n }\n }\n for (const nestedRoot of stateRes.value.mountRoots) {\n const raw = nestedRoot as unknown as number;\n if (seen.has(raw)) continue;\n seen.add(raw);\n list.push(nestedRoot);\n collect(nestedRoot);\n }\n };\n collect(root);\n const childOfToken = world.components.resolve('ChildOf');\n // ChildOf uses linkedSpawn, so a parent-first pass would recursively retire\n // its children before this function can count them. Sort the ownership set\n // by its live ChildOf depth instead of relying on mirror traversal order;\n // nested SceneInstance roots are siblings of their mount carrier in the\n // flattened traversal but parents of the mounted members.\n const owned = new Set(list.map((entity) => Number(entity)));\n const ownedDepth = (entity: EntityHandle): number => {\n if (childOfToken === undefined) return 0;\n let current = entity;\n let depth = 0;\n const visited = new Set<number>();\n while (!visited.has(Number(current))) {\n visited.add(Number(current));\n const parentRes = world.get(current, childOfToken);\n if (!parentRes.ok) break;\n const parent = (parentRes.value as { parent: EntityHandle }).parent;\n if (!owned.has(Number(parent))) break;\n depth += 1;\n current = parent;\n }\n return depth;\n };\n list.sort((a, b) => ownedDepth(b) - ownedDepth(a));\n for (const e of list) {\n if (detached !== null) {\n const lid = entityToLocalId?.get(e);\n if (lid !== undefined && detached.has(lid)) {\n if (childOfToken !== undefined) {\n world.removeComponent(e, childOfToken);\n }\n continue;\n }\n }\n const r = world.despawn(e);\n if (!r.ok) {\n if (r.error.code === 'stale-entity') continue;\n return r;\n }\n count += 1;\n }\n return ok(count);\n}\n/**\n * Write a runtime override to a member entity belonging to `root`. Routes\n * through `world.set(member, comp, { [field]: value })` after an entity-\n * scope guard so cross-instance writes fail-fast. Type-mismatch surfaces\n * `EcsErrorCode = 'scene-override-type-mismatch'` (D-9).\n */\nexport function worldSetSceneOverride<S extends ComponentSchema>(\n world: World,\n root: EntityHandle,\n member: EntityHandle,\n component: Component<string, S>,\n field: keyof ShapeOf<S> & string,\n value: unknown,\n): Result<void, EcsError> {\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (!stateRes.ok) return stateRes;\n const state = stateRes.value;\n const lid = state.entityToLocalId.get(member);\n if (lid === undefined) {\n return err(\n new StaleEntityError(\n member as unknown as number,\n entityIndex(member),\n entityGeneration(member),\n {\n operation: 'setSceneOverride',\n component: component.name,\n expectedGeneration: entityGeneration(member),\n actualGeneration: entityGeneration(member),\n },\n ),\n );\n }\n // Type guard: only check primitive scalar field types where we can\n // narrow `typeof`; ref / handle / entity / array / buffer fields skip\n // (write would surface a deeper error from set).\n const schemaType = (componentSchema(component) as Record<string, string>)[field];\n if (schemaType !== undefined && isPrimitiveScalarFieldType(schemaType)) {\n const expectJsType = primitiveJsType(schemaType);\n const actualJsType = typeof value;\n if (expectJsType !== actualJsType) {\n return err({\n code: 'scene-override-type-mismatch' as const,\n expected: `value typeof === ${expectJsType}`,\n hint:\n `setSceneOverride(${component.name}.${field}) expected ${expectJsType}, ` +\n `got ${actualJsType}; coerce or pick a different override path.`,\n detail: {\n code: 'scene-override-type-mismatch' as const,\n comp: component.name,\n field: field as string,\n expectedType: schemaType,\n actualType: actualJsType,\n },\n } as unknown as EcsError);\n }\n }\n const setRes = world.set(member, component, { [field]: value } as Partial<InputShapeOf<S>>);\n if (!setRes.ok) return setRes;\n // Record into state.overrides\n let fieldMap = state.overrides.get(lid);\n if (fieldMap === undefined) {\n fieldMap = new Map();\n state.overrides.set(lid, fieldMap);\n }\n fieldMap.set(`${component.name}:${field}`, {\n comp: component.name,\n field: field as string,\n value,\n });\n return ok(undefined);\n}\n/**\n * Drop a runtime override (and any mount-time override for the same\n * (member, comp, field) triple); roll the live column value back to the\n * source SceneAsset's layer-1 explicit value (M2 v1 — M3+ widens to layer\n * 2/3 defaults via fillComponentDefaults).\n */\nexport function worldRemoveSceneOverride<S extends ComponentSchema>(\n world: World,\n root: EntityHandle,\n member: EntityHandle,\n component: Component<string, S>,\n field: keyof ShapeOf<S> & string,\n): Result<void, EcsError> {\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (!stateRes.ok) return stateRes;\n const state = stateRes.value;\n const lid = state.entityToLocalId.get(member);\n if (lid === undefined) return ok(undefined);\n const fieldMap = state.overrides.get(lid);\n if (fieldMap !== undefined) {\n fieldMap.delete(`${component.name}:${field}`);\n if (fieldMap.size === 0) state.overrides.delete(lid);\n }\n // Look up the source SceneAsset layer-1 value.\n const assetRes = worldResolveSceneAsset(world, state.source);\n if (!assetRes.ok) return assetRes;\n const node = assetRes.value.entities.find(\n (n) => (n.localId as unknown as number) === (lid as unknown as number),\n );\n const layer1 = node?.components[component.name] as Record<string, unknown> | undefined;\n if (layer1 !== undefined && field in layer1) {\n const r = world.set(member, component, { [field]: layer1[field] } as Partial<InputShapeOf<S>>);\n if (!r.ok) return r;\n }\n return ok(undefined);\n}\n/** Mark a member entity detached. Idempotent (set semantics). */\nexport function worldDetachSceneMember(\n world: World,\n root: EntityHandle,\n member: EntityHandle,\n): Result<void, EcsError> {\n const sceneInstanceToken = world.components.resolve('SceneInstance');\n if (sceneInstanceToken === undefined) {\n return err(new ComponentNotDefinedError('SceneInstance'));\n }\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (!stateRes.ok) return stateRes;\n const state = stateRes.value;\n const lid = state.entityToLocalId.get(member);\n if (lid === undefined) return ok(undefined);\n state.detachedLocalIds.add(lid);\n return ok(undefined);\n}\n/** Clear a detached mark. Idempotent (set semantics). */\nexport function worldReattachSceneMember(\n world: World,\n root: EntityHandle,\n member: EntityHandle,\n): Result<void, EcsError> {\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (!stateRes.ok) return stateRes;\n const state = stateRes.value;\n const lid = state.entityToLocalId.get(member);\n if (lid === undefined) return ok(undefined);\n state.detachedLocalIds.delete(lid);\n return ok(undefined);\n}\n/**\n * Get the SceneAsset handle a SceneInstance root was instantiated from.\n * Returns Err on a plain entity (no SceneInstance component).\n */\nexport function worldGetSceneAssetForInstance(\n world: World,\n root: EntityHandle,\n): Result<Handle<'SceneAsset', 'shared'>, EcsError> {\n const stateRes = worldResolveSceneInstanceStatePayload(world, root);\n if (!stateRes.ok) return stateRes;\n return ok(stateRes.value.source);\n}\n\n/**\n * Topological sort over the implicit ChildOf graph (parents before children).\n * Cycle-free input always covers all n nodes; cyclic input emits whatever was\n * reachable from indegree-0 (the fallback caller handles cycle reporting via\n * `pack-cyclic-reference` at the upstream scanner / runtime path).\n */\nfunction sceneTopoSort(\n nodes: readonly import('@forgeax/engine-types').SceneEntity[],\n): readonly number[] {\n const n = nodes.length;\n const childrenOf: number[][] = Array.from({ length: n }, () => []);\n const indeg = new Uint32Array(n);\n const localIdToIdx = new Map<number, number>();\n for (let i = 0; i < n; i += 1) {\n const node = nodes[i];\n if (node === undefined) continue;\n localIdToIdx.set(node.localId as unknown as number, i);\n }\n for (let i = 0; i < n; i += 1) {\n const node = nodes[i];\n if (node === undefined) continue;\n const child = node.components.ChildOf;\n if (child === undefined) continue;\n const p = (child as Record<string, unknown>).parent;\n if (typeof p === 'number') {\n const parentIdx = localIdToIdx.get(p);\n if (parentIdx !== undefined && parentIdx !== i) {\n childrenOf[parentIdx]?.push(i);\n indeg[i] = (indeg[i] ?? 0) + 1;\n }\n }\n }\n const order: number[] = [];\n const queue: number[] = [];\n for (let i = 0; i < n; i += 1) if ((indeg[i] ?? 0) === 0) queue.push(i);\n while (queue.length > 0) {\n const head = queue.shift();\n if (head === undefined) break;\n order.push(head);\n for (const c of childrenOf[head] ?? []) {\n indeg[c] = (indeg[c] ?? 0) - 1;\n if ((indeg[c] ?? 0) === 0) queue.push(c);\n }\n }\n // Append any nodes left unvisited (defensive — cycle would surface here).\n for (let i = 0; i < n; i += 1) {\n if (!order.includes(i) && nodes[i] !== undefined) order.push(i);\n }\n return order;\n}\n","import type { EntityHandle, World } from '@forgeax/engine-ecs';\nimport type { Handle, LocalEntityId, MountOverride } from '@forgeax/engine-types';\n\n/** Internal state retained by a SceneInstance root. */\nexport interface SceneInstanceStatePayload {\n readonly source: Handle<'SceneAsset', 'shared'>;\n readonly sceneSourceKey?: string;\n readonly bindings: Map<string, EntityHandle>;\n readonly entityToLocalId: Map<EntityHandle, LocalEntityId>;\n readonly detachedLocalIds: Set<LocalEntityId>;\n readonly overrides: Map<\n LocalEntityId,\n Map<string, { readonly comp: string; readonly field?: string; readonly value: unknown }>\n >;\n readonly rootEntities: EntityHandle[];\n readonly mountRoots: EntityHandle[];\n readonly totalSlots: number;\n readonly mountTimeOverrides: readonly MountOverride[];\n}\n\nexport interface SceneWorldState {\n resolver: unknown;\n readonly statePayloads: Map<number, unknown>;\n}\n\nconst sceneWorldStates = new WeakMap<World, SceneWorldState>();\n\nexport function sceneWorldState(world: World): SceneWorldState {\n const current = sceneWorldStates.get(world);\n if (current !== undefined) return current;\n const created: SceneWorldState = { resolver: null, statePayloads: new Map<number, unknown>() };\n sceneWorldStates.set(world, created);\n return created;\n}\n\nexport function mountOverrideStateKey(ov: MountOverride): string {\n return ov.field !== undefined ? `${ov.comp}:${ov.field}` : ov.comp;\n}\n\nexport function isPrimitiveScalarFieldType(fieldType: string): boolean {\n if (\n fieldType === 'f32' ||\n fieldType === 'f64' ||\n fieldType === 'u32' ||\n fieldType === 'i32' ||\n fieldType === 'u8' ||\n fieldType === 'i8' ||\n fieldType === 'u16' ||\n fieldType === 'i16' ||\n fieldType === 'bool' ||\n fieldType === 'string'\n ) {\n return true;\n }\n return fieldType.startsWith('enum<');\n}\n\nexport function primitiveJsType(fieldType: string): string {\n if (fieldType === 'bool') return 'boolean';\n if (fieldType === 'string') return 'string';\n return 'number';\n}\n","import {\n defineSystem,\n defineSystemSet,\n type EcsError,\n type EntityHandle,\n FixedUpdate,\n type Query,\n type SystemHandle,\n Update,\n type World,\n} from '@forgeax/engine-ecs';\nimport { type Mat4, mat4 } from '@forgeax/engine-math';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { ChildOf } from '../components/child-of';\nimport { GlobalTransform, Transform } from '../components/transform';\nimport { SceneError } from '../errors';\n\nexport const PROPAGATE_TRANSFORMS_SYSTEM = 'propagateTransforms' as const;\nexport const PROPAGATE_TRANSFORMS_FIXED_SYSTEM = 'propagateTransformsFixed' as const;\nexport const TransformSet = defineSystemSet({ name: 'transform' });\nexport const TransformFixedSet = defineSystemSet({ name: 'transform-fixed' });\n\ninterface Scratch {\n position: Float32Array;\n rotation: Float32Array;\n scale: Float32Array;\n local: Mat4;\n hierarchyPath: number[];\n flatQuery?: FlatQuery;\n outputQuery?: OutputQuery;\n hierarchyQuery?: HierarchyQuery;\n missingGlobalQuery?: MissingGlobalQuery;\n missingTransformQuery?: MissingTransformQuery;\n}\n\ntype OutputQuery = Query<readonly [], readonly [typeof GlobalTransform]>;\ntype FlatQuery = Query<readonly [typeof Transform], readonly [typeof GlobalTransform]>;\ntype HierarchyQuery = Query<readonly [typeof Transform, typeof ChildOf]>;\ntype MissingGlobalQuery = Query<readonly [], readonly [], readonly []>;\ntype MissingTransformQuery = Query<readonly [], readonly [], readonly []>;\n\ninterface RegistrationLease {\n refs: number;\n}\n\nconst SCRATCH = new WeakMap<World, Scratch>();\nconst REGISTRATION_LEASES = new WeakMap<World, RegistrationLease>();\n\nfunction pairError(entity: EntityHandle, expected: string): Result<void, SceneError> {\n return err(\n new SceneError({\n code: 'hierarchy-broken',\n expected,\n hint: 'attach both Transform and GlobalTransform at scene authoring or import time, then retry propagation',\n detail: { entity, parent: entity },\n }),\n );\n}\n\nfunction ensureQueries(world: World, scratch: Scratch): Result<void, SceneError> {\n if (\n scratch.flatQuery !== undefined &&\n scratch.outputQuery !== undefined &&\n scratch.hierarchyQuery !== undefined &&\n scratch.missingGlobalQuery !== undefined &&\n scratch.missingTransformQuery !== undefined\n ) {\n return ok(undefined);\n }\n const flatOutput = world.query({\n read: [Transform],\n write: [GlobalTransform],\n without: [ChildOf],\n changed: [Transform],\n });\n const output = world.query({ write: [GlobalTransform] });\n const hierarchy = world.query({ read: [Transform, ChildOf] });\n const missingGlobal = world.query({ with: [Transform], without: [GlobalTransform] });\n const missingTransform = world.query({ with: [GlobalTransform], without: [Transform] });\n if (!flatOutput.ok || !output.ok || !hierarchy.ok || !missingGlobal.ok || !missingTransform.ok) {\n return pairError(0 as EntityHandle, 'valid Transform and GlobalTransform pair queries');\n }\n scratch.flatQuery = flatOutput.value as FlatQuery;\n scratch.outputQuery = output.value as OutputQuery;\n scratch.hierarchyQuery = hierarchy.value as HierarchyQuery;\n scratch.missingGlobalQuery = missingGlobal.value as MissingGlobalQuery;\n scratch.missingTransformQuery = missingTransform.value as MissingTransformQuery;\n return ok(undefined);\n}\n\nfunction validateTransformPairs(world: World, scratch: Scratch): Result<void, SceneError> {\n const queryResult = ensureQueries(world, scratch);\n if (!queryResult.ok) return queryResult;\n const missingGlobal = scratch.missingGlobalQuery;\n const missingTransform = scratch.missingTransformQuery;\n if (missingGlobal === undefined || missingTransform === undefined) {\n return pairError(0 as EntityHandle, 'valid Transform and GlobalTransform pair queries');\n }\n for (const row of missingGlobal) {\n return pairError(row.entity, 'each Transform entity to carry a GlobalTransform pair');\n }\n for (const row of missingTransform) {\n return pairError(row.entity, 'each GlobalTransform entity to carry a Transform pair');\n }\n return ok(undefined);\n}\n\nfunction scratchFor(world: World): Scratch {\n const existing = SCRATCH.get(world);\n if (existing !== undefined) return existing;\n const created = {\n position: new Float32Array(3),\n rotation: new Float32Array(4),\n scale: new Float32Array(3),\n local: mat4.create(),\n hierarchyPath: [] as number[],\n };\n SCRATCH.set(world, created);\n return created;\n}\n\nfunction composeColumns(\n position: ArrayLike<number>,\n rotation: ArrayLike<number>,\n scale: ArrayLike<number>,\n out: Mat4,\n scratch: Scratch,\n positionStart = 0,\n rotationStart = 0,\n): void {\n scratch.position[0] = position[positionStart] ?? 0;\n scratch.position[1] = position[positionStart + 1] ?? 0;\n scratch.position[2] = position[positionStart + 2] ?? 0;\n scratch.rotation[0] = rotation[rotationStart] ?? 0;\n scratch.rotation[1] = rotation[rotationStart + 1] ?? 0;\n scratch.rotation[2] = rotation[rotationStart + 2] ?? 0;\n scratch.rotation[3] = rotation[rotationStart + 3] ?? 1;\n scratch.scale[0] = scale[positionStart] ?? 1;\n scratch.scale[1] = scale[positionStart + 1] ?? 1;\n scratch.scale[2] = scale[positionStart + 2] ?? 1;\n mat4.compose(out, scratch.position, scratch.rotation, scratch.scale);\n}\n\nfunction composeFlatColumns(\n positions: ArrayLike<number>,\n rotations: ArrayLike<number>,\n scales: ArrayLike<number>,\n worlds: Float32Array,\n count: number,\n): void {\n for (let row = 0; row < count; row += 1) {\n const position = row * 3;\n const rotation = row * 4;\n const world = row * 16;\n const x = rotations[rotation] ?? 0;\n const y = rotations[rotation + 1] ?? 0;\n const z = rotations[rotation + 2] ?? 0;\n const w = rotations[rotation + 3] ?? 1;\n const x2 = x + x;\n const y2 = y + y;\n const z2 = z + z;\n const xx = x * x2;\n const xy = x * y2;\n const xz = x * z2;\n const yy = y * y2;\n const yz = y * z2;\n const zz = z * z2;\n const wx = w * x2;\n const wy = w * y2;\n const wz = w * z2;\n const sx = scales[position] ?? 1;\n const sy = scales[position + 1] ?? 1;\n const sz = scales[position + 2] ?? 1;\n\n worlds[world] = (1 - (yy + zz)) * sx;\n worlds[world + 1] = (xy + wz) * sx;\n worlds[world + 2] = (xz - wy) * sx;\n worlds[world + 3] = 0;\n worlds[world + 4] = (xy - wz) * sy;\n worlds[world + 5] = (1 - (xx + zz)) * sy;\n worlds[world + 6] = (yz + wx) * sy;\n worlds[world + 7] = 0;\n worlds[world + 8] = (xz + wy) * sz;\n worlds[world + 9] = (yz - wx) * sz;\n worlds[world + 10] = (1 - (xx + yy)) * sz;\n worlds[world + 11] = 0;\n worlds[world + 12] = positions[position] ?? 0;\n worlds[world + 13] = positions[position + 1] ?? 0;\n worlds[world + 14] = positions[position + 2] ?? 0;\n worlds[world + 15] = 1;\n }\n}\n\nfunction writeWorld(\n world: World,\n output: ReturnType<World['query']> extends Result<infer Q, unknown> ? Q : never,\n entity: EntityHandle,\n value: Mat4,\n): Result<void, SceneError> {\n const row = output.at(entity);\n if (row === undefined) {\n return err(\n new SceneError({\n code: 'hierarchy-broken',\n expected: 'each Transform entity to carry a GlobalTransform pair',\n hint: 'attach GlobalTransform at scene authoring or import time, then retry propagation',\n detail: { entity, parent: entity },\n }),\n );\n }\n const current = world.get(entity, GlobalTransform);\n if (!current.ok)\n return err(\n new SceneError({\n code: 'hierarchy-broken',\n expected: 'each Transform entity to carry a GlobalTransform pair',\n hint: 'attach GlobalTransform at scene authoring or import time, then retry propagation',\n detail: { entity, parent: entity },\n }),\n );\n let changed = false;\n for (let index = 0; index < value.length; index += 1) {\n if (current.value.world[index] !== value[index]) {\n changed = true;\n break;\n }\n }\n if (!changed) return ok(undefined);\n row.mut(GlobalTransform).world.set(value);\n return ok(undefined);\n}\n\nfunction propagateFlat(scratch: Scratch): Result<void, SceneError> {\n const query = scratch.flatQuery;\n if (query === undefined)\n return err(\n new SceneError({\n code: 'hierarchy-broken',\n expected: 'a valid changed Transform write query',\n hint: 'register the scene components before running TransformPropagation',\n }),\n );\n const spans = query.spans();\n if (!spans.ok) return pairError(0 as EntityHandle, 'dense numeric Transform spans');\n let bindingIndex = 0;\n try {\n for (const span of spans.value) {\n const local = span.get(Transform);\n const world = span.mut(GlobalTransform).world;\n composeFlatColumns(local.pos, local.quat, local.scale, world, span.length);\n bindingIndex += 1;\n }\n } catch (cause) {\n const error = cause as EcsError;\n return err(\n new SceneError({\n code: 'hierarchy-broken',\n expected: 'derived GlobalTransform range publication to succeed',\n hint: error.hint,\n detail: {\n kind: 'derived-write',\n entity: 0 as EntityHandle,\n parent: 0 as EntityHandle,\n bindingIndex,\n base: 0,\n start: 0,\n count: 0,\n cause: error,\n },\n }),\n );\n }\n return ok(undefined);\n}\n\ninterface HierarchyEntry {\n readonly entity: EntityHandle;\n parent: EntityHandle | undefined;\n readonly position: Float32Array;\n readonly rotation: Float32Array;\n readonly scale: Float32Array;\n readonly world: Mat4;\n state: 0 | 1 | 2;\n}\n\nfunction findEntry(entries: readonly HierarchyEntry[], entity: EntityHandle): number {\n for (let index = 0; index < entries.length; index += 1) {\n if (entries[index]?.entity === entity) return index;\n }\n return -1;\n}\n\nfunction resolveEntry(\n index: number,\n entries: HierarchyEntry[],\n world: World,\n output: ReturnType<World['query']> extends Result<infer Q, unknown> ? Q : never,\n scratch: Scratch,\n): Result<void, SceneError> {\n const entry = entries[index];\n if (entry === undefined || entry.state === 2) return ok(undefined);\n if (entry.state === 1) {\n // A cycle is an input error, but leaving every member on its previous\n // GlobalTransform would make the renderer consume stale derived facts.\n // Cut the complete active cycle segment to roots for this failed frame;\n // the authored ChildOf values remain untouched and the next repaired\n // propagation recomputes the normal hierarchy.\n const cycleParent = entry.parent ?? entry.entity;\n const cycleStart = scratch.hierarchyPath.indexOf(index);\n const start = cycleStart < 0 ? 0 : cycleStart;\n for (let pathIndex = start; pathIndex < scratch.hierarchyPath.length; pathIndex += 1) {\n const cycleEntry = entries[scratch.hierarchyPath[pathIndex] ?? -1];\n if (cycleEntry !== undefined) cycleEntry.parent = undefined;\n }\n return err(\n new SceneError({\n code: 'hierarchy-cycle',\n expected: 'a parent-before-child Transform hierarchy',\n hint: 'repair the ChildOf cycle and retry TransformPropagation',\n detail: { entity: entry.entity, parent: cycleParent },\n }),\n );\n }\n entry.state = 1;\n scratch.hierarchyPath.push(index);\n let parentIndex = entry.parent === undefined ? -1 : findEntry(entries, entry.parent);\n let failure: SceneError | undefined;\n if (entry.parent !== undefined && parentIndex < 0) {\n const local = world.get(entry.parent, Transform);\n const global = world.get(entry.parent, GlobalTransform);\n if (!local.ok || !global.ok) {\n // The edge is invalid for this frame. Treat the child as a local root\n // so the output column reflects current authored input instead of the\n // previous frame's world matrix, while still returning the structured\n // error to the caller.\n failure = new SceneError({\n code: 'hierarchy-broken',\n expected: 'each ChildOf parent to carry Transform and GlobalTransform',\n hint: 'repair the missing parent pair before retrying propagation',\n detail: { entity: entry.entity, parent: entry.parent },\n });\n entry.parent = undefined;\n parentIndex = -1;\n } else {\n const relation = world.get(entry.parent, ChildOf);\n entries.push({\n entity: entry.parent,\n parent: relation.ok && relation.value.parent !== null ? relation.value.parent : undefined,\n position: new Float32Array(local.value.pos),\n rotation: new Float32Array(local.value.quat),\n scale: new Float32Array(local.value.scale),\n world: mat4.create(),\n state: 0,\n });\n parentIndex = entries.length - 1;\n }\n }\n if (parentIndex >= 0) {\n const parentResult = resolveEntry(parentIndex, entries, world, output, scratch);\n if (!parentResult.ok) failure = parentResult.error;\n // A cycle fallback can cut this entry's authored edge while resolving its\n // parent. Re-read the edge before composing so no cycle member consumes an\n // uninitialized parent matrix.\n parentIndex = entry.parent === undefined ? -1 : findEntry(entries, entry.parent);\n if (parentIndex >= 0 && entries[parentIndex]?.state !== 2) parentIndex = -1;\n }\n composeColumns(entry.position, entry.rotation, entry.scale, scratch.local, scratch);\n if (parentIndex >= 0) {\n const parent = entries[parentIndex];\n if (parent !== undefined) mat4.multiply(entry.world, parent.world, scratch.local);\n } else {\n entry.world.set(scratch.local);\n }\n const write = writeWorld(world, output, entry.entity, entry.world);\n if (!write.ok) {\n scratch.hierarchyPath.pop();\n return write;\n }\n entry.state = 2;\n scratch.hierarchyPath.pop();\n return failure === undefined ? ok(undefined) : err(failure);\n}\n\nfunction propagateHierarchy(world: World, scratch: Scratch): Result<void, SceneError> {\n const query = scratch.hierarchyQuery;\n const output = scratch.outputQuery;\n if (query === undefined || output === undefined) {\n return err(\n new SceneError({\n code: 'hierarchy-broken',\n expected: 'paired Transform and GlobalTransform query access',\n hint: 'register the scene components before running TransformPropagation',\n }),\n );\n }\n const entries: HierarchyEntry[] = [];\n for (const row of query) {\n if (findEntry(entries, row.entity) >= 0) continue;\n const local = row.get(Transform);\n const parentValue = row.get(ChildOf).parent;\n const parent = parentValue === null ? undefined : parentValue;\n entries.push({\n entity: row.entity,\n parent,\n position: new Float32Array(local.pos),\n rotation: new Float32Array(local.quat),\n scale: new Float32Array(local.scale),\n world: mat4.create(),\n state: 0,\n });\n }\n scratch.hierarchyPath.length = 0;\n let firstError: SceneError | undefined;\n for (let index = 0; index < entries.length; index += 1) {\n const result = resolveEntry(index, entries, world, output, scratch);\n if (!result.ok) {\n const currentEntity = Number(result.error.detail?.entity ?? Number.MAX_SAFE_INTEGER);\n if (firstError === undefined) {\n firstError = result.error;\n } else {\n const firstEntity = Number(firstError.detail?.entity ?? Number.MAX_SAFE_INTEGER);\n if (\n currentEntity < firstEntity ||\n (currentEntity === firstEntity && result.error.code.localeCompare(firstError.code) < 0)\n ) {\n firstError = result.error;\n }\n }\n }\n }\n return firstError === undefined ? ok(undefined) : err(firstError);\n}\n\nexport function propagateTransforms(world: World): Result<void, SceneError> {\n const scratch = scratchFor(world);\n const pairs = validateTransformPairs(world, scratch);\n if (!pairs.ok) return pairs;\n const flat = propagateFlat(scratch);\n if (!flat.ok) return flat;\n return propagateHierarchy(world, scratch);\n}\n\nexport const PropagateTransforms: SystemHandle<readonly []> = defineSystem({\n name: PROPAGATE_TRANSFORMS_SYSTEM,\n queries: [],\n fn: (world) => {\n const result = propagateTransforms(world);\n if (!result.ok) throw result.error;\n },\n});\n\nexport const PropagateTransformsFixed: SystemHandle<readonly []> = defineSystem({\n name: PROPAGATE_TRANSFORMS_FIXED_SYSTEM,\n queries: [],\n fn: PropagateTransforms.fn,\n});\n\nexport function registerPropagateTransforms(\n world: World,\n options: { beforeSystemName?: string } = {},\n): () => void {\n const existing = REGISTRATION_LEASES.get(world);\n if (existing !== undefined) {\n existing.refs += 1;\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n existing.refs -= 1;\n if (existing.refs === 0) {\n world.removeSystem(FixedUpdate, PROPAGATE_TRANSFORMS_FIXED_SYSTEM);\n world.removeSystem(Update, PROPAGATE_TRANSFORMS_SYSTEM);\n REGISTRATION_LEASES.delete(world);\n SCRATCH.delete(world);\n }\n };\n }\n if (options.beforeSystemName === undefined) {\n world.addSystems(Update, TransformSet, [PropagateTransforms]).unwrap();\n } else {\n world\n .addSystems(Update, TransformSet, [\n {\n name: PROPAGATE_TRANSFORMS_SYSTEM,\n queries: [],\n fn: PropagateTransforms.fn,\n before: [options.beforeSystemName],\n },\n ])\n .unwrap();\n }\n world.addSystems(FixedUpdate, TransformFixedSet, [PropagateTransformsFixed]).unwrap();\n REGISTRATION_LEASES.set(world, { refs: 1 });\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n const lease = REGISTRATION_LEASES.get(world);\n if (lease === undefined) return;\n lease.refs -= 1;\n if (lease.refs !== 0) return;\n world.removeSystem(FixedUpdate, PROPAGATE_TRANSFORMS_FIXED_SYSTEM);\n world.removeSystem(Update, PROPAGATE_TRANSFORMS_SYSTEM);\n REGISTRATION_LEASES.delete(world);\n SCRATCH.delete(world);\n };\n}\n","import type { Component, World } from '@forgeax/engine-ecs';\nimport type { Plugin } from '@forgeax/engine-plugin';\nimport { ChildOf } from './components/child-of';\nimport { Children } from './components/children';\nimport { MorphWeights } from './components/morph-weights';\nimport { Name } from './components/name';\nimport { GlobalTransform, Transform } from './components/transform';\nimport { registerPropagateTransforms } from './systems/propagate-transforms';\n\nconst SCENE_COMPONENTS: readonly Component[] = [\n ChildOf,\n Children,\n MorphWeights,\n Name,\n Transform,\n GlobalTransform,\n];\n\nfunction registerSceneComponents(world: World): () => void {\n const leases = SCENE_COMPONENTS.map((component) => world.components.register(component).unwrap());\n return () => {\n for (let index = leases.length - 1; index >= 0; index -= 1) leases[index]?.dispose();\n };\n}\n\nexport function scenePlugin(): Plugin {\n return {\n name: 'scene',\n inject: ['world'],\n apply(ctx) {\n ctx.effect(() => registerSceneComponents(ctx.world), 'scene/components');\n ctx.effect(() => registerPropagateTransforms(ctx.world), 'scene/propagate-transforms');\n },\n };\n}\n","import { Entity, type EntityHandle, type Query, type World } from '@forgeax/engine-ecs';\nimport { ChildOf } from '../components/child-of';\nimport type { SceneErrorCode, SceneErrorDetail } from '../errors';\n\nexport interface SceneHierarchyDiagnostic {\n readonly code: SceneErrorCode;\n readonly expected: string;\n readonly hint: string;\n readonly detail: SceneErrorDetail;\n}\n\nexport interface SceneHierarchySnapshot {\n readonly parentOf: ReadonlyMap<EntityHandle, EntityHandle>;\n readonly diagnostics: readonly SceneHierarchyDiagnostic[];\n getParent(entity: EntityHandle): EntityHandle | undefined;\n}\n\ninterface HierarchyProjectionCacheEntry {\n readonly structureEpoch: number;\n readonly childOfChanges: Query;\n readonly snapshot: SceneHierarchySnapshot;\n}\n\n// A World can be observed by the transform system, renderer visibility, and\n// editor projections in the same frame. Keep one World-local projection so\n// those consumers do not each rescan every archetype. Structure changes and\n// the ChildOf component's own mutation token are the invalidation keys; the\n// global mutation epoch is intentionally too broad because animation and\n// runtime-only component writes may advance it every frame. Direct table\n// writes are internal-only and must not mutate authored hierarchy state.\nconst HIERARCHY_PROJECTION_CACHE = new WeakMap<World, HierarchyProjectionCacheEntry>();\n\nfunction createChildOfChangeQuery(world: World): Query {\n const result = world.query({ changed: [ChildOf] });\n if (!result.ok) throw result.error;\n return result.value;\n}\n\nfunction drainChanges(query: Query): boolean {\n let changed = false;\n for (const span of query.spans().unwrap()) changed ||= span.length > 0;\n return changed;\n}\n\nfunction diagnostic(\n code: SceneErrorCode,\n entity: EntityHandle,\n parent: EntityHandle,\n): SceneHierarchyDiagnostic {\n if (code === 'hierarchy-cycle') {\n return {\n code,\n expected: 'ChildOf parent edges form an acyclic live hierarchy',\n hint: 'remove one ChildOf edge from the reported cycle, then re-run the extract',\n detail: { entity, parent },\n };\n }\n return {\n code,\n expected: 'ChildOf.parent references a live entity in the same World',\n hint: 'remove the stale ChildOf component or restore the referenced parent in this World',\n detail: { entity, parent },\n };\n}\n\n/** Build the only World-local projection of ChildOf parent facts. */\nexport function projectHierarchy(world: World): SceneHierarchySnapshot {\n const cached = HIERARCHY_PROJECTION_CACHE.get(world);\n if (\n cached !== undefined &&\n cached.structureEpoch === world.getStructureEpoch() &&\n !drainChanges(cached.childOfChanges)\n ) {\n return cached.snapshot;\n }\n const liveEntities = new Set<EntityHandle>();\n const authoredParents = new Map<EntityHandle, EntityHandle>();\n\n const query = world.query({ read: [Entity], optional: [ChildOf] });\n if (query.ok) {\n for (const row of query.value) {\n liveEntities.add(row.entity);\n const parent = row.get(ChildOf)?.parent;\n if (parent !== undefined && parent !== null) authoredParents.set(row.entity, parent);\n }\n }\n\n const parentOf = new Map<EntityHandle, EntityHandle>();\n const diagnostics: SceneHierarchyDiagnostic[] = [];\n for (const [entity, parent] of authoredParents) {\n if (liveEntities.has(parent)) {\n parentOf.set(entity, parent);\n } else {\n diagnostics.push(diagnostic('hierarchy-broken', entity, parent));\n }\n }\n\n const state = new Map<EntityHandle, 0 | 1 | 2>();\n const stack: EntityHandle[] = [];\n const cycleMembers = new Set<EntityHandle>();\n const visit = (entity: EntityHandle): void => {\n const currentState = state.get(entity) ?? 0;\n if (currentState === 2) return;\n if (currentState === 1) {\n const cycleStart = stack.indexOf(entity);\n for (let index = cycleStart; index >= 0 && index < stack.length; index++) {\n const member = stack[index];\n if (member !== undefined) cycleMembers.add(member);\n }\n return;\n }\n\n state.set(entity, 1);\n stack.push(entity);\n const parent = parentOf.get(entity);\n if (parent !== undefined) visit(parent);\n stack.pop();\n state.set(entity, 2);\n };\n\n for (const entity of liveEntities) visit(entity);\n for (const entity of cycleMembers) {\n const parent = authoredParents.get(entity);\n if (parent !== undefined) diagnostics.push(diagnostic('hierarchy-cycle', entity, parent));\n parentOf.delete(entity);\n }\n\n diagnostics.sort((left, right) => {\n const entityDelta = (left.detail.entity as number) - (right.detail.entity as number);\n if (entityDelta !== 0) return entityDelta;\n return left.code.localeCompare(right.code);\n });\n\n const stableParentOf = new Map(parentOf);\n const stableDiagnostics = Object.freeze(diagnostics.slice());\n const snapshot: SceneHierarchySnapshot = {\n parentOf: stableParentOf,\n diagnostics: stableDiagnostics,\n getParent(entity: EntityHandle): EntityHandle | undefined {\n return stableParentOf.get(entity);\n },\n };\n const childOfChanges = createChildOfChangeQuery(world);\n drainChanges(childOfChanges);\n HIERARCHY_PROJECTION_CACHE.set(world, {\n structureEpoch: world.getStructureEpoch(),\n childOfChanges,\n snapshot,\n });\n return snapshot;\n}\n"],"mappings":";AAAA;AAAA,EAKE;AAAA,EACA;AAAA,OAKK;AAE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