@vgai/engine 0.2.0

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.
Files changed (147) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +35 -0
  3. package/package.json +55 -0
  4. package/src/adapter/authoring.ts +402 -0
  5. package/src/adapter/colyseus-networking-adapter.ts +72 -0
  6. package/src/adapter/first-party-systems.ts +103 -0
  7. package/src/adapter/game-adapter.ts +151 -0
  8. package/src/adapter/host-context.ts +77 -0
  9. package/src/adapter/index.ts +85 -0
  10. package/src/adapter/ingest/game-contract.ts +59 -0
  11. package/src/adapter/ingest/overlay-applier.ts +207 -0
  12. package/src/adapter/ingest/overlay-apply.ts +124 -0
  13. package/src/adapter/ingest/overlay-file.ts +126 -0
  14. package/src/adapter/ingest/overlay-report.ts +176 -0
  15. package/src/adapter/ingest/scene-capture.ts +307 -0
  16. package/src/adapter/ingest/upstream-pin.ts +52 -0
  17. package/src/adapter/loop-gate-report.ts +54 -0
  18. package/src/adapter/rapier-physics-adapter.ts +56 -0
  19. package/src/adapter/system-adapter.ts +154 -0
  20. package/src/adapter/transform.ts +18 -0
  21. package/src/adapter/vgai-scene-game-adapter.ts +886 -0
  22. package/src/adapter/world-kind.ts +34 -0
  23. package/src/ai/navigation.ts +164 -0
  24. package/src/animation/anim-graph-types.ts +56 -0
  25. package/src/animation/anim-graph.ts +406 -0
  26. package/src/animation/anim-system.ts +28 -0
  27. package/src/animation/blend-node.ts +119 -0
  28. package/src/animation/property-track.ts +178 -0
  29. package/src/animation/schema.ts +204 -0
  30. package/src/assets.ts +80 -0
  31. package/src/audio/ambient.ts +300 -0
  32. package/src/audio/impacts.ts +212 -0
  33. package/src/audio/index.ts +7 -0
  34. package/src/audio/movement.ts +140 -0
  35. package/src/audio/musical.ts +200 -0
  36. package/src/audio/ui-sounds.ts +171 -0
  37. package/src/audio/vehicle.ts +235 -0
  38. package/src/audio/weapons.ts +152 -0
  39. package/src/core/game-loop.ts +127 -0
  40. package/src/core/system-runner.ts +298 -0
  41. package/src/core/types.ts +58 -0
  42. package/src/dev/console-bridge.ts +83 -0
  43. package/src/dev/debug-draw.ts +80 -0
  44. package/src/dev/logger.ts +119 -0
  45. package/src/ecs/component-manager.ts +748 -0
  46. package/src/ecs/game-component.ts +147 -0
  47. package/src/ecs/hmr-swap-report.ts +65 -0
  48. package/src/input/input-manager.ts +439 -0
  49. package/src/input/input-types.ts +19 -0
  50. package/src/input/schema.ts +129 -0
  51. package/src/loader.ts +70 -0
  52. package/src/manifest/index.ts +24 -0
  53. package/src/manifest/load-file.ts +16 -0
  54. package/src/manifest/load.ts +378 -0
  55. package/src/manifest/schema.ts +375 -0
  56. package/src/physics/collision-system.ts +76 -0
  57. package/src/physics/physics-registry.ts +83 -0
  58. package/src/physics/transform-writer.ts +41 -0
  59. package/src/physics/trigger-dispatch.ts +97 -0
  60. package/src/react/game-state.tsx +172 -0
  61. package/src/render/auto-batcher.ts +169 -0
  62. package/src/render/render-batch-system.ts +268 -0
  63. package/src/render/render-features.ts +146 -0
  64. package/src/render/render-settings.ts +72 -0
  65. package/src/runtime/create-runtime.ts +1152 -0
  66. package/src/runtime/frame-selector-cache.ts +81 -0
  67. package/src/runtime/game.ts +1003 -0
  68. package/src/runtime/input-router.ts +213 -0
  69. package/src/runtime/mount-game.ts +269 -0
  70. package/src/runtime/mount-manifest.ts +361 -0
  71. package/src/runtime/scene-ui-bridge.ts +86 -0
  72. package/src/runtime/scene-ui-data.ts +119 -0
  73. package/src/runtime/state-bridge.ts +79 -0
  74. package/src/runtime/types.ts +196 -0
  75. package/src/scene/asset-loaders.ts +195 -0
  76. package/src/scene/asset-paths.ts +123 -0
  77. package/src/scene/asset-registry.ts +67 -0
  78. package/src/scene/collider-dimensions.ts +125 -0
  79. package/src/scene/component-registry.ts +40 -0
  80. package/src/scene/defaults.ts +164 -0
  81. package/src/scene/geometries/index.ts +7 -0
  82. package/src/scene/geometries/terrain.ts +42 -0
  83. package/src/scene/geometry-registry.ts +42 -0
  84. package/src/scene/instance-registry.ts +84 -0
  85. package/src/scene/instancers/grid.ts +38 -0
  86. package/src/scene/instancers/index.ts +7 -0
  87. package/src/scene/light-camera-factory.ts +97 -0
  88. package/src/scene/material-factory.ts +211 -0
  89. package/src/scene/material-registry.ts +73 -0
  90. package/src/scene/materials/index.ts +7 -0
  91. package/src/scene/materials/water.ts +56 -0
  92. package/src/scene/parse.ts +71 -0
  93. package/src/scene/particles-factory.ts +383 -0
  94. package/src/scene/scene-apply.ts +356 -0
  95. package/src/scene/scene-diff-schema.ts +115 -0
  96. package/src/scene/scene-diff-types.ts +29 -0
  97. package/src/scene/scene-loader.ts +1533 -0
  98. package/src/scene/scene-query.ts +63 -0
  99. package/src/scene/scene-types.ts +34 -0
  100. package/src/scene/scene-version.ts +40 -0
  101. package/src/scene/schema/animation.ts +95 -0
  102. package/src/scene/schema/audio.ts +25 -0
  103. package/src/scene/schema/camera.ts +21 -0
  104. package/src/scene/schema/collider.ts +69 -0
  105. package/src/scene/schema/entity-ref.ts +78 -0
  106. package/src/scene/schema/entity.ts +169 -0
  107. package/src/scene/schema/environment.ts +384 -0
  108. package/src/scene/schema/index.ts +95 -0
  109. package/src/scene/schema/instances.ts +35 -0
  110. package/src/scene/schema/joint.ts +26 -0
  111. package/src/scene/schema/light.ts +38 -0
  112. package/src/scene/schema/material.ts +113 -0
  113. package/src/scene/schema/mesh.ts +108 -0
  114. package/src/scene/schema/particles.ts +398 -0
  115. package/src/scene/schema/physics.ts +49 -0
  116. package/src/scene/schema/scene-file.ts +299 -0
  117. package/src/scene/schema/shadow.ts +24 -0
  118. package/src/scene/schema/spline.ts +21 -0
  119. package/src/scene/schema/tuples.ts +21 -0
  120. package/src/scene/schema/ui.ts +602 -0
  121. package/src/scene/user-data.ts +203 -0
  122. package/src/setup/setup-audio.ts +60 -0
  123. package/src/setup/setup-particles.ts +23 -0
  124. package/src/setup/setup-physics.ts +67 -0
  125. package/src/setup/setup-renderer.ts +529 -0
  126. package/src/types-n8ao.d.ts +37 -0
  127. package/src/types-realism-effects.d.ts +61 -0
  128. package/src/world2d/authoring-2d.ts +208 -0
  129. package/src/world2d/capture-to-scene2d.ts +52 -0
  130. package/src/world2d/collision-2d.ts +106 -0
  131. package/src/world2d/components-2d.ts +86 -0
  132. package/src/world2d/index.ts +66 -0
  133. package/src/world2d/ingest-iframe-2d.ts +255 -0
  134. package/src/world2d/ingest2d.ts +131 -0
  135. package/src/world2d/physics2d-registry.ts +49 -0
  136. package/src/world2d/pixi-game-adapter.ts +325 -0
  137. package/src/world2d/pixi-surface.ts +78 -0
  138. package/src/world2d/scene-capture-2d.ts +117 -0
  139. package/src/world2d/scene2d-loader.ts +308 -0
  140. package/src/world2d/schema/entity2d.ts +145 -0
  141. package/src/world2d/schema/physics2d.ts +53 -0
  142. package/src/world2d/schema/sprite.ts +71 -0
  143. package/src/world2d/schema/tilemap.ts +22 -0
  144. package/src/world2d/schema/tuples2d.ts +25 -0
  145. package/src/world2d/system-adapters-2d.ts +49 -0
  146. package/src/world2d/transform-writer-2d.ts +24 -0
  147. package/src/world2d/types.ts +55 -0
