@threenative/core 0.3.12 → 0.3.15

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 (165) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1047 -44
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/{canvas-layer-CWuFRT7G.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  5. package/dist/{chunk-7UUT3TY5.js → chunk-2GPHICV6.js} +1 -1
  6. package/dist/{chunk-GMHATRPW.js → chunk-GEMQJBY4.js} +1650 -383
  7. package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
  8. package/dist/{chunk-5O73CDMR.js → chunk-QAMSM3Z5.js} +415 -27
  9. package/dist/{chunk-2Z44XSI2.js → chunk-QAQHYOWY.js} +3 -7
  10. package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
  11. package/dist/{chunk-OKXUCASC.js → chunk-VBBYWGAT.js} +3 -4
  12. package/dist/chunk-VP43GIWW.js +18 -0
  13. package/dist/{chunk-N5LRP4BR.js → chunk-VQRPEOKY.js} +66 -3
  14. package/dist/{chunk-6KLNISRJ.js → chunk-XDTZ4QMO.js} +11 -4
  15. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  16. package/dist/{game-D7pAzZUY.d.ts → game-k8K3hZai.d.ts} +72 -8
  17. package/dist/hot.d.ts +5 -4
  18. package/dist/hot.js +5 -8
  19. package/dist/index.d.ts +871 -1018
  20. package/dist/index.js +4786 -1631
  21. package/dist/{model-lod-B6BMqS1r.d.ts → model-lod-DPTzeCcD.d.ts} +4 -2
  22. package/dist/playtest.d.ts +5 -4
  23. package/dist/playtest.js +6 -5
  24. package/dist/quality-BADStsTn.d.ts +868 -0
  25. package/dist/react.d.ts +3 -2
  26. package/dist/render-environment.d.ts +170 -0
  27. package/dist/render-environment.js +352 -0
  28. package/dist/{renderer-DvFVoAgj.d.ts → renderer-BtOSseYf.d.ts} +29 -31
  29. package/dist/spells/index.js +1 -1
  30. package/dist/ui-layer.js +3 -2
  31. package/dist/worker.js +12 -5
  32. package/dist/world.d.ts +280 -16
  33. package/dist/world.js +1529 -642
  34. package/mcp/animation-server.mjs +1 -1
  35. package/mcp/engine-server.mjs +135 -11
  36. package/mcp/servers.mjs +4 -4
  37. package/package.json +10 -6
  38. package/scripts/ensure-mcp.mjs +6 -1
  39. package/src/animation-batch.ts +193 -0
  40. package/src/animation-layers.ts +7 -3
  41. package/src/animation.ts +209 -29
  42. package/src/asset-cache.ts +3 -3
  43. package/src/asset-memo.ts +202 -0
  44. package/src/assets.ts +436 -131
  45. package/src/auto-batch.ts +190 -44
  46. package/src/clustered-batch.ts +146 -3
  47. package/src/clustered-mesh.ts +548 -20
  48. package/src/compute-driven.ts +1 -1
  49. package/src/config.ts +8 -0
  50. package/src/debug.ts +119 -22
  51. package/src/dev-global.ts +54 -0
  52. package/src/displaced-surface.ts +428 -0
  53. package/src/engine-hooks.ts +37 -0
  54. package/src/frame-budget.ts +35 -3
  55. package/src/game-boot-phase.ts +269 -0
  56. package/src/game-dev-tools.ts +7 -14
  57. package/src/game-frame-loop.ts +45 -82
  58. package/src/game-startup.ts +145 -70
  59. package/src/game-ui.ts +84 -0
  60. package/src/game.ts +168 -552
  61. package/src/gamepad-mappings.ts +269 -0
  62. package/src/generated/console-markers.ts +14 -0
  63. package/src/geometry-capture.ts +28 -4
  64. package/src/gpu-readings.ts +98 -0
  65. package/src/gpu-scene-bvh.ts +149 -36
  66. package/src/grass-field.ts +628 -0
  67. package/src/hot.ts +4 -7
  68. package/src/index.ts +227 -8
  69. package/src/input.ts +237 -25
  70. package/src/instanced-batch-lod.ts +3 -8
  71. package/src/interpolation.ts +171 -40
  72. package/src/look/ao-admission.ts +4 -3
  73. package/src/look/auto-exposure.ts +5 -16
  74. package/src/look/default-tone-mapping.ts +41 -5
  75. package/src/look/local-exposure.ts +2 -7
  76. package/src/look/quad-pass.ts +21 -0
  77. package/src/look/quality.ts +4 -0
  78. package/src/look/unreal-bloom.ts +4 -13
  79. package/src/look/world-environment.ts +58 -115
  80. package/src/merge-parts.ts +20 -24
  81. package/src/model-lod.ts +97 -14
  82. package/src/particle-significance.ts +12 -0
  83. package/src/particles.ts +19 -10
  84. package/src/platform.ts +23 -4
  85. package/src/profiling/FrameStages.ts +5 -6
  86. package/src/profiling/Spans.ts +3 -17
  87. package/src/profiling/debug-telemetry.ts +2 -6
  88. package/src/profiling/render-list-validate.ts +6 -15
  89. package/src/projection-marker.ts +2 -1
  90. package/src/quiet-markers.ts +3 -10
  91. package/src/render/cpu-bvh.ts +100 -0
  92. package/src/render/depth-pyramid.ts +6 -14
  93. package/src/render/environment/environmentContribution.ts +202 -0
  94. package/src/render/environment/environmentRadiance.ts +44 -0
  95. package/src/render/environment/environmentSampleCache.ts +56 -0
  96. package/src/render/environment/environmentSampling.ts +201 -0
  97. package/src/render/environment/environmentSnapshot.ts +71 -0
  98. package/src/render/environment/gate.ts +57 -0
  99. package/src/render/material-key.ts +21 -1
  100. package/src/render/mesh-pool.ts +3 -19
  101. package/src/render/probe-trace.ts +872 -0
  102. package/src/render/probe-volume.ts +780 -34
  103. package/src/render/radiance-cache.ts +17 -0
  104. package/src/render/screen-probe-gather.ts +303 -0
  105. package/src/render/short-range-ao.ts +274 -0
  106. package/src/render/virtual-shadow-partial.ts +13 -0
  107. package/src/render/virtual-shadow.ts +18 -16
  108. package/src/render/world-impostor-surface.ts +207 -9
  109. package/src/render/world-impostor.ts +5 -2
  110. package/src/render-camera-cull.ts +105 -4
  111. package/src/render-environment.ts +41 -0
  112. package/src/renderer-config.ts +36 -0
  113. package/src/renderer-facts.ts +37 -0
  114. package/src/renderer.ts +78 -32
  115. package/src/resolution-scaler.ts +3 -2
  116. package/src/scatter-field.ts +496 -0
  117. package/src/scene-entry-inspectors.ts +61 -0
  118. package/src/snow-field.ts +1 -0
  119. package/src/startup-offscreen-bytes.ts +84 -0
  120. package/src/state.ts +16 -3
  121. package/src/static-transform.ts +100 -25
  122. package/src/streamed-textures.ts +112 -0
  123. package/src/streaming.ts +68 -4
  124. package/src/texture-streaming.ts +331 -0
  125. package/src/tile-ring.ts +294 -0
  126. package/src/version.ts +1 -1
  127. package/src/warmup.ts +15 -2
  128. package/src/worker.ts +12 -2
  129. package/src/world-bundle-safety.ts +55 -10
  130. package/src/world-cell-batches.ts +166 -200
  131. package/src/world-cell-chunks.ts +3 -7
  132. package/src/world-cell-data.ts +7 -0
  133. package/src/world-cell-impostors.ts +20 -8
  134. package/src/world-cell-models.ts +36 -8
  135. package/src/world-cell-options.ts +2 -14
  136. package/src/world-cell-placements.ts +194 -90
  137. package/src/world-cell-prewarm.ts +39 -4
  138. package/src/world-cell-records.ts +401 -0
  139. package/src/world-cell-render-bundles.ts +2 -2
  140. package/src/world-cell-render-gpu-dress.ts +17 -19
  141. package/src/world-cell-render-main-cull.ts +73 -17
  142. package/src/world-cell-render-util.ts +18 -5
  143. package/src/world-cell-render.ts +13 -5
  144. package/src/world-cell-residency.ts +15 -6
  145. package/src/world-cell-stale.ts +238 -0
  146. package/src/world-cells.ts +23 -6
  147. package/src/world-gpu-flags.ts +18 -50
  148. package/src/world-gpu-reference.ts +22 -8
  149. package/src/world-gpu-scene.ts +44 -24
  150. package/src/world-gpu-shadow.ts +21 -8
  151. package/src/world-gpu-types.ts +41 -13
  152. package/src/world-load-limiter.ts +5 -0
  153. package/src/world-model-sections.ts +80 -0
  154. package/src/world-river-ribbon.ts +273 -0
  155. package/src/world-root-frame.ts +39 -0
  156. package/src/world-shore-field.ts +91 -0
  157. package/src/world-static-pose.ts +163 -0
  158. package/src/world-surface-sampler.ts +48 -0
  159. package/src/world-terrain-splat.ts +10 -18
  160. package/src/world-tile-budget.ts +4 -11
  161. package/src/world-tiles.ts +79 -12
  162. package/src/world-validate.ts +6 -14
  163. package/src/world-warm.ts +51 -0
  164. package/src/world-water-bodies.ts +113 -3
  165. package/src/world.ts +13 -0
@@ -1,24 +1,26 @@
1
- import { type Camera, type Object3D, Scene as ThreeScene, Vector2 } from "three";
1
+ import { type Object3D, Scene as ThreeScene, Vector2 } from "three";
2
2
  import { createAssetLoader } from "./assets.js";
3
3
  import { AutoBatch } from "./auto-batch.js";
4
4
  import { CanvasLayer } from "./canvas-layer.js";
5
- import type { ComputeDrivenRegistry } from "./compute-driven.js";
6
5
  import { isComputeDriven } from "./compute-driven.js";
7
6
  import { Registry } from "./entities.js";
8
- import type { FrameBudget } from "./frame-budget.js";
7
+ import {
8
+ type IBootPhase,
9
+ type ILoopPhase,
10
+ clearScene,
11
+ runAll,
12
+ throwFirst,
13
+ } from "./game-boot-phase.js";
9
14
  import { type DevToolsHost, installDevTools } from "./game-dev-tools.js";
10
- import type { IGameBootGame, IGameFrameLoop } from "./game-frame-loop.js";
15
+ import type { IGameFrameLoop } from "./game-frame-loop.js";
11
16
  import { createCamera } from "./game-validate.js";
12
17
  import type {
13
- IGameConfig,
14
18
  IGameObservationContribution,
15
- IGamePlatformSource,
16
19
  IGamePluginHooks,
17
20
  IGamePluginRuntime,
18
21
  IGameRuntimeObservations,
19
22
  PluginCleanup,
20
23
  } from "./game.js";
21
- import type { GeometryCapture } from "./geometry-capture.js";
22
24
  import { InputMap } from "./input.js";
23
25
  import { PhysicsInterpolation } from "./interpolation.js";
24
26
  import {
@@ -27,7 +29,6 @@ import {
27
29
  watchDeviceLoss,
28
30
  watchStartupStall,
29
31
  } from "./launch-diagnostics.js";
30
- import type { IAfterPhysicsPhase } from "./loop.js";
31
32
  import { type FixedStepLoop, createAfterPhysicsPhase } from "./loop.js";
32
33
  import { MatrixWorldPass } from "./matrix-world.js";
33
34
  import { ScenePicker } from "./picking.js";
@@ -39,7 +40,7 @@ import {
39
40
  formatUnlitFoliageWarning,
40
41
  unlitFoliageWarning,
41
42
  } from "./profiling/unlit-foliage-warning.js";
42
- import { type IRandom, createRandom } from "./random.js";
43
+ import { createRandom } from "./random.js";
43
44
  import { RenderCameraCull } from "./render-camera-cull.js";
44
45
  import type { VirtualShadowNode } from "./render/virtual-shadow.js";
45
46
  import { SceneRenderProjection } from "./renderProjection.js";
@@ -49,13 +50,15 @@ import {
49
50
  resolveRendererAntialias,
50
51
  resolveRendererScaleSetting,
51
52
  } from "./renderer-config.js";
52
- import { type IRendererLike, createRenderer } from "./renderer.js";
53
- import type { ICtx, IStartupStatus, IStartupTimeline, Scene, SceneFrame } from "./scene.js";
53
+ import { rendererFacts } from "./renderer-facts.js";
54
+ import { createRenderer } from "./renderer.js";
55
+ import type { ICtx, IStartupStatus, IStartupTimeline } from "./scene.js";
54
56
  import { Scheduler } from "./schedule.js";
55
57
  import {
56
58
  type IStartupOffscreenBytes,
57
59
  STARTUP_OFFSCREEN_BYTES_MARKER,
58
60
  measureStartupOffscreenBytes,
61
+ reportUnusedModelsLater,
59
62
  } from "./startup-offscreen-bytes.js";
60
63
  import {
61
64
  type IStartupImageState,
@@ -64,8 +67,6 @@ import {
64
67
  type StartupCompile,
65
68
  StartupReadiness,
66
69
  } from "./startup-readiness.js";
67
- import type { GameStore } from "./state.js";
68
- import type { IUiBridge } from "./ui-bridge.js";
69
70
  import { Viewport } from "./viewport.js";
70
71
  import {
71
72
  type IWarmUpOptions,
@@ -107,23 +108,8 @@ function createRuntimeObservations(): IGameRuntimeObservations {
107
108
  /** The first phase of `#boot`: everything up to the entered start scene. */
108
109
 
109
110
  export async function startGameWorld<TState extends Record<string, unknown>, TPhysics>(
110
- game: IGameBootGame<TState, TPhysics>,
111
+ game: IBootPhase<TState, TPhysics>,
111
112
  ) {
112
- const releases: Array<() => void> = [];
113
- const dispose = (): void => {
114
- const failures: unknown[] = [];
115
- for (const release of releases.splice(0)) {
116
- try {
117
- release();
118
- } catch (error) {
119
- failures.push(error);
120
- }
121
- }
122
- if (failures.length > 0) throw failures[0];
123
- };
124
- // Registered too: a boot that throws before answering leaves these for a later `stop()`.
125
- game.cleanup.push(dispose);
126
-
127
113
  const progress = {
128
114
  explicitWarmUpSettled: !game.warmUpConfiguredExplicitly(),
129
115
  gpuTallyProvider: undefined as GpuTally | undefined,
@@ -145,28 +131,20 @@ export async function startGameWorld<TState extends Record<string, unknown>, TPh
145
131
  const renderer = await createRenderer({
146
132
  ...game.config.renderer,
147
133
  canvas: game.config.canvas ?? game.config.renderer?.canvas,
148
- preferWebGPU: game.config.render?.preferWebGPU ?? game.config.renderer?.preferWebGPU,
134
+ preferWebGPU: game.config.renderer?.preferWebGPU,
149
135
  // One rule on both runtimes, decided 2026-09-01 after a HiDPI desktop browser upscaled a
150
136
  // DPR-1 web buffer into visible pixelation: the device's real density, with an explicit
151
137
  // `renderer.pixelRatio` winning over it (the old branch silently clobbered that value).
152
138
  // Headless capture lanes run at DPR 1 and are unaffected; the resolution scaler composes
153
139
  // on top, so a density the GPU cannot afford is trimmed by rungs, not by the developer.
154
140
  pixelRatio: game.config.renderer?.pixelRatio ?? globalThis.devicePixelRatio ?? 1,
155
- antialias: resolveRendererAntialias(
156
- game.config.render,
157
- game.config.renderer?.antialias,
158
- getPlatform().os,
159
- ),
141
+ antialias: resolveRendererAntialias(game.config.renderer, undefined, getPlatform().os),
160
142
  alphaAntialiasing: resolveRendererAlphaAntialiasing(
161
- game.config.render,
162
- game.config.renderer?.alphaAntialiasing,
163
- getPlatform().os,
164
- ),
165
- ...resolveRendererScaleSetting(
166
- game.config.render,
167
- game.config.renderer?.resolutionScale,
143
+ game.config.renderer,
144
+ undefined,
168
145
  getPlatform().os,
169
146
  ),
147
+ ...resolveRendererScaleSetting(game.config.renderer, undefined, getPlatform().os),
170
148
  source: game.config.renderer?.source ?? game.platform?.renderer,
171
149
  });
172
150
  if (game.aborted) {
@@ -174,12 +152,21 @@ export async function startGameWorld<TState extends Record<string, unknown>, TPh
174
152
  return;
175
153
  }
176
154
  game.renderer = renderer;
155
+ // Pushed first, so it runs last: nothing acquired after the renderer outlives it, and the
156
+ // presentation hold below lifts just before the renderer goes.
157
+ game.cleanup.push(() => {
158
+ renderer.dispose();
159
+ const mounted = game.platform;
160
+ if (mounted === undefined) renderer.domElement.remove?.();
161
+ else mounted.unmountCanvas(renderer.domElement);
162
+ game.renderer = undefined;
163
+ });
177
164
  // Before anything draws for this startup, including the warm-up and every covered world frame: the owned
178
165
  // engine keeps drawing, but presents nothing until a frame's shadow and exposure inputs are ready, so the
179
166
  // player never sees the two unsettled pictures a cold post chain produced (measured 185 -> 124 -> 108 mean
180
167
  // brightness). A renderer without the seam presents every frame exactly as before.
181
168
  renderer.setPresentationHeld?.(true);
182
- releases.push(() => renderer.setPresentationHeld?.(false));
169
+ game.cleanup.push(() => renderer.setPresentationHeld?.(false));
183
170
  const canvas = renderer.domElement;
184
171
  const platform = game.platform;
185
172
  const page = hostDocument();
@@ -191,34 +178,52 @@ export async function startGameWorld<TState extends Record<string, unknown>, TPh
191
178
  const inputTarget =
192
179
  game.config.inputTarget ??
193
180
  (platform === undefined ? (hostWindow() ?? canvas) : (platform.inputTarget ?? canvas));
194
- game.input = new InputMap(
181
+ // The store starts before the input and so stops after it: `stop()` releases the input, then the store.
182
+ game.state.start();
183
+ game.cleanup.push(() => game.state.stop());
184
+ const input = new InputMap(
195
185
  game.config.input,
196
186
  inputTarget,
197
187
  canvas,
198
188
  platform?.input,
199
189
  game.config.contextMenu,
190
+ { gamepadDeadZone: game.config.gamepadDeadZone },
200
191
  );
201
- game.state.start();
192
+ game.input = input;
193
+ game.cleanup.push(() => {
194
+ input.dispose();
195
+ game.input = undefined;
196
+ });
202
197
  const threeScene = new ThreeScene();
198
+ // Pushed before the objects built on this scene, so it runs after they are released.
199
+ game.cleanup.push(() => clearScene(threeScene, game.computeDriven));
203
200
  if (debug && "__debugTelemetry" in threeScene)
204
201
  (threeScene as ThreeScene & { __debugTelemetry: boolean }).__debugTelemetry = true;
205
202
  const camera = createCamera(game.config.camera);
206
203
  const interpolation = new PhysicsInterpolation(game.config.physicsInterpolation);
207
204
  game.interpolation = interpolation;
205
+ game.cleanup.push(() => {
206
+ interpolation.clear();
207
+ game.interpolation = undefined;
208
+ });
208
209
  interpolation.track(camera);
209
210
  const viewport = new Viewport({ camera, renderer: game.renderer, source: platform?.viewport });
210
- const canvasLayer = new CanvasLayer(viewport);
211
211
  game.viewport = viewport;
212
+ game.cleanup.push(() => {
213
+ viewport.dispose();
214
+ game.viewport = undefined;
215
+ });
216
+ const canvasLayer = new CanvasLayer(viewport);
217
+ game.cleanup.push(() => canvasLayer.dispose());
212
218
  // The renderer goes to the asset loader so compiled KTX2 textures detect transcoding
213
219
  // support against the real backend; a target that supports none fails right here.
214
220
  const assets = createAssetLoader({ ...game.config.assets, renderer: renderer.raw });
215
221
  if (assets.compressedTextures !== undefined) await assets.compressedTextures.ready;
216
- releases.push(() => assets.dispose());
222
+ game.cleanup.push(() => assets.dispose());
217
223
  const entities = new Registry();
218
224
  const random = createRandom(game.config.seed);
219
225
  const scheduler = new Scheduler();
220
226
  const afterPhysicsPhase = createAfterPhysicsPhase();
221
- const input = game.input;
222
227
  const picker = new ScenePicker({
223
228
  camera,
224
229
  // Input reports window-relative client coordinates; the picker's NDC math is
@@ -235,6 +240,10 @@ export async function startGameWorld<TState extends Record<string, unknown>, TPh
235
240
  viewport,
236
241
  });
237
242
  game.picker = picker;
243
+ game.cleanup.push(() => {
244
+ picker.dispose();
245
+ game.picker = undefined;
246
+ });
238
247
  const pointerEvents = new PointerEvents3D({
239
248
  screen: (position, target) => {
240
249
  const rect = (canvas as { getBoundingClientRect?: () => DOMRect }).getBoundingClientRect?.();
@@ -244,25 +253,32 @@ export async function startGameWorld<TState extends Record<string, unknown>, TPh
244
253
  },
245
254
  });
246
255
  game.pointerEvents = pointerEvents;
256
+ game.cleanup.push(() => {
257
+ pointerEvents.dispose();
258
+ game.pointerEvents = undefined;
259
+ });
247
260
  const loopState: { current?: FixedStepLoop } = {};
248
261
  // The engine owns the world-matrix walk, not three's renderer: on by default it does not recurse
249
262
  // into a hidden subtree, and `renderer.matrixWorld: "all"` restores the every-node walk. The
250
263
  // authored scene is marked once, here, so three never walks it a second time; the mirror scene
251
264
  // is marked at the render site, where whichever root is drawn this frame is known.
252
265
  const matrixWorldPass = new MatrixWorldPass({
253
- mode: resolveMatrixWorldMode(game.config.render),
266
+ mode: resolveMatrixWorldMode(game.config.renderer),
254
267
  });
255
268
  game.matrixWorld = matrixWorldPass;
269
+ game.cleanup.push(() => {
270
+ matrixWorldPass.dispose();
271
+ game.matrixWorld = undefined;
272
+ });
256
273
  threeScene.matrixWorldAutoUpdate = false;
257
274
  // Built before the context because `ctx.startup` reads it: a game asks what the framework's
258
275
  // startup is doing, and the answer is this pass.
259
276
  // The owned renderer retains its own velocity history; JS snapshots serve Three's accessors.
260
- const engineInfo = (renderer.raw as { info?: object }).info;
261
- const ownedEngine = engineInfo !== undefined && "engine" in engineInfo;
277
+ const { ownedEngine } = rendererFacts(renderer);
262
278
  const projection = new SceneRenderProjection(threeScene, {
263
279
  // The game's `renderer.projection` value verbatim: `false` declines the mirror, an object
264
280
  // names the material check beside accepting it, and the projection owns both readings.
265
- projection: game.config.render?.projection,
281
+ projection: game.config.renderer?.projection,
266
282
  velocity: () => !ownedEngine && (renderer.renderChainUsesPerObjectVelocity?.() ?? false),
267
283
  matrixWorld: matrixWorldPass,
268
284
  });
@@ -277,13 +293,19 @@ export async function startGameWorld<TState extends Record<string, unknown>, TPh
277
293
  console.info(line),
278
294
  });
279
295
  game.autoBatch = autoBatch;
296
+ // Runs before the scene is cleared (pushed after it), so the batches give their sources back first.
297
+ game.cleanup.push(() => autoBatch.reset());
280
298
  // Do not submit what the render camera cannot resolve. On by default at a conservative 0.5 px,
281
299
  // and measured whether or not the game narrows or declines it. Its decision is per camera, so
282
300
  // a shadow caster and anything attached to the camera are never dropped on the main view alone.
283
301
  const cameraCull = new RenderCameraCull({
284
- minimumPixels: game.config.render?.minimumProjectedPixels,
302
+ minimumPixels: game.config.renderer?.minimumProjectedPixels,
285
303
  });
286
304
  game.cameraCull = cameraCull;
305
+ game.cleanup.push(() => {
306
+ cameraCull.dispose();
307
+ game.cameraCull = undefined;
308
+ });
287
309
  /**
288
310
  * Progress is a high-water mark over the measured load state, never a value that can fall.
289
311
  *
@@ -364,7 +386,7 @@ export async function startGameWorld<TState extends Record<string, unknown>, TPh
364
386
  return renderer.firstWorldFrame?.() ?? true;
365
387
  },
366
388
  });
367
- releases.push(() => startupReadiness.cancel());
389
+ game.cleanup.push(() => startupReadiness.cancel());
368
390
  // Startup readiness does not wait on `ui-ready`, and cannot. The intent proves the page's
369
391
  // script ran, not that a pixel reached the screen, so waiting on it never closed the race it
370
392
  // was added for — it only made the losing side lose later, after up to 45 s of held frames.
@@ -405,7 +427,7 @@ export async function startGameWorld<TState extends Record<string, unknown>, TPh
405
427
  workProgress: () => assets.progress.settled + startupReadiness.workProgress,
406
428
  stallMs: STARTUP_STALL_MS,
407
429
  });
408
- releases.push(stopStallWatch);
430
+ game.cleanup.push(stopStallWatch);
409
431
  watchDeviceLoss(
410
432
  (
411
433
  renderer.raw as {
@@ -469,6 +491,7 @@ export async function startGameWorld<TState extends Record<string, unknown>, TPh
469
491
  // The first world frame the player sees is the next one this renderer draws, so the hold comes off
470
492
  // here and only here: every exit before it (abort, dispose, a failed launch) leaves the cover up.
471
493
  renderer.setPresentationHeld?.(false);
494
+ game.frameBudget?.markRevealed();
472
495
  for (const node of startupShadows) node.startupCovered = false;
473
496
  startupShadows.clear();
474
497
  // What a game does on `whenReady()` (lift its cover, show its HUD) reaches the page with the
@@ -496,6 +519,14 @@ export async function startGameWorld<TState extends Record<string, unknown>, TPh
496
519
  `${STARTUP_OFFSCREEN_BYTES_MARKER}_FAILED: ${error instanceof Error ? error.message : String(error)}`,
497
520
  );
498
521
  }
522
+ // Once, a minute on: an awaited model no scene object came from (TN_ASSET_UNUSED).
523
+ game.cleanup.push(
524
+ reportUnusedModelsLater(
525
+ new Map(assets.resolved),
526
+ threeScene,
527
+ () => game.aborted || game.renderer !== renderer,
528
+ ),
529
+ );
499
530
  // Again at ready: a world that streams its foliage in under `startup.hold` has none at entry.
500
531
  const unlit = unlitFoliageWarning(threeScene);
501
532
  if (unlit !== undefined)
@@ -720,13 +751,26 @@ export async function startGameWorld<TState extends Record<string, unknown>, TPh
720
751
  game.entities = entities;
721
752
  game.scheduler = scheduler;
722
753
  game.afterPhysicsPhase = afterPhysicsPhase;
754
+ // The scene-owned registries. Pushed after the autobatcher, so they empty before it resets (the
755
+ // order `#teardown` always had), and before the frame loop and plugins, so both release first.
756
+ game.cleanup.push(() => {
757
+ afterPhysicsPhase.clear();
758
+ game.beforeRenderCallbacks.clear();
759
+ scheduler.clear();
760
+ entities.clear();
761
+ game.afterPhysicsPhase = undefined;
762
+ game.scheduler = undefined;
763
+ game.entities = undefined;
764
+ });
723
765
  const devToolsHost = platform === undefined ? hostWindow() : platform.devToolsHost;
724
- releases.push(
766
+ game.cleanup.push(
725
767
  installDevTools(entities, devToolsHost as DevToolsHost | undefined, () => game.geometryCapture),
726
768
  );
727
769
  game.scene = new SceneType();
728
770
  game.sceneName = bootSceneName;
729
771
 
772
+ // The frame loop and scene entry see the narrower view; the compiler holds `IBootPhase` to it.
773
+ const loopPhase: ILoopPhase<TState, TPhysics> = game;
730
774
  return Object.assign(progress, {
731
775
  afterPhysicsPhase,
732
776
  autoBatch,
@@ -734,8 +778,7 @@ export async function startGameWorld<TState extends Record<string, unknown>, TPh
734
778
  canvasLayer,
735
779
  ctx,
736
780
  debug,
737
- dispose,
738
- game,
781
+ game: loopPhase,
739
782
  input,
740
783
  interpolation,
741
784
  loopState,
@@ -834,6 +877,36 @@ export async function startScenes<TState extends Record<string, unknown>, TPhysi
834
877
  Object.assign(runtime, {
835
878
  _setClockMode: (mode: "fixed-step" | "wall-clock") => gameLoop._setClockMode(mode),
836
879
  });
880
+ // Release order, newest push first (see `drainCleanup`): the loop stops, the scene exits, then every active
881
+ // plugin's `dispose`, then every plugin's setup cleanup, each group in the order its plugins were
882
+ // set up. Both plugin groups are pushed before the first `setup` runs, so a boot that aborts or
883
+ // throws inside the loop below still releases the plugins it had reached.
884
+ const pluginCleanups: PluginCleanup[] = [];
885
+ game.cleanup.push(() => throwFirst(runAll(pluginCleanups.splice(0))));
886
+ const disposed = new Set<IGamePluginHooks<TState, TPhysics>>();
887
+ game.cleanup.push(() => {
888
+ const active = game.activePlugins;
889
+ game.activePlugins = [];
890
+ throwFirst(
891
+ runAll(
892
+ active.map((plugin) => () => {
893
+ if (disposed.has(plugin)) return;
894
+ disposed.add(plugin);
895
+ plugin.dispose?.(ctx);
896
+ }),
897
+ ),
898
+ );
899
+ });
900
+ game.cleanup.push(() => {
901
+ try {
902
+ if (game.sceneEntered) game.scene?.exit(ctx);
903
+ } finally {
904
+ game.sceneFrame = undefined;
905
+ game.sceneEntered = false;
906
+ }
907
+ });
908
+ // Pushed last of all, so the loop stops before anything it drives is released.
909
+ game.cleanup.push(() => gameLoop.stop());
837
910
  // A boot that throws must end exactly like an aborted boot: every cleanup attempted, every
838
911
  // resource released — and the original error rethrown, not a teardown error standing in
839
912
  // for it. The abort branches below stay outside these guards: they tear down themselves.
@@ -842,20 +915,19 @@ export async function startScenes<TState extends Record<string, unknown>, TPhysi
842
915
  try {
843
916
  cleanup = typeof plugin === "function" ? plugin(ctx) : await plugin.setup?.(ctx, runtime);
844
917
  } catch (error) {
845
- game.teardown(ctx);
918
+ game.teardown();
846
919
  throw error;
847
920
  }
848
921
  if (typeof plugin !== "function") game.activePlugins.push(plugin);
922
+ if (cleanup !== undefined) pluginCleanups.push(cleanup);
849
923
  if (game.aborted) {
850
- if (cleanup !== undefined) game.cleanup.push(cleanup);
851
- game.teardown(ctx);
924
+ game.teardown();
852
925
  return;
853
926
  }
854
- if (cleanup !== undefined) game.cleanup.push(cleanup);
855
927
  }
856
928
  const scene = game.scene;
857
929
  if (scene === undefined) {
858
- game.teardown(ctx);
930
+ game.teardown();
859
931
  return;
860
932
  }
861
933
  // Held: the loop renders every frame from here but steps nothing. On native the render loop
@@ -876,11 +948,14 @@ export async function startScenes<TState extends Record<string, unknown>, TPhysi
876
948
  } catch (error) {
877
949
  reportSceneLoadFailure(error);
878
950
  settleLoaded(error);
879
- game.teardown(ctx);
951
+ // A runner's describe waits on these: answer it with the failure now, as every other start
952
+ // failure below does, instead of leaving it to run out its whole handshake budget.
953
+ for (const startGate of startGates) startGate.rejectEntered(error);
954
+ game.teardown();
880
955
  throw error;
881
956
  }
882
957
  if (game.aborted) {
883
- game.teardown(ctx);
958
+ game.teardown();
884
959
  return;
885
960
  }
886
961
  // Plugins that need to mutate scene-load placeholders hold here. Setup must land before
@@ -890,13 +965,13 @@ export async function startScenes<TState extends Record<string, unknown>, TPhysi
890
965
  await Promise.all(startGates.map(({ gate }) => gate));
891
966
  } catch (error) {
892
967
  for (const startGate of startGates) startGate.rejectEntered(error);
893
- game.teardown(ctx);
968
+ game.teardown();
894
969
  throw error;
895
970
  }
896
971
  if (game.aborted) {
897
972
  const error = new Error("Game start was aborted before the start scene entered.");
898
973
  for (const startGate of startGates) startGate.rejectEntered(error);
899
- game.teardown(ctx);
974
+ game.teardown();
900
975
  return;
901
976
  }
902
977
  }
@@ -913,11 +988,11 @@ export async function startScenes<TState extends Record<string, unknown>, TPhysi
913
988
  });
914
989
  } catch (error) {
915
990
  for (const startGate of startGates) startGate.rejectEntered(error);
916
- game.teardown(ctx);
991
+ game.teardown();
917
992
  throw error;
918
993
  }
919
994
  if (game.aborted) {
920
- game.teardown(ctx);
995
+ game.teardown();
921
996
  return;
922
997
  }
923
998
  // The scene is built and the loop is still held, which is the only window where compiling can
@@ -989,7 +1064,7 @@ export async function startScenes<TState extends Record<string, unknown>, TPhysi
989
1064
  );
990
1065
  startup.explicitWarmUpSettled = true;
991
1066
  if (game.aborted) {
992
- game.teardown(ctx);
1067
+ game.teardown();
993
1068
  return;
994
1069
  }
995
1070
  }
package/src/game-ui.ts ADDED
@@ -0,0 +1,84 @@
1
+ import type { IBootState } from "./game-boot-phase.js";
2
+ import type { IGameUi } from "./game.js";
3
+ import {
4
+ type IUiBridge,
5
+ UI_READY_INTENT,
6
+ UI_STARTUP_MESSAGE,
7
+ connectUiBridge,
8
+ } from "./ui-bridge.js";
9
+ import { type IUiStatePublisher, onUiIntent, publishUiState } from "./ui-state.js";
10
+
11
+ /** The slice of the boot state the UI seam reads and writes. */
12
+ export type IGameUiState<TState extends Record<string, unknown>> = Pick<
13
+ IBootState<TState, unknown>,
14
+ "state" | "uiBridge" | "uiReady" | "uiRevealed"
15
+ >;
16
+
17
+ /** The game's UI seam: one bridge, connected on first use, with the state published through it. */
18
+ export interface IGameUiSeam {
19
+ /** Connects the bridge once, however many callers ask. */
20
+ connect(): IUiBridge;
21
+ /** Closes the bridge and forgets that a UI was ready or the cover had lifted. */
22
+ disconnect(): void;
23
+ /** What `game.ui` returns; it connects early so a game can register intents before `start()`. */
24
+ facade(): IGameUi;
25
+ /** Tells a waiting page whether the loading cover is still up. */
26
+ postStartup(): void;
27
+ }
28
+
29
+ export function createGameUi<TState extends Record<string, unknown>>(
30
+ boot: IGameUiState<TState>,
31
+ ): IGameUiSeam {
32
+ let publisher: IUiStatePublisher | undefined;
33
+
34
+ const postStartup = (): void => {
35
+ boot.uiBridge?.post({
36
+ type: UI_STARTUP_MESSAGE,
37
+ phase: boot.uiRevealed ? "ready" : "covered",
38
+ });
39
+ };
40
+
41
+ const connect = (): IUiBridge => {
42
+ if (boot.uiBridge !== undefined) return boot.uiBridge;
43
+ const bridge = connectUiBridge({ end: "game" });
44
+ boot.uiBridge = bridge;
45
+ // The store already coalesces writes at flush. Deferring this again waits for the native
46
+ // host's next microtask pump, after that frame's WebView event pump has already passed.
47
+ // Ahead of the first state, which `publishUiState` sends at once when a UI is already waiting.
48
+ if (bridge.hasPeer()) postStartup();
49
+ publisher = publishUiState(bridge, boot.state, { schedule: (flush) => flush() });
50
+ onUiIntent(bridge, (intent) => {
51
+ if (intent !== UI_READY_INTENT) return;
52
+ boot.uiReady = true;
53
+ // Before the state: a UI that mounts after the reveal must learn the cover is gone, and one
54
+ // that mounts before it must learn to hide.
55
+ postStartup();
56
+ // Publish immediately: the UI has just rendered against nothing, and waiting for the store's
57
+ // next change would leave a HUD showing its initial values for up to a tick.
58
+ publisher?.publish();
59
+ });
60
+ return bridge;
61
+ };
62
+
63
+ const disconnect = (): void => {
64
+ boot.uiRevealed = false;
65
+ publisher?.stop();
66
+ publisher = undefined;
67
+ boot.uiReady = false;
68
+ boot.uiBridge?.close();
69
+ boot.uiBridge = undefined;
70
+ };
71
+
72
+ const facade = (): IGameUi => {
73
+ const bridge = connect();
74
+ return {
75
+ get connected() {
76
+ return bridge.hasPeer() && boot.uiReady;
77
+ },
78
+ onIntent: (listener) => onUiIntent(bridge, listener),
79
+ publish: () => publisher?.publish(),
80
+ };
81
+ };
82
+
83
+ return { connect, disconnect, facade, postStartup };
84
+ }