@threenative/core 0.3.10 → 0.3.12

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 (158) hide show
  1. package/capabilities.json +1096 -26
  2. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  3. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-CWuFRT7G.d.ts} +1 -1
  4. package/dist/chunk-2Z44XSI2.js +35 -0
  5. package/dist/chunk-5O73CDMR.js +1849 -0
  6. package/dist/chunk-6KLNISRJ.js +153 -0
  7. package/dist/chunk-7UUT3TY5.js +133 -0
  8. package/dist/chunk-CFGTPFUH.js +231 -0
  9. package/dist/chunk-DBELTTTM.js +615 -0
  10. package/dist/chunk-GMHATRPW.js +7701 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-KIRUKTBQ.js +187 -0
  13. package/dist/chunk-N5LRP4BR.js +220 -0
  14. package/dist/chunk-OKXUCASC.js +2238 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-VAZM36TV.js +497 -0
  17. package/dist/{game-DzMcitDO.d.ts → game-D7pAzZUY.d.ts} +15 -3
  18. package/dist/hot.d.ts +3 -3
  19. package/dist/hot.js +2 -46
  20. package/dist/index.d.ts +329 -302
  21. package/dist/index.js +10565 -22533
  22. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-B6BMqS1r.d.ts} +33 -3
  23. package/dist/playtest.d.ts +3 -3
  24. package/dist/playtest.js +24 -75
  25. package/dist/react-css.js +1 -215
  26. package/dist/react.d.ts +2 -2
  27. package/dist/{renderer-rZm0hVqq.d.ts → renderer-DvFVoAgj.d.ts} +13 -4
  28. package/dist/spells/index.d.ts +643 -0
  29. package/dist/spells/index.js +1558 -0
  30. package/dist/spells/ultra/index.d.ts +1600 -0
  31. package/dist/spells/ultra/index.js +6804 -0
  32. package/dist/terrain-jobs-worker.js +1 -123
  33. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  34. package/dist/ui-layer.js +5 -384
  35. package/dist/worker.js +4 -41
  36. package/dist/world.d.ts +725 -259
  37. package/dist/world.js +16714 -18284
  38. package/mcp/animation-server.mjs +1 -1
  39. package/mcp/animation.mjs +2 -3
  40. package/mcp/engine-server.mjs +142 -47
  41. package/mcp/servers.mjs +9 -2
  42. package/mcp/terrain.mjs +8 -0
  43. package/package.json +14 -6
  44. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  45. package/patches/three@0.187.0.patch +2004 -407
  46. package/src/assets.ts +9 -2
  47. package/src/card-lod.ts +152 -0
  48. package/src/compressed-texture-preparation.ts +1008 -0
  49. package/src/frame-budget.ts +31 -20
  50. package/src/game-dev-tools.ts +93 -0
  51. package/src/game-frame-loop.ts +995 -0
  52. package/src/game-renderer-metrics.ts +77 -0
  53. package/src/game-startup.ts +1001 -0
  54. package/src/game-validate.ts +70 -0
  55. package/src/game.ts +253 -1935
  56. package/src/index.ts +27 -2
  57. package/src/launch-diagnostics.ts +22 -12
  58. package/src/look/ao-admission.ts +24 -0
  59. package/src/look/filmic-tone-mapping.ts +15 -13
  60. package/src/look/look-diagnostics.ts +3 -3
  61. package/src/look/quality.ts +10 -5
  62. package/src/look/world-environment.ts +76 -9
  63. package/src/loop.ts +29 -0
  64. package/src/model-lod.ts +42 -3
  65. package/src/particle-kinds.ts +515 -0
  66. package/src/picking.ts +17 -3
  67. package/src/playtest.ts +27 -1
  68. package/src/projection-apply.ts +4 -1
  69. package/src/projection-plan.ts +9 -6
  70. package/src/render/mesh-pool.ts +1 -1
  71. package/src/render/resolution-subrect.ts +2 -0
  72. package/src/render/rough-diffuse.ts +46 -12
  73. package/src/render/soft-shadow.ts +27 -12
  74. package/src/render/virtual-shadow-adaptive.ts +55 -0
  75. package/src/render/virtual-shadow-casters.ts +175 -0
  76. package/src/render/virtual-shadow-layers.ts +76 -0
  77. package/src/render/virtual-shadow-level.ts +224 -0
  78. package/src/render/virtual-shadow-markers.ts +193 -0
  79. package/src/render/virtual-shadow-options.ts +370 -0
  80. package/src/render/virtual-shadow-pages.ts +5 -0
  81. package/src/render/virtual-shadow.ts +213 -992
  82. package/src/render/world-impostor-surface.ts +293 -34
  83. package/src/render-camera-cull.ts +32 -1
  84. package/src/render-pass-budget.ts +34 -7
  85. package/src/renderProjection.ts +22 -0
  86. package/src/renderer.ts +92 -37
  87. package/src/snow-field.ts +1 -1
  88. package/src/spells/cast-pool.ts +361 -0
  89. package/src/spells/index.ts +177 -0
  90. package/src/spells/mechanisms.ts +295 -0
  91. package/src/spells/reaction-field.ts +415 -0
  92. package/src/spells/spell-lights.ts +139 -0
  93. package/src/spells/spell-world.ts +187 -0
  94. package/src/spells/spell.ts +397 -0
  95. package/src/spells/spells.ts +283 -0
  96. package/src/spells/ultra/engine/camera.ts +184 -0
  97. package/src/spells/ultra/engine/quality.ts +96 -0
  98. package/src/spells/ultra/index.ts +52 -0
  99. package/src/spells/ultra/main.ts +305 -0
  100. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  101. package/src/spells/ultra/spells/cast.ts +233 -0
  102. package/src/spells/ultra/spells/fire.ts +1267 -0
  103. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  104. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  105. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  106. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  107. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  108. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  109. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  110. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  111. package/src/spells/ultra/vfx/common.ts +1195 -0
  112. package/src/spells/ultra/vfx/noise.ts +441 -0
  113. package/src/startup-readiness.ts +128 -34
  114. package/src/version.ts +1 -1
  115. package/src/warmup.ts +56 -8
  116. package/src/water-surface.ts +9 -3
  117. package/src/world-bundle-safety.ts +401 -0
  118. package/src/world-cell-batches.ts +1216 -0
  119. package/src/world-cell-chunks.ts +1132 -0
  120. package/src/world-cell-data.ts +995 -0
  121. package/src/world-cell-impostors.ts +1449 -0
  122. package/src/world-cell-lod-bias.ts +151 -0
  123. package/src/world-cell-models.ts +1074 -0
  124. package/src/world-cell-options.ts +189 -0
  125. package/src/world-cell-placements.ts +694 -0
  126. package/src/world-cell-prewarm.ts +557 -0
  127. package/src/world-cell-readiness.ts +357 -0
  128. package/src/world-cell-render-bundles.ts +459 -0
  129. package/src/world-cell-render-gpu-dress.ts +714 -0
  130. package/src/world-cell-render-main-cull.ts +484 -0
  131. package/src/world-cell-render-shadow-claims.ts +198 -0
  132. package/src/world-cell-render-util.ts +246 -0
  133. package/src/world-cell-render.ts +1493 -0
  134. package/src/world-cell-residency.ts +745 -0
  135. package/src/world-cells.ts +1318 -10418
  136. package/src/world-chunk-shadow.ts +308 -0
  137. package/src/world-collar.ts +315 -0
  138. package/src/world-gpu-flags.ts +163 -0
  139. package/src/world-gpu-readback.ts +881 -0
  140. package/src/world-gpu-reference.ts +510 -0
  141. package/src/world-gpu-scene.ts +214 -2264
  142. package/src/world-gpu-shadow.ts +190 -0
  143. package/src/world-gpu-types.ts +381 -0
  144. package/src/world-gpu-validation.ts +518 -0
  145. package/src/world-heightfield.ts +802 -0
  146. package/src/world-load-limiter.ts +106 -0
  147. package/src/world-noise.ts +241 -0
  148. package/src/world-package.ts +42 -0
  149. package/src/world-region.ts +1 -1
  150. package/src/world-terrain-splat.ts +365 -149
  151. package/src/world-tile-budget.ts +256 -0
  152. package/src/world-tile-geometry.ts +469 -0
  153. package/src/world-tile-lod.ts +408 -0
  154. package/src/world-tile-observation.ts +566 -0
  155. package/src/world-tile-stitch.ts +166 -0
  156. package/src/world-tiles.ts +170 -1745
  157. package/src/world-water-bodies.ts +359 -0
  158. package/src/world.ts +35 -741
package/src/game.ts CHANGED
@@ -1,154 +1,55 @@
1
- import {
2
- type Camera,
3
- type Object3D,
4
- OrthographicCamera,
5
- PerspectiveCamera,
6
- Scene as ThreeScene,
7
- Vector2,
8
- } from "three";
9
- import { type IAssetLoaderOptions, createAssetLoader } from "./assets.js";
10
- import { AutoBatch, type IAutoBatchConfig } from "./auto-batch.js";
11
- import { CanvasLayer } from "./canvas-layer.js";
12
- import { updateClusteredMeshes } from "./clustered-mesh.js";
13
- import { ComputeDrivenRegistry, isComputeDriven } from "./compute-driven.js";
1
+ import type { Scene as ThreeScene } from "three";
2
+ import type { IAssetLoaderOptions } from "./assets.js";
3
+ import type { AutoBatch, IAutoBatchConfig } from "./auto-batch.js";
4
+ import { ComputeDrivenRegistry } from "./compute-driven.js";
14
5
  import type { IThreeNativeConfig } from "./config.js";
