@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,151 @@
1
+ /**
2
+ * GameAdapter — the host ⇄ runtime contract. A "game" is *anything that mounts*.
3
+ *
4
+ * This is the interface the HOST depends on. It replaces the old
5
+ * `{ setup, components }` shape: the host no longer knows about `GameSetupFn`,
6
+ * `.vscn`, or `GameComponent` — those are the internals of ONE implementer
7
+ * (`VgaiSceneGameAdapter`). First-party content and an unmodified external game
8
+ * are peer implementers of THIS interface; the host has no branch on which.
9
+ */
10
+
11
+ import type { Container } from 'pixi.js';
12
+ import type * as THREE from 'three';
13
+ import type { AuthoringAdapter } from './authoring';
14
+ import type { HostContext } from './host-context';
15
+ import type { SystemAdapters } from './system-adapter';
16
+ import type { WorldKind } from './world-kind';
17
+
18
+ /**
19
+ * The ingested-world observation contract (T7.4 slice 2 — `docs/
20
+ * REACT-STATE-BRIDGE.md` §4, "the must-answer"). Cross-world data flow with a
21
+ * foreign game is observation via an adapter-provided interface, not ordinary
22
+ * component access (that's D7's answer for first-party↔first-party flow —
23
+ * foreign games host no `GameComponent`s). Optional on {@link MountedGame} —
24
+ * absence means the adapter has nothing genuinely observable to expose (the
25
+ * anti-shim rule: never fabricate state), and the world takes the honest
26
+ * "no state bridge" tier hit (see `Game.registerWorld` in `runtime/game.ts`)
27
+ * rather than silently offering an `undefined`-forever subscription.
28
+ */
29
+ export interface WorldStateObserver {
30
+ /**
31
+ * Notified at most once per frame IF the adapter can hook the game's own
32
+ * update (`loop: 'gated'` worlds, `docs/CAPABILITY-TIERS.md` §(d));
33
+ * self-driven worlds (`loop: 'self-driven'`, raw-rAF) may notify on their
34
+ * OWN rAF cadence instead — consumers must not assume our frame timing.
35
+ * Returns an unsubscribe function.
36
+ */
37
+ subscribe(onChange: () => void): () => void;
38
+ /**
39
+ * A cheap, adapter-chosen snapshot of this world's observable state.
40
+ * Returns a STABLE reference while nothing has changed (so a selector run
41
+ * over it can cheaply bail out by reference, same spirit as
42
+ * `GameStateBridge`'s frame-version cache). Shape is adapter-defined —
43
+ * not centrally schematized in v1 (see `docs/REACT-STATE-BRIDGE.md` §6).
44
+ */
45
+ snapshot(): unknown;
46
+ }
47
+
48
+ /**
49
+ * Everything a mounted world provides EXCEPT its render surface (T7.5,
50
+ * `docs/BACKBONE-TASKS.md`'s D6 row — "replace THREE.Scene/THREE.Camera
51
+ * typing with kind-tagged world surfaces"). Split out of the old flat
52
+ * `MountedGame` so a non-threejs world can carry its own kind-appropriate
53
+ * surface field (a pixi `stage`, a react `container`) instead of being
54
+ * force-fit through THREE `scene`/`camera` fields it doesn't have.
55
+ */
56
+ export interface MountedWorldBase {
57
+ /**
58
+ * Loop model:
59
+ * - `false` (host-driven): first-party + "clean" externals. The host ticks
60
+ * `update(dt)` in its loop.
61
+ * - `true` (self-driven): an unmodified game that owns its renderer + rAF.
62
+ * The host does NOT tick it. Pause/step control is a DECLARED CAPABILITY,
63
+ * not a promise: implement `setPaused`/`step` only where the game exposes
64
+ * a sanctioned pause/step mechanism. Gating a raw-rAF loop from outside
65
+ * was demonstrated and REJECTED (D5, docs/COMPOSITION-DESIGN.md §5.2 —
66
+ * it halts the loop rather than pausing it); such games are the
67
+ * "composited, unsynchronized" tier: `setPaused` absent, host degrades
68
+ * loudly (T7.6 owns the tier surface).
69
+ */
70
+ readonly drivesOwnLoop: boolean;
71
+
72
+ update?(dt: number): void; // host-driven only
73
+ fixedUpdate?(dt: number): void;
74
+ setPaused?(paused: boolean): void; // capability, not promise — see loop-model note above
75
+ step?(): void;
76
+
77
+ resize?(width: number, height: number): void;
78
+ dispose(): void;
79
+
80
+ /** Optional capability providers — absence = "not supported", host degrades. */
81
+ readonly authoring?: AuthoringAdapter;
82
+ readonly systems?: SystemAdapters;
83
+ /** Optional state-observation capability (T7.4 slice 2, §4) — absent means
84
+ * "no state bridge"; `Game.registerWorld` reports this loudly, once, for
85
+ * any non-first-party mount. First-party mounts are exempt — their state
86
+ * is observed through `Game.state`/`useGameState` instead (§3), not this
87
+ * field. */
88
+ readonly observe?: WorldStateObserver;
89
+ }
90
+
91
+ /** A live, mounted threejs world. The host obtains `scene`/`camera` to
92
+ * render+author. This is what `MountedGame` (the permanent alias every
93
+ * pre-T7.5 threejs-world call site still names) now means. */
94
+ export interface MountedThreeWorld extends MountedWorldBase {
95
+ readonly kind: 'threejs';
96
+ /** The live scene + camera the editor inspects/renders for authoring. */
97
+ readonly scene: THREE.Scene;
98
+ readonly camera: THREE.Camera;
99
+ }
100
+
101
+ /** A live, mounted pixijs world (T7.3) — the pixi analog of
102
+ * {@link MountedThreeWorld}. `stage` is the pixi world container the host
103
+ * renders/authors, the surface `WorldInstance.pixiRoot()` returns. */
104
+ export interface MountedPixiWorld extends MountedWorldBase {
105
+ readonly kind: 'pixijs';
106
+ readonly stage: Container;
107
+ }
108
+
109
+ /** A live, mounted react world (T6.2) — the react analog of
110
+ * {@link MountedThreeWorld}. `container` is the DOM-root layer the host
111
+ * handed the adapter's `mount` (the SAME element `WorldInstance.reactRoot()`
112
+ * returns) — a react world's tree renders into it via `createRoot`. */
113
+ export interface MountedReactWorld extends MountedWorldBase {
114
+ readonly kind: 'react';
115
+ readonly container: HTMLElement;
116
+ }
117
+
118
+ /** Every kind of live, mounted world (T7.5) — the union `WorldInstance.mounted`
119
+ * is typed against now, replacing the THREE-only `MountedGame`. */
120
+ export type MountedWorld = MountedThreeWorld | MountedPixiWorld | MountedReactWorld;
121
+
122
+ /** Map a {@link WorldKind} to its mounted-world shape (mirrors `NodeOf`/
123
+ * `BodyOf`/`ColliderOf` in `ecs/game-component.ts`) — lets generic code over
124
+ * `K extends WorldKind` name the right surface without a manual union. */
125
+ export type MountedWorldFor<K extends WorldKind> = K extends 'threejs'
126
+ ? MountedThreeWorld
127
+ : K extends 'pixijs'
128
+ ? MountedPixiWorld
129
+ : K extends 'react'
130
+ ? MountedReactWorld
131
+ : never;
132
+
133
+ /**
134
+ * Permanent alias (T7.1 precedent — old names stay valid forever once a
135
+ * generalization lands): `MountedGame` now means "a mounted THREEJS world."
136
+ * Every pre-T7.5 threejs-only call site (`VgaiMountedGame extends MountedGame`,
137
+ * `registerThreeWorld`, ingest adapters, …) keeps compiling unchanged.
138
+ */
139
+ export type MountedGame = MountedThreeWorld;
140
+
141
+ /** The interface every game implements to run on the host. Generic over
142
+ * {@link WorldKind} (T7.5) so a non-threejs implementer's `mount` returns its
143
+ * OWN kind-tagged surface instead of being cast through the threejs shape —
144
+ * defaults to `'threejs'` so every pre-T7.5 implementer/call site
145
+ * (`GameAdapter`, unparameterized) keeps compiling unchanged. */
146
+ export interface GameAdapter<K extends WorldKind = 'threejs'> {
147
+ /** Stable id (telemetry/registry/conformance). */
148
+ readonly id: string;
149
+ /** Build/start the game against a host-provided context; return the handle. */
150
+ mount(host: HostContext): Promise<MountedWorldFor<K>>;
151
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * HostContext — the NEUTRAL primitives the host hands a game when mounting it.
3
+ *
4
+ * This generalizes the old `GameContext`, which baked in first-party system
5
+ * choices (a Rapier world, the postprocessing composer, the InputManager, …).
6
+ * `HostContext` provides only what ANY game needs — the shared three instance, a
7
+ * surface, a renderer, a loop, assets, a UI overlay — and lets a game *ask* for
8
+ * a first-party subsystem via `requestSystem`, which the host may or may not
9
+ * supply. The host never assumes Rapier/Colyseus; those live behind
10
+ * `SystemAdapters` owned by the first-party implementer.
11
+ *
12
+ * Migration note: `VgaiSceneGameAdapter.mount` builds today's `GameContext`
13
+ * (Rapier world, composer, …) internally from a `HostContext`. New code targets
14
+ * `HostContext`; `GameContext` is now a first-party implementation detail.
15
+ */
16
+
17
+ import type * as THREE from 'three';
18
+ import type { AssetCache } from '../assets';
19
+ import type { GameInternal } from '../runtime/game';
20
+
21
+ /** The canvas/container the game renders into, plus its size. */
22
+ export interface HostSurface {
23
+ readonly canvas: HTMLCanvasElement;
24
+ readonly width: number;
25
+ readonly height: number;
26
+ }
27
+
28
+ /** Host-owned scheduling. A game may register extra per-frame callbacks; the
29
+ * host owns when they run. (First-party ticks its own system runner inside
30
+ * `MountedGame.update`, so it does not need this — it exists for games that
31
+ * want to hook the host loop directly.) */
32
+ export interface LoopHandle {
33
+ /** Register a per-frame callback; returns an unregister fn. */
34
+ onUpdate(fn: (dt: number) => void): () => void;
35
+ }
36
+
37
+ /**
38
+ * First-party subsystems a game MAY request from the host. The host returns
39
+ * `null` when it does not provide the kind, so a game must tolerate absence —
40
+ * the host never forces a subsystem on a game. Extended as new first-party
41
+ * systems become host-provisioned.
42
+ */
43
+ // biome-ignore lint/suspicious/noEmptyInterface: extended by first-party host wiring as systems become provisionable
44
+ export interface SystemRegistry {}
45
+
46
+ export interface HostContext {
47
+ /** The ONE shared three instance — identity matters for capture (see ingest). */
48
+ readonly three: typeof THREE;
49
+ /** Canvas/container + size; a self-driven game may take the surface over. */
50
+ readonly surface: HostSurface;
51
+ /** Host renderer — host-driven games render through it. */
52
+ readonly renderer: THREE.WebGLRenderer;
53
+ /** Host-owned loop scheduling. */
54
+ readonly loop: LoopHandle;
55
+ /** Shared GLTF/texture cache. */
56
+ readonly assets: AssetCache;
57
+ /** HUD overlay container (pointer-events:none by default). */
58
+ readonly ui: HTMLElement;
59
+ /**
60
+ * No GPU/DOM/audio available (Node conformance tests). A first-party adapter
61
+ * skips postprocessing/render/audio/input-map loading but still builds the
62
+ * scene + Rapier + components, so its scene/authoring/physics can be exercised
63
+ * headlessly. Browser hosts leave this false/undefined → full behavior.
64
+ */
65
+ readonly headless?: boolean;
66
+ /** Ask the host for a first-party subsystem; `null` if not provided. */
67
+ requestSystem<T extends keyof SystemRegistry>(kind: T): SystemRegistry[T] | null;
68
+ /**
69
+ * The Game root (T7.1 slice 1 — GAME-ROOT-DESIGN.md D6). The host
70
+ * constructs the Game shell BEFORE mounting a `GameAdapter` and hands it
71
+ * down here so an adapter can expose `ctx.game`/`ctx.worlds` to the game it
72
+ * mounts. Absent in headless harnesses and foreign hosts that predate the
73
+ * Game root — everything must keep working when this is undefined (the
74
+ * zero-break guarantee for this slice).
75
+ */
76
+ readonly game?: GameInternal | undefined;
77
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Adapter interfaces — the seams the engine host and the editor DEPEND ON.
3
+ *
4
+ * host → GameAdapter ← { VgaiSceneGameAdapter, IngestGameAdapter, … }
5
+ * editor → AuthoringAdapter ← { VgaiSceneAuthoringAdapter, IngestAuthoringAdapter, … }
6
+ * game → SystemAdapters (physics/networking/input/assets)
7
+ *
8
+ * The first-party `.vscn`/`GameComponent`/Rapier/Colyseus stack is ONE
9
+ * implementer of these interfaces, not the engine's vocabulary. See
10
+ * docs/ADAPTER-ARCHITECTURE.md.
11
+ */
12
+
13
+ export type {
14
+ AssetDropProvider,
15
+ AuthoringAdapter,
16
+ AuthoringCapabilities,
17
+ BoxEditProvider,
18
+ ColorSampleProvider,
19
+ ComponentsProvider,
20
+ DOMRectLike,
21
+ EditorNode,
22
+ FileMapProvider,
23
+ HierarchyProvider,
24
+ InspectorProvider,
25
+ LayoutProvider,
26
+ PersistenceProvider,
27
+ PickProvider,
28
+ PropertyDescriptor,
29
+ RectProvider,
30
+ RootGroup,
31
+ RootGroupsProvider,
32
+ SelectionProvider,
33
+ StoriesProvider,
34
+ StoryRef,
35
+ StructureProvider,
36
+ TextProvider,
37
+ TransformProvider,
38
+ } from './authoring';
39
+ export {
40
+ type ColyseusNetworkingConfig,
41
+ createColyseusNetworkingAdapter,
42
+ } from './colyseus-networking-adapter';
43
+ export {
44
+ createAnimationAdapter,
45
+ createInputManagerAdapter,
46
+ createNavigationAdapter,
47
+ createVgaiAssetAdapter,
48
+ } from './first-party-systems';
49
+ export type {
50
+ GameAdapter,
51
+ MountedGame,
52
+ MountedPixiWorld,
53
+ MountedReactWorld,
54
+ MountedThreeWorld,
55
+ MountedWorld,
56
+ MountedWorldBase,
57
+ MountedWorldFor,
58
+ WorldStateObserver,
59
+ } from './game-adapter';
60
+ export type { HostContext, HostSurface, LoopHandle, SystemRegistry } from './host-context';
61
+ export { createRapierPhysicsAdapter } from './rapier-physics-adapter';
62
+ export type {
63
+ AnimationAdapter,
64
+ AnimationGraphInfo,
65
+ AssetAdapter,
66
+ ConnectionState,
67
+ InputAdapter,
68
+ NavigationAdapter,
69
+ NavPoint,
70
+ NetPeer,
71
+ NetworkingAdapter,
72
+ PhysicsAdapter,
73
+ ReplicationStats,
74
+ RoomInfo,
75
+ SystemAdapters,
76
+ Unsubscribe,
77
+ } from './system-adapter';
78
+ export type { Transform, TransformOwner } from './transform';
79
+ export {
80
+ fromSetup,
81
+ type VgaiMountedGame,
82
+ type VgaiSceneConfig,
83
+ VgaiSceneGameAdapter,
84
+ } from './vgai-scene-game-adapter';
85
+ export type { WorldKind } from './world-kind';
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The game→host contract: ONE pre-defined interface an external game may
3
+ * declare on `window.vgaiGame` to let the editor work with it like native
4
+ * content. Capabilities are by PRESENCE — every field is optional, and a game
5
+ * that declares nothing runs exactly as before (doctrine: adaptation enables
6
+ * editor features; it never bends a game around host internals). This file is
7
+ * the single source of truth for the contract's shape — host code reads it
8
+ * through {@link readGameContract} instead of ad-hoc `window` casts, so the
9
+ * spec and the implementation cannot drift apart.
10
+ *
11
+ * Relationship to the native engine: first-party content implements the SAME
12
+ * conceptual surface (mount root, lifecycle, loop gating) through
13
+ * `GameAdapter`/`MountedGame` — the native engine is the premade 100%
14
+ * implementation of this contract. An ingested game climbs the same ladder
15
+ * endpoint by endpoint: capture infers what it can (the scene), the game
16
+ * declares what inference can't reach (its DOM root, its session lifecycle).
17
+ *
18
+ * Origin: docs/FTUE-EXTERNAL-R3F-GAME.md F16 (root), F17+F21 (lifecycle).
19
+ */
20
+
21
+ /**
22
+ * Session lifecycle endpoints. Declaring `start` means "I support cold
23
+ * mount": when the host sets `window.__vgaiMountCold` before the game's entry
24
+ * executes, the game may defer its session side-effects (backend connections,
25
+ * narrative, audio) and render a quiet, inspectable scene; the host calls
26
+ * `start()` — at most once per mount — when the user presses ▶. Declaring
27
+ * `pause`/`resume` means the game can genuinely freeze/unfreeze itself; the
28
+ * host prefers these over its outside-in loop gate (which cannot gate a raw
29
+ * requestAnimationFrame loop at all — R3F games, notably).
30
+ */
31
+ export interface VgaiGameLifecycle {
32
+ start?(): void;
33
+ pause?(): void;
34
+ resume?(): void;
35
+ }
36
+
37
+ export interface VgaiGameContract {
38
+ /** Bump only on breaking shape changes; additive endpoints keep version 1. */
39
+ contractVersion: 1;
40
+ /**
41
+ * The element that OWNS the game's whole DOM (canvas + HUD + overlay
42
+ * portals). The host adopts it wholesale into the game pane, so DOM-hybrid
43
+ * games keep their UI instead of stranding it at page level. The host
44
+ * verifies it actually contains the captured canvas before adopting.
45
+ */
46
+ root?: HTMLElement;
47
+ lifecycle?: VgaiGameLifecycle;
48
+ }
49
+
50
+ /**
51
+ * Read the declared contract, if any. The `contractVersion` gate is the
52
+ * forward-compatibility hinge: a future v2 game on a v1 host is ignored
53
+ * (pre-contract fallbacks apply) rather than half-interpreted.
54
+ */
55
+ export function readGameContract(): VgaiGameContract | null {
56
+ const declared = (window as unknown as { vgaiGame?: VgaiGameContract }).vgaiGame;
57
+ if (!declared || declared.contractVersion !== 1) return null;
58
+ return declared;
59
+ }
@@ -0,0 +1,207 @@
1
+ /**
2
+ * `applyVgaiOverlay` — the T3.8 deliverable (docs/DECISIONS-PENDING.md §D9):
3
+ * the opt-in runtime overlay applier a game owner adds to THEIR OWN deployment
4
+ * so an adapted (ingested-then-edited) game ships with the editor's edits
5
+ * visible, with zero involvement from the editor at runtime.
6
+ *
7
+ * The opt-in shape (D9's "minimal source opt-in, consistent with the
8
+ * zero-diff-unless-opted-in invariant"): one import + one call, placed before
9
+ * the game's own entry point runs (so the capture trap below is installed
10
+ * before the game's `WebGLRenderer` is constructed):
11
+ *
12
+ * import * as THREE from 'three';
13
+ * import { applyVgaiOverlay } from '@vgai/engine/adapter/ingest/overlay-applier';
14
+ *
15
+ * applyVgaiOverlay({ three: THREE, gameId: 'my-game' }); // fire-and-forget
16
+ * import('./my-game-entry.js'); // the UNMODIFIED game, unchanged
17
+ *
18
+ * No scene is passed manually — this reuses the SAME render-accessor trap
19
+ * (`./scene-capture.ts`) the editor's ingest mode uses to obtain the game's
20
+ * live `Scene`/camera the moment it first renders, so this works for ANY
21
+ * unmodified three.js game the SAME way ingestion already captures it (per
22
+ * `scene-capture.ts`'s own caveat, this requires the game to share the host's
23
+ * `three` module instance — a bundled/vendored copy of `three` cannot be
24
+ * captured this way, matching the editor's own capture ceiling).
25
+ *
26
+ * Failure modes are all graceful (the game always keeps running unmodified)
27
+ * but never silent — every one is logged via `console.warn` under the shared
28
+ * `overlay-report` prefix (`./overlay-report.ts`) so ops can grep one string
29
+ * for every overlay-related issue across both the editor and the ship path:
30
+ * - no overlay file at `overlayUrl` (never authored, or a 404/network
31
+ * error) → nothing applied, logged, scene never even captured;
32
+ * - the game never renders within `captureTimeoutMs` (bundled/non-shared
33
+ * three, or the game simply never boots) → nothing applied, logged;
34
+ * - a version mismatch and/or orphaned overlay ids (D9) → whatever DOES
35
+ * resolve is still applied; the report names what didn't.
36
+ *
37
+ * Precedence (D9 "overlay-vs-game-save-system precedence"): the overlay is
38
+ * applied exactly ONCE, synchronously, in the continuation of the game's
39
+ * FIRST captured render call — i.e. between that frame finishing and the
40
+ * game's own next frame starting. Any later mutation of the SAME
41
+ * property by the game's own logic (its own save/load system, a per-frame
42
+ * animation, etc.) therefore wins from then on purely by construction: this
43
+ * applier never re-applies and never re-reads the overlay after this one
44
+ * pass. A property the game's own logic never revisits stays overlaid for
45
+ * the life of the session; a property the game's own logic re-derives every
46
+ * frame reverts to the game's own value on the very next frame. This
47
+ * ordering is exercised directly by `overlay-applier.test.ts`'s "precedence"
48
+ * case (apply, then simulate one more game-owned mutation frame).
49
+ */
50
+
51
+ import type * as THREE from 'three';
52
+ import { applyOverlayToObjects, assignStructuralIds } from './overlay-apply';
53
+ import { type OverlayFile, overlayPath, parseOverlayFile } from './overlay-file';
54
+ import {
55
+ buildOverlayApplyReport,
56
+ logOverlayApplyReport,
57
+ OVERLAY_REPORT_PREFIX,
58
+ type OverlayApplyReport,
59
+ } from './overlay-report';
60
+ import { installSceneCapture } from './scene-capture';
61
+
62
+ export interface ApplyVgaiOverlayOptions {
63
+ /**
64
+ * The game's own `three` module namespace — pass `import * as THREE from
65
+ * 'three'` from the SAME module instance the game imports (required for the
66
+ * capture trap to see the game's renderer; see `scene-capture.ts`).
67
+ */
68
+ three: unknown;
69
+ /** Stable id for this game — namespaces the overlay file (matches the editor's `overlayPath(gameId)`). */
70
+ gameId: string;
71
+ /** Where to fetch the saved overlay from. Defaults to `overlayPath(gameId)` (`.vgai/overlays/<gameId>.json`, resolved relative to the deployed page — the editor saves to `<projectRoot>/.vgai/overlays/`; a deployment copies that file next to the built page). */
72
+ overlayUrl?: string | undefined;
73
+ /**
74
+ * The deployed game's own version, if known — compared against the
75
+ * overlay's `authoredAgainst.gameVersion` for drift reporting. Omit/null:
76
+ * never fabricated (anti-shim) — a mismatch is only ever reported when
77
+ * BOTH sides are known (`./overlay-report.ts`).
78
+ */
79
+ gameVersion?: string | null | undefined;
80
+ /**
81
+ * R5 (docs/MASTER-ARCHITECTURE-REVIEW.md §4(c)): the deployed game's own
82
+ * `UPSTREAM.md` pin, if the game owner happens to know it (e.g. baked in at
83
+ * build time from their own vendoring step). Compared against the overlay's
84
+ * `authoredAgainst.upstreamPin` for the same drift reporting `gameVersion`
85
+ * gets, but catches a same-slot SUBSTITUTION that `gameVersion` alone
86
+ * cannot (see `./upstream-pin.ts` + `./overlay-report.ts`'s header).
87
+ * DELIBERATE NO-OP by default: this ship-path applier runs in the game
88
+ * owner's OWN deployed build, which has no filesystem access to the
89
+ * `UPSTREAM.md` that lived in the vgai monorepo/editor project at
90
+ * ingest-authoring time — there is no way for this applier to discover the
91
+ * pin itself, so it is never fabricated (anti-shim) and the check silently
92
+ * skips (report's `upstreamPin.mismatch` stays `false`) unless the caller
93
+ * supplies this option explicitly.
94
+ */
95
+ upstreamPin?: string | null | undefined;
96
+ /** How long to wait for the game's first captured render call before giving up (ms). Defaults to `installSceneCapture`'s own default (10s). */
97
+ captureTimeoutMs?: number | undefined;
98
+ /** Injectable `fetch` (tests / non-browser hosts). Defaults to the global `fetch`. */
99
+ fetchImpl?: typeof fetch | undefined;
100
+ }
101
+
102
+ export interface ApplyVgaiOverlayResult {
103
+ /** Whether the game's scene was actually captured (false only when capture itself timed out or no overlay was found — either way the game runs unmodified). */
104
+ captured: boolean;
105
+ /** The D9 apply report, or `null` when there was no overlay to apply at all (not an error — the game runs unmodified). */
106
+ report: OverlayApplyReport | null;
107
+ /**
108
+ * The captured scene/camera, present only when `captured` is true. Most
109
+ * callers (a game's own entry point) have no reason to touch this — it's
110
+ * surfaced for diagnostics/tooling (and for tests, which use it to inspect
111
+ * the live post-apply scene the same way the editor's ingest proof pages do)
112
+ * rather than requiring a second, independent capture.
113
+ */
114
+ scene?: THREE.Scene | undefined;
115
+ camera?: THREE.Camera | undefined;
116
+ }
117
+
118
+ /** Shared warn helper — every graceful-failure path below logs through here. */
119
+ function warn(gameId: string, message: string): void {
120
+ // biome-ignore lint/suspicious/noConsole: deliberate, greppable (mirrors overlay-report.ts's own console.warn)
121
+ console.warn(`${OVERLAY_REPORT_PREFIX} game "${gameId}": ${message}`);
122
+ }
123
+
124
+ async function fetchOverlayFile(
125
+ url: string,
126
+ gameId: string,
127
+ fetchImpl: typeof fetch | undefined,
128
+ ): Promise<OverlayFile | null> {
129
+ const doFetch = fetchImpl ?? (typeof fetch === 'function' ? fetch : undefined);
130
+ if (!doFetch) {
131
+ warn(gameId, 'no fetch implementation available — overlay not applied, running unmodified.');
132
+ return null;
133
+ }
134
+ try {
135
+ const res = await doFetch(url);
136
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
137
+ const raw: unknown = await res.json();
138
+ return parseOverlayFile(raw);
139
+ } catch (err) {
140
+ const reason = err instanceof Error ? err.message : String(err);
141
+ warn(gameId, `no overlay applied (${reason}) — running unmodified.`);
142
+ return null;
143
+ }
144
+ }
145
+
146
+ /**
147
+ * The opt-in ship-path applier — see this module's header for the full
148
+ * contract. Installs the scene-capture trap SYNCHRONOUSLY (before the first
149
+ * `await`), so a caller that follows the documented pattern (call this, THEN
150
+ * import/boot the game) never races the trap against the game's first frame
151
+ * — the trap's `captured` slot latches on the game's first render regardless
152
+ * of when (or whether) this function later calls `waitForCapture` on it.
153
+ * Only PROCEEDS to actually wait for that capture once an overlay has been
154
+ * found (fetched first, deliberately) — the common "never edited this game"
155
+ * case then costs one fetch, never a multi-second capture-timeout wait.
156
+ */
157
+ export async function applyVgaiOverlay(
158
+ options: ApplyVgaiOverlayOptions,
159
+ ): Promise<ApplyVgaiOverlayResult> {
160
+ const { three, gameId, gameVersion = null, upstreamPin = null, fetchImpl } = options;
161
+ const overlayUrl = options.overlayUrl ?? overlayPath(gameId);
162
+
163
+ // Install the capture trap before anything else in this function (and
164
+ // before returning control to the caller's microtask queue) — see the
165
+ // header comment's ordering guarantee.
166
+ const capture = installSceneCapture(three);
167
+
168
+ const overlayFile = await fetchOverlayFile(overlayUrl, gameId, fetchImpl);
169
+ if (!overlayFile) {
170
+ // Nothing to apply (never authored, 404, network error — already logged
171
+ // by fetchOverlayFile) — don't bother waiting for a render at all.
172
+ capture.uninstall();
173
+ return { captured: false, report: null };
174
+ }
175
+
176
+ let rt: Awaited<ReturnType<typeof capture.waitForCapture>>;
177
+ try {
178
+ rt = await capture.waitForCapture(options.captureTimeoutMs);
179
+ } catch (err) {
180
+ capture.uninstall();
181
+ const reason = err instanceof Error ? err.message : String(err);
182
+ warn(gameId, `scene capture failed (${reason}) — overlay not applied, running unmodified.`);
183
+ return { captured: false, report: null };
184
+ }
185
+ capture.uninstall(); // one-shot: we have what we need, stop wrapping future renders.
186
+
187
+ const { byId } = assignStructuralIds(rt.scene, rt.camera);
188
+ const { applied, orphanedIds } = applyOverlayToObjects(byId, overlayFile.overrides);
189
+
190
+ const report = buildOverlayApplyReport({
191
+ gameId,
192
+ authoredAgainst: overlayFile.authoredAgainst.gameVersion,
193
+ currentVersion: gameVersion,
194
+ applied,
195
+ orphanedIds,
196
+ // R5: `authoredUpstreamPin` passes through undefined for a legacy overlay
197
+ // (the key was never in `authoredAgainst` at all — see overlay-file.ts),
198
+ // preserving the "never checked" vs. "checked, found nothing" distinction
199
+ // all the way from disk. `currentUpstreamPin` is this no-op-by-default
200
+ // option (see its doc comment above) — `null` unless a game owner passes it.
201
+ authoredUpstreamPin: overlayFile.authoredAgainst.upstreamPin,
202
+ currentUpstreamPin: upstreamPin,
203
+ });
204
+ logOverlayApplyReport(report);
205
+
206
+ return { captured: true, report, scene: rt.scene, camera: rt.camera };
207
+ }