@@ -0,0 +1,213 @@
1
+ /**
2
+ * The delegating input router (COMPOSITION-DESIGN.md D5 §2a) —
3
+ * `createGameRuntime`'s worlds path (T6.1 slice 1,
4
+ * docs/MULTI-WORLD-DESIGN.md §1.C) uses this to route pointer input across
5
+ * N stacked world canvases with exactly ONE root listener.
6
+ *
7
+ * Split into two layers so the decision logic is unit-testable with plain
8
+ * fake worlds — no real DOM/canvas needed:
9
+ *
10
+ * - `stackOrder` / `resolveClaimingWorld`: pure functions over
11
+ * `{id, zOrder, hitTest?}` — "who claims this point".
12
+ * - `applyPointerEventsStacking` / `createInputRouter`: the DOM wiring —
13
+ * sets `pointer-events` CSS per D5 §2a and forwards a claimed event to
14
+ * the claiming world's own canvas.
15
+ *
16
+ * Per-event fall-through (D5 §2b — the sanctioned mechanism for an
17
+ * authoring surface's own interior drag affordances, e.g. the world2d
18
+ * editor's gizmos) is explicitly NOT this file's job (MULTI-WORLD-DESIGN.md
19
+ * task 4) — it stays inside whatever authoring surface needs it.
20
+ */
21
+
22
+ /** The pure decision inputs — no DOM. */
23
+ export interface ClaimEntry {
24
+ readonly id: string;
25
+ readonly zOrder: number;
26
+ /**
27
+ * Optional claim predicate over a point RELATIVE TO THE CONTAINER. Absent
28
+ * means: "this world claims only if it is the bottom (lowest zOrder)
29
+ * world" — D5 §2a's stated default ("transparent upper worlds do not
30
+ * claim, the bottom world claims everything").
31
+ */
32
+ readonly hitTest?: ((x: number, y: number) => boolean) | undefined;
33
+ }
34
+
35
+ /** The DOM-wiring inputs — one real canvas per world. */
36
+ export interface RouterWorldEntry extends ClaimEntry {
37
+ readonly canvas: HTMLCanvasElement;
38
+ }
39
+
40
+ /**
41
+ * Bottom-to-top paint order: ascending `zOrder`, ties -> original array
42
+ * order — the SAME rule `manifest/load.ts`'s `loadGameManifest` sorts
43
+ * worlds by, so a world's DOM stacking position always matches its
44
+ * manifest-resolved zOrder. The last element is the topmost (visually on
45
+ * top / highest z-index).
46
+ */
47
+ export function stackOrder<T extends ClaimEntry>(entries: readonly T[]): T[] {
48
+ return entries
49
+ .map((entry, index) => ({ entry, index }))
50
+ .sort((a, b) => a.entry.zOrder - b.entry.zOrder || a.index - b.index)
51
+ .map(({ entry }) => entry);
52
+ }
53
+
54
+ /**
55
+ * Resolve which world's id claims a container-relative point `(x, y)` — D5
56
+ * §2a: walk top-down (topmost first); the first world whose `hitTest`
57
+ * returns true wins ("topmost-claim wins"). A world with no `hitTest` never
58
+ * claims UNLESS it is the bottom-most world, which claims unconditionally
59
+ * (or via its own `hitTest`, if it declares one) — "no-claim falls to
60
+ * bottom". Returns `null` only when `entries` is empty.
61
+ */
62
+ export function resolveClaimingWorld(
63
+ entries: readonly ClaimEntry[],
64
+ x: number,
65
+ y: number,
66
+ ): string | null {
67
+ if (entries.length === 0) return null;
68
+ const order = stackOrder(entries); // bottom -> top
69
+ for (let i = order.length - 1; i >= 1; i--) {
70
+ const entry = order[i]!;
71
+ if (entry.hitTest?.(x, y)) return entry.id;
72
+ }
73
+ // No upper world claimed (or there is only one world) -> the bottom world
74
+ // claims — honoring its own hitTest if it declares one (rare: the bottom
75
+ // world usually claims everything unconditionally per D5 §2a's default).
76
+ return order[0]!.id;
77
+ }
78
+
79
+ /**
80
+ * Sets `canvas.style.pointerEvents` per D5 §1/§2a: the bottom (lowest
81
+ * zOrder) world's canvas is `'auto'` (real user input DOM-hit-tests it by
82
+ * default); every canvas above it is `'none'` (real user input never
83
+ * DOM-hit-tests it — the router's JS-level `hitTest` is what still lets it
84
+ * claim a point via `createInputRouter`'s forwarding).
85
+ */
86
+ export function applyPointerEventsStacking(entries: readonly RouterWorldEntry[]): void {
87
+ const order = stackOrder(entries);
88
+ order.forEach((entry, i) => {
89
+ entry.canvas.style.pointerEvents = i === 0 ? 'auto' : 'none';
90
+ });
91
+ }
92
+
93
+ const ROUTED_EVENT_TYPES = ['pointerdown', 'pointerup', 'pointermove', 'click', 'wheel'] as const;
94
+
95
+ /** Common pointer/mouse/wheel event fields this router knows how to carry
96
+ * over when forwarding a claimed event to a different canvas (see
97
+ * `forwardEvent` below) — not an exhaustive Event surface, just the fields
98
+ * games/libraries actually read for hit-testing and input state. */
99
+ function pickEventInit(original: Event): Record<string, unknown> {
100
+ const src = original as unknown as Record<string, unknown>;
101
+ const keys = [
102
+ 'clientX',
103
+ 'clientY',
104
+ 'screenX',
105
+ 'screenY',
106
+ 'offsetX',
107
+ 'offsetY',
108
+ 'button',
109
+ 'buttons',
110
+ 'ctrlKey',
111
+ 'altKey',
112
+ 'shiftKey',
113
+ 'metaKey',
114
+ 'pointerId',
115
+ 'pointerType',
116
+ 'pressure',
117
+ 'isPrimary',
118
+ 'deltaX',
119
+ 'deltaY',
120
+ 'deltaZ',
121
+ 'deltaMode',
122
+ ];
123
+ const init: Record<string, unknown> = { bubbles: false, cancelable: true, composed: true };
124
+ for (const key of keys) if (key in src) init[key] = src[key];
125
+ return init;
126
+ }
127
+
128
+ /**
129
+ * Forward `original` onto `canvas` as a NEW, non-bubbling event of the same
130
+ * event-type family — so a canvas with `pointer-events:none` (never a
131
+ * native DOM hit-test target) still receives the interaction its own event
132
+ * pipeline (Pixi's `EventSystem`, a raycast-driven three controller, …)
133
+ * listens for on ITS canvas. `bubbles:false` is deliberate: it stops the
134
+ * clone from re-triggering the container's own capture listener (an
135
+ * infinite loop) — re-dispatching the SAME event object is not an option
136
+ * either (the DOM forbids re-dispatching an event still being dispatched).
137
+ *
138
+ * Best-effort: environments with no `PointerEvent`/`MouseEvent`/
139
+ * `WheelEvent` global (Node unit tests) skip forwarding silently — those
140
+ * tests exercise the pure claim-resolution logic above instead, which needs
141
+ * no real `Event` objects at all.
142
+ */
143
+ function forwardEvent(canvas: HTMLCanvasElement, original: Event): void {
144
+ const g = globalThis as unknown as {
145
+ PointerEvent?: new (type: string, init?: unknown) => Event;
146
+ MouseEvent?: new (type: string, init?: unknown) => Event;
147
+ WheelEvent?: new (type: string, init?: unknown) => Event;
148
+ };
149
+ const Ctor =
150
+ original.type === 'wheel'
151
+ ? g.WheelEvent
152
+ : original.type.startsWith('pointer')
153
+ ? g.PointerEvent
154
+ : (g.MouseEvent ?? g.PointerEvent);
155
+ if (!Ctor || typeof canvas.dispatchEvent !== 'function') return;
156
+ try {
157
+ canvas.dispatchEvent(new Ctor(original.type, pickEventInit(original)));
158
+ } catch {
159
+ // Best-effort forwarding — a construction failure here must never break
160
+ // the (already-delivered) original event's own handling.
161
+ }
162
+ }
163
+
164
+ export interface InputRouterHandle {
165
+ /** Resolve which world claims a container-relative point right now — the
166
+ * pure decision, exposed for callers/tests that don't want to simulate a
167
+ * real DOM event. */
168
+ resolveClaim(x: number, y: number): string | null;
169
+ /** Detach the container listener(s). Idempotent. */
170
+ dispose(): void;
171
+ }
172
+
173
+ /**
174
+ * Wire the delegating router onto `container` for `entries` (D5 §2a): apply
175
+ * the pointer-events stacking, then attach ONE capture-phase listener per
176
+ * routed event type that resolves the claiming world and forwards the event
177
+ * to ITS canvas when that world isn't already the natural DOM target (the
178
+ * bottom world, whose canvas is the only one with `pointer-events:auto`).
179
+ */
180
+ export function createInputRouter(
181
+ container: HTMLElement,
182
+ entries: readonly RouterWorldEntry[],
183
+ ): InputRouterHandle {
184
+ applyPointerEventsStacking(entries);
185
+ const byId = new Map(entries.map((e) => [e.id, e] as const));
186
+ const bottomId = stackOrder(entries)[0]?.id;
187
+
188
+ const handler = (evt: Event) => {
189
+ const rect = container.getBoundingClientRect?.() ?? { left: 0, top: 0 };
190
+ const clientX = (evt as unknown as { clientX?: number }).clientX ?? 0;
191
+ const clientY = (evt as unknown as { clientY?: number }).clientY ?? 0;
192
+ const x = clientX - rect.left;
193
+ const y = clientY - rect.top;
194
+ const claimant = resolveClaimingWorld(entries, x, y);
195
+ if (claimant && claimant !== bottomId) {
196
+ const entry = byId.get(claimant);
197
+ if (entry) forwardEvent(entry.canvas, evt);
198
+ }
199
+ };
200
+
201
+ for (const type of ROUTED_EVENT_TYPES) {
202
+ container.addEventListener?.(type, handler, true);
203
+ }
204
+
205
+ return {
206
+ resolveClaim: (x, y) => resolveClaimingWorld(entries, x, y),
207
+ dispose() {
208
+ for (const type of ROUTED_EVENT_TYPES) {
209
+ container.removeEventListener?.(type, handler, true);
210
+ }
211
+ },
212
+ };
213
+ }
@@ -0,0 +1,269 @@
1
+ // E4 — the S-D composer (docs/unified-world-editor/27-visual-react-editing.md
2
+ // §7 E4; design lineage docs/unified-world-editor/26-unified-editor-spec.md
3
+ // §5 Stage S-D). Builds ON `mount-manifest.ts`'s `mountManifestWorlds` (never
4
+ // duplicates its per-kind dispatch/validation) to add the one thing that
5
+ // module deliberately does NOT have: a KIND REGISTRY, so a project doesn't
6
+ // have to hand-build an `entries` map inline in its own `main.ts` every time
7
+ // — it registers a `WorldKindFactory` per kind it uses (once, at module load)
8
+ // and then mounts with a single `mountGameFromManifest(manifest, host)` call.
9
+ //
10
+ // Engine-core react/pixi-free discipline (mirrors `mount-manifest.ts`'s own
11
+ // header comment, and the HARD INVARIANT this file was built under): this
12
+ // registry is pure mechanism — it holds whatever `WorldKindFactory` functions
13
+ // callers register, but it registers NONE itself. In particular there is no
14
+ // built-in 'pixijs'/'react' registration here (that would require this file
15
+ // to value-import `pixi.js`/`react`/`react-dom`, exactly what `mount-manifest
16
+ // .ts` forbids); a project that has a pixijs or react world MUST register a
17
+ // factory for that kind itself — see `defaultThreeKindFactory` below for why
18
+ // even the 'threejs' convenience export is a plain function the CALLER
19
+ // registers, not something this module wires up automatically.
20
+
21
+ import type { GameAdapter } from '../adapter/game-adapter';
22
+ import type { ResolvedWorldEntry } from '../manifest/load';
23
+ import type { ComponentRegistry } from '../scene/component-registry';
24
+ import type { GameSession } from './create-runtime';
25
+ import { type MountEntry, mountManifestWorlds, resolveManifest } from './mount-manifest';
26
+ import type { GameSetupFn } from './types';
27
+
28
+ // ---------------------------------------------------------------------------
29
+ // The host contract (design/26 §5 D1's `ManifestHost`)
30
+ // ---------------------------------------------------------------------------
31
+
32
+ /**
33
+ * What a caller of `mountGameFromManifest` provides. Deliberately minimal —
34
+ * this file never fetches/reads the manifest itself (same rule
35
+ * `mount-manifest.ts` follows: the caller already has a parsed manifest or a
36
+ * raw JSON value in hand).
37
+ */
38
+ export interface ManifestHost {
39
+ /** The host creates one absolutely-positioned surface per world inside
40
+ * this element — see `WorldsRuntimeConfig.container`. */
41
+ readonly container: HTMLElement;
42
+ /**
43
+ * Resolve a manifest-declared `entry` (a project-relative module path,
44
+ * e.g. `"src/scripts/main.ts"`) to the ALREADY-IMPORTED module namespace a
45
+ * registered {@link WorldKindFactory} needs to build a `MountEntry` from.
46
+ *
47
+ * Deliberately NOT "import this arbitrary string path" — a static bundler
48
+ * (Vite/rollup building a `dist/`) cannot resolve a runtime-computed import
49
+ * specifier, so the recommended shape is a small caller-owned lookup table
50
+ * of STATIC imports keyed by the manifest's own `entry` strings (see
51
+ * `packages/editor/template/src/main.ts` for the worked pattern) rather
52
+ * than a literal `import(path)`. Optional — a manifest whose every world
53
+ * either declares no `entry` or is fully satisfied by an explicit
54
+ * `opts.entries` needs none at all.
55
+ */
56
+ loadEntryModule?(path: string): Promise<unknown>;
57
+ /** Resolve asset/scene URLs relative to the project — forwarded to a
58
+ * registered {@link WorldKindFactory} via {@link WorldKindFactoryContext},
59
+ * never called by this module itself (a factory only needs it for a
60
+ * non-default resolution scheme, e.g. a hosted-editor iframe). */
61
+ resolveUrl?(path: string): string;
62
+ readonly width?: number | undefined;
63
+ readonly height?: number | undefined;
64
+ /** Forwarded to `createGameRuntime` — Node/headless test harnesses only,
65
+ * never a real host. See `WorldsRuntimeConfig.headless`. */
66
+ readonly headless?: boolean | undefined;
67
+ }
68
+
69
+ /** What a registered {@link WorldKindFactory} is handed for one world. */
70
+ export interface WorldKindFactoryContext {
71
+ readonly host: ManifestHost;
72
+ /**
73
+ * The result of `host.loadEntryModule(world.entry)`, if the world declares
74
+ * an `entry` AND the host supports loading it — `undefined` for a
75
+ * scene-only world, or when the host has no `loadEntryModule`.
76
+ */
77
+ readonly entryModule?: unknown;
78
+ }
79
+
80
+ /**
81
+ * A caller-registered per-kind mount strategy: given the world's resolved
82
+ * manifest entry and the loaded entry module (if any), produce the
83
+ * `MountEntry` `mountManifestWorlds` needs to mount it (exactly what a
84
+ * project used to hand-build inline as its own `entries[id]` — see
85
+ * `examples/tri-world/src/main.ts`'s pre-E4 shape). May be async (loading an
86
+ * asset, fetching a scene file, etc.).
87
+ */
88
+ export type WorldKindFactory = (
89
+ world: ResolvedWorldEntry,
90
+ ctx: WorldKindFactoryContext,
91
+ ) => MountEntry | Promise<MountEntry>;
92
+
93
+ // ---------------------------------------------------------------------------
94
+ // The registry
95
+ // ---------------------------------------------------------------------------
96
+
97
+ const registry = new Map<string, WorldKindFactory>();
98
+
99
+ /**
100
+ * Register a `WorldKindFactory` for a manifest world `kind` (`'threejs'` /
101
+ * `'pixijs'` / `'react'`, or any future kind the manifest schema grows).
102
+ * Call once, at module load — mirrors `registerSceneUIRenderer()`'s existing
103
+ * "call before mounting" convention (`packages/editor/template/src/main.ts`).
104
+ *
105
+ * Throws on double-registration of the SAME kind: an accidental duplicate
106
+ * (two side-effect imports of the same registration module, or a copy-paste)
107
+ * is far more likely than an intentional runtime swap — a caller that really
108
+ * wants to replace a registration must `unregisterWorldKind` first, making
109
+ * the intent explicit.
110
+ */
111
+ export function registerWorldKind(kind: string, factory: WorldKindFactory): void {
112
+ if (registry.has(kind)) {
113
+ throw new Error(
114
+ `registerWorldKind: a factory is already registered for kind "${kind}" — ` +
115
+ 'call unregisterWorldKind(kind) first if you intend to replace it (an accidental ' +
116
+ 'double-registration, e.g. two side-effect imports of the same registration module, ' +
117
+ 'is far more common than an intentional swap).',
118
+ );
119
+ }
120
+ registry.set(kind, factory);
121
+ }
122
+
123
+ /** Remove a kind's registration (e.g. before re-registering a replacement). */
124
+ export function unregisterWorldKind(kind: string): void {
125
+ registry.delete(kind);
126
+ }
127
+
128
+ /** Whether a factory is currently registered for `kind`. */
129
+ export function isWorldKindRegistered(kind: string): boolean {
130
+ return registry.has(kind);
131
+ }
132
+
133
+ /**
134
+ * Test-only escape hatch: clears every registration. Registrations are
135
+ * meant to be one-time, process-lifetime — production code should never
136
+ * call this; it exists so unit tests can start each case from a clean
137
+ * registry without cross-test leakage.
138
+ */
139
+ export function __clearWorldKindRegistryForTests(): void {
140
+ registry.clear();
141
+ }
142
+
143
+ // ---------------------------------------------------------------------------
144
+ // `defaultThreeKindFactory` — an OPT-IN convenience, never auto-registered
145
+ // ---------------------------------------------------------------------------
146
+
147
+ /** The entry-module export shape every first-party entry module follows
148
+ * (`packages/editor/template/src/scripts/main.ts`, every `examples/*`
149
+ * project's `src/index.ts` — see CLAUDE.md's "Adding an example project"). */
150
+ interface ThreeEntryModuleExports {
151
+ readonly adapter?: GameAdapter;
152
+ readonly setup?: GameSetupFn;
153
+ readonly componentRegistry?: ComponentRegistry;
154
+ }
155
+
156
+ /**
157
+ * A ready-to-register {@link WorldKindFactory} for `kind: 'threejs'` worlds
158
+ * that follow the first-party entry-module convention (`export const
159
+ * adapter` and/or `export async function setup`) or are plain scene files
160
+ * with an optional named `componentRegistry` export. Threejs is safe to
161
+ * ship as an exported convenience (unlike pixijs/react) because `three`/
162
+ * `VgaiSceneGameAdapter` are already unconditional engine dependencies —
163
+ * see `mount-manifest.ts`'s header comment. Still never auto-registered:
164
+ * the registry itself stays zero-policy (see this file's header comment) —
165
+ * a caller opts in with `registerWorldKind('threejs', defaultThreeKindFactory)`.
166
+ *
167
+ * Resolution mirrors `mount-manifest.ts`'s own `resolveThreeAdapter` branch
168
+ * order: an entry module's `adapter` export wins outright; else its `setup`
169
+ * export (wrapping via `fromSetup` happens inside `mountManifestWorlds`
170
+ * itself — this factory just returns the `MountEntry` shape); else (no
171
+ * `entry` at all) a scene-driven world, forwarding `componentRegistry` if
172
+ * the entry module supplied one.
173
+ */
174
+ export const defaultThreeKindFactory: WorldKindFactory = (world, ctx) => {
175
+ const mod = ctx.entryModule as ThreeEntryModuleExports | undefined;
176
+ if (mod?.adapter) return { kind: 'threejs', adapter: mod.adapter };
177
+ if (mod?.setup) return { kind: 'threejs', setup: mod.setup };
178
+ if (world.entry !== undefined) {
179
+ throw new Error(
180
+ `defaultThreeKindFactory: entry module "${world.entry}" for world "${world.id}" exports ` +
181
+ 'neither `adapter` nor `setup` — every first-party entry module exports at least one ' +
182
+ '(see packages/editor/template/src/scripts/main.ts).',
183
+ );
184
+ }
185
+ return { kind: 'threejs', componentRegistry: mod?.componentRegistry };
186
+ };
187
+
188
+ // ---------------------------------------------------------------------------
189
+ // The composer
190
+ // ---------------------------------------------------------------------------
191
+
192
+ export interface MountGameOptions {
193
+ /** Explicit per-world entries, same shape `mountManifestWorlds` accepts —
194
+ * ALWAYS wins over a registered kind factory for that world id (backward
195
+ * compat: a caller mid-migration, or one that just prefers building one
196
+ * entry by hand, never has to touch the registry at all). */
197
+ readonly entries?: Readonly<Record<string, MountEntry>> | undefined;
198
+ }
199
+
200
+ /** True for the one shape `mountManifestWorlds` can ALREADY mount with zero
201
+ * `entries[id]` at all (a plain `default`-adapter, scene-driven, no-`entry`
202
+ * threejs world — `resolveThreeAdapter`'s own scene branch, which needs
203
+ * nothing beyond the manifest itself). Every other shape (pixijs, react, an
204
+ * entry-declaring or module/ingest-adapter threejs world) needs SOMETHING
205
+ * in `entries[id]` to succeed. */
206
+ function worldIsSelfSufficient(world: ResolvedWorldEntry): boolean {
207
+ return world.kind === 'threejs' && world.adapter.type === 'default' && world.entry === undefined;
208
+ }
209
+
210
+ /**
211
+ * Mount every world declared by a `vgai.game.json` manifest onto `host
212
+ * .container`, resolving each world's kind through the `registerWorldKind`
213
+ * registry — falling back to an explicit `opts.entries[id]` where supplied,
214
+ * exactly like `mountManifestWorlds` (so a caller can migrate one world at a
215
+ * time, or never touch the registry if it prefers hand-building entries).
216
+ *
217
+ * This is the "one call" scaffold/example projects mount through (E4
218
+ * acceptance): register whatever kinds you need once, then
219
+ * `await mountGameFromManifest(manifest, host)` — see
220
+ * `packages/editor/template/src/main.ts` for the worked single-world
221
+ * example and `examples/tri-world/src/main.ts` for a multi-kind one.
222
+ *
223
+ * Degrades loudly (`docs/WAVE3-ADAPTER-PLUMBING-DESIGN.md` D-Z2, carried
224
+ * into E4): a world whose kind has no registered factory AND no explicit
225
+ * entry, and which cannot self-mount from the manifest alone, throws a named
226
+ * `Error` identifying the world id + kind and BOTH ways to fix it
227
+ * (`registerWorldKind` or `opts.entries`) — never a silent skip.
228
+ */
229
+ export async function mountGameFromManifest(
230
+ manifestInput: unknown,
231
+ host: ManifestHost,
232
+ opts: MountGameOptions = {},
233
+ ): Promise<GameSession> {
234
+ const manifest = resolveManifest(manifestInput);
235
+ const entries: Record<string, MountEntry> = { ...opts.entries };
236
+
237
+ for (const world of manifest.worlds) {
238
+ if (entries[world.id] !== undefined) continue; // explicit entry always wins
239
+
240
+ const factory = registry.get(world.kind);
241
+ if (factory) {
242
+ const entryModule =
243
+ world.entry !== undefined && host.loadEntryModule
244
+ ? await host.loadEntryModule(world.entry)
245
+ : undefined;
246
+ entries[world.id] = await factory(world, { host, entryModule });
247
+ continue;
248
+ }
249
+
250
+ if (worldIsSelfSufficient(world)) continue; // mountManifestWorlds needs nothing further
251
+
252
+ throw new Error(
253
+ `mountGameFromManifest: world "${world.id}" (kind "${world.kind}") has no registered ` +
254
+ `world-kind factory and no explicit entries["${world.id}"] — call ` +
255
+ `registerWorldKind("${world.kind}", factory) before mounting (see ` +
256
+ '`defaultThreeKindFactory` for a worked threejs example), or pass ' +
257
+ `opts.entries["${world.id}"] directly (see mount-manifest.ts's \`MountEntry\`).`,
258
+ );
259
+ }
260
+
261
+ return mountManifestWorlds({
262
+ manifest,
263
+ container: host.container,
264
+ entries,
265
+ width: host.width,
266
+ height: host.height,
267
+ headless: host.headless,
268
+ });
269
+ }