15
- import { type EntitySnapshot, Registry } from "./entities.js";
16
- import { FrameBudget, type IFrameBudgetOptions, type IFrameBudgetWindow } from "./frame-budget.js";
17
- import {
6
+ import type { Registry } from "./entities.js";
7
+ import type { FrameBudget, IFrameBudgetOptions, IFrameBudgetWindow } from "./frame-budget.js";
8
+ import { startFrameLoop } from "./game-frame-loop.js";
9
+ import type { IGameBootGame } from "./game-frame-loop.js";
10
+ import { startGameWorld, startScenes } from "./game-startup.js";
11
+ import { assertCarry, validateCameraConfig } from "./game-validate.js";
12
+ import type {
18
13
  GeometryCapture,
19
- type IGeometryCaptureReport,
20
- type IGeometryCaptureRequest,
21
- rendererBackendIdentity,
14
+ IGeometryCaptureReport,
15
+ IGeometryCaptureRequest,
22
16
  } from "./geometry-capture.js";
23
- import { type ContextMenuPolicy, type InputBindings, InputMap } from "./input.js";
24
- import { PhysicsInterpolation } from "./interpolation.js";
25
- import { reportLaunchFailure, watchDeviceLoss, watchStartupStall } from "./launch-diagnostics.js";
26
- import {
27
- FixedStepLoop,
28
- type IAfterPhysicsPhase,
29
- type IRenderPerformanceMetrics,
30
- type IRenderPerformanceSample,
31
- createAfterPhysicsPhase,
32
- } from "./loop.js";
33
- import { MatrixWorldPass } from "./matrix-world.js";
34
- import { updateModelLods } from "./model-lod.js";
35
- import { ScenePicker } from "./picking.js";
17
+ import type { ContextMenuPolicy, InputBindings, InputMap } from "./input.js";
18
+ import type { PhysicsInterpolation } from "./interpolation.js";
19
+ import { reportLaunchFailure, reportSceneLoadFailure } from "./launch-diagnostics.js";
20
+ import type { IAfterPhysicsPhase, IRenderPerformanceSample } from "./loop.js";
21
+ import type { MatrixWorldPass } from "./matrix-world.js";
22
+ import type { ScenePicker } from "./picking.js";
36
23
  import type { IPipelineCensus } from "./pipeline-census.js";
37
- import { getPlatform, hostDocument, hostWindow } from "./platform.js";
38
- import { PointerEvents3D } from "./pointer-events.js";
39
- import {
40
- FrameCounters,
41
- counterDeviceOf,
42
- createCrossingReader,
43
- createEngineCounterReader,
44
- } from "./profiling/FrameCounters.js";
45
- import {
46
- createStageReader,
47
- createWorkReader,
48
- stageMetersRequested,
49
- } from "./profiling/FrameStages.js";
50
- import {
51
- SPANS,
52
- SpanRecorder,
53
- addSpan,
54
- beginSpan,
55
- endSpan,
56
- formatSpansWindow,
57
- setSpanRecorder,
58
- spanNow,
59
- spansRequested,
60
- } from "./profiling/Spans.js";
61
- import {
62
- countDebug,
63
- debugRequested,
64
- measureDebug,
65
- observeDebugGc,
66
- } from "./profiling/debug-telemetry.js";
24
+ import type { PointerEvents3D } from "./pointer-events.js";
67
25
  import { applyOpacityConvention } from "./profiling/opacity-convention.js";
68
- import {
69
- RenderListValidator,
70
- formatValidationReport,
71
- renderListValidationRequested,
72
- } from "./profiling/render-list-validate.js";
73
26
  import { renderTrapAudit } from "./profiling/render-trap-audit.js";
74
- import {
75
- describeSceneShape,
76
- describeSceneWarning,
77
- formatSceneWarning,
78
- sceneWarning,
79
- } from "./profiling/scene-warning.js";
80
- import { installSpanProbes } from "./profiling/span-probes.js";
81
27
  import {
82
28
  UNLIT_FOLIAGE_FIX,
83
29
  formatUnlitFoliageWarning,
84
30
  unlitFoliageWarning,
85
31
  } from "./profiling/unlit-foliage-warning.js";
86
- import { formatProjectionWindow } from "./projection-marker.js";
87
32
  import { installQuietMarkers, uninstallQuietMarkers } from "./quiet-markers.js";
88
- import { type IRandom, createRandom } from "./random.js";
89
- import { RenderCameraCull } from "./render-camera-cull.js";
90
- import { RenderPassBudget } from "./render-pass-budget.js";
91
- import { SceneRenderProjection } from "./renderProjection.js";
92
- import {
93
- resolveMatrixWorldMode,
94
- resolvePlatformResolutionFloor,
95
- resolveRendererAlphaAntialiasing,
96
- resolveRendererAntialias,
97
- resolveRendererScaleSetting,
98
- } from "./renderer-config.js";
99
- import {
100
- type IRendererLike,
101
- type IRendererOptions,
102
- type RendererKind,
103
- createRenderer,
104
- rendererFrameGateSkips,
105
- rendererWorldPresented,
106
- } from "./renderer.js";
107
- import { RESOLUTION_SCALER, ResolutionScaler } from "./resolution-scaler.js";
108
- import type {
109
- ICtx,
110
- IStartupStatus,
111
- IStartupTimeline,
112
- Scene,
113
- SceneConstructor,
114
- SceneFrame,
115
- } from "./scene.js";
116
- import { Scheduler } from "./schedule.js";
117
- import {
118
- type IStartupOffscreenBytes,
119
- STARTUP_OFFSCREEN_BYTES_MARKER,
120
- measureStartupOffscreenBytes,
121
- } from "./startup-offscreen-bytes.js";
122
- import {
123
- type IStartupImageState,
124
- STARTUP_COMPILE_BUDGET_MS,
125
- STARTUP_STABLE_WINDOW_MS,
126
- STARTUP_STALL_MS,
127
- type StartupCompile,
128
- StartupReadiness,
129
- } from "./startup-readiness.js";
33
+ import type { IRandom } from "./random.js";
34
+ import type { RenderCameraCull } from "./render-camera-cull.js";
35
+ import type { SceneRenderProjection } from "./renderProjection.js";
36
+ import type { IRendererLike, IRendererOptions } from "./renderer.js";
37
+ import type { ICtx, IStartupTimeline, Scene, SceneConstructor, SceneFrame } from "./scene.js";
38
+ import type { Scheduler } from "./schedule.js";
39
+ import type { IStartupOffscreenBytes } from "./startup-offscreen-bytes.js";
40
+ import { STARTUP_COMPILE_BUDGET_MS } from "./startup-readiness.js";
130
41
  import { type GameStore, createGameStore } from "./state.js";
131
- import {
132
- STATIC_TRANSFORM_MARKER,
133
- refreshStaticTransforms,
134
- staticRoots,
135
- staticTransformCensus,
136
- } from "./static-transform.js";
137
- import { resolveTargetFps } from "./target-fps.js";
138
42
  import {
139
43
  type IUiBridge,
140
- UI_DEV_METRICS_MESSAGE,
141
44
  UI_READY_INTENT,
142
45
  UI_STARTUP_MESSAGE,
143
46
  connectUiBridge,
144
47
  } from "./ui-bridge.js";
145
48
  import { type IUiStatePublisher, onUiIntent, publishUiState } from "./ui-state.js";
146
- import { type IViewportOptions, Viewport } from "./viewport.js";
49
+ import type { IViewportOptions, Viewport } from "./viewport.js";
147
50
  import {
148
51
  type IWarmUpOptions,
149
- type IWarmUpReport,
150
52
  prepareSceneEnvironment,
151
- sceneNeedsEnvironmentPreparation,
152
53
  warmUpComputeNodes,
153
54
  warmUpScene,
154
55
  } from "./warmup.js";
@@ -211,8 +112,20 @@ export interface IGamePluginRuntime {
211
112
  * A run that counts fixed-step ticks must not also accumulate real seconds into the same
212
113
  * simulation, and the frames before its first `advance()` are exactly where a boot's seconds
213
114
  * used to land. Optional: a runtime without a clock just never freezes one.
115
+ *
116
+ * `settleSteps` is the settling pass the world is owed: a zero freeze lets `settleClock` spend it
117
+ * instead, once the world's scene is live.
214
118
  */
215
- readonly freezeClock?: () => void;
119
+ readonly freezeClock?: (settleSteps?: number) => void;
120
+ /**
121
+ * Spend the settling pass now, from a caller that knows the world's scene is live.
122
+ *
123
+ * Present only when the runtime can spend it later than the freeze: a game that boots through a
124
+ * loading scene otherwise settles the loading scene, and the world's own clock misses those fixed
125
+ * steps — a playtest pose then depends on how fast the machine booted. Optional, and paired with
126
+ * `freezeClock(0)`: a runtime without it settles on its first live frame, as before.
127
+ */
128
+ readonly settleClock?: (steps?: number) => void;
216
129
  /**
217
130
  * Draw the current world once without advancing it, for a screenshot taken while the loop is
218
131
  * driven by `fixedStep` and presents nothing between ticks. Optional: a runtime without a frozen
@@ -267,17 +180,6 @@ export interface IGamePluginRuntime {
267
180
  readonly step: number;
268
181
  }
269
182
 
270
- interface IDevTools {
271
- snapshot(): EntitySnapshot;
272
- /**
273
- * Arms one per-object geometry capture for a development overlay. Absent until the game has a
274
- * render loop; the overlay treats that as "not ready", never as an empty scene.
275
- */
276
- geometry?(request?: IGeometryCaptureRequest): Promise<IGeometryCaptureReport>;
277
- }
278
-
279
- type DevToolsHost = Record<string, unknown> & Partial<Record<"__THREENATIVE__", IDevTools>>;
280
-
281
183
  export interface IGamePlatformSource {
282
184
  readonly devToolsHost?: Record<string, unknown>;
283
185
  readonly input: NonNullable<ConstructorParameters<typeof InputMap>[3]>;
@@ -288,84 +190,6 @@ export interface IGamePlatformSource {
288
190
  unmountCanvas(canvas: HTMLCanvasElement): void;
289
191
  }
290
192
 
291
- /**
292
- * Whether this launch is a development one.
293
- *
294
- * A web build answers through Vite's own flag. A native build has no bundler flag at launch, so the
295
- * host publishes `DEV_MODE` on `process.env` — the one place a game can read how it was started —
296
- * and this reads it. Both routes answer the same question: should the dev surfaces exist.
297
- */
298
- /**
299
- * The bundler's dev flag.
300
- *
301
- * The `import.meta.env` access must stay written out exactly here. Vite replaces that member
302
- * expression at build time; any indirection — a variable holding `import.meta`, or a helper that
303
- * takes it as an argument — survives into the bundle, where the game is compiled as a script and
304
- * not a module, and the whole bundle then fails to parse with "Cannot use 'import.meta' outside a
305
- * module". That is a game that never starts, so the literal access is load-bearing, not style.
306
- */
307
- function bundlerDevFlag(): boolean {
308
- // quality-allow: DEV is the bundler's own name for the flag, so the name rule cannot apply.
309
- // biome-ignore lint/style/useNamingConvention: the bundler's own flag name.
310
- return (import.meta as unknown as { env?: { DEV?: boolean } }).env?.DEV === true;
311
- }
312
-
313
- function isDevLaunch(): boolean {
314
- // `process.env` exists only where a host installed one: the native runtime does, a browser
315
- // bundle does not. Narrowed rather than asserted, so a host that installs something else
316
- // answers "not dev" instead of reading a field that is not there.
317
- const scope: unknown = globalThis;
318
- if (typeof scope === "object" && scope !== null && "process" in scope) {
319
- const hostProcess: unknown = scope.process;
320
- if (typeof hostProcess === "object" && hostProcess !== null && "env" in hostProcess) {
321
- const env: unknown = hostProcess.env;
322
- if (typeof env === "object" && env !== null && "DEV_MODE" in env) {
323
- const flag: unknown = env.DEV_MODE;
324
- if (typeof flag === "string" && flag !== "" && flag !== "0" && flag !== "false")
325
- return true;
326
- }
327
- }
328
- }
329
- return bundlerDevFlag();
330
- }
331
-
332
- function installDevTools(
333
- entities: Registry,
334
- host: DevToolsHost | undefined,
335
- // Late-bound: the capture is constructed with the render loop, after this install runs.
336
- geometry: () => GeometryCapture | undefined,
337
- ): PluginCleanup {
338
- // Written out here, not through `isDevLaunch()`: the bundler must see the literal flag to strip
339
- // this whole install from a production build, and a runtime `DEV_MODE` check cannot be stripped.
340
- const isDev =
341
- (import.meta as ImportMeta & { env?: Record<"DEV", boolean | undefined> }).env?.DEV === true;
342
- if (!isDev || host === undefined) return () => undefined;
343
- const devTools: IDevTools = {
344
- ...(host.__THREENATIVE__ as (IDevTools & Record<string, unknown>) | undefined),
345
- geometry: async (request) => {
346
- const capture = geometry();
347
- if (capture === undefined) {
348
- return {
349
- reason: "TN_GEOMETRY_CAPTURE_NO_LOOP: the game has no running render loop to capture.",
350
- status: "unavailable",
351
- };
352
- }
353
- return capture.request(request);
354
- },
355
- snapshot: () => entities.snapshot(),
356
- };
357
- host.__THREENATIVE__ = devTools;
358
- return () => {
359
- if (host.__THREENATIVE__ !== devTools) return;
360
- const remaining = Object.fromEntries(
361
- Object.entries(devTools).filter(([key]) => key !== "snapshot" && key !== "geometry"),
362
- );
363
- host.__THREENATIVE__ =
364
- // quality-allow: what other dev tools left on the shared global after this game removed its own.
365
- Object.keys(remaining).length === 0 ? undefined : (remaining as unknown as IDevTools);
366
- };
367
- }
368
-
369
193
  export type GamePluginFunction<
370
194
  TState extends Record<string, unknown> = Record<string, unknown>,
371
195
  TPhysics = undefined,
@@ -390,21 +214,6 @@ export type GamePlugin<
390
214
  TPhysics = undefined,
391
215
  > = GamePluginFunction<TState, TPhysics> | IGamePluginHooks<TState, TPhysics>;
392
216
 
393
- /**
394
- * The global a native host reads to know the world is on screen. Named here rather than written
395
- * inline so the host and the framework agree on one spelling.
396
- */
397
- const STARTUP_READY_GLOBAL = "__TN_STARTUP_READY__";
398
-
399
- /**
400
- * Drawn frames the state publish waits after startup readiness. The page paints a state change on
401
- * the next vsync, but the canvas frame that lifts the cover reaches the screen only when the GPU has
402
- * drawn it: Lantern Vale's HUD (`loaded` on `whenReady()`) painted one frame over its loading cover.
403
- * Three, because a renderer keeps at most two frames on the GPU (the Wasm engine's gate declines a
404
- * third), so the third drawn frame proves the first uncovered one has left the GPU.
405
- */
406
- const STARTUP_HANDOFF_FRAMES = 3;
407
-
408
217
  export interface IGameConfig<
409
218
  TState extends Record<string, unknown> = Record<string, unknown>,
410
219
  TPhysics = undefined,
@@ -571,63 +380,6 @@ export interface IGame<
571
380
  stop(): void;
572
381
  }
573
382
 
574
- function positiveCameraValue(name: string, value: number): number {
575
- if (!Number.isFinite(value) || value <= 0)
576
- throw new Error(`camera.${name} must be finite and positive.`);
577
- return value;
578
- }
579
-
580
- function assertJsonSafe(value: unknown, path = "$", seen = new WeakSet<object>()): void {
581
- if (value === null || typeof value === "string" || typeof value === "boolean") return;
582
- if (typeof value === "number") {
583
- if (Number.isFinite(value)) return;
584
- throw new TypeError(`${path} must contain only finite JSON numbers.`);
585
- }
586
- if (typeof value === "object") {
587
- if (seen.has(value)) throw new TypeError(`${path} must be JSON-safe and cannot be cyclic.`);
588
- seen.add(value);
589
- if (Array.isArray(value)) {
590
- if (Object.getPrototypeOf(value) !== Array.prototype) {
591
- throw new TypeError(`${path} must be a JSON-safe array.`);
592
- }
593
- for (let index = 0; index < value.length; index += 1) {
594
- assertJsonSafe(value[index], `${path}[${index}]`, seen);
595
- }
596
- seen.delete(value);
597
- return;
598
- }
599
- const prototype = Object.getPrototypeOf(value);
600
- if (prototype !== Object.prototype && prototype !== null) {
601
- throw new TypeError(`${path} must be a JSON-safe plain object.`);
602
- }
603
- for (const [key, item] of Object.entries(value)) assertJsonSafe(item, `${path}.${key}`, seen);
604
- seen.delete(value);
605
- return;
606
- }
607
- throw new TypeError(`${path} must be JSON-safe.`);
608
- }
609
-
610
- function assertCarry(value: unknown): asserts value is Record<string, unknown> {
611
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
612
- throw new TypeError("goto carry must be a JSON object.");
613
- }
614
- assertJsonSafe(value, "$.carry");
615
- }
616
-
617
- function validateCameraConfig(config: CameraConfig | undefined): void {
618
- if (config === undefined) return;
619
- const near = positiveCameraValue("near", config.near ?? 0.1);
620
- const far = positiveCameraValue("far", config.far ?? 2_000);
621
- if (far <= near) throw new Error("camera.far must be greater than camera.near.");
622
- if (config.projection === "perspective") {
623
- const fov = config.fov ?? 60;
624
- if (!Number.isFinite(fov) || fov <= 0 || fov >= 180)
625
- throw new Error("camera.fov must be finite and between 0 and 180 degrees.");
626
- return;
627
- }
628
- positiveCameraValue("size", config.size);
629
- }
630
-
631
383
  function clearScene(scene: ThreeScene, computeDriven: ComputeDrivenRegistry): void {
632
384
  computeDriven.clear();
633
385
  scene.clear();
@@ -636,92 +388,6 @@ function clearScene(scene: ThreeScene, computeDriven: ComputeDrivenRegistry): vo
636
388
  scene.fog = null;
637
389
  }
638
390
 
639
- /** The measured draw count on its own, for the projection line that reads it every frame. */
640
- function rendererDrawCallCount(raw: unknown): number | undefined {
641
- if (typeof raw !== "object" || raw === null) return undefined;
642
- const info = (raw as { info?: unknown }).info;
643
- if (typeof info !== "object" || info === null) return undefined;
644
- const render = (info as { render?: unknown }).render;
645
- if (typeof render !== "object" || render === null) return undefined;
646
- const drawCalls = (render as { drawCalls?: unknown }).drawCalls;
647
- const calls = drawCalls ?? (render as { calls?: unknown }).calls;
648
- return typeof calls === "number" && Number.isFinite(calls) && calls >= 0 ? calls : undefined;
649
- }
650
-
651
- function rendererPerformanceMetrics(raw: unknown): {
652
- drawCalls?: number;
653
- triangles?: number;
654
- } {
655
- if (typeof raw !== "object" || raw === null) return {};
656
- const info = (raw as { info?: unknown }).info;
657
- if (typeof info !== "object" || info === null) return {};
658
- const render = (info as { render?: unknown }).render;
659
- if (typeof render !== "object" || render === null) return {};
660
- const triangles = (render as { triangles?: unknown }).triangles;
661
- const drawCalls = rendererDrawCallCount(raw);
662
- return {
663
- ...(drawCalls === undefined ? {} : { drawCalls }),
664
- ...(typeof triangles === "number" && Number.isFinite(triangles) && triangles >= 0
665
- ? { triangles }
666
- : {}),
667
- };
668
- }
669
-
670
- function resetRendererPerformanceMetrics(raw: unknown): void {
671
- if (typeof raw !== "object" || raw === null) return;
672
- const info = (raw as { info?: unknown }).info;
673
- if (typeof info !== "object" || info === null) return;
674
- const reset = (info as { reset?: unknown }).reset;
675
- if (typeof reset === "function") reset.call(info);
676
- }
677
-
678
- /**
679
- * One frame's two render calls, combined.
680
- *
681
- * The two renderers' `info` do not mean the same thing, and the old sum only ever held for one of
682
- * them. `WebGLRenderer` ends every `render()` with `info.reset()`, so the world sample and the
683
- * overlay sample are disjoint and add up. WebGPU never resets: the engine owns the
684
- * requestAnimationFrame loop, so it calls `info.reset()` itself once per frame before the world
685
- * draw (see the render block), which leaves the overlay sample *cumulative* — world plus overlay.
686
- * Adding it to the world sample reported every world draw twice, and the packed racing scenario
687
- * read 358 draw calls against a 330 ceiling on a frame that submits far fewer.
688
- *
689
- * The world pass split belongs to the world call in both renderers and rides the same sample, so
690
- * it is carried across rather than summed — a summed split attributes the world's shadow and
691
- * reflection passes to the overlay too.
692
- */
693
- function combineRenderPerformanceMetrics(
694
- kind: RendererKind,
695
- world: IRenderPerformanceMetrics | undefined,
696
- overlay: IRenderPerformanceMetrics,
697
- ): IRenderPerformanceMetrics {
698
- const passes = world?.passes;
699
- if (kind === "webgpu") {
700
- return passes === undefined ? overlay : { ...overlay, passes };
701
- }
702
- if (world === undefined) return overlay;
703
- return {
704
- ...(world.drawCalls === undefined || overlay.drawCalls === undefined
705
- ? {}
706
- : { drawCalls: world.drawCalls + overlay.drawCalls }),
707
- ...(world.triangles === undefined || overlay.triangles === undefined
708
- ? {}
709
- : { triangles: world.triangles + overlay.triangles }),
710
- ...(passes === undefined ? {} : { passes }),
711
- };
712
- }
713
-
714
- function createCamera(config: CameraConfig | undefined): Camera {
715
- if (config === undefined) return new PerspectiveCamera(60, 1, 0.1, 2_000);
716
- validateCameraConfig(config);
717
- const near = config.near ?? 0.1;
718
- const far = config.far ?? 2_000;
719
- if (config.projection === "perspective")
720
- return new PerspectiveCamera(config.fov ?? 60, 1, near, far);
721
- const size = config.size;
722
- return new OrthographicCamera(-size, size, size, -size, near, far);
723
- }
724
-
725
391
  class GameImpl<TState extends Record<string, unknown>, TPhysics>
726
392
  implements IGame<TState, TPhysics>
727
393
  {
@@ -771,7 +437,6 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
771
437
  #input: InputMap | undefined;
772
438
  #state: GameStore<TState>;
773
439
  #initialState: TState;
774
- #loop: FixedStepLoop | undefined;
775
440
  #interpolation: PhysicsInterpolation | undefined;
776
441
  #projection: SceneRenderProjection | undefined;
777
442
  #autoBatch: AutoBatch | undefined;
@@ -797,6 +462,10 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
797
462
  #activePlugins: Array<IGamePluginHooks<TState, TPhysics>> = [];
798
463
  #disposedPlugins = new Set<IGamePluginHooks<TState, TPhysics>>();
799
464
  #pendingStart: Promise<void> | undefined;
465
+ /** Releases the frame loop and its instruments, in the place `#teardown` always released them. */
466
+ #frameLoopDispose: PluginCleanup | undefined;
467
+ /** Releases what the startup phase started, in `#teardown`'s cleanups step. */
468
+ #startupDispose: PluginCleanup | undefined;
800
469
  #aborted = false;
801
470
  #sceneEntered = false;
802
471
  /** Startup readiness has begun its first-use gate; before that, it bakes the entered environment. */
@@ -978,7 +647,13 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
978
647
  const scene = new SceneType();
979
648
  this.#scene = scene;
980
649
  this.#sceneName = name;
981
- const loaded = scene.load(ctx);
650
+ let loaded: ReturnType<Scene<TState, TPhysics>["load"]>;
651
+ try {
652
+ loaded = scene.load(ctx);
653
+ } catch (error) {
654
+ reportSceneLoadFailure(error);
655
+ throw error;
656
+ }
982
657
  const transition =
983
658
  loaded === undefined
984
659
  ? this.#enterTransitionScene(scene, ctx)
@@ -1137,1575 +812,217 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1137
812
  }
1138
813
 
1139
814
  async #boot(): Promise<void> {
1140
- const debug = debugRequested();
1141
- const bootSceneName = this.#resumeScene ?? this.#config.start;
1142
- this.#resumeScene = undefined;
1143
- const SceneType = this.#config.scenes[bootSceneName];
1144
- if (SceneType === undefined) throw new Error(`Unknown start scene '${bootSceneName}'.`);
1145
- this.#connectUi();
1146
-
1147
- const renderer = await createRenderer({
1148
- ...this.#config.renderer,
1149
- canvas: this.#config.canvas ?? this.#config.renderer?.canvas,
1150
- preferWebGPU: this.#config.render?.preferWebGPU ?? this.#config.renderer?.preferWebGPU,
1151
- // One rule on both runtimes, decided 2026-09-01 after a HiDPI desktop browser upscaled a
1152
- // DPR-1 web buffer into visible pixelation: the device's real density, with an explicit
1153
- // `renderer.pixelRatio` winning over it (the old branch silently clobbered that value).
1154
- // Headless capture lanes run at DPR 1 and are unaffected; the resolution scaler composes
1155
- // on top, so a density the GPU cannot afford is trimmed by rungs, not by the developer.
1156
- pixelRatio: this.#config.renderer?.pixelRatio ?? globalThis.devicePixelRatio ?? 1,
1157
- antialias: resolveRendererAntialias(
1158
- this.#config.render,
1159
- this.#config.renderer?.antialias,
1160
- getPlatform().os,
1161
- ),
1162
- alphaAntialiasing: resolveRendererAlphaAntialiasing(
1163
- this.#config.render,
1164
- this.#config.renderer?.alphaAntialiasing,
1165
- getPlatform().os,
1166
- ),
1167
- ...resolveRendererScaleSetting(
1168
- this.#config.render,
1169
- this.#config.renderer?.resolutionScale,
1170
- getPlatform().os,
1171
- ),
1172
- source: this.#config.renderer?.source ?? this.#platform?.renderer,
1173
- });
1174
- if (this.#aborted) {
1175
- renderer.dispose();
1176
- return;
1177
- }
1178
- this.#renderer = renderer;
1179
- // Before anything draws for this startup, including the warm-up and every covered world frame: the owned
1180
- // engine keeps drawing, but presents nothing until a frame's shadow and exposure inputs are ready, so the
1181
- // player never sees the two unsettled pictures a cold post chain produced (measured 185 -> 124 -> 108 mean
1182
- // brightness). A renderer without the seam presents every frame exactly as before.
1183
- renderer.setPresentationHeld?.(true);
1184
- this.#cleanup.push(() => renderer.setPresentationHeld?.(false));
1185
- const canvas = renderer.domElement;
1186
- const platform = this.#platform;
1187
- const page = hostDocument();
1188
- if (platform !== undefined) platform.mountCanvas(canvas, this.#config.container);
1189
- else if (
1190
- this.#config.container !== undefined &&
1191
- canvas.parentElement !== this.#config.container
1192
- )
1193
- this.#config.container.append(canvas);
1194
- else if (canvas.parentElement === null && page !== undefined) page.body.append(canvas);
815
+ const startup = await startGameWorld(this.#bootGame());
816
+ if (startup === undefined) return;
817
+ this.#startupDispose = startup.dispose;
818
+ const frameLoop = startFrameLoop(startup);
819
+ this.#frameLoopDispose = frameLoop.dispose;
820
+ await startScenes(startup, frameLoop);
821
+ }
1195
822
 
1196
- const inputTarget =
1197
- this.#config.inputTarget ??
1198
- (platform === undefined ? (hostWindow() ?? canvas) : (platform.inputTarget ?? canvas));
1199
- this.#input = new InputMap(
1200
- this.#config.input,
1201
- inputTarget,
1202
- canvas,
1203
- platform?.input,
1204
- this.#config.contextMenu,
1205
- );
1206
- this.#state.start();
1207
- const threeScene = new ThreeScene();
1208
- if (debug && "__debugTelemetry" in threeScene)
1209
- (threeScene as ThreeScene & { __debugTelemetry: boolean }).__debugTelemetry = true;
1210
- const camera = createCamera(this.#config.camera);
1211
- const interpolation = new PhysicsInterpolation(this.#config.physicsInterpolation);
1212
- this.#interpolation = interpolation;
1213
- interpolation.track(camera);
1214
- const viewport = new Viewport({ camera, renderer: this.#renderer, source: platform?.viewport });
1215
- const canvasLayer = new CanvasLayer(viewport);
1216
- this.#viewport = viewport;
1217
- // The renderer goes to the asset loader so compiled KTX2 textures detect transcoding
1218
- // support against the real backend; a target that supports none fails right here.
1219
- const assets = createAssetLoader({ ...this.#config.assets, renderer: renderer.raw });
1220
- if (assets.compressedTextures !== undefined) await assets.compressedTextures.ready;
1221
- this.#cleanup.push(() => assets.dispose());
1222
- const entities = new Registry();
1223
- const random = createRandom(this.#config.seed);
1224
- const scheduler = new Scheduler();
1225
- const afterPhysicsPhase = createAfterPhysicsPhase();
1226
- const input = this.#input;
1227
- const picker = new ScenePicker({
1228
- camera,
1229
- // Input reports window-relative client coordinates; the picker's NDC math is
1230
- // canvas-relative. Subtract the canvas page offset like replay.ts does for recorded
1231
- // pointers, or every pick lands displaced by wherever the canvas sits in the layout.
1232
- pointer: () => {
1233
- const position = input.raw.pointer.position;
1234
- const rect = (
1235
- canvas as { getBoundingClientRect?: () => DOMRect }
1236
- ).getBoundingClientRect?.();
1237
- return rect === undefined
1238
- ? position
1239
- : new Vector2(position.x - rect.left, position.y - rect.top);
823
+ /**
824
+ * The boot's view of this game, for the two phases that live beside it.
825
+ *
826
+ * Every member is the private field of the same name, so a phase assigns and reads exactly
827
+ * what `#boot` did: the same resources, in the same order, with nothing in between.
828
+ */
829
+ #bootGame(): IGameBootGame<TState, TPhysics> {
830
+ return Object.defineProperties({} as IGameBootGame<TState, TPhysics>, {
831
+ // The boot's own calls, bound to this game.
832
+ connectUi: { value: (): IUiBridge => this.#connectUi() },
833
+ enterScene: {
834
+ value: (scene: Scene<TState, TPhysics>, ctx: ICtx<TState, TPhysics>): boolean =>
835
+ this.#enterScene(scene, ctx),
1240
836
  },
1241
- scene: threeScene,
1242
- viewport,
1243
- });
1244
- this.#picker = picker;
1245
- const pointerEvents = new PointerEvents3D({
1246
- screen: (position, target) => {
1247
- const rect = (
1248
- canvas as { getBoundingClientRect?: () => DOMRect }
1249
- ).getBoundingClientRect?.();
1250
- return rect === undefined
1251
- ? target.copy(position)
1252
- : target.set(position.x - rect.left, position.y - rect.top);
837
+ goto: {
838
+ value: (name: string, ctx: ICtx<TState, TPhysics>): Promise<void> => this.#goto(name, ctx),
1253
839
  },
1254
- });
1255
- this.#pointerEvents = pointerEvents;
1256
- const loopState: { current?: FixedStepLoop } = {};
1257
- // The engine owns the world-matrix walk, not three's renderer: on by default it does not recurse
1258
- // into a hidden subtree, and `renderer.matrixWorld: "all"` restores the every-node walk. The
1259
- // authored scene is marked once, here, so three never walks it a second time; the mirror scene
1260
- // is marked at the render site, where whichever root is drawn this frame is known.
1261
- const matrixWorldPass = new MatrixWorldPass({
1262
- mode: resolveMatrixWorldMode(this.#config.render),
1263
- });
1264
- this.#matrixWorld = matrixWorldPass;
1265
- threeScene.matrixWorldAutoUpdate = false;
1266
- // Built before the context because `ctx.startup` reads it: a game asks what the framework's
1267
- // startup is doing, and the answer is this pass.
1268
- // The owned renderer retains its own velocity history; JS snapshots serve Three's accessors.
1269
- const engineInfo = (renderer.raw as { info?: object }).info;
1270
- const ownedEngine = engineInfo !== undefined && "engine" in engineInfo;
1271
- const projection = new SceneRenderProjection(threeScene, {
1272
- // The game's `renderer.projection` value verbatim: `false` declines the mirror, an object
1273
- // names the material check beside accepting it, and the projection owns both readings.
1274
- projection: this.#config.render?.projection,
1275
- velocity: () => !ownedEngine && (renderer.renderChainUsesPerObjectVelocity?.() ?? false),
1276
- matrixWorld: matrixWorldPass,
1277
- });
1278
- this.#projection = projection;
1279
- const autoBatchConfig = this.#config.autoBatch;
1280
- const autoBatch = new AutoBatch(threeScene, {
1281
- enabled: autoBatchConfig !== false,
1282
- entities,
1283
- ...(typeof autoBatchConfig === "object" ? autoBatchConfig : {}),
1284
- report: (line) =>
1285
- (this.#config.frameBudget === false ? undefined : this.#config.frameBudget?.report)?.(
1286
- line,
1287
- ) ?? console.info(line),
1288
- });
1289
- this.#autoBatch = autoBatch;
1290
- // Do not submit what the render camera cannot resolve. On by default at a conservative 0.5 px,
1291
- // and measured whether or not the game narrows or declines it. Its decision is per camera, so
1292
- // a shadow caster and anything attached to the camera are never dropped on the main view alone.
1293
- const cameraCull = new RenderCameraCull({
1294
- minimumPixels: this.#config.render?.minimumProjectedPixels,
1295
- });
1296
- this.#cameraCull = cameraCull;
1297
- let projectionSettled = false;
1298
- let offscreenBytes: IStartupOffscreenBytes | undefined;
1299
- /**
1300
- * Progress is a high-water mark over the measured load state, never a value that can fall.
1301
- *
1302
- * The ratio's denominator grows: a request registered after an earlier one settled shrinks
1303
- * `settled / requested`, and the file-count and byte branches can disagree across the switch
1304
- * the first weighed manifest entry triggers. Both make the bar jump backwards, which a player
1305
- * reads as the load restarting. Measured: a second texture requested after the first settled
1306
- * took the reported value from 0.7 to 0.35.
1307
- */
1308
- let reportedProgress = 0;
1309
- /** What the load state says right now. This may fall; `startup.progress` is what never does. */
1310
- const measuredProgress = (): number => {
1311
- if (projectionSettled) return 1;
1312
- // A registered hold owns the last tenth. Without this the bar sat at 0.9 for the whole
1313
- // of the game's own tier and then jumped, which is the reading a player calls frozen.
1314
- if (startupReadiness.frameworkReady) {
1315
- const held = startupReadiness.holdReport.length;
1316
- if (held === 0) return 0.9;
1317
- const settled = held - startupReadiness.pendingHolds.length;
1318
- return 0.9 + 0.1 * (settled / held);
1319
- }
1320
- if (startupReadiness.compileSettled) return 0.9;
1321
- if (timeline.enteredMs !== undefined) return 0.8;
1322
- const { requested, requestedBytes, settled, settledBytes } = assets.progress;
1323
- // Bytes when the manifest knows them, files when it does not. A file count spends the
1324
- // same travel on a 4 KB icon as on a 710 MB model, which is how a bar reaches 92% and
1325
- // then stands still for the rest of the download.
1326
- if (requestedBytes > 0) return 0.7 * Math.min(1, settledBytes / requestedBytes);
1327
- return requested === 0 ? 0 : 0.7 * Math.min(1, settled / requested);
1328
- };
1329
- let worldRendered = false;
1330
- let loadingFramePresented = false;
1331
- let stateHandOffFrames = 0;
1332
- let markProjectionSettled: () => void = () => undefined;
1333
- const projectionReady = new Promise<void>((resolve) => {
1334
- markProjectionSettled = resolve;
1335
- });
1336
- const startupReadiness = new StartupReadiness({
1337
- /**
1338
- * The second warm-up: everything a game attached while it held startup.
1339
- *
1340
- * The first pass runs at framework readiness, which for a streaming game is before most of
1341
- * the world exists. Without this, `hold()` buys a complete *picture* and leaves a scene whose
1342
- * every material still compiles on first sight — which is worse than the pop-in it replaced,
1343
- * because a compile stall lands while the player is walking rather than while they are
1344
- * waiting. Measured on a 46,190-instance forest: 8 pipelines warmed, then 28 main-thread
1345
- * tasks over 40 ms in a minute of play, the worst 267 ms.
1346
- *
1347
- * A third of the compile budget, not the whole of it, because this one is spent with the
1348
- * player already waiting behind a curtain that has been up for seconds. Whatever does not
1349
- * fit still compiles lazily — the same as before — so the ceiling on the wait is bounded and
1350
- * the worst case is the behaviour we already had.
1351
- */
1352
- afterHolds: async () => {
1353
- await warmUp("TN_STARTUP_WARMUP_HELD", Math.round(STARTUP_COMPILE_BUDGET_MS / 3), false);
840
+ postUiStartup: { value: (): void => this.#postUiStartup() },
841
+ teardown: { value: (ctx?: ICtx<TState, TPhysics>): void => this.#teardown(ctx) },
842
+ warmUpConfiguredExplicitly: { value: (): boolean => this.#warmUpConfiguredExplicitly() },
843
+ warmUpOptions: { value: (): IWarmUpOptions => this.#warmUpOptions() },
844
+ // Read through the field every time: a phase runs while `#boot` is still assigning it.
845
+ cleanup: { get: () => this.#cleanup },
846
+ computeDriven: { get: () => this.#computeDriven },
847
+ config: { get: () => this.#config },
848
+ platform: { get: () => this.#platform },
849
+ state: { get: () => this.#state },
850
+ beforeRenderCallbacks: { get: () => this.#beforeRenderCallbacks },
851
+ activePlugins: { get: () => this.#activePlugins },
852
+ uiBridge: { get: () => this.#uiBridge },
853
+ sceneFrame: { get: () => this.#sceneFrame },
854
+ sceneEntered: { get: () => this.#sceneEntered },
855
+ sceneGeneration: { get: () => this.#sceneGeneration },
856
+ pendingSceneEnter: { get: () => this.#pendingSceneEnter },
857
+ paused: { get: () => this.#paused },
858
+ aborted: { get: () => this.#aborted },
859
+ uiReady: { get: () => this.#uiReady },
860
+ // Assigned by a phase, exactly as `#boot` assigned the field.
861
+ renderer: {
862
+ get: () => this.#renderer,
863
+ set: (value) => {
864
+ this.#renderer = value;
865
+ },
1354
866
  },
1355
- /**
1356
- * The renderer's own answer, which no timer may stand in for: a world frame whose shadow inputs are
1357
- * initialized and whose meter has measured within 3% of its target. On the owned engine the hidden world
1358
- * keeps drawing behind the cover, so this becomes true on its own; a renderer without the seam answers
1359
- * true, and its launch is exactly what it was. The answer names the input it is short of, so a launch that
1360
- * reached its deadline (`STARTUP_IMAGE_TIMEOUT_MS`) reports which one never arrived.
1361
- */
1362
- imageReady: (): boolean | IStartupImageState => {
1363
- // A cover the game asked not to draw the world behind has no frame to wait for, and waiting would
1364
- // hold it open forever; every other game keeps drawing and reaches this on its own.
1365
- if (
1366
- canvasLayer.opaque &&
1367
- !canvasLayer.renderWorldDuringStartup &&
1368
- !canvasLayer.keepWorldRendering
1369
- )
1370
- return true;
1371
- return renderer.firstWorldFrame?.() ?? true;
867
+ scene: {
868
+ get: () => this.#scene,
869
+ set: (value) => {
870
+ this.#scene = value;
871
+ },
1372
872
  },
1373
- });
1374
- // Startup readiness does not wait on `ui-ready`, and cannot. The intent proves the page's
1375
- // script ran, not that a pixel reached the screen, so waiting on it never closed the race it
1376
- // was added for — it only made the losing side lose later, after up to 45 s of held frames.
1377
- // The race no longer exists: the native UI is now composited into the game's own frame, so the
1378
- // cover and the world share one swapchain and there is no second surface left to arrive late.
1379
- // The held loop starts before an explicit warm-up so the loading surface can animate. A native
1380
- // frame may therefore arrive while that pass is still awaiting a compile promise; keep first-use
1381
- // rendering and compute behind the same held boundary until the explicit pass has settled.
1382
- let explicitWarmUpSettled = !this.#warmUpConfiguredExplicitly();
1383
- // A web UI is the loading surface on native and on the web. Its bridge must be both attached
1384
- // and announced ready: an attached but unrendered web view is not a cover the player can see.
1385
- // Keep this predicate tied to an actually attached and rendered web UI. The render path still
1386
- // lets a settled world render behind either kind of cover; only the unresolved first-use work
1387
- // is held, so a persistent HUD cannot stop the world pass after loading.
1388
- const startupCoverActive = (): boolean =>
1389
- !startupReadiness.ready &&
1390
- (canvasLayer.opaque || (this.#uiReady && this.#uiBridge?.hasPeer() === true));
1391
- // A draw the warm-up makes in a timer task is presented by the browser on its own, without the
1392
- // frame loop's overlay: a Wasm engine still baking the environment presents black, and the
1393
- // cover flickers against it. Paint the cover again in the same task.
1394
- const repaintCover = (): void => {
1395
- if (canvasLayer.opaque && canvasLayer.scene.children.length > 0)
1396
- renderer.renderOverlay(canvasLayer.scene, canvasLayer.camera);
1397
- };
1398
- const timeline: { -readonly [K in keyof IStartupTimeline]: IStartupTimeline[K] } = {};
1399
- let warmUpStatus: IStartupStatus["warmup"];
1400
- const now = (): number => globalThis.performance?.now() ?? Date.now();
1401
- /**
1402
- * A launch that stops making progress says so, on the page, instead of leaving a loading
1403
- * screen up forever. Measured on `midway-open-pacific`: a 104 s launch and then a lost GPU
1404
- * device, with the only account of either on a terminal the player does not have.
1405
- */
1406
- const stopStallWatch = watchStartupStall({
1407
- pending: () => [
1408
- ...assets.progress.pending,
1409
- ...startupReadiness.pendingHolds,
1410
- ...startupReadiness.pendingImage,
1411
- ],
1412
- progress: () => this.#ctx?.startup.progress ?? 0,
1413
- workProgress: () => assets.progress.settled + startupReadiness.workProgress,
1414
- stallMs: STARTUP_STALL_MS,
1415
- });
1416
- this.#cleanup.push(stopStallWatch);
1417
- watchDeviceLoss(
1418
- (
1419
- renderer.raw as {
1420
- backend?: { device?: { lost?: Promise<{ reason?: string; message?: string }> } };
1421
- }
1422
- ).backend?.device,
1423
- () => this.#aborted || this.#renderer !== renderer,
1424
- );
1425
- // Stamped when the FRAMEWORK is done, which is before `whenReady()` whenever the game has
1426
- // registered a `startup.hold()`. Two stamps, because one number cannot be both "what the
1427
- // framework cost" and "what the player waited for", and collapsing them is how a valley that
1428
- // took 8.8 s to appear reported 1.5 s.
1429
- void startupReadiness.whenFrameworkReady().then(() => {
1430
- timeline.compileSettledMs ??= now();
1431
- timeline.frameworkReadyMs ??= now();
1432
- });
1433
- void startupReadiness.whenReady().then(() => {
1434
- stopStallWatch();
1435
- // A renderer without first-use compilation settles without running the compile closure
1436
- // below, so the settle stamp is guaranteed here at the latest.
1437
- timeline.compileSettledMs ??= now();
1438
- timeline.frameworkReadyMs ??= now();
1439
- timeline.readyMs ??= now();
1440
- projectionSettled = true;
1441
- // The first world frame the player sees is the next one this renderer draws, so the hold comes off
1442
- // here and only here: every exit before it (abort, dispose, a failed launch) leaves the cover up.
1443
- renderer.setPresentationHeld?.(false);
1444
- // What a game does on `whenReady()` (lift its cover, show its HUD) reaches the page with the
1445
- // world frame, not before it: see `STARTUP_HANDOFF_FRAMES`.
1446
- stateHandOffFrames = STARTUP_HANDOFF_FRAMES;
1447
- markProjectionSettled();
1448
- // The reveal is the first moment the network is free and the player is playing: fill the
1449
- // rest of the release at idle priority from here, never before.
1450
- void assets.startBackgroundFill();
1451
- // A host capturing a frame has no other way to know the world is on screen. Counting frames
1452
- // cannot express it: on a software rasteriser the gate resolves on its bounded window rather
1453
- // than on five in-budget frames, so a fast 300-frame run finishes before the world is shown
1454
- // and captures the loading state. The native screenshot path waits on this flag.
1455
- (globalThis as Record<string, unknown>)[STARTUP_READY_GLOBAL] = true;
1456
- // Measurement only: what the reveal waited for that the spawn camera does not show. A throw
1457
- // here must cost the report, never the game that is already ready.
1458
- try {
1459
- offscreenBytes = measureStartupOffscreenBytes(assets.resolved, threeScene, camera);
1460
- if (offscreenBytes.offscreenBytes > 0)
1461
- (offscreenBytes.warn ? console.warn : console.log)(
1462
- `${STARTUP_OFFSCREEN_BYTES_MARKER}:${JSON.stringify(offscreenBytes)}`,
1463
- );
1464
- } catch (error) {
1465
- console.warn(
1466
- `${STARTUP_OFFSCREEN_BYTES_MARKER}_FAILED: ${error instanceof Error ? error.message : String(error)}`,
1467
- );
1468
- }
1469
- // Again at ready: a world that streams its foliage in under `startup.hold` has none at entry.
1470
- const unlit = unlitFoliageWarning(threeScene);
1471
- if (unlit !== undefined)
1472
- console.warn(`${formatUnlitFoliageWarning(unlit)} ${UNLIT_FOLIAGE_FIX}`);
1473
- });
1474
- const warmUp = async (marker: string, budgetMs: number, stamp: boolean): Promise<void> => {
1475
- if (this.#aborted || this.#renderer === undefined) return;
1476
- let report: IWarmUpReport | undefined;
1477
- let failure: string | undefined;
1478
- try {
1479
- projection.reconcile();
1480
- // The frame loop's own walk, run here too because the warm-up draws before that loop does.
1481
- // Three is told not to walk the scene (`matrixWorldAutoUpdate = false`), and a declined
1482
- // projection returns from `reconcile()` without walking it, so without this the warm render
1483
- // compiles every pipeline against stale world matrices and the real frames then build the
1484
- // rest synchronously -- tens of seconds each on a software adapter, which loses the device.
1485
- this.#matrixWorld?.apply(projection.root);
1486
- report = await warmUpScene(renderer, projection.root, camera, {
1487
- afterCoveredDraw: repaintCover,
1488
- budgetMs,
1489
- computeNodes: this.#computeDriven.warmupNodes,
1490
- renderPasses: this.#warmUpOptions().renderPasses,
1491
- includeHidden: this.#warmUpOptions().includeHidden,
1492
- });
1493
- } catch (error) {
1494
- failure = error instanceof Error ? error.message : String(error);
1495
- }
1496
- // With an explicit warm-up, this held pass is only the first half of startup. Stamp after
1497
- // the explicit pass so its own pipelines remain inside the settled boundary; without one,
1498
- // this is the only warm-up completion.
1499
- if (stamp || !this.#warmUpConfiguredExplicitly()) renderer.warmUpSettled?.();
1500
- warmUpStatus =
1501
- report === undefined
1502
- ? { status: "unavailable" }
1503
- : {
1504
- attempted: report.attempted,
1505
- candidates: report.candidates,
1506
- observed: report.observed,
1507
- status: report.observed.status,
1508
- };
1509
- if (stamp) timeline.compileSettledMs ??= now();
1510
- console.log(
1511
- `${marker}:${JSON.stringify(
1512
- report === undefined
1513
- ? { failed: failure ?? "unknown" }
1514
- : {
1515
- compiled: report.compiled,
1516
- pipelines: report.pipelines,
1517
- candidates: report.candidates,
1518
- attempted: report.attempted,
1519
- observed: report.observed,
1520
- slices: report.slices,
1521
- elapsedMs: Math.round(report.elapsedMs),
1522
- unsupported: report.unsupported,
1523
- abandoned: report.abandoned,
1524
- timedOut: report.timedOut,
1525
- computeCompiled: report.computeCompiled,
1526
- computeAbandoned: report.computeAbandoned,
1527
- computeUnsupported: report.computeUnsupported,
1528
- computeTimedOut: report.computeTimedOut,
1529
- passes: report.passes,
1530
- passPipelines: report.passPipelines,
1531
- cullingForced: report.cullingForced,
1532
- visibilityForced: report.visibilityForced,
1533
- cache: report.cache,
1534
- },
1535
- )}`,
1536
- );
1537
- };
1538
- const startupCompile: StartupCompile = async (): Promise<void> => {
1539
- await warmUp("TN_STARTUP_WARMUP", STARTUP_COMPILE_BUDGET_MS, true);
1540
- };
1541
- // A game with no cover skips the compile above, yet readiness still waits for the scene's
1542
- // environment: the owned engine skips every frame while it bakes, and a skipped frame is fast,
1543
- // so the frame window would pass before the world drew once. (An explicit warm-up bakes it.)
1544
- const startupEnvironment = (): StartupCompile | undefined =>
1545
- sceneNeedsEnvironmentPreparation(renderer, projection.root) ? bakeEnvironment : undefined;
1546
- const bakeEnvironment: StartupCompile = async (): Promise<void> => {
1547
- if (this.#aborted) return;
1548
- await prepareSceneEnvironment(
1549
- renderer,
1550
- projection.root,
1551
- camera,
1552
- now() + STARTUP_COMPILE_BUDGET_MS,
1553
- repaintCover,
1554
- );
1555
- };
1556
- // The GPU-selected main-pass tally, registered by whichever streamed world is added to the
1557
- // scene. The frame budget reads it once per window; a world with no sample reports undefined, so
1558
- // the window carries nothing rather than a zero no frame selected.
1559
- let gpuTallyProvider:
1560
- | (() => { readonly instances: number; readonly triangles: number } | undefined)
1561
- | undefined;
1562
- const ctx: ICtx<TState, TPhysics> = {
1563
- get frameTime() {
1564
- return loopState.current?.frameTime ?? 0;
873
+ sceneName: {
874
+ get: () => this.#sceneName,
875
+ set: (value) => {
876
+ this.#sceneName = value;
877
+ },
1565
878
  },
1566
- get alpha() {
1567
- return loopState.current?.alpha ?? 0;
879
+ ctx: {
880
+ get: () => this.#ctx,
881
+ set: (value) => {
882
+ this.#ctx = value;
883
+ },
1568
884
  },
1569
- interpolate: (object) => interpolation.track(object),
1570
- resetInterpolation: (object) => interpolation.reset(object),
1571
- add: (object) => {
1572
- // Narrowed through a plain `Object3D` rather than the type parameter: a type guard applied
1573
- // to `T` yields `T & IComputeDriven`, which TypeScript will not carry to the registry's
1574
- // `Object3D & IComputeDriven` without a cast. The local keeps the guard honest and the
1575
- // return keeps the caller's own type, so a game never casts back what it just built.
1576
- const node: Object3D = object;
1577
- threeScene.add(node);
1578
- if (typeof (node as { aerialPerspective?: unknown }).aerialPerspective === "function") {
1579
- this.#hasDepthCoupledOutput = true;
1580
- }
1581
- if (isComputeDriven(node)) {
1582
- const activeRenderer = this.#renderer;
1583
- if (activeRenderer === undefined)
1584
- throw new Error("Cannot add a compute-driven object before the game starts.");
1585
- this.#computeDriven.add(node, activeRenderer);
1586
- }
1587
- // A streamed world that can say what the GPU selected, so `TN_FRAME_BUDGET` reports the
1588
- // GPU-selected main-pass count beside its pass record. The tally is asked for only when the
1589
- // frame budget is on: with it off and no validation, the world adds no readback at all.
1590
- const tallySource = node as {
1591
- enableGpuSceneTally?: () => void;
1592
- gpuSceneTally?: () =>
1593
- | { readonly instances: number; readonly triangles: number }
1594
- | undefined;
1595
- };
1596
- if (typeof tallySource.gpuSceneTally === "function") {
1597
- gpuTallyProvider = tallySource.gpuSceneTally.bind(node);
1598
- if (this.#config.frameBudget !== false) tallySource.enableGpuSceneTally?.();
1599
- }
1600
- return object;
885
+ input: {
886
+ get: () => this.#input,
887
+ set: (value) => {
888
+ this.#input = value;
889
+ },
1601
890
  },
1602
- assets,
1603
- after: (delay, callback) => scheduler.after(delay, callback),
1604
- afterPhysics: (callback) => afterPhysicsPhase.register(callback),
1605
- beforeRender: (callback) => {
1606
- if (typeof callback !== "function")
1607
- throw new Error("beforeRender requires a callback function.");
1608
- this.#beforeRenderCallbacks.add(callback);
1609
- return () => this.#beforeRenderCallbacks.delete(callback);
891
+ viewport: {
892
+ get: () => this.#viewport,
893
+ set: (value) => {
894
+ this.#viewport = value;
895
+ },
1610
896
  },
1611
- camera,
1612
- canvasLayer,
1613
- entities,
1614
- every: (callback) => scheduler.every(callback),
1615
- get fps() {
1616
- return loopState.current?.fps ?? 0;
897
+ picker: {
898
+ get: () => this.#picker,
899
+ set: (value) => {
900
+ this.#picker = value;
901
+ },
1617
902
  },
1618
- goto: (name) => this.#goto(name, ctx),
1619
- input: this.#input,
1620
- pointer: pointerEvents,
1621
- physics: undefined as TPhysics,
1622
- random,
1623
- raycast: (options) => picker.raycast(options),
1624
- raycastAll: (options, target) => picker.raycastAll(options, target),
1625
- startup: {
1626
- get warmup() {
1627
- return warmUpStatus;
903
+ pointerEvents: {
904
+ get: () => this.#pointerEvents,
905
+ set: (value) => {
906
+ this.#pointerEvents = value;
1628
907
  },
1629
- get phase() {
1630
- // The projection is reconciled before the first world draw, but readiness is not reported
1631
- // until first-use work and a sustained in-budget window have completed. An opaque loading
1632
- // layer cannot turn `whenReady()` into a first-present signal while work is still waiting
1633
- // behind it.
1634
- if (projectionSettled) return "ready" as const;
1635
- return "collapsing" as const;
908
+ },
909
+ matrixWorld: {
910
+ get: () => this.#matrixWorld,
911
+ set: (value) => {
912
+ this.#matrixWorld = value;
1636
913
  },
1637
- // True once first-use compilation has settled, which is earlier than `phase === "ready"`
1638
- // and is the signal a game wants when it must not act during the launch. `phase` cannot
1639
- // express it: it is binary, and readiness additionally requires a sustained in-budget
1640
- // frame window that a software rasteriser can only ever let expire. A game gated on
1641
- // `phase` alone therefore does nothing for ~25s on such a lane — measured as a chase route
1642
- // of length 0.000000 where 6 was required, because the scenario ended first.
1643
- get compileSettled() {
1644
- return startupReadiness.compileSettled;
914
+ },
915
+ projection: {
916
+ get: () => this.#projection,
917
+ set: (value) => {
918
+ this.#projection = value;
1645
919
  },
1646
- // Honest and monotonic: the asset ratio carries the first 70% while the start scene
1647
- // loads, entering the world is 80%, compile settling 90%, and only readiness is 1.
1648
- // Monotonicity is enforced rather than assumed — see the high-water mark above.
1649
- get progress() {
1650
- reportedProgress = Math.max(reportedProgress, measuredProgress());
1651
- return reportedProgress;
920
+ },
921
+ autoBatch: {
922
+ get: () => this.#autoBatch,
923
+ set: (value) => {
924
+ this.#autoBatch = value;
1652
925
  },
1653
- hold: (label, work, budgetMs, progress) => {
1654
- startupReadiness.hold(label, work, budgetMs, progress);
926
+ },
927
+ cameraCull: {
928
+ get: () => this.#cameraCull,
929
+ set: (value) => {
930
+ this.#cameraCull = value;
1655
931
  },
1656
- get timeline() {
1657
- return { ...timeline };
932
+ },
933
+ entities: {
934
+ get: () => this.#entities,
935
+ set: (value) => {
936
+ this.#entities = value;
1658
937
  },
1659
- whenReady: () => projectionReady,
1660
- whenFrameworkReady: () => startupReadiness.whenFrameworkReady(),
1661
938
  },
1662
- renderer: this.#renderer,
1663
- viewport,
1664
- scene: threeScene,
1665
- state: this.#state,
1666
- tween: (target, properties, duration, options) =>
1667
- scheduler.tween(target, properties, duration, options),
1668
- };
1669
- this.#ctx = ctx;
1670
- this.#entities = entities;
1671
- this.#scheduler = scheduler;
1672
- this.#afterPhysicsPhase = afterPhysicsPhase;
1673
- const devToolsHost = platform === undefined ? hostWindow() : platform.devToolsHost;
1674
- this.#cleanup.push(
1675
- installDevTools(
1676
- entities,
1677
- devToolsHost as DevToolsHost | undefined,
1678
- () => this.#geometryCapture,
1679
- ),
1680
- );
1681
- this.#scene = new SceneType();
1682
- this.#sceneName = bootSceneName;
1683
- // The scaler exists whenever the scale is automatic, which now includes a game that said
1684
- // nothing about it. A pinned number leaves this undefined, which is what makes "pinned" a
1685
- // guarantee rather than a preference the loop may overrule. `maxFps: 0` removes the ceiling,
1686
- // and a scaler with no budget is not a scaler with a loose one, so an uncapped game simply
1687
- // does not get adaptive scaling.
1688
- const initialTarget = resolveTargetFps(this.#config, getPlatform());
1689
- let heldTargetFps = initialTarget.targetFps;
1690
- // Frame-share budgets elsewhere (the world's adaptive LOD) read the target, not the last frame.
1691
- renderer.noteTargetFps?.(initialTarget.targetFps);
1692
- const automaticScale = renderer.surface().scaleSource === "auto";
1693
- const createScaler = () =>
1694
- automaticScale && heldTargetFps > 0
1695
- ? new ResolutionScaler({
1696
- // Phones keep the device ladder; a desktop stops before its bottom, where a picture
1697
- // with nothing reconstructing it stops being a faster frame and becomes a blur.
1698
- minScale: resolvePlatformResolutionFloor(getPlatform().os),
1699
- // The adapter family picks the first rung; the first eligible window still decides.
1700
- start:
1701
- renderer.temporalUpscaleStartScale?.() ??
1702
- (renderer.gpuClass === undefined
1703
- ? undefined
1704
- : RESOLUTION_SCALER.startScaleByGpuClass[renderer.gpuClass.class]),
1705
- targetFps: heldTargetFps,
1706
- temporalUpscale: () => renderer.temporalUpscale?.() === true,
1707
- })
1708
- : undefined;
1709
- let scaler = createScaler();
1710
- let temporalStartApplied = renderer.temporalUpscale?.() === true;
1711
- // A class that starts below the ceiling must draw there from the first frame; the scaler only
1712
- // reports a scale, and nothing else would apply it until a window steps.
1713
- if (scaler !== undefined && scaler.scale !== 1)
1714
- renderer.setResolutionScale(scaler.scale, scaler.scaleSource);
1715
- // The panel's own rate, once a window of presented frames can say it. The native host's
1716
- // present counter is the only series there that counts displays rather than loop iterations;
1717
- // on the web one rAF callback is one vblank, so the median presented interval is the period.
1718
- let measuredRefreshHz: number | undefined;
1719
- // The world pass's own draw-call count, kept from the last frame of the window so the
1720
- // projection line can report what the renderer was handed beside what the plan predicted.
1721
- // A plan and a measurement that disagree is the finding; one number pretending to be both
1722
- // is how an optimizer reports a win it did not deliver.
1723
- let lastWorldDrawCalls: number | undefined;
1724
- // Completion on the last frame must not make an otherwise compiling window look clean.
1725
- let compilingInWindow = false;
1726
- let lastCompileCount = renderer.compileCount;
1727
- const observeCompilation = (): void => {
1728
- const count = renderer.compileCount;
1729
- compilingInWindow ||= renderer.compiling === true || count !== lastCompileCount;
1730
- lastCompileCount = count;
1731
- };
1732
- // Built here rather than inside the loop so `frameBudget: false` is a single decision with a
1733
- // single owner, and so the render phases below feed the same instrument the loop feeds.
1734
- const frameBudget =
1735
- this.#config.frameBudget === false
1736
- ? undefined
1737
- : new FrameBudget({
1738
- ...this.#config.frameBudget,
1739
- simulation: {
1740
- tick: () => gameLoop.tick(),
1741
- get step() {
1742
- return gameLoop.step;
1743
- },
1744
- },
1745
- // The scaler reads the same windows the marker reports, so what it acted on and what
1746
- // the record shows are the same measurement rather than two sampling paths.
1747
- onWindow: (reported) => {
1748
- const sink =
1749
- this.#config.frameBudget === false ? undefined : this.#config.frameBudget?.report;
1750
- const reportInfo = sink ?? console.info;
1751
- const reportWarning = sink ?? console.warn;
1752
- observeCompilation();
1753
- const compileObserved = compilingInWindow;
1754
- compilingInWindow = false;
1755
- // The display's own rate, read once per window from the cadence the loop already
1756
- // measured: the host's present counter where there is one, else the median presented
1757
- // interval, which on the web is the vblank period because rAF is the presentation.
1758
- measuredRefreshHz =
1759
- reported.presentedFps ??
1760
- (reported.presented.p50 > 0 ? 1_000 / reported.presented.p50 : undefined);
1761
- const target = resolveTargetFps(this.#config, getPlatform(), measuredRefreshHz);
1762
- renderer.noteTargetFps?.(target.targetFps);
1763
- if (
1764
- scaler !== undefined &&
1765
- target.targetFps > 0 &&
1766
- target.targetFps !== heldTargetFps
1767
- ) {
1768
- heldTargetFps = target.targetFps;
1769
- scaler.retarget(heldTargetFps);
1770
- }
1771
- renderer.observeRenderChainBudget?.(reported);
1772
- this.#computeDriven.observeBudget(reported);
1773
- const projection = this.#projection;
1774
- // Printed every window, projecting or declined. `TN_RENDER_PROJECTION` says once
1775
- // whether the optimizer engaged; this says, repeatedly, what it is still leaving on
1776
- // the exact lane and whether the renderer agrees with the plan.
1777
- if (projection !== undefined) {
1778
- reportInfo(
1779
- formatProjectionWindow(
1780
- projection.windowReport,
1781
- reported.window,
1782
- lastWorldDrawCalls,
1783
- this.#cameraCull?.report,
1784
- this.#matrixWorld?.report,
1785
- ),
1786
- );
1787
- }
1788
- if (this.#config.frameBudget !== false)
1789
- this.#config.frameBudget?.onWindow?.(reported);
1790
- // The span tree closes on the same window, so the two lines in a log describe the
1791
- // same frames and a reader can subtract one from the other without a second clock.
1792
- const spanWindow = spans?.window();
1793
- if (spanWindow !== undefined) reportInfo(formatSpansWindow(spanWindow));
1794
- // The scene-shape verdict, on by default in a debug launch, from the census the
1795
- // frame already took. An agent building a scene of the wrong shape reads it in the
1796
- // log before a human ever plays the game and calls it slow.
1797
- const staticCensus = staticTransformCensus();
1798
- if (staticCensus.roots > 0)
1799
- reportInfo(`${STATIC_TRANSFORM_MARKER}:${JSON.stringify(staticCensus)}`);
1800
- const validation = renderListValidator?.report();
1801
- if (validation !== undefined) reportInfo(formatValidationReport(validation));
1802
- const warning = devMetricsEnabled
1803
- ? sceneWarning(
1804
- reported,
1805
- describeSceneShape(reported, this.#cameraCull?.report),
1806
- target.targetFps,
1807
- renderer.gpuClass?.class,
1808
- )
1809
- : undefined;
1810
- if (warning !== undefined) reportWarning(formatSceneWarning(warning));
1811
- // The same sentence goes to the UI on a dev launch, so a human watching the window
1812
- // and an agent reading the log are told the same thing at the same time. No frame
1813
- // rate rides it: the loop's own rAF rate reads throttled under a compositor or a
1814
- // virtual display, so a number drawn from it lies in exactly the sessions where
1815
- // somebody is trying to measure.
1816
- if (
1817
- devMetricsEnabled &&
1818
- warning !== undefined &&
1819
- this.#uiBridge?.hasPeer() === true
1820
- ) {
1821
- const verdict = describeSceneWarning(warning);
1822
- if (verdict !== postedVerdict) {
1823
- postedVerdict = verdict;
1824
- this.#uiBridge.post({ type: UI_DEV_METRICS_MESSAGE, sceneWarning: verdict });
1825
- }
1826
- }
1827
- if (scaler === undefined) return;
1828
- // **Not while the world is still arriving.** The scaler judges the game by closed
1829
- // frame-budget windows, and the windows that close during a launch are not the game:
1830
- // they are asset decode, scene construction and first-use compilation. Measured on
1831
- // sandbox/wildwood, a 46,190-instance forest, the first two windows reported 18.8
1832
- // and 27.3 fps against a 60 fps budget — a deficit large enough that `#rungsToDrop`
1833
- // crossed three rungs at once and the buffer went from 1600x900 to 976x549 before
1834
- // the player had control. It then settled at 0.72, which is 52% of the pixels, and
1835
- // re-probed 0.85 every thirty seconds, missed, and fell back — so the picture went
1836
- // soft a few seconds in and never fully recovered. The owner's report was "after a
1837
- // while everything becomes blurry, and keeps getting worse".
1838
- //
1839
- // Readiness is the right gate rather than a frame count or a timer: it is the moment
1840
- // the framework already defines as "the world is safe to show", it now includes
1841
- // anything the game held startup for, and a host that never reaches it still gets
1842
- // there on the bounded fallbacks inside `StartupReadiness`.
1843
- if (!startupReadiness.ready || compileObserved) return;
1844
- const stepped = scaler.observe(reported);
1845
- if (stepped !== undefined) renderer.setResolutionScale(stepped, scaler.scaleSource);
1846
- },
1847
- // Last, so the engine's own renderer answers this and a game cannot report a
1848
- // resolution it is not drawing at. The window carries it in both pinned and auto
1849
- // modes: turning the convention off does not turn its measurement off.
1850
- readGpuAgeFrames: () => renderer.gpuFrameAge?.(),
1851
- // The world's own count of what the GPU selected, not `info.render.triangles`' upper
1852
- // bound over mesh capacity. Absent until the world's first tally lands.
1853
- readGpuTally: () => gpuTallyProvider?.(),
1854
- // The resolved budget rides the window rather than a marker of its own, so a harness
1855
- // reads the target and the frames it was judged against out of one line. It lags the
1856
- // window by one, because the window is built before this callback runs.
1857
- readTarget: () => resolveTargetFps(this.#config, getPlatform(), measuredRefreshHz),
1858
- readSurface: () => {
1859
- observeCompilation();
1860
- return {
1861
- ...renderer.surface(),
1862
- ...(scaler === undefined ? {} : { atFloor: scaler.atFloor }),
1863
- compiling: compilingInWindow,
1864
- };
1865
- },
1866
- });
1867
- this.#frameBudget = frameBudget;
1868
- // Per-pass draws and triangles ride the frame budget's window by default. The same property
1869
- // that makes `info.render` an aggregate — one reset per frame before the world render, and
1870
- // nested shadow/reflection renders sharing that counter — is what this recorder unwinds.
1871
- const renderPassBudget =
1872
- frameBudget === undefined
1873
- ? undefined
1874
- : RenderPassBudget.install(renderer.raw as Parameters<typeof RenderPassBudget.install>[0]);
1875
- // Spans are a diagnostic, never a convention: nothing installs them unless `TN_FRAME_SPANS`
1876
- // asks for them, and every call site below is one guarded return when it does not. They wrap
1877
- // three's own render path rather than reimplementing it, so what they measure is the path that
1878
- // ships, and they are removed with the game.
1879
- const spans = spansRequested() ? new SpanRecorder() : undefined;
1880
- if (spans !== undefined) setSpanRecorder(spans);
1881
- const removeSpanProbes =
1882
- spans === undefined
1883
- ? undefined
1884
- : installSpanProbes(renderer.raw as Parameters<typeof installSpanProbes>[0], threeScene);
1885
- // The boundary counts ride the same flag: they wrap every WebGPU command of the frame, which is
1886
- // work a shipped build must not pay for a diagnostic it did not ask for.
1887
- const frameCounters =
1888
- spans === undefined ? undefined : FrameCounters.install(counterDeviceOf(renderer.raw));
1889
- // The engine's own ABI crossings ride every budget window, not the spans flag: one difference of
1890
- // two reads per frame, and the series a fix for repeated crossings is judged on.
1891
- const bridgeCrossings = createCrossingReader();
1892
- // Every engine work counter, per frame, when a playtest bounds them (PRD-748 engine-cost row).
1893
- const engineCounters = createEngineCounterReader();
1894
- if (debug) engineCounters();
1895
- // The parity oracle for the static freeze. Off by default and expensive on purpose: it
1896
- // recomputes every world matrix the long way and throws on the first that disagrees with what
1897
- // the frame is about to draw.
1898
- const renderListValidator = renderListValidationRequested()
1899
- ? new RenderListValidator()
1900
- : undefined;
1901
- if (removeSpanProbes !== undefined) {
1902
- this.#cleanup.push(() => {
1903
- removeSpanProbes();
1904
- setSpanRecorder(undefined);
1905
- });
1906
- }
1907
- if (frameCounters !== undefined) this.#cleanup.push(() => frameCounters.uninstall());
1908
- if (debug) {
1909
- const stopGc = observeDebugGc();
1910
- if (stopGc !== undefined) this.#cleanup.push(stopGc);
1911
- }
1912
- // Holds no hook and does no work between requests, so an idle game pays nothing for it.
1913
- const geometryCapture = new GeometryCapture();
1914
- this.#geometryCapture = geometryCapture;
1915
- const budgetNow = (): number => globalThis.performance?.now() ?? Date.now();
1916
- // The stage meters split the render phase (PRD-771): three clock reads a frame and one difference of the
1917
- // engine's running totals. Decided once; `?tnStages=0` turns the whole path off, here and in the engine.
1918
- const stageMeters = frameBudget !== undefined && stageMetersRequested();
1919
- const readStages = stageMeters ? createStageReader(() => renderer.raw) : undefined;
1920
- const readWork = stageMeters ? createWorkReader(() => renderer.raw) : undefined;
1921
- if (!stageMeters)
1922
- (renderer.raw as { setStageMeters?: (enabled: boolean) => void }).setStageMeters?.(false);
1923
- let computeStageMs = 0;
1924
- // The dev verdict is decided once per launch, and sent when it changes rather than on a timer:
1925
- // a chip that re-sent an unchanged sentence four times a second would pay a JSON round trip to
1926
- // say nothing new.
1927
- const devMetricsEnabled = isDevLaunch();
1928
- let postedVerdict: string | undefined;
1929
- let updates = 0;
1930
- let renders = 0;
1931
- let lastGateSkips = 0;
1932
- let readinessGateSkips = 0;
1933
- const gameLoop: FixedStepLoop = new FixedStepLoop({
1934
- interpolation,
1935
- ...(frameBudget === undefined ? {} : { budget: frameBudget }),
1936
- ...(spans === undefined ? {} : { spans }),
1937
- maxSteps: this.#config.maxSteps,
1938
- onBeginFrame: () => {
1939
- // The engine owns this requestAnimationFrame loop instead of delegating to Three's
1940
- // setAnimationLoop(). Three's renderer therefore cannot reset its frame counters for us;
1941
- // a concurrent internal renderer callback can otherwise leave stale work in the first
1942
- // sample after a held playtest start.
1943
- resetRendererPerformanceMetrics(renderer.raw);
1944
- renderer.beginFrame?.();
939
+ scheduler: {
940
+ get: () => this.#scheduler,
941
+ set: (value) => {
942
+ this.#scheduler = value;
943
+ },
1945
944
  },
1946
- onRender: (alpha) => {
1947
- observeCompilation();
1948
- // Before the first world pass compiles anything: the merged meshes it compiles are the ones
1949
- // the player will see. A scene that has not entered has nothing built to settle.
1950
- if (this.#sceneEntered) {
1951
- if (debug)
1952
- measureDebug("autoBatch", "renderer", "AutoBatch.update", () => autoBatch.update());
1953
- else autoBatch.update();
1954
- }
1955
- renderPassBudget?.beginFrame();
1956
- // Runs on web as well as native, so the two stay one behaviour rather than diverging into
1957
- // a fast path nobody tests. When the world is drawn, reconciliation happens immediately
1958
- // before the render, inside the same frame, so a change the game made this tick reaches
1959
- // the screen this tick instead of the next one. Scenes under its mesh floor get their own
1960
- // graph back and pay nothing.
1961
- // A goto clears the graph before its destination enters, and the projection has to drop
1962
- // those objects on the very next frame. During the first-use hold, however, reconciling a
1963
- // large scene would be more work before the loader has even presented. Present one
1964
- // loader-only frame and keep reconciling skipped until first-use work settles; then the
1965
- // world pass and projection start together behind the still-opaque layer.
1966
- let worldMetrics: IRenderPerformanceMetrics | undefined;
1967
- const firstWorldPass = !worldRendered && this.#sceneEntered;
1968
- const explicitWarmUpPending = this.#warmUpConfiguredExplicitly() && !explicitWarmUpSettled;
1969
- const loaderHasPixels = canvasLayer.scene.children.length > 0;
1970
- const mustPresentLoader =
1971
- firstWorldPass && canvasLayer.opaque && loaderHasPixels && !loadingFramePresented;
1972
- if (firstWorldPass && !explicitWarmUpPending) {
1973
- this.#startupGateStarted = true;
1974
- // `startupCompile` is the fallback that compiles inside the readiness gate. When warm-up
1975
- // is on it has already happened behind the loading screen, so running it again here
1976
- // would pay the same cost twice.
1977
- startupReadiness.start(
1978
- this.#warmUpConfiguredExplicitly()
1979
- ? undefined
1980
- : startupCoverActive()
1981
- ? startupCompile
1982
- : startupEnvironment(),
1983
- );
1984
- }
1985
- // Ordinary render compute waits for startup readiness. Streaming explicitly opts in
1986
- // after compilation so a spawn hold can finish behind the curtain. Present the loader
1987
- // first; charge this admission to the same render phase as normal render compute.
1988
- if (
1989
- this.#renderer !== undefined &&
1990
- this.#sceneEntered &&
1991
- !explicitWarmUpPending &&
1992
- !mustPresentLoader &&
1993
- (!startupCoverActive() || startupReadiness.compileSettled)
1994
- ) {
1995
- const computeStart = frameBudget === undefined ? 0 : budgetNow();
1996
- computeStageMs = 0;
1997
- beginSpan(SPANS.compute);
1998
- try {
1999
- // The render camera comes with it, because a render-cadence consumer that culls by the
2000
- // view — a streamed world's main batches — has to be driven from here and not from a draw
2001
- // three skips for a mesh that is hidden because it has nothing to draw.
2002
- this.#computeDriven.processRender(
2003
- this.#renderer,
2004
- camera,
2005
- startupCoverActive() && !startupReadiness.ready,
2006
- gameLoop,
2007
- );
2008
- } finally {
2009
- endSpan(SPANS.compute);
2010
- }
2011
- computeStageMs = frameBudget === undefined ? 0 : budgetNow() - computeStart;
2012
- frameBudget?.addRender(computeStageMs);
2013
- }
2014
- const waitingForFirstUse =
2015
- firstWorldPass &&
2016
- (explicitWarmUpPending || (startupCoverActive() && !startupReadiness.compileSettled));
2017
- let worldPasses: ReturnType<RenderPassBudget["passes"]> | undefined;
2018
- // Before the scene has entered, the world pass runs only under an opaque cover. With nothing
2019
- // over it, the draw presents the clear colour: Hop Garden showed three black frames during
2020
- // `load()` for 0.5 s when the page mounted the canvas. Under the cover it is what compiles the
2021
- // world's pipelines inside the load: skipped, Hop's 10 s first-use compile landed after a
2022
- // playtest's setup had released enter(), and setup.place runs failed.
2023
- if (
2024
- (this.#sceneEntered || canvasLayer.opaque) &&
2025
- !mustPresentLoader &&
2026
- !waitingForFirstUse &&
2027
- (!canvasLayer.opaque ||
2028
- (!startupReadiness.ready && canvasLayer.renderWorldDuringStartup) ||
2029
- canvasLayer.keepWorldRendering)
2030
- ) {
2031
- // The projection's own scene when it is faithful, the game's when it is not. Nothing
2032
- // here branches on which: `root` is the single render input either way, so there is no
2033
- // second optional render path to leave untested.
2034
- // The reconcile is bracketed with the render it feeds: its walk, grouping and matrix
2035
- // sync are render-path work, and a frame budget that hid it in `residual` made the
2036
- // optimizer's own cost unmeasurable exactly where the optimizer is engaged.
2037
- const renderStart = frameBudget === undefined ? 0 : budgetNow();
2038
- // Before anything walks: a frozen subtree whose author moved its root thaws here, so the
2039
- // walk that follows sees a transform nobody had to remember to announce.
2040
- refreshStaticTransforms();
2041
- // Camera-rate metadata is an input to scene-owned beforeRender work and the projection
2042
- // palette write, not a post-draw observation. Publish it before either can skip a rig;
2043
- // this pass observes animation only and does not decide draw visibility.
2044
- const drawingBufferHeight = renderer.surface().drawingBufferHeight;
2045
- const cullPrepareStart = spans === undefined ? 0 : spanNow();
2046
- this.#cameraCull?.prepareAnimation(
2047
- this.#projection?.root ?? threeScene,
2048
- camera,
2049
- drawingBufferHeight,
2050
- );
2051
- if (spans !== undefined) addSpan(SPANS.cull, spanNow() - cullPrepareStart);
2052
- // Scene prep that must read the frame's last solved state before the projection packs and
2053
- // the renderer draws. Inside the world-render block it cannot land on a held loader frame.
2054
- if (this.#beforeRenderCallbacks.size > 0) {
2055
- let snapshot = this.#beforeRenderSnapshots[this.#beforeRenderDepth];
2056
- if (snapshot === undefined) {
2057
- snapshot = [];
2058
- this.#beforeRenderSnapshots[this.#beforeRenderDepth] = snapshot;
2059
- }
2060
- this.#beforeRenderDepth += 1;
2061
- snapshot.length = 0;
2062
- for (const callback of this.#beforeRenderCallbacks) snapshot.push(callback);
2063
- beginSpan(SPANS.beforeRender);
2064
- try {
2065
- for (const callback of snapshot) {
2066
- if (debug)
2067
- measureDebug(
2068
- `beforeRender.${callback.name || "anonymous"}`,
2069
- "update",
2070
- callback.name || "ctx.beforeRender",
2071
- callback,
2072
- );
2073
- else callback();
2074
- }
2075
- } finally {
2076
- endSpan(SPANS.beforeRender);
2077
- this.#beforeRenderDepth -= 1;
2078
- }
2079
- }
2080
- interpolation.render(gameLoop.clockFrozen || this.#paused ? 1 : alpha, () => {
2081
- // Let a depth-coupled scene update its output node while the scene pass is still the
2082
- // next render. Ordinary scenes keep the historical hook order and timing.
2083
- const depthCoupledOutput = this.#hasDepthCoupledOutput;
2084
- if (depthCoupledOutput && this.#sceneEntered) this.#scene?.render(ctx);
2085
- // The engine's own walk owns the frame's world matrices, so the count starts here and
2086
- // covers both applications below: the authored scene the projection reconciles from and
2087
- // the root the renderer is actually handed.
2088
- this.#matrixWorld?.beginFrame();
2089
- if (this.#projection !== undefined) {
2090
- beginSpan(SPANS.reconcile);
2091
- try {
2092
- this.#projection.reconcile();
2093
- } finally {
2094
- endSpan(SPANS.reconcile);
2095
- }
2096
- }
2097
- // Virtual geometry ships on by default, so the engine takes the cut rather than waiting
2098
- // for a game to know it should. It runs here, before the render and after the reconcile,
2099
- // because an empty cut has to skip its draw rather than submit a zero-count one — and a
2100
- // scene holding no clustered mesh pays no traversal at all, only the tracked set.
2101
- beginSpan(SPANS.clustered);
2102
- try {
2103
- updateClusteredMeshes(
2104
- this.#projection?.root ?? threeScene,
2105
- camera,
2106
- renderer.surfaceDrawingBufferHeight?.() ?? renderer.surface().drawingBufferHeight,
2107
- );
2108
- } finally {
2109
- endSpan(SPANS.clustered);
2110
- }
2111
- // Automatic discrete LOD ships on with the pipeline, so the engine takes the selection
2112
- // too. It shares the render root and the same drawing-buffer height, and a scene with no
2113
- // managed mesh pays only the tracked-set walk.
2114
- beginSpan(SPANS.lod);
2115
- try {
2116
- updateModelLods(
2117
- this.#projection?.root ?? threeScene,
2118
- camera,
2119
- renderer.surface().drawingBufferHeight,
2120
- );
2121
- } finally {
2122
- endSpan(SPANS.lod);
2123
- }
2124
- const renderRoot = this.#projection?.root ?? threeScene;
2125
- // The cull reads the matrices the renderer will draw. Projection exact proxies carry the
2126
- // authored world matrix in their local matrix, so their own world walk must precede both
2127
- // the cull and the render rather than following the cull.
2128
- renderRoot.matrixWorldAutoUpdate = false;
2129
- this.#matrixWorld?.apply(renderRoot);
2130
- // Projected-size cull, per render camera, default on. It writes only `object.visible` —
2131
- // the one per-frame flag the projection's batch key ignores — and restores what it hid
2132
- // immediately after the draw, so the authored scene is untouched between frames. The
2133
- // renderer walks the same root the projection is about to draw, so a declined projection
2134
- // and an active one both get the gate.
2135
- const cullApplyStart = spans === undefined ? 0 : spanNow();
2136
- this.#cameraCull?.apply(
2137
- this.#projection?.root ?? threeScene,
2138
- camera,
2139
- drawingBufferHeight,
2140
- );
2141
- // Added, not bracketed: the render call sits between the apply and the restore, and a
2142
- // span that contained it would report the world pass as cull work.
2143
- if (spans !== undefined) addSpan(SPANS.cull, spanNow() - cullApplyStart);
2144
- const capturing = geometryCapture.armed();
2145
- if (capturing) {
2146
- // The mirror is what the renderer sees; arming the authored scene would attribute the
2147
- // frame to objects that were never submitted.
2148
- geometryCapture.beginFrame({
2149
- camera,
2150
- generation: this.#sceneGeneration,
2151
- root: this.#projection?.root ?? threeScene,
2152
- tick: gameLoop.tick(),
2153
- viewportHeight: renderer.surface().drawingBufferHeight,
2154
- viewportWidth: renderer.surface().drawingBufferWidth,
2155
- ...(renderPassBudget === undefined
2156
- ? {}
2157
- : { activePassKind: () => renderPassBudget.activeKind() }),
2158
- ...(this.#projection === undefined
2159
- ? {}
2160
- : { ownership: this.#projection.describeOwnership() }),
2161
- ...(rendererBackendIdentity(renderer.raw) === undefined
2162
- ? {}
2163
- : { backend: rendererBackendIdentity(renderer.raw) as string }),
2164
- });
2165
- }
2166
- // Scene.enter installs the chain after the scaler is created; choose its tier before its first draw.
2167
- if (!temporalStartApplied && scaler !== undefined && renderer.temporalUpscale?.()) {
2168
- scaler = createScaler();
2169
- temporalStartApplied = true;
2170
- if (scaler !== undefined)
2171
- renderer.setResolutionScale(scaler.scale, scaler.scaleSource);
2172
- }
2173
- const engineStart = readStages === undefined ? 0 : budgetNow();
2174
- renderer.render(renderRoot, camera);
2175
- const engineEnd = readStages === undefined ? 0 : budgetNow();
2176
- renders += 1;
2177
- // Count declined frames without treating them as drawn-frame render cost.
2178
- const gateSkips = rendererFrameGateSkips(renderer.raw);
2179
- if (gateSkips !== undefined) {
2180
- if (gateSkips > lastGateSkips) frameBudget?.addRenderSkip();
2181
- lastGateSkips = gateSkips;
2182
- }
2183
- // *After* the render, because that is where the draw happened. The matrices read here are
2184
- // the ones drawn: the walk above refreshed them and `render()` did not touch them. The
2185
- // frozen roots are passed because the draw root is the projection's mirror when the
2186
- // engine is collapsing, and validating only that reassured about a scene it never
2187
- // looked at. `?.` short-circuits before the spread, so `staticRoots()` is not called
2188
- // at all on a frame without the flag — verified, a million optional calls evaluate the
2189
- // argument zero times — and this stays a single undefined check in a shipped game.
2190
- renderListValidator?.frame(renderRoot, ...staticRoots());
2191
- const cullRestoreStart = spans === undefined ? 0 : spanNow();
2192
- this.#cameraCull?.restore();
2193
- if (spans !== undefined) addSpan(SPANS.cull, spanNow() - cullRestoreStart);
2194
- this.#projection?.commit();
2195
- renderer.observeRenderChainFrame?.();
2196
- if (frameBudget !== undefined) {
2197
- const renderEnd = budgetNow();
2198
- frameBudget.addRender(renderEnd - renderStart);
2199
- const stages = readStages?.(
2200
- computeStageMs + (engineStart - renderStart),
2201
- engineEnd - engineStart,
2202
- renderEnd - engineEnd,
2203
- );
2204
- if (stages !== undefined) frameBudget.addStages(stages);
2205
- }
2206
- computeStageMs = 0;
2207
- // Read the split before the overlay renders: the overlay is its own draw, not part of the
2208
- // world pass, and the budget window already accounts for it in its own phase.
2209
- worldPasses = renderPassBudget?.passes();
2210
- if (worldPasses !== undefined && worldPasses.length > 0)
2211
- frameBudget?.addRenderPasses(worldPasses);
2212
- // After the passes are read, so the rows reconcile against this frame's own totals.
2213
- if (capturing) geometryCapture.finishFrame(worldPasses ?? []);
2214
- // Resolve the GPU timestamps every frame, not once per reported window.
2215
- //
2216
- // `trackTimestamp` spends two queries per render pass, and three's pool holds 2048.
2217
- // A scene with a post-processing chain runs tens of passes per frame — a cathedral
2218
- // with SSGI, denoise, godrays, SSR and bloom measured 27 — so the pool fills in
2219
- // 2048 / (2 x 27) = 38 frames. The resolve used to be wired to the frame-budget
2220
- // window boundary, 300 frames by default, which is eight times too slow: three
2221
- // warned `Maximum number of queries exceeded`, stopped recording, and every window
2222
- // after the first reported `gpuMs: undefined`. The one instrument that exists so the
2223
- // GPU record is not wall-clock algebra was reading nothing.
2224
- //
2225
- // This does not put the GPU on the frame path. `resolveTimestampsAsync` is
2226
- // fire-and-forget and already catch-guarded, which was the original cadence's only
2227
- // stated concern.
2228
- // Deliberately unspanned. The resolve runs *after* `addRender` closed the render phase,
2229
- // so its milliseconds are in the frame's `residual`, not in `render`. A span for it was
2230
- // measured on the native smoke game at 0.18 ms and showed up as exactly that much
2231
- // negative residual — the tree reporting, correctly, that it had been handed a term from
2232
- // outside the phase it is dividing up. The frame budget already carries this cost.
2233
- renderer.resolveGpuFrame();
2234
- frameBudget?.addGpuPyramidMs(renderer.gpuPyramidMs?.());
2235
- // The budget's GPU series is fed every frame, not read once per reported window. A
2236
- // single window-close read is one instantaneous, lagged `info.render.timestamp` — the
2237
- // sample that made a 17.6 ms frame read as 2.98–10.40 ms. The sample carries the
2238
- // resolved frame id so a resolve still in flight is counted stale, not measured twice.
2239
- //
2240
- // The reading is the frame's own passes out of three's per-pass map, handed out one
2241
- // resolved frame per presented frame. Three's resolve answers with one number for the
2242
- // batch — the last frame in it — so reading that instead dropped every frame a batch
2243
- // caught up on, and because the resolve is asked for on the same 1-in-8 stride the
2244
- // sampler uses, how many frames a batch caught up on was a function of frame rate.
2245
- // The pass recorder is what reads three's per-pass map back into per-frame numbers; a
2246
- // renderer it cannot instrument falls back to the batch's own single number, which is the
2247
- // reading there was before — one sample per resolve rather than one per sampled frame.
2248
- const gpuFrame = renderPassBudget?.nextGpuFrame();
2249
- const gpuSample = gpuFrame === undefined ? renderer.gpuFrameSample?.() : undefined;
2250
- frameBudget?.addGpuMs(
2251
- gpuFrame?.total ?? gpuSample?.ms,
2252
- gpuFrame?.frame ?? gpuSample?.frame,
2253
- );
2254
- // Where one resolved frame's GPU time went: main and shadow come from the pass
2255
- // recorder's per-uid query results, and everything else in that pool (post chain,
2256
- // reflections, HUD) is the remainder. Compute is its own pool.
2257
- if (gpuFrame !== undefined) {
2258
- const computeMs = renderer.gpuComputeMs?.();
2259
- // The recorder hands out a frame only when every pass it recorded resolved, so `total`
2260
- // is the whole frame and never a partial sum; `main` and `shadow` are whole or zero.
2261
- // `other` is the remainder of the frame (post chain, reflection, HUD). `shadowPasses`
2262
- // rides along so a consumer can tell a frame that rendered a shadow from one that drew
2263
- // none, since a real render can resolve to 0 ms.
2264
- frameBudget?.addGpuBucketMs({
2265
- main: gpuFrame.main,
2266
- shadow: gpuFrame.shadow,
2267
- shadowPasses: gpuFrame.shadowPasses,
2268
- other: Math.max(0, gpuFrame.total - gpuFrame.main - gpuFrame.shadow),
2269
- ...(computeMs === undefined ? {} : { compute: computeMs }),
2270
- });
2271
- // The main pass's own GPU series, for the adaptive LOD control loop: the frame
2272
- // budget's `gpuMain` bucket is the record, and this is the same number smoothed on the
2273
- // renderer so a world holding only the renderer can read it. Fed per delivered frame,
2274
- // fresh or not.
2275
- renderer.noteGpuMainMs?.(gpuFrame.main, gpuFrame.frame);
2276
- } else {
2277
- renderer.noteGpuMainMs?.(undefined);
2278
- }
2279
- if (!depthCoupledOutput && this.#sceneEntered) this.#scene?.render(ctx);
2280
- if (this.#sceneEntered) {
2281
- if (!worldRendered) gameLoop.clearRuntimeDiagnostics();
2282
- worldRendered = true;
2283
- }
2284
- if (this.#renderMetricsEnabled) {
2285
- const metrics = rendererPerformanceMetrics(renderer.raw);
2286
- worldMetrics =
2287
- worldPasses === undefined || worldPasses.length === 0
2288
- ? metrics
2289
- : { ...metrics, passes: worldPasses.map((pass) => ({ ...pass })) };
2290
- }
2291
- // Read whether or not the game asked for render metrics: the projection line reports
2292
- // the measured draw count, and a convention's measurement does not switch off with the
2293
- // convention that happens to sit beside it.
2294
- lastWorldDrawCalls = rendererDrawCallCount(renderer.raw);
2295
- });
2296
- }
2297
- if (mustPresentLoader) loadingFramePresented = true;
2298
- // Include state written by beforeRender and Scene.render in this frame's UI snapshot.
2299
- if (this.#config.stateFlushMs === undefined && stateHandOffFrames === 0)
2300
- this.#state.flush();
2301
- // Every frame, including one whose canvas layer is empty: the native UI is composited into
2302
- // the game's own frame whether or not the game draws a HUD of its own, so a frame that
2303
- // skipped this would report work it did pay as `residual`. The host reports what the
2304
- // *previous* frame's composite cost — the only reading that exists when a frame begins —
2305
- // so this charges the phase to the frame that paid it, one frame late rather than never.
2306
- // Absent on the web target and on any host with no overlay, where the work is zero rather
2307
- // than unknown, so an absent global must read as zero and not as a missing measurement.
2308
- // The boundary counts ride the span flag, but the simulation tick does not need them: it is
2309
- // fed every frame so a plain `TN_FRAME_BUDGET` log can join a window's start and end ticks
2310
- // without `TN_FRAME_SPANS`. `addCounters` keeps the last tick a caller did provide.
2311
- const crossings = bridgeCrossings();
2312
- if (debug) {
2313
- const matrix = this.#matrixWorld?.report;
2314
- if (matrix !== undefined)
2315
- countDebug("matrixWorldVisits", matrix.visited, "scene", "MatrixWorldPass");
2316
- const cull = this.#cameraCull?.report;
2317
- if (cull !== undefined) {
2318
- countDebug("cullConsidered", cull.considered, "renderer", "RenderCameraCull");
2319
- countDebug("cullRejected", cull.culled, "renderer", "RenderCameraCull");
2320
- }
2321
- const batch = autoBatch.census;
2322
- countDebug("autoBatchSources", batch.meshes, "renderer", "AutoBatch.census");
2323
- countDebug("autoBatchDraws", batch.draws, "renderer", "AutoBatch.census");
2324
- countDebug("autoBatchRefused", batch.refused, "renderer", "AutoBatch.census");
2325
- countDebug("autoBatchUnsettled", batch.unsettled, "renderer", "AutoBatch.census");
2326
- }
2327
- const boundary = frameCounters?.read();
2328
- const engine = engineCounters();
2329
- // The owned engine's work counts; a JS back end with its own queue counters (`boundary`) outranks them.
2330
- const work = readWork?.(crossings);
2331
- frameBudget?.addCounters({
2332
- ...(work ?? {}),
2333
- ...(boundary ?? {}),
2334
- ...(crossings === undefined ? {} : { bridgeCrossings: crossings }),
2335
- ...(engine === undefined ? {} : { engine }),
2336
- simulationTick: gameLoop.tick(),
2337
- });
2338
- const uiHost = globalThis as { __tnUiCompositeMs?: () => number };
2339
- frameBudget?.addUi(
2340
- typeof uiHost.__tnUiCompositeMs === "function" ? (uiHost.__tnUiCompositeMs() ?? 0) : 0,
2341
- );
2342
- if (canvasLayer.scene.children.length > 0) {
2343
- const overlayStart = frameBudget === undefined ? 0 : budgetNow();
2344
- // The overlay is its own render call and its own frame-budget phase. The span probes sit
2345
- // on `render`, so without this they would charge the HUD's draw to the render phase the
2346
- // spans are explaining — measured on the native smoke game as `coverage 1.03` and a
2347
- // residual of −0.37 ms, two render calls per frame where the phase paid for one. The
2348
- // recorder is unhooked rather than flagged, so every probe takes the same guarded return
2349
- // it takes in a shipped build and the span stack cannot be left half-open.
2350
- if (spans !== undefined) setSpanRecorder(undefined);
2351
- try {
2352
- renderer.renderOverlay(canvasLayer.scene, canvasLayer.camera);
2353
- } finally {
2354
- if (spans !== undefined) setSpanRecorder(spans);
2355
- }
2356
- frameBudget?.addOverlay(budgetNow() - overlayStart);
2357
- if (!this.#renderMetricsEnabled) return undefined;
2358
- const overlayMetrics = rendererPerformanceMetrics(renderer.raw);
2359
- return combineRenderPerformanceMetrics(renderer.kind, worldMetrics, overlayMetrics);
2360
- }
2361
- return this.#renderMetricsEnabled ? worldMetrics : undefined;
945
+ afterPhysicsPhase: {
946
+ get: () => this.#afterPhysicsPhase,
947
+ set: (value) => {
948
+ this.#afterPhysicsPhase = value;
949
+ },
2362
950
  },
2363
- onAfterPhysics: (dt) => {
2364
- if (this.#paused) return;
2365
- if (debug)
2366
- measureDebug("afterPhysics", "update", "afterPhysicsPhase.run", () =>
2367
- afterPhysicsPhase.run(dt),
2368
- );
2369
- else afterPhysicsPhase.run(dt);
951
+ frameBudget: {
952
+ get: () => this.#frameBudget,
953
+ set: (value) => {
954
+ this.#frameBudget = value;
955
+ },
2370
956
  },
2371
- onUpdate: (dt) => {
2372
- if (this.#paused) return;
2373
- if (debug) {
2374
- measureDebug("input", "update", "Input.tick", () => this.#input?.tick());
2375
- measureDebug("scheduler", "update", "Scheduler.tick", () => scheduler.tick(dt));
2376
- measureDebug("picking", "update", "PointerEvents3D.tick", () =>
2377
- pointerEvents.tick(
2378
- input.raw.pointers,
2379
- picker,
2380
- input.raw.pointer,
2381
- input.raw.pointerEdges,
2382
- ),
2383
- );
2384
- } else {
2385
- this.#input?.tick();
2386
- scheduler.tick(dt);
2387
- pointerEvents.tick(input.raw.pointers, picker, input.raw.pointer, input.raw.pointerEdges);
2388
- }
2389
- for (const plugin of this.#activePlugins) {
2390
- if (debug && plugin.beforeUpdate !== undefined)
2391
- measureDebug(
2392
- `beforeUpdate.${this.#activePlugins.indexOf(plugin)}.${plugin.beforeUpdate.name || "anonymous"}`,
2393
- "update",
2394
- `plugins[${this.#activePlugins.indexOf(plugin)}].${plugin.beforeUpdate.name || "beforeUpdate"}`,
2395
- () => plugin.beforeUpdate?.(ctx, dt),
2396
- );
2397
- else plugin.beforeUpdate?.(ctx, dt);
2398
- }
2399
- const scene = this.#scene;
2400
- const frame = this.#sceneFrame;
2401
- if (this.#sceneEntered && frame !== undefined) {
2402
- if (debug)
2403
- measureDebug(
2404
- "sceneCallbacks",
2405
- "update",
2406
- `${scene?.constructor.name}.${frame.name || "frame"}`,
2407
- () => frame(ctx, dt),
2408
- );
2409
- else frame(ctx, dt);
2410
- updates += 1;
2411
- }
2412
- // An async goto() installs the incoming scene before its load resolves; until enter()
2413
- // has run there is no gameplay to step and a game-overridden update() would run against
2414
- // a cleared graph.
2415
- else if (this.#sceneEntered && scene !== undefined) {
2416
- if (debug)
2417
- measureDebug("sceneCallbacks", "update", `${scene.constructor.name}.update`, () =>
2418
- scene.update(ctx, dt),
2419
- );
2420
- else scene.update(ctx, dt);
2421
- updates += 1;
2422
- }
2423
- if (this.#scene !== scene || this.#sceneFrame !== frame) return;
2424
- for (const plugin of this.#activePlugins) {
2425
- if (debug && plugin.update !== undefined)
2426
- measureDebug(
2427
- `plugins.${this.#activePlugins.indexOf(plugin)}.${plugin.update.name || "anonymous"}`,
2428
- "update",
2429
- `plugins[${this.#activePlugins.indexOf(plugin)}].${plugin.update.name || "update"}`,
2430
- () => plugin.update?.(ctx, dt),
2431
- );
2432
- else plugin.update?.(ctx, dt);
2433
- }
2434
- if (debug)
2435
- measureDebug("entities", "update", "Registry.sweep", () => this.#entities?.sweep());
2436
- else this.#entities?.sweep();
2437
- if (this.#renderer !== undefined && this.#sceneEntered) {
2438
- if (debug)
2439
- measureDebug(
2440
- "computeDriven",
2441
- "update",
2442
- "ComputeDriven.process",
2443
- () => this.#renderer && this.#computeDriven.process(this.#renderer),
2444
- );
2445
- else this.#computeDriven.process(this.#renderer);
2446
- }
957
+ interpolation: {
958
+ get: () => this.#interpolation,
959
+ set: (value) => {
960
+ this.#interpolation = value;
961
+ },
2447
962
  },
2448
- // A frame the renderer declined to draw (the Wasm engine's gate: two frames still on the GPU)
2449
- // is no frame at all for the readiness window. Counted, five cheap declined frames closed the
2450
- // window while the first world frame was still compiling on the GPU, so the cover lifted and
2451
- // the player saw a 0.9 s stall and then a first frame with unmetered exposure (Hop Garden, 4
2452
- // of 13 launches). Not a reset either: a GPU-bound world under the cover declines every other
2453
- // frame, and a reset held every Hop launch to the 10 s window bound.
2454
- onFrame: (frameMs) => {
2455
- const skips = rendererFrameGateSkips(renderer.raw);
2456
- const declined = skips !== undefined && skips > readinessGateSkips;
2457
- if (skips !== undefined) readinessGateSkips = skips;
2458
- if (!declined) startupReadiness.observe(frameMs);
2459
- // Bounded like every other startup wait: a renderer that retires no frame (hosted CI's
2460
- // SwiftShader declined 73 of 73 after readiness) would otherwise keep the HUD covered for
2461
- // the whole session. Past the window the cover lifts anyway, and says why.
2462
- const handOffWaitedMs = now() - (timeline.readyMs ?? now());
2463
- const handOffBounded = handOffWaitedMs >= STARTUP_STABLE_WINDOW_MS;
2464
- // A draw the gate accepted is only queued: the cover lifts once the GPU has finished the first world frame.
2465
- const worldOnDisplay = rendererWorldPresented(renderer.raw) !== false;
2466
- if (stateHandOffFrames > 0 && ((!declined && worldOnDisplay) || handOffBounded)) {
2467
- if (handOffBounded) {
2468
- console.warn(
2469
- `TN_STARTUP_HANDOFF_BOUNDED:${JSON.stringify({
2470
- retiredFrames: STARTUP_HANDOFF_FRAMES - stateHandOffFrames,
2471
- requiredFrames: STARTUP_HANDOFF_FRAMES,
2472
- waitedMs: Math.round(handOffWaitedMs),
2473
- reason:
2474
- "the GPU retired fewer frames than the hand-off needs; the cover lifted at the bound",
2475
- })}`,
2476
- );
2477
- stateHandOffFrames = 0;
2478
- } else stateHandOffFrames -= 1;
2479
- // The frame the held state publishes again is the frame the cover is gone.
2480
- if (stateHandOffFrames === 0) {
2481
- this.#uiRevealed = true;
2482
- if (this.#uiBridge?.hasPeer()) this.#postUiStartup();
2483
- }
2484
- }
963
+ geometryCapture: {
964
+ get: () => this.#geometryCapture,
965
+ set: (value) => {
966
+ this.#geometryCapture = value;
967
+ },
2485
968
  },
2486
- step: this.#config.step,
2487
- });
2488
- loopState.current = gameLoop;
2489
- this.#loop = gameLoop;
2490
- const startGates: Array<{
2491
- readonly gate: Promise<void>;
2492
- readonly rejectEntered: (error: unknown) => void;
2493
- readonly resolveEntered: () => void;
2494
- }> = [];
2495
- let settleLoaded: (error?: unknown) => void = () => undefined;
2496
- const startLoaded = new Promise<void>((resolve, reject) => {
2497
- settleLoaded = (error) => (error === undefined ? resolve() : reject(error));
2498
- });
2499
- // A run with no setup never awaits it; a failed load is reported by start() itself.
2500
- void startLoaded.catch(() => undefined);
2501
- const runtime: IGamePluginRuntime = {
2502
- startSceneLoaded: () => startLoaded,
2503
- fixedStep: (ticks, options) =>
2504
- gameLoop.advance(ticks, { ...options, until: () => this.#pendingSceneEnter !== undefined }),
2505
- sceneTransition: () =>
2506
- this.#pendingSceneEnter?.then(
2507
- () => undefined,
2508
- () => undefined,
2509
- ),
2510
- frameCounts: () => ({ updates, renders }),
2511
- frameBudgetWindow: () => this.#frameBudget?.window(),
2512
- freezeClock: () => gameLoop.freezeClock(),
2513
- renderCurrent: () => gameLoop.renderCurrentFrame(),
2514
- enableRuntimeDiagnostics: () => {
2515
- this.#renderMetricsEnabled = true;
2516
- gameLoop.setCollectMetrics(true);
969
+ beforeRenderSnapshots: {
970
+ get: () => this.#beforeRenderSnapshots,
971
+ set: (value) => {
972
+ this.#beforeRenderSnapshots = value;
973
+ },
2517
974
  },
2518
- holdStart: (gate) => {
2519
- let rejectEntered: (error: unknown) => void = () => undefined;
2520
- let resolveEntered: () => void = () => undefined;
2521
- const entered = new Promise<void>((resolve, reject) => {
2522
- rejectEntered = reject;
2523
- resolveEntered = resolve;
2524
- });
2525
- startGates.push({ gate, rejectEntered, resolveEntered });
2526
- return entered;
975
+ beforeRenderDepth: {
976
+ get: () => this.#beforeRenderDepth,
977
+ set: (value) => {
978
+ this.#beforeRenderDepth = value;
979
+ },
2527
980
  },
2528
- geometryCapture: (request) => geometryCapture.request(request),
2529
- observations: createRuntimeObservations(),
2530
- ...(renderer.pipelineCensus === undefined ? {} : { pipelineCensus: renderer.pipelineCensus }),
2531
- tick: gameLoop.tick,
2532
- random,
2533
- rapier: null,
2534
- seed: this.#config.seed ?? null,
2535
- startupCompileSettled: () => startupReadiness.compileSettled,
2536
- startupRevealed: () => this.#uiRevealed,
2537
- startupTimeline: () => ({ ...timeline }),
2538
- startupOffscreenBytes: () => offscreenBytes,
2539
- step: gameLoop.step,
2540
- runtimeDiagnosticsSeries: () => gameLoop.runtimeDiagnosticsSeries(),
2541
- };
2542
- Object.assign(runtime, {
2543
- _setClockMode: (mode: "fixed-step" | "wall-clock") => gameLoop._setClockMode(mode),
2544
- });
2545
- // A boot that throws must end exactly like an aborted boot: every cleanup attempted, every
2546
- // resource released — and the original error rethrown, not a teardown error standing in
2547
- // for it. The abort branches below stay outside these guards: they tear down themselves.
2548
- for (const plugin of this.#config.plugins ?? []) {
2549
- let cleanup: PluginCleanup | undefined;
2550
- try {
2551
- cleanup = typeof plugin === "function" ? plugin(ctx) : await plugin.setup?.(ctx, runtime);
2552
- } catch (error) {
2553
- this.#teardown(ctx);
2554
- throw error;
2555
- }
2556
- if (typeof plugin !== "function") this.#activePlugins.push(plugin);
2557
- if (this.#aborted) {
2558
- if (cleanup !== undefined) this.#cleanup.push(cleanup);
2559
- this.#teardown(ctx);
2560
- return;
2561
- }
2562
- if (cleanup !== undefined) this.#cleanup.push(cleanup);
2563
- }
2564
- const scene = this.#scene;
2565
- if (scene === undefined) {
2566
- this.#teardown(ctx);
2567
- return;
2568
- }
2569
- // Held: the loop renders every frame from here but steps nothing. On native the render loop
2570
- // is the only thing that can put pixels on the screen, so an async load starts it before the
2571
- // await; a synchronous load has already completed and starts it after the call. Holding rather
2572
- // than simply starting keeps the determinism contract intact: no tick advances and no elapsed
2573
- // time is banked before the release below.
2574
- const startHeldLoop = (): void => {
2575
- gameLoop.setHeld(true);
2576
- gameLoop.start();
2577
- };
2578
- try {
2579
- timeline.loadStartedMs ??= now();
2580
- const loaded = scene.load(ctx);
2581
- startHeldLoop();
2582
- if (loaded !== undefined) await loaded;
2583
- settleLoaded();
2584
- } catch (error) {
2585
- settleLoaded(error);
2586
- this.#teardown(ctx);
2587
- throw error;
2588
- }
2589
- if (this.#aborted) {
2590
- this.#teardown(ctx);
2591
- return;
2592
- }
2593
- // Plugins that need to mutate scene-load placeholders hold here. Setup must land before
2594
- // Scene.enter() transfers those values into authoritative physics/gameplay state.
2595
- if (startGates.length > 0) {
2596
- try {
2597
- await Promise.all(startGates.map(({ gate }) => gate));
2598
- } catch (error) {
2599
- for (const startGate of startGates) startGate.rejectEntered(error);
2600
- this.#teardown(ctx);
2601
- throw error;
2602
- }
2603
- if (this.#aborted) {
2604
- const error = new Error("Game start was aborted before the start scene entered.");
2605
- for (const startGate of startGates) startGate.rejectEntered(error);
2606
- this.#teardown(ctx);
2607
- return;
2608
- }
2609
- }
2610
- try {
2611
- // A boot scene can navigate during enter(). Describe the destination's registered entities
2612
- // after it enters, while readiness and the full goto() still wait for first-use warm-up.
2613
- this.#onStartSceneEntered = () => {
2614
- for (const startGate of startGates) startGate.resolveEntered();
2615
- };
2616
- this.#enterScene(scene, ctx);
2617
- timeline.enteredMs ??= now();
2618
- void this.#pendingSceneEnter?.catch((error: unknown) => {
2619
- for (const startGate of startGates) startGate.rejectEntered(error);
2620
- });
2621
- } catch (error) {
2622
- for (const startGate of startGates) startGate.rejectEntered(error);
2623
- this.#teardown(ctx);
2624
- throw error;
2625
- }
2626
- if (this.#aborted) {
2627
- this.#teardown(ctx);
2628
- return;
2629
- }
2630
- // The scene is built and the loop is still held, which is the only window where compiling can
2631
- // cost frames nobody is playing. Warming up here rather than letting the first real frame do
2632
- // it is what keeps a launch from freezing inside one 24-second frame. PRD-218.
2633
- if (this.#warmUpConfiguredExplicitly() && this.#renderer !== undefined) {
2634
- // Never fatal, and never able to hang the launch. This block sits between "the scene is
2635
- // built" and "the game may start", so anything it does wrong is something the player
2636
- // experiences as the game not starting -- which is exactly what the first version did: a
2637
- // `compileAsync` that never resolved on a Pixel 8 left this `await` pending forever, the
2638
- // loop stayed held, the simulation never advanced, and the game sat on its loading screen
2639
- // with no error anywhere. A warm-up that fails must cost the launch its speed, never its
2640
- // start, so the failure is reported and boot carries on.
2641
- let report: IWarmUpReport | undefined;
2642
- let failure: string | undefined;
2643
- try {
2644
- projection.reconcile();
2645
- // Same walk as the held warm-up above: the explicit warm-up also draws before the frame
2646
- // loop's own matrix pass, and a declined projection left the scene un-walked.
2647
- this.#matrixWorld?.apply(projection.root);
2648
- const warmUpOptions: IWarmUpOptions = this.#warmUpOptions();
2649
- report = await warmUpScene(this.#renderer, projection.root, camera, {
2650
- afterCoveredDraw: repaintCover,
2651
- ...warmUpOptions,
2652
- computeNodes: [...(warmUpOptions.computeNodes ?? []), ...this.#computeDriven.warmupNodes],
2653
- });
2654
- } catch (error) {
2655
- failure = error instanceof Error ? error.message : String(error);
2656
- }
2657
- this.#renderer.warmUpSettled?.();
2658
- warmUpStatus =
2659
- report === undefined
2660
- ? { status: "unavailable" }
2661
- : {
2662
- attempted: report.attempted,
2663
- candidates: report.candidates,
2664
- observed: report.observed,
2665
- status: report.observed.status,
2666
- };
2667
- // One greppable line on every platform, so a device lane reads what the warm-up did without
2668
- // instrumenting anything -- including the cases where it could do nothing, ran out of
2669
- // budget, or threw.
2670
- console.log(
2671
- `TN_WARMUP:${JSON.stringify(
2672
- report === undefined
2673
- ? { failed: failure ?? "unknown" }
2674
- : {
2675
- compiled: report.compiled,
2676
- pipelines: report.pipelines,
2677
- candidates: report.candidates,
2678
- attempted: report.attempted,
2679
- observed: report.observed,
2680
- slices: report.slices,
2681
- elapsedMs: Math.round(report.elapsedMs),
2682
- unsupported: report.unsupported,
2683
- abandoned: report.abandoned,
2684
- timedOut: report.timedOut,
2685
- computeCompiled: report.computeCompiled,
2686
- computeAbandoned: report.computeAbandoned,
2687
- computeUnsupported: report.computeUnsupported,
2688
- computeTimedOut: report.computeTimedOut,
2689
- passes: report.passes,
2690
- passPipelines: report.passPipelines,
2691
- cullingForced: report.cullingForced,
2692
- visibilityForced: report.visibilityForced,
2693
- cache: report.cache,
2694
- },
2695
- )}`,
2696
- );
2697
- explicitWarmUpSettled = true;
2698
- if (this.#aborted) {
2699
- this.#teardown(ctx);
2700
- return;
2701
- }
2702
- }
2703
- this.#started = true;
2704
- // Every gate has resolved and the scene has entered, so the simulation may move. The first
2705
- // tick after this reads a single frame's dt, not one spanning the load.
2706
- gameLoop.setHeld(false);
2707
- gameLoop.start();
981
+ hasDepthCoupledOutput: {
982
+ get: () => this.#hasDepthCoupledOutput,
983
+ set: (value) => {
984
+ this.#hasDepthCoupledOutput = value;
985
+ },
986
+ },
987
+ startupGateStarted: {
988
+ get: () => this.#startupGateStarted,
989
+ set: (value) => {
990
+ this.#startupGateStarted = value;
991
+ },
992
+ },
993
+ onStartSceneEntered: {
994
+ get: () => this.#onStartSceneEntered,
995
+ set: (value) => {
996
+ this.#onStartSceneEntered = value;
997
+ },
998
+ },
999
+ renderMetricsEnabled: {
1000
+ get: () => this.#renderMetricsEnabled,
1001
+ set: (value) => {
1002
+ this.#renderMetricsEnabled = value;
1003
+ },
1004
+ },
1005
+ uiRevealed: {
1006
+ get: () => this.#uiRevealed,
1007
+ set: (value) => {
1008
+ this.#uiRevealed = value;
1009
+ },
1010
+ },
1011
+ started: {
1012
+ get: () => this.#started,
1013
+ set: (value) => {
1014
+ this.#started = value;
1015
+ },
1016
+ },
1017
+ resumeScene: {
1018
+ get: () => this.#resumeScene,
1019
+ set: (value) => {
1020
+ this.#resumeScene = value;
1021
+ },
1022
+ },
1023
+ } satisfies Partial<Record<keyof IGameBootGame<TState, TPhysics>, PropertyDescriptor>>);
2708
1024
  }
1025
+
2709
1026
  pause(): void {
2710
1027
  this.#paused = true;
2711
1028
  }
@@ -2735,7 +1052,11 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2735
1052
  // once all attempts and the final leak check have completed.
2736
1053
  const failures: unknown[] = [];
2737
1054
  this.#disconnectUi();
2738
- this.#loop?.stop();
1055
+ this.#frameLoopDispose?.();
1056
+ this.#frameLoopDispose = undefined;
1057
+ // After the loop that reports into it, and reached on every path: the field is set the moment
1058
+ // the budget exists, so a launch that threw inside the frame-loop phase before it could answer
1059
+ // still loses nothing here. This is the release the un-split `#teardown` performed.
2739
1060
  this.#frameBudget?.dispose();
2740
1061
  this.#afterPhysicsPhase?.clear();
2741
1062
  this.#beforeRenderCallbacks.clear();
@@ -2762,6 +1083,15 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2762
1083
  }
2763
1084
  }
2764
1085
  this.#activePlugins = [];
1086
+ if (this.#startupDispose !== undefined) {
1087
+ const release = this.#startupDispose;
1088
+ this.#startupDispose = undefined;
1089
+ try {
1090
+ release();
1091
+ } catch (error) {
1092
+ failures.push(error);
1093
+ }
1094
+ }
2765
1095
  for (const cleanup of this.#cleanup.splice(0)) {
2766
1096
  try {
2767
1097
  cleanup();
@@ -2792,7 +1122,6 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2792
1122
  this.#scene = undefined;
2793
1123
  this.#ctx = undefined;
2794
1124
  this.#hasDepthCoupledOutput = false;
2795
- this.#loop = undefined;
2796
1125
  this.#pointerEvents?.dispose();
2797
1126
  this.#pointerEvents = undefined;
2798
1127
  this.#picker?.dispose();
@@ -2810,17 +1139,6 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2810
1139
  }
2811
1140
  }
2812
1141
 
2813
- function createRuntimeObservations(): IGameRuntimeObservations {
2814
- const contributions = new Set<IGameObservationContribution>();
2815
- return {
2816
- contribute: (contribution) => {
2817
- contributions.add(contribution);
2818
- return () => contributions.delete(contribution);
2819
- },
2820
- contributions: () => [...contributions],
2821
- };
2822
- }
2823
-
2824
1142
  export function defineGame<TState extends Record<string, unknown>, TPhysics = undefined>(
2825
1143
  config: IGameConfig<TState, TPhysics>,
2826
1144
  ): IGame<TState, TPhysics> {