@threenative/core 0.3.3 → 0.3.5

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 (182) hide show
  1. package/capabilities.json +2019 -59
  2. package/dist/{assets-CYKk2WTu.d.ts → assets-CqvE429w.d.ts} +45 -3
  3. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  4. package/dist/{canvas-layer-C1SnMoJ-.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  5. package/dist/{game-D_6r-k4Y.d.ts → game-Bj8G1wmD.d.ts} +242 -17
  6. package/dist/hot.d.ts +5 -5
  7. package/dist/index.d.ts +1131 -105
  8. package/dist/index.js +15201 -4782
  9. package/dist/model-lod-BDAUYgsS.d.ts +197 -0
  10. package/dist/playtest.d.ts +6 -4
  11. package/dist/playtest.js +84 -11
  12. package/dist/react-css.d.ts +62 -0
  13. package/dist/react-css.js +591 -0
  14. package/dist/react.d.ts +2 -2
  15. package/dist/{renderer-Cy4qeBOA.d.ts → renderer-9yEo9hPa.d.ts} +676 -21
  16. package/dist/terrain-jobs-worker.d.ts +2 -0
  17. package/dist/terrain-jobs-worker.js +130 -0
  18. package/dist/ui-layer.d.ts +5 -3
  19. package/dist/ui-layer.js +59 -8
  20. package/dist/world.d.ts +1596 -17
  21. package/dist/world.js +17035 -521
  22. package/gpl/fixtures/make_world_fixture.py +184 -0
  23. package/gpl/recipes/_common.py +11 -0
  24. package/gpl/recipes/decimate.py +11 -5
  25. package/gpl/recipes/export_world.py +699 -0
  26. package/mcp/blender-server.mjs +61 -4
  27. package/mcp/blender.mjs +3 -4
  28. package/mcp/engine-server.mjs +55 -21
  29. package/mcp/servers.mjs +4 -4
  30. package/package.json +15 -9
  31. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  32. package/patches/three@0.185.1.patch +8246 -389
  33. package/scripts/apply-three-patch.mjs +123 -41
  34. package/src/animation-blend.ts +264 -0
  35. package/src/animation-composition.ts +362 -0
  36. package/src/animation-layers.ts +260 -0
  37. package/src/animation-root-motion.ts +283 -0
  38. package/src/animation.ts +896 -0
  39. package/src/assets.ts +1303 -0
  40. package/src/atmosphere/index.ts +335 -0
  41. package/src/atmosphere/luts.ts +298 -0
  42. package/src/atmosphere/params.ts +323 -0
  43. package/src/audio.ts +912 -0
  44. package/src/billboard.ts +124 -0
  45. package/src/bone-lengths.ts +157 -0
  46. package/src/camera-shake.ts +116 -0
  47. package/src/canvas-layer.ts +47 -0
  48. package/src/clip-audit.ts +401 -0
  49. package/src/clustered-batch.ts +492 -0
  50. package/src/clustered-mesh.ts +638 -0
  51. package/src/compute-driven.ts +176 -0
  52. package/src/compute-timing.ts +318 -0
  53. package/src/config.ts +593 -0
  54. package/src/debug.ts +82 -0
  55. package/src/engine-render-hook.ts +25 -0
  56. package/src/entities.ts +79 -0
  57. package/src/entity-snapshot.ts +53 -0
  58. package/src/flight.ts +683 -0
  59. package/src/fluid-field.ts +748 -0
  60. package/src/fluid-particles.ts +1253 -0
  61. package/src/frame-budget.ts +1368 -0
  62. package/src/game.ts +2390 -0
  63. package/src/geometry-capture.ts +1098 -0
  64. package/src/gpu-class.ts +160 -0
  65. package/src/gpu-frame-observation.ts +424 -0
  66. package/src/gpu-readback.ts +143 -0
  67. package/src/gpu-scene-bvh.ts +464 -0
  68. package/src/grounding.ts +100 -0
  69. package/src/hot.ts +161 -0
  70. package/src/import-meta.d.ts +13 -0
  71. package/src/index.ts +1536 -0
  72. package/src/input.ts +690 -0
  73. package/src/instanced-batch-lod.ts +283 -0
  74. package/src/instanced-batch.ts +274 -0
  75. package/src/interpolation.ts +129 -0
  76. package/src/launch-diagnostics.ts +161 -0
  77. package/src/loop.ts +564 -0
  78. package/src/matrix-world.ts +245 -0
  79. package/src/merge-parts.ts +812 -0
  80. package/src/model-lod.ts +1315 -0
  81. package/src/net-protocol.ts +333 -0
  82. package/src/net-session.ts +477 -0
  83. package/src/net.ts +80 -0
  84. package/src/ocean/fft.ts +72 -0
  85. package/src/ocean/spectral.ts +728 -0
  86. package/src/particle-significance.ts +102 -0
  87. package/src/particles.ts +648 -0
  88. package/src/path-follow.ts +175 -0
  89. package/src/picking.ts +250 -0
  90. package/src/pipeline-census.ts +1566 -0
  91. package/src/platform.ts +210 -0
  92. package/src/playtest.ts +839 -0
  93. package/src/pointer-events.ts +411 -0
  94. package/src/pose-measure.ts +435 -0
  95. package/src/profiling/FrameCounters.ts +231 -0
  96. package/src/profiling/Spans.ts +548 -0
  97. package/src/profiling/opacity-convention.ts +21 -0
  98. package/src/profiling/render-list-validate.ts +175 -0
  99. package/src/profiling/render-trap-audit.ts +84 -0
  100. package/src/profiling/scene-warning.ts +190 -0
  101. package/src/profiling/span-probes.ts +191 -0
  102. package/src/profiling/unlit-foliage-warning.ts +149 -0
  103. package/src/projection-apply.ts +1529 -0
  104. package/src/projection-marker.ts +142 -0
  105. package/src/projection-plan.ts +1258 -0
  106. package/src/projection-skinned.ts +419 -0
  107. package/src/projection-stability.ts +409 -0
  108. package/src/projection-uniform.ts +328 -0
  109. package/src/random.ts +41 -0
  110. package/src/react-css.ts +604 -0
  111. package/src/react-glyphs.ts +114 -0
  112. package/src/react-host.ts +576 -0
  113. package/src/react-layout.ts +265 -0
  114. package/src/react.ts +60 -0
  115. package/src/render/alpha-antialiasing.ts +159 -0
  116. package/src/render/batched-velocity.ts +126 -0
  117. package/src/render/chain.ts +1021 -0
  118. package/src/render/daylight.ts +189 -0
  119. package/src/render/depth-pyramid.ts +596 -0
  120. package/src/render/foliage-alpha.ts +166 -0
  121. package/src/render/material-key.ts +60 -0
  122. package/src/render/mesh-pool.ts +144 -0
  123. package/src/render/probe-volume.ts +1668 -0
  124. package/src/render/resolution-subrect.ts +253 -0
  125. package/src/render/velocity.ts +442 -0
  126. package/src/render/virtual-shadow-pages.ts +827 -0
  127. package/src/render/virtual-shadow-partial.ts +174 -0
  128. package/src/render/virtual-shadow.ts +3330 -0
  129. package/src/render/world-impostor-surface.ts +722 -0
  130. package/src/render/world-impostor.ts +558 -0
  131. package/src/render-camera-cull.ts +441 -0
  132. package/src/render-pass-budget.ts +501 -0
  133. package/src/renderProjection.ts +758 -0
  134. package/src/renderer-config.ts +127 -0
  135. package/src/renderer.ts +1847 -0
  136. package/src/replay-protocol.ts +85 -0
  137. package/src/replay.ts +205 -0
  138. package/src/resolution-scaler.ts +819 -0
  139. package/src/rig-preparation.ts +271 -0
  140. package/src/ripple-field.ts +432 -0
  141. package/src/scale.ts +109 -0
  142. package/src/scene.ts +239 -0
  143. package/src/schedule.ts +155 -0
  144. package/src/skeletal-mesh.ts +61 -0
  145. package/src/skeleton.ts +100 -0
  146. package/src/snow-field.ts +744 -0
  147. package/src/softbody-topology.ts +269 -0
  148. package/src/softbody.ts +516 -0
  149. package/src/sprite-animator.ts +222 -0
  150. package/src/startup-readiness.ts +386 -0
  151. package/src/state.ts +66 -0
  152. package/src/static-transform.ts +274 -0
  153. package/src/storage-buffer.ts +253 -0
  154. package/src/streaming.ts +308 -0
  155. package/src/target-fps.ts +92 -0
  156. package/src/terrain-jobs-worker.ts +17 -0
  157. package/src/terrain-jobs.ts +353 -0
  158. package/src/textures.ts +39 -0
  159. package/src/tracers.ts +237 -0
  160. package/src/ui-bridge.ts +368 -0
  161. package/src/ui-hit-regions.ts +380 -0
  162. package/src/ui-layer.ts +83 -0
  163. package/src/ui-state.ts +220 -0
  164. package/src/version.ts +2 -0
  165. package/src/viewport.ts +253 -0
  166. package/src/warmup.ts +1357 -0
  167. package/src/water-surface.ts +384 -0
  168. package/src/wave-field.ts +524 -0
  169. package/src/world-capabilities.ts +131 -0
  170. package/src/world-cell-proxy.ts +392 -0
  171. package/src/world-cells.ts +10564 -0
  172. package/src/world-gpu-scene.ts +3354 -0
  173. package/src/world-heightmap.ts +82 -0
  174. package/src/world-package.ts +469 -0
  175. package/src/world-passes.ts +582 -0
  176. package/src/world-region.ts +17 -0
  177. package/src/world-terrain-splat.ts +564 -0
  178. package/src/world-tiles.ts +3826 -0
  179. package/src/world-topology.ts +370 -0
  180. package/src/world-validate.ts +48 -0
  181. package/src/world.ts +805 -0
  182. package/dist/gpu-readback-CMklJs6r.d.ts +0 -112
package/src/game.ts ADDED
@@ -0,0 +1,2390 @@
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 { CanvasLayer } from "./canvas-layer.js";
11
+ import { updateClusteredMeshes } from "./clustered-mesh.js";
12
+ import { ComputeDrivenRegistry, isComputeDriven } from "./compute-driven.js";
13
+ import type { IThreeNativeConfig } from "./config.js";
14
+ import { type EntitySnapshot, Registry } from "./entities.js";
15
+ import { FrameBudget, type IFrameBudgetOptions, type IFrameBudgetWindow } from "./frame-budget.js";
16
+ import {
17
+ GeometryCapture,
18
+ type IGeometryCaptureReport,
19
+ type IGeometryCaptureRequest,
20
+ rendererBackendIdentity,
21
+ } from "./geometry-capture.js";
22
+ import { type ContextMenuPolicy, type InputBindings, InputMap } from "./input.js";
23
+ import { PhysicsInterpolation } from "./interpolation.js";
24
+ import { reportLaunchFailure, watchDeviceLoss, watchStartupStall } from "./launch-diagnostics.js";
25
+ import {
26
+ FixedStepLoop,
27
+ type IAfterPhysicsPhase,
28
+ type IRenderPerformanceMetrics,
29
+ type IRenderPerformanceSample,
30
+ createAfterPhysicsPhase,
31
+ } from "./loop.js";
32
+ import { MatrixWorldPass } from "./matrix-world.js";
33
+ import { updateModelLods } from "./model-lod.js";
34
+ import { ScenePicker } from "./picking.js";
35
+ import type { IPipelineCensus } from "./pipeline-census.js";
36
+ import { getPlatform } from "./platform.js";
37
+ import { PointerEvents3D } from "./pointer-events.js";
38
+ import { FrameCounters, counterDeviceOf } from "./profiling/FrameCounters.js";
39
+ import {
40
+ SPANS,
41
+ SpanRecorder,
42
+ addSpan,
43
+ beginSpan,
44
+ endSpan,
45
+ formatSpansWindow,
46
+ setSpanRecorder,
47
+ spanNow,
48
+ spansRequested,
49
+ } from "./profiling/Spans.js";
50
+ import { applyOpacityConvention } from "./profiling/opacity-convention.js";
51
+ import {
52
+ RenderListValidator,
53
+ formatValidationReport,
54
+ renderListValidationRequested,
55
+ } from "./profiling/render-list-validate.js";
56
+ import { renderTrapAudit } from "./profiling/render-trap-audit.js";
57
+ import {
58
+ describeSceneShape,
59
+ describeSceneWarning,
60
+ formatSceneWarning,
61
+ sceneWarning,
62
+ } from "./profiling/scene-warning.js";
63
+ import { installSpanProbes } from "./profiling/span-probes.js";
64
+ import {
65
+ UNLIT_FOLIAGE_FIX,
66
+ formatUnlitFoliageWarning,
67
+ unlitFoliageWarning,
68
+ } from "./profiling/unlit-foliage-warning.js";
69
+ import { formatProjectionWindow } from "./projection-marker.js";
70
+ import { type IRandom, createRandom } from "./random.js";
71
+ import { RenderCameraCull } from "./render-camera-cull.js";
72
+ import { RenderPassBudget } from "./render-pass-budget.js";
73
+ import { SceneRenderProjection } from "./renderProjection.js";
74
+ import {
75
+ resolveMatrixWorldMode,
76
+ resolvePlatformResolutionFloor,
77
+ resolveRendererAlphaAntialiasing,
78
+ resolveRendererAntialias,
79
+ resolveRendererScaleSetting,
80
+ } from "./renderer-config.js";
81
+ import {
82
+ type IRendererLike,
83
+ type IRendererOptions,
84
+ type RendererKind,
85
+ createRenderer,
86
+ } from "./renderer.js";
87
+ import { RESOLUTION_SCALER, ResolutionScaler } from "./resolution-scaler.js";
88
+ import type {
89
+ ICtx,
90
+ IStartupStatus,
91
+ IStartupTimeline,
92
+ Scene,
93
+ SceneConstructor,
94
+ SceneFrame,
95
+ } from "./scene.js";
96
+ import { Scheduler } from "./schedule.js";
97
+ import {
98
+ STARTUP_COMPILE_BUDGET_MS,
99
+ STARTUP_STALL_MS,
100
+ type StartupCompile,
101
+ StartupReadiness,
102
+ } from "./startup-readiness.js";
103
+ import { type GameStore, createGameStore } from "./state.js";
104
+ import {
105
+ STATIC_TRANSFORM_MARKER,
106
+ refreshStaticTransforms,
107
+ staticRoots,
108
+ staticTransformCensus,
109
+ } from "./static-transform.js";
110
+ import { resolveTargetFps } from "./target-fps.js";
111
+ import {
112
+ type IUiBridge,
113
+ UI_DEV_METRICS_MESSAGE,
114
+ UI_READY_INTENT,
115
+ connectUiBridge,
116
+ } from "./ui-bridge.js";
117
+ import { type IUiStatePublisher, onUiIntent, publishUiState } from "./ui-state.js";
118
+ import { type IViewportOptions, Viewport } from "./viewport.js";
119
+ import {
120
+ type IWarmUpOptions,
121
+ type IWarmUpReport,
122
+ warmUpComputeNodes,
123
+ warmUpScene,
124
+ } from "./warmup.js";
125
+
126
+ export type PluginCleanup = () => void;
127
+
128
+ export interface IGameObservationSampleRequest {
129
+ readonly entities?: readonly string[];
130
+ /** Asks for one armed per-object geometry capture. Absent means no capture is collected. */
131
+ readonly geometry?: IGeometryCaptureRequest;
132
+ readonly include?: readonly string[];
133
+ readonly label?: string;
134
+ readonly resources?: readonly string[];
135
+ }
136
+
137
+ export interface IGameObservationContribution {
138
+ readonly capabilities: readonly string[];
139
+ /**
140
+ * May answer a promise: an observation that has to wait for the renderer — a geometry capture
141
+ * waits for one presented world frame — cannot be produced inside the request that asked for it.
142
+ */
143
+ readonly sample: (
144
+ request: IGameObservationSampleRequest,
145
+ ) => Readonly<Record<string, unknown>> | Promise<Readonly<Record<string, unknown>>>;
146
+ }
147
+
148
+ export interface IGameRuntimeObservations {
149
+ contribute(contribution: IGameObservationContribution): PluginCleanup;
150
+ contributions(): readonly IGameObservationContribution[];
151
+ }
152
+
153
+ export interface IGamePluginRuntime {
154
+ readonly fixedStep: (ticks: number, options?: { render?: boolean }) => number;
155
+ /** Completed scene updates and primary world render requests, independent of budget windows. */
156
+ readonly frameCounts?: () => { updates: number; renders: number };
157
+ /**
158
+ * Announces that a diagnostics consumer is going to read render metrics, turning per-frame
159
+ * sample collection on for the rest of the run. Optional: a runtime without collection
160
+ * support just never enables. Games collect nothing until this fires — the samples exist for
161
+ * assertions, not for every frame of every game.
162
+ */
163
+ readonly enableRuntimeDiagnostics?: () => void;
164
+ /** The frame's cost attribution so far, or undefined when the game turned the budget off. */
165
+ readonly frameBudgetWindow?: () => IFrameBudgetWindow | undefined;
166
+ /**
167
+ * Stop the live clock, so a rendered frame simulates nothing and banks no wall-clock time.
168
+ *
169
+ * A run that counts fixed-step ticks must not also accumulate real seconds into the same
170
+ * simulation, and the frames before its first `advance()` are exactly where a boot's seconds
171
+ * used to land. Optional: a runtime without a clock just never freezes one.
172
+ */
173
+ readonly freezeClock?: () => void;
174
+ /**
175
+ * Draw the current world once without advancing it, for a screenshot taken while the loop is
176
+ * driven by `fixedStep` and presents nothing between ticks. Optional: a runtime without a frozen
177
+ * render loop just never draws a standing frame. The runner asks for it only when the bridge
178
+ * advertises it and the capture cannot otherwise see a present.
179
+ */
180
+ readonly renderCurrent?: () => number;
181
+ /**
182
+ * Hold start-scene entry until `gate` settles.
183
+ *
184
+ * The returned promise settles after the scene that owns the world has entered: the start scene
185
+ * unless it navigated out of its own `enter()`, in which case it is the scene it navigated to,
186
+ * loaded and entered. A runner can therefore release the gate after applying pre-entry setup,
187
+ * then await the returned promise before describing entity-derived capabilities — the entities
188
+ * they read are the ones the world actually has. The frame loop remains held throughout.
189
+ */
190
+ readonly holdStart?: (gate: Promise<void>) => Promise<void>;
191
+ readonly observations: IGameRuntimeObservations;
192
+ readonly tick: () => number;
193
+ readonly runtimeDiagnosticsSeries?: () => readonly IRenderPerformanceSample[];
194
+ readonly random?: Pick<IRandom, "state">;
195
+ rapier?: string | null;
196
+ readonly seed: number | null;
197
+ /**
198
+ * Whether first-use compilation has settled, separately from full readiness.
199
+ *
200
+ * Readiness also requires a sustained in-budget frame window, which is a player-experience
201
+ * gate — a CPU rasteriser never meets it and resolves on the window's own timeout instead. A
202
+ * harness that has been told the machine has no GPU needs the earlier, cheaper signal, and it
203
+ * must be reported rather than inferred from a phase that cannot distinguish the two.
204
+ */
205
+ readonly startupCompileSettled?: () => boolean;
206
+ /** When the startup milestones happened, for the playtest bridge's startup observation. */
207
+ readonly startupTimeline?: () => IStartupTimeline;
208
+ /** The renderer-owned bounded pipeline capture, when the renderer has not been opted out. */
209
+ readonly pipelineCensus?: () => IPipelineCensus;
210
+ /**
211
+ * Arms one per-object geometry capture and answers its report after the next presented world
212
+ * frame. Absent on a runtime with no render loop to arm.
213
+ */
214
+ readonly geometryCapture?: (request?: IGeometryCaptureRequest) => Promise<IGeometryCaptureReport>;
215
+ readonly step: number;
216
+ }
217
+
218
+ interface IDevTools {
219
+ snapshot(): EntitySnapshot;
220
+ /**
221
+ * Arms one per-object geometry capture for a development overlay. Absent until the game has a
222
+ * render loop; the overlay treats that as "not ready", never as an empty scene.
223
+ */
224
+ geometry?(request?: IGeometryCaptureRequest): Promise<IGeometryCaptureReport>;
225
+ }
226
+
227
+ type DevToolsHost = Record<string, unknown> & Partial<Record<"__THREENATIVE__", IDevTools>>;
228
+
229
+ export interface IGamePlatformSource {
230
+ readonly devToolsHost?: Record<string, unknown>;
231
+ readonly input: NonNullable<ConstructorParameters<typeof InputMap>[3]>;
232
+ readonly inputTarget?: EventTarget;
233
+ readonly renderer: NonNullable<IRendererOptions["source"]>;
234
+ readonly viewport: NonNullable<IViewportOptions["source"]>;
235
+ mountCanvas(canvas: HTMLCanvasElement, container?: HTMLElement): void;
236
+ unmountCanvas(canvas: HTMLCanvasElement): void;
237
+ }
238
+
239
+ /**
240
+ * Whether this launch is a development one.
241
+ *
242
+ * A web build answers through Vite's own flag. A native build has no bundler flag at launch, so the
243
+ * host publishes `DEV_MODE` on `process.env` — the one place a game can read how it was started —
244
+ * and this reads it. Both routes answer the same question: should the dev surfaces exist.
245
+ */
246
+ /**
247
+ * The bundler's dev flag.
248
+ *
249
+ * The `import.meta.env` access must stay written out exactly here. Vite replaces that member
250
+ * expression at build time; any indirection — a variable holding `import.meta`, or a helper that
251
+ * takes it as an argument — survives into the bundle, where the game is compiled as a script and
252
+ * not a module, and the whole bundle then fails to parse with "Cannot use 'import.meta' outside a
253
+ * module". That is a game that never starts, so the literal access is load-bearing, not style.
254
+ */
255
+ function bundlerDevFlag(): boolean {
256
+ // quality-allow: DEV is the bundler's own name for the flag, so the name rule cannot apply.
257
+ // biome-ignore lint/style/useNamingConvention: the bundler's own flag name.
258
+ return (import.meta as unknown as { env?: { DEV?: boolean } }).env?.DEV === true;
259
+ }
260
+
261
+ function isDevLaunch(): boolean {
262
+ // `process.env` exists only where a host installed one: the native runtime does, a browser
263
+ // bundle does not. Narrowed rather than asserted, so a host that installs something else
264
+ // answers "not dev" instead of reading a field that is not there.
265
+ const scope: unknown = globalThis;
266
+ if (typeof scope === "object" && scope !== null && "process" in scope) {
267
+ const hostProcess: unknown = scope.process;
268
+ if (typeof hostProcess === "object" && hostProcess !== null && "env" in hostProcess) {
269
+ const env: unknown = hostProcess.env;
270
+ if (typeof env === "object" && env !== null && "DEV_MODE" in env) {
271
+ const flag: unknown = env.DEV_MODE;
272
+ if (typeof flag === "string" && flag !== "" && flag !== "0" && flag !== "false")
273
+ return true;
274
+ }
275
+ }
276
+ }
277
+ return bundlerDevFlag();
278
+ }
279
+
280
+ function installDevTools(
281
+ entities: Registry,
282
+ host: DevToolsHost | undefined,
283
+ // Late-bound: the capture is constructed with the render loop, after this install runs.
284
+ geometry: () => GeometryCapture | undefined,
285
+ ): PluginCleanup {
286
+ // Written out here, not through `isDevLaunch()`: the bundler must see the literal flag to strip
287
+ // this whole install from a production build, and a runtime `DEV_MODE` check cannot be stripped.
288
+ const isDev =
289
+ (import.meta as ImportMeta & { env?: Record<"DEV", boolean | undefined> }).env?.DEV === true;
290
+ if (!isDev || host === undefined) return () => undefined;
291
+ const devTools: IDevTools = {
292
+ ...(host.__THREENATIVE__ as (IDevTools & Record<string, unknown>) | undefined),
293
+ geometry: async (request) => {
294
+ const capture = geometry();
295
+ if (capture === undefined) {
296
+ return {
297
+ reason: "TN_GEOMETRY_CAPTURE_NO_LOOP: the game has no running render loop to capture.",
298
+ status: "unavailable",
299
+ };
300
+ }
301
+ return capture.request(request);
302
+ },
303
+ snapshot: () => entities.snapshot(),
304
+ };
305
+ host.__THREENATIVE__ = devTools;
306
+ return () => {
307
+ if (host.__THREENATIVE__ !== devTools) return;
308
+ const remaining = Object.fromEntries(
309
+ Object.entries(devTools).filter(([key]) => key !== "snapshot" && key !== "geometry"),
310
+ );
311
+ host.__THREENATIVE__ =
312
+ // quality-allow: what other dev tools left on the shared global after this game removed its own.
313
+ Object.keys(remaining).length === 0 ? undefined : (remaining as unknown as IDevTools);
314
+ };
315
+ }
316
+
317
+ export type GamePluginFunction<
318
+ TState extends Record<string, unknown> = Record<string, unknown>,
319
+ TPhysics = undefined,
320
+ > = (ctx: ICtx<TState, TPhysics>) => undefined | PluginCleanup;
321
+
322
+ export interface IGamePluginHooks<
323
+ TState extends Record<string, unknown> = Record<string, unknown>,
324
+ TPhysics = undefined,
325
+ > {
326
+ setup?(
327
+ ctx: ICtx<TState, TPhysics>,
328
+ runtime?: IGamePluginRuntime,
329
+ ): undefined | PluginCleanup | Promise<undefined | PluginCleanup>;
330
+ beforeUpdate?(ctx: ICtx<TState, TPhysics>, dt: number): void;
331
+ update?(ctx: ICtx<TState, TPhysics>, dt: number): void;
332
+ sceneExit?(ctx: ICtx<TState, TPhysics>): void;
333
+ dispose?(ctx: ICtx<TState, TPhysics>): void;
334
+ }
335
+
336
+ export type GamePlugin<
337
+ TState extends Record<string, unknown> = Record<string, unknown>,
338
+ TPhysics = undefined,
339
+ > = GamePluginFunction<TState, TPhysics> | IGamePluginHooks<TState, TPhysics>;
340
+
341
+ /**
342
+ * The global a native host reads to know the world is on screen. Named here rather than written
343
+ * inline so the host and the framework agree on one spelling.
344
+ */
345
+ const STARTUP_READY_GLOBAL = "__TN_STARTUP_READY__";
346
+
347
+ export interface IGameConfig<
348
+ TState extends Record<string, unknown> = Record<string, unknown>,
349
+ TPhysics = undefined,
350
+ > {
351
+ readonly assets?: IAssetLoaderOptions;
352
+ readonly camera?: CameraConfig;
353
+ readonly canvas?: HTMLCanvasElement;
354
+ readonly container?: HTMLElement;
355
+ readonly input?: InputBindings;
356
+ /**
357
+ * Browser context menu over the game surface. Defaults to `"suppress"`, which is what a game
358
+ * wants: right-click is a binding, not a menu. Set `"allow"` only if your game genuinely needs
359
+ * the browser menu over its canvas.
360
+ */
361
+ readonly contextMenu?: ContextMenuPolicy;
362
+ /**
363
+ * Per-frame cost attribution, on by default. Every `reportEvery` presented frames the game
364
+ * prints one `TN_FRAME_BUDGET` line naming where the frame went — present wait, simulation,
365
+ * three.js render, overlay, the rest — which is what a device lane reads instead of guessing.
366
+ * Pass `false` to silence the marker; the same numbers still reach a playtest `performance`
367
+ * assertion, because turning a convention off must not turn its measurement off.
368
+ */
369
+ readonly frameBudget?: IFrameBudgetOptions | false;
370
+ readonly initialState?: TState;
371
+ /**
372
+ * The **pre-start** shader warm-up. Off by default, and that is not the same as no warm-up.
373
+ *
374
+ * Every distinct pipeline is otherwise built the first time something using it is drawn, inside
375
+ * the first rendered frame of a fully built scene. On a Pixel 8 that frame lasted **12.0 s, of
376
+ * which 8.0 s was 105 pipeline compiles** — a launch the player reads as a hang, because the
377
+ * loop presents nothing for the whole span. Warming those pipelines while the loading screen is
378
+ * up is the obvious fix, and it is the one this option exists for.
379
+ *
380
+ * **A game with this unset still warms up.** `startupCompile` runs the same `warmUpScene` from
381
+ * inside the loading layer's bounded readiness gate, where the opaque layer is on screen and the
382
+ * loop is turning. This option only moves that work *earlier*, to before `start()` releases the
383
+ * loop, where nothing is presenting — which is a thing to choose deliberately, not a default.
384
+ *
385
+ * **What PRD-327 changed is the mechanism, not this default.** The native host used to answer
386
+ * `createRenderPipelineAsync` with the synchronous create wrapped in a resolved promise, so
387
+ * `compileAsync` compiled on the main loop and was abandoned by its own budget having finished
388
+ * nothing — `TN_WARMUP:{"compiled":0,"abandoned":1,"timedOut":true,"elapsedMs":15325}` — while
389
+ * the first frame compiled the identical pipelines in 8.0 s anyway. Both entries are native
390
+ * handlers now, handing the descriptor to a host compile pool and holding the main thread for
391
+ * 0.27 ms of a 70 ms compile (ratio 0.0038 against a pre-registered bar of 0.25, asserted by
392
+ * `threenative-async-pipeline-thread-test`). The default path started working without its
393
+ * default moving.
394
+ *
395
+ * Pass `{}` or an options object to opt in, or `false` to opt out of warm-up entirely. Either
396
+ * way `TN_WARMUP` and `TN_STARTUP_WARMUP` report what happened, because turning a convention off
397
+ * must not turn its measurement off.
398
+ */
399
+ readonly warmUp?: IWarmUpOptions | false | true;
400
+ readonly inputTarget?: EventTarget;
401
+ /**
402
+ * Maximum simulation steps per rendered frame. Default 5. Caps the catch-up burst after a
403
+ * stall so a slow frame cannot cascade into a spiral of longer frames.
404
+ */
405
+ /** Smooth physics objects and the camera between fixed ticks. Default true. */
406
+ readonly physicsInterpolation?: boolean;
407
+ readonly maxSteps?: number;
408
+ readonly platform?: IGamePlatformSource;
409
+ readonly plugins?: readonly GamePlugin<TState, TPhysics>[];
410
+ /**
411
+ * The project's `display` block, passed straight through from `threenative.config.ts`. The
412
+ * adaptive scale holds `maxFps` as its budget, so a game that does not pass this gets the
413
+ * 60 fps default rather than a scaler with no target.
414
+ */
415
+ readonly display?: NonNullable<IThreeNativeConfig["display"]>;
416
+ readonly render?: NonNullable<IThreeNativeConfig["renderer"]>;
417
+ readonly renderer?: IRendererOptions;
418
+ readonly seed?: number;
419
+ readonly scenes: Record<string, SceneConstructor<TState, TPhysics>>;
420
+ /**
421
+ * Fixed simulation step in seconds, e.g. `1 / 60`. **This is the fixed-step knob a game
422
+ * wants**; every `update(ctx, dt)` receives exactly this `dt`, never a variable frame time,
423
+ * so gameplay and physics advance together and never see a stall.
424
+ *
425
+ * Do not write your own accumulator on top of this. Doing so runs the scene's update several
426
+ * times per already-fixed step and decouples gameplay from the simulation — a real build lost
427
+ * its largest wrong turn to exactly that, because this field carried no documentation.
428
+ */
429
+ readonly step?: number;
430
+ readonly start: string;
431
+ /** Optional slower UI publication interval. Omitted publishes once per rendered frame. */
432
+ readonly stateFlushMs?: number;
433
+ }
434
+
435
+ export interface IPerspectiveCameraConfig {
436
+ readonly projection: "perspective";
437
+ readonly fov?: number;
438
+ readonly near?: number;
439
+ readonly far?: number;
440
+ }
441
+
442
+ export interface IOrthogonalCameraConfig {
443
+ readonly projection: "orthogonal";
444
+ readonly size: number;
445
+ readonly near?: number;
446
+ readonly far?: number;
447
+ }
448
+
449
+ export type CameraConfig = IPerspectiveCameraConfig | IOrthogonalCameraConfig;
450
+
451
+ /**
452
+ * The game's end of the UI bridge.
453
+ *
454
+ * The UI renders through the platform's own browser-class renderer, which on every native
455
+ * target is a different realm from this one — so it holds a mirror of the game's published
456
+ * state and sends intents back rather than calling into the game. The web target uses the same
457
+ * two channels through an in-process broker, which is what keeps one `src/ui/` honest: a HUD
458
+ * that works here works on a phone.
459
+ *
460
+ * Publication is automatic at the rendered frame cadence (or the named stateFlushMs override), and it stops
461
+ * entirely when nothing is listening — a game whose `ui.renderer` is `native` pays nothing.
462
+ */
463
+ export interface IGameUi {
464
+ /**
465
+ * Whether a UI layer has announced itself.
466
+ *
467
+ * Stricter than "a transport exists": the UI sends `tn:ready` once its tree has rendered and its
468
+ * interactive rectangles are published, and only then is this true. A transport with nothing on
469
+ * the other end and a UI that failed to render look the same to a game otherwise.
470
+ */
471
+ readonly connected: boolean;
472
+ /** Handle an intent the UI sent — `restart`, `pause`, whatever the game defines. */
473
+ onIntent(listener: (intent: string, payload: unknown) => void): () => void;
474
+ /** Publish the current state now, whether or not it changed. */
475
+ publish(): void;
476
+ }
477
+
478
+ export interface IGotoOptions<TState extends Record<string, unknown>> {
479
+ readonly carry?: Partial<TState>;
480
+ }
481
+
482
+ export interface IGame<
483
+ TState extends Record<string, unknown> = Record<string, unknown>,
484
+ TPhysics = undefined,
485
+ > {
486
+ readonly ctx: ICtx<TState, TPhysics> | undefined;
487
+ readonly scene: Scene<TState, TPhysics> | undefined;
488
+ /** The name of the entered scene, or undefined before `start()`. */
489
+ readonly sceneName: string | undefined;
490
+ readonly state: GameStore<TState>;
491
+ /** The seam between the game and its UI layer, on every target. @see IGameUi */
492
+ readonly ui: IGameUi;
493
+ /** Rebuilds the requested scene from its initial state, then merges an optional carry patch. */
494
+ goto(name: string, options?: IGotoOptions<TState>): Promise<void>;
495
+ /** Boot into `name` instead of `config.start` on the next `start()`. Hot reload's restore path. */
496
+ resumeScene(name: string): void;
497
+ start(): Promise<void>;
498
+ pause(): void;
499
+ resume(): void;
500
+ stop(): void;
501
+ }
502
+
503
+ function positiveCameraValue(name: string, value: number): number {
504
+ if (!Number.isFinite(value) || value <= 0)
505
+ throw new Error(`camera.${name} must be finite and positive.`);
506
+ return value;
507
+ }
508
+
509
+ function assertJsonSafe(value: unknown, path = "$", seen = new WeakSet<object>()): void {
510
+ if (value === null || typeof value === "string" || typeof value === "boolean") return;
511
+ if (typeof value === "number") {
512
+ if (Number.isFinite(value)) return;
513
+ throw new TypeError(`${path} must contain only finite JSON numbers.`);
514
+ }
515
+ if (typeof value === "object") {
516
+ if (seen.has(value)) throw new TypeError(`${path} must be JSON-safe and cannot be cyclic.`);
517
+ seen.add(value);
518
+ if (Array.isArray(value)) {
519
+ if (Object.getPrototypeOf(value) !== Array.prototype) {
520
+ throw new TypeError(`${path} must be a JSON-safe array.`);
521
+ }
522
+ for (let index = 0; index < value.length; index += 1) {
523
+ assertJsonSafe(value[index], `${path}[${index}]`, seen);
524
+ }
525
+ seen.delete(value);
526
+ return;
527
+ }
528
+ const prototype = Object.getPrototypeOf(value);
529
+ if (prototype !== Object.prototype && prototype !== null) {
530
+ throw new TypeError(`${path} must be a JSON-safe plain object.`);
531
+ }
532
+ for (const [key, item] of Object.entries(value)) assertJsonSafe(item, `${path}.${key}`, seen);
533
+ seen.delete(value);
534
+ return;
535
+ }
536
+ throw new TypeError(`${path} must be JSON-safe.`);
537
+ }
538
+
539
+ function assertCarry(value: unknown): asserts value is Record<string, unknown> {
540
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
541
+ throw new TypeError("goto carry must be a JSON object.");
542
+ }
543
+ assertJsonSafe(value, "$.carry");
544
+ }
545
+
546
+ function validateCameraConfig(config: CameraConfig | undefined): void {
547
+ if (config === undefined) return;
548
+ const near = positiveCameraValue("near", config.near ?? 0.1);
549
+ const far = positiveCameraValue("far", config.far ?? 2_000);
550
+ if (far <= near) throw new Error("camera.far must be greater than camera.near.");
551
+ if (config.projection === "perspective") {
552
+ const fov = config.fov ?? 60;
553
+ if (!Number.isFinite(fov) || fov <= 0 || fov >= 180)
554
+ throw new Error("camera.fov must be finite and between 0 and 180 degrees.");
555
+ return;
556
+ }
557
+ positiveCameraValue("size", config.size);
558
+ }
559
+
560
+ function clearScene(scene: ThreeScene, computeDriven: ComputeDrivenRegistry): void {
561
+ computeDriven.clear();
562
+ scene.clear();
563
+ scene.background = null;
564
+ scene.environment = null;
565
+ scene.fog = null;
566
+ }
567
+
568
+ /** The measured draw count on its own, for the projection line that reads it every frame. */
569
+ function rendererDrawCallCount(raw: unknown): number | undefined {
570
+ if (typeof raw !== "object" || raw === null) return undefined;
571
+ const info = (raw as { info?: unknown }).info;
572
+ if (typeof info !== "object" || info === null) return undefined;
573
+ const render = (info as { render?: unknown }).render;
574
+ if (typeof render !== "object" || render === null) return undefined;
575
+ const drawCalls = (render as { drawCalls?: unknown }).drawCalls;
576
+ const calls = drawCalls ?? (render as { calls?: unknown }).calls;
577
+ return typeof calls === "number" && Number.isFinite(calls) && calls >= 0 ? calls : undefined;
578
+ }
579
+
580
+ /** Cumulative render() calls the renderer declined to draw (the Wasm web engine's frame gate), when it counts them. */
581
+ function rendererFrameGateSkips(raw: unknown): number | undefined {
582
+ const info = (raw as { info?: { engine?: { frameGateSkips?: unknown } } } | null)?.info;
583
+ const skips = info?.engine?.frameGateSkips;
584
+ return typeof skips === "number" && Number.isFinite(skips) ? skips : undefined;
585
+ }
586
+
587
+ function rendererPerformanceMetrics(raw: unknown): {
588
+ drawCalls?: number;
589
+ triangles?: number;
590
+ } {
591
+ if (typeof raw !== "object" || raw === null) return {};
592
+ const info = (raw as { info?: unknown }).info;
593
+ if (typeof info !== "object" || info === null) return {};
594
+ const render = (info as { render?: unknown }).render;
595
+ if (typeof render !== "object" || render === null) return {};
596
+ const triangles = (render as { triangles?: unknown }).triangles;
597
+ const drawCalls = rendererDrawCallCount(raw);
598
+ return {
599
+ ...(drawCalls === undefined ? {} : { drawCalls }),
600
+ ...(typeof triangles === "number" && Number.isFinite(triangles) && triangles >= 0
601
+ ? { triangles }
602
+ : {}),
603
+ };
604
+ }
605
+
606
+ function resetRendererPerformanceMetrics(raw: unknown): void {
607
+ if (typeof raw !== "object" || raw === null) return;
608
+ const info = (raw as { info?: unknown }).info;
609
+ if (typeof info !== "object" || info === null) return;
610
+ const reset = (info as { reset?: unknown }).reset;
611
+ if (typeof reset === "function") reset.call(info);
612
+ }
613
+
614
+ /**
615
+ * One frame's two render calls, combined.
616
+ *
617
+ * The two renderers' `info` do not mean the same thing, and the old sum only ever held for one of
618
+ * them. `WebGLRenderer` ends every `render()` with `info.reset()`, so the world sample and the
619
+ * overlay sample are disjoint and add up. WebGPU never resets: the engine owns the
620
+ * requestAnimationFrame loop, so it calls `info.reset()` itself once per frame before the world
621
+ * draw (see the render block), which leaves the overlay sample *cumulative* — world plus overlay.
622
+ * Adding it to the world sample reported every world draw twice, and the packed racing scenario
623
+ * read 358 draw calls against a 330 ceiling on a frame that submits far fewer.
624
+ *
625
+ * The world pass split belongs to the world call in both renderers and rides the same sample, so
626
+ * it is carried across rather than summed — a summed split attributes the world's shadow and
627
+ * reflection passes to the overlay too.
628
+ */
629
+ function combineRenderPerformanceMetrics(
630
+ kind: RendererKind,
631
+ world: IRenderPerformanceMetrics | undefined,
632
+ overlay: IRenderPerformanceMetrics,
633
+ ): IRenderPerformanceMetrics {
634
+ const passes = world?.passes;
635
+ if (kind === "webgpu") {
636
+ return passes === undefined ? overlay : { ...overlay, passes };
637
+ }
638
+ if (world === undefined) return overlay;
639
+ return {
640
+ ...(world.drawCalls === undefined || overlay.drawCalls === undefined
641
+ ? {}
642
+ : { drawCalls: world.drawCalls + overlay.drawCalls }),
643
+ ...(world.triangles === undefined || overlay.triangles === undefined
644
+ ? {}
645
+ : { triangles: world.triangles + overlay.triangles }),
646
+ ...(passes === undefined ? {} : { passes }),
647
+ };
648
+ }
649
+
650
+ function createCamera(config: CameraConfig | undefined): Camera {
651
+ if (config === undefined) return new PerspectiveCamera(60, 1, 0.1, 2_000);
652
+ validateCameraConfig(config);
653
+ const near = config.near ?? 0.1;
654
+ const far = config.far ?? 2_000;
655
+ if (config.projection === "perspective")
656
+ return new PerspectiveCamera(config.fov ?? 60, 1, near, far);
657
+ const size = config.size;
658
+ return new OrthographicCamera(-size, size, size, -size, near, far);
659
+ }
660
+
661
+ class GameImpl<TState extends Record<string, unknown>, TPhysics>
662
+ implements IGame<TState, TPhysics>
663
+ {
664
+ #config: IGameConfig<TState, TPhysics>;
665
+
666
+ /**
667
+ * Whether the caller asked for the pre-start warm-up *by hand*.
668
+ *
669
+ * PRD-327 Phase 2 proposed flipping this default on for native. Executing it showed the
670
+ * prescription was wrong, and the reason is worth keeping: **the framework already warms up by
671
+ * default, in a better place.** `startupCompile` below calls the same `warmUpScene`, but from
672
+ * inside the loading layer's readiness gate — opaque layer on screen, loop turning — whereas the
673
+ * pre-start block runs before `start()` releases the loop, with nothing presenting.
674
+ *
675
+ * What was actually broken was the mechanism, not the default: `compileAsync` could not resolve
676
+ * on native because `createRenderPipelineAsync` was the synchronous create wrapped in a resolved
677
+ * promise, so the default path compiled nothing and reported
678
+ * `{"compiled":0,"abandoned":1,"timedOut":true}`. Phase 1 fixed that, and the default path
679
+ * started working without its default moving.
680
+ *
681
+ * Flipping it anyway cost two regressions CI caught and a local run did not: the loading screen
682
+ * stopped covering startup (`verify-desktop-loading.mjs`: `loadingVisible: false` at every
683
+ * startup sample, on macOS and Windows), and the scene then compiled twice — once before the
684
+ * loop and once inside the gate — which pushed `verify-desktop-physics.mjs` past its 180-frame
685
+ * budget on macOS. Both are gone with the default back where it was.
686
+ */
687
+ #warmUpConfiguredExplicitly(): boolean {
688
+ return this.#config.warmUp !== undefined && this.#config.warmUp !== false;
689
+ }
690
+
691
+ /** The warm-up options for the pre-start block, once an explicit opt-in has asked for it. */
692
+ #warmUpOptions(): IWarmUpOptions {
693
+ const configured = this.#config.warmUp;
694
+ return configured === undefined || configured === true || configured === false
695
+ ? {}
696
+ : configured;
697
+ }
698
+ #ctx: ICtx<TState, TPhysics> | undefined;
699
+ #scene: Scene<TState, TPhysics> | undefined;
700
+ /** The name of the scene currently entered. Carried across a hot update so a reload resumes
701
+ * where the session was, instead of restoring the game's state into its start scene. */
702
+ #sceneName: string | undefined;
703
+ #resumeScene: string | undefined;
704
+ #sceneFrame: SceneFrame<TState, TPhysics> | undefined;
705
+ #renderer: IRendererLike | undefined;
706
+ #viewport: Viewport | undefined;
707
+ #input: InputMap | undefined;
708
+ #state: GameStore<TState>;
709
+ #initialState: TState;
710
+ #loop: FixedStepLoop | undefined;
711
+ #interpolation: PhysicsInterpolation | undefined;
712
+ #projection: SceneRenderProjection | undefined;
713
+ #cameraCull: RenderCameraCull | undefined;
714
+ #matrixWorld: MatrixWorldPass | undefined;
715
+ #cleanup: Array<() => void> = [];
716
+ #computeDriven = new ComputeDrivenRegistry();
717
+ #entities: Registry | undefined;
718
+ #picker: ScenePicker | undefined;
719
+ #pointerEvents: PointerEvents3D | undefined;
720
+ #scheduler: Scheduler | undefined;
721
+ #afterPhysicsPhase: IAfterPhysicsPhase | undefined;
722
+ // Unlike afterPhysics, this seam's frame boundary is the world-render block below, so it is a
723
+ // plain scene-owned set rather than a phase on the loop.
724
+ #beforeRenderCallbacks = new Set<() => void>();
725
+ // Reused snapshot buffers, one per nesting depth, so a steady frame allocates no callback array.
726
+ #beforeRenderSnapshots: Array<Array<() => void>> = [];
727
+ #beforeRenderDepth = 0;
728
+ #frameBudget: FrameBudget | undefined;
729
+ #geometryCapture: GeometryCapture | undefined;
730
+ /** Bumped on every scene change, so a row id is stable exactly as long as the scene is. */
731
+ #sceneGeneration = 0;
732
+ #activePlugins: Array<IGamePluginHooks<TState, TPhysics>> = [];
733
+ #disposedPlugins = new Set<IGamePluginHooks<TState, TPhysics>>();
734
+ #pendingStart: Promise<void> | undefined;
735
+ #aborted = false;
736
+ #sceneEntered = false;
737
+ /**
738
+ * The scene a `goto()` is loading right now, or undefined when none is.
739
+ *
740
+ * Between a `goto()` and its `enter()` the registry is cleared and nothing owns the world, so a
741
+ * reader that needs the world's entities has to wait for this rather than for the scene it
742
+ * navigated from. The playtest handshake reads exactly that.
743
+ */
744
+ #pendingSceneEnter: Promise<void> | undefined;
745
+ #paused = false;
746
+ #started = false;
747
+ #uiBridge: IUiBridge | undefined;
748
+ #uiPublisher: IUiStatePublisher | undefined;
749
+ #uiReady = false;
750
+ // Flipped only by a diagnostics consumer announcing itself; see enableRuntimeDiagnostics().
751
+ #renderMetricsEnabled = false;
752
+ // Depth-coupled output needs the scene hook before its pass; ordinary scenes retain the
753
+ // historical after-render hook so an atmosphere-free game has the same render path as HEAD.
754
+ #hasDepthCoupledOutput = false;
755
+
756
+ constructor(config: IGameConfig<TState, TPhysics>) {
757
+ this.#config = config;
758
+ validateCameraConfig(config.camera);
759
+ const startScene = this.#config.scenes[this.#config.start];
760
+ if (startScene === undefined) throw new Error(`Unknown start scene '${this.#config.start}'.`);
761
+ const initialState =
762
+ this.#config.initialState ??
763
+ (startScene as SceneConstructor<TState, TPhysics> & { initialState?: TState }).initialState;
764
+ if (initialState === undefined) {
765
+ throw new Error(
766
+ `Scene '${this.#config.start}' must declare static initialState or provide config.initialState.`,
767
+ );
768
+ }
769
+ this.#state = createGameStore(initialState, this.#config.stateFlushMs);
770
+ this.#initialState = { ...initialState };
771
+ }
772
+
773
+ get ctx(): ICtx<TState, TPhysics> | undefined {
774
+ return this.#ctx;
775
+ }
776
+
777
+ get scene(): Scene<TState, TPhysics> | undefined {
778
+ return this.#scene;
779
+ }
780
+
781
+ /** The name of the entered scene, or undefined before `start()`. */
782
+ get sceneName(): string | undefined {
783
+ return this.#sceneName;
784
+ }
785
+
786
+ /**
787
+ * Boot into `name` instead of `config.start` on the next `start()`.
788
+ *
789
+ * Hot reload's restore path is the only caller. `acceptHotUpdate` carries the state store across
790
+ * a module update and hands it back before the game runs — and without this the game rebuilt
791
+ * itself at `config.start`, so a session that was playing came back holding its own state on the
792
+ * main menu, with every entity and its physics world gone. Calling `goto()` instead is not
793
+ * available here: it throws before `start()`, and it resets state to the destination's
794
+ * `initialState`, which would discard the very state being restored.
795
+ */
796
+ resumeScene(name: string): void {
797
+ if (this.#config.scenes[name] === undefined) throw new Error(`Unknown scene '${name}'.`);
798
+ this.#resumeScene = name;
799
+ }
800
+
801
+ get state(): GameStore<TState> {
802
+ return this.#state;
803
+ }
804
+
805
+ /**
806
+ * The UI seam. Startup connects it even for a read-only HUD; accessing it before startup
807
+ * connects early so the game can register intents. No state is serialized without a UI peer.
808
+ */
809
+ get ui(): IGameUi {
810
+ const bridge = this.#connectUi();
811
+ const ready = () => this.#uiReady;
812
+ return {
813
+ get connected() {
814
+ return bridge.hasPeer() && ready();
815
+ },
816
+ onIntent: (listener) => onUiIntent(bridge, listener),
817
+ publish: () => this.#uiPublisher?.publish(),
818
+ };
819
+ }
820
+
821
+ #connectUi(): IUiBridge {
822
+ if (this.#uiBridge !== undefined) return this.#uiBridge;
823
+ const bridge = connectUiBridge({ end: "game" });
824
+ this.#uiBridge = bridge;
825
+ // The store already coalesces writes at flush. Deferring this again waits for the native
826
+ // host's next microtask pump, after that frame's WebView event pump has already passed.
827
+ this.#uiPublisher = publishUiState(bridge, this.#state, { schedule: (flush) => flush() });
828
+ onUiIntent(bridge, (intent) => {
829
+ if (intent !== UI_READY_INTENT) return;
830
+ this.#uiReady = true;
831
+ // Publish immediately: the UI has just rendered against nothing, and waiting for the store's
832
+ // next change would leave a HUD showing its initial values for up to a tick.
833
+ this.#uiPublisher?.publish();
834
+ });
835
+ return bridge;
836
+ }
837
+
838
+ #disconnectUi(): void {
839
+ this.#uiPublisher?.stop();
840
+ this.#uiPublisher = undefined;
841
+ this.#uiReady = false;
842
+ this.#uiBridge?.close();
843
+ this.#uiBridge = undefined;
844
+ }
845
+
846
+ goto(name: string, options?: IGotoOptions<TState>): Promise<void> {
847
+ if (this.#ctx === undefined) throw new Error("Cannot call game.goto() before start().");
848
+ // Validate before the reset: a typo'd scene name must not wipe the live session's state on
849
+ // its way to throwing.
850
+ const SceneType = this.#config.scenes[name];
851
+ if (SceneType === undefined) throw new Error(`Unknown scene '${name}'.`);
852
+ const carry = options?.carry;
853
+ if (carry !== undefined) assertCarry(carry);
854
+ const destinationInitialState =
855
+ (SceneType as SceneConstructor<TState, TPhysics> & { initialState?: TState }).initialState ??
856
+ this.#initialState;
857
+ this.#state.stop();
858
+ this.#state.setState({ ...destinationInitialState, ...(carry as Partial<TState> | undefined) });
859
+ this.#state.start();
860
+ return this.#goto(name, this.#ctx);
861
+ }
862
+
863
+ #goto(name: string, ctx: ICtx<TState, TPhysics>): Promise<void> {
864
+ const SceneType = this.#config.scenes[name];
865
+ if (SceneType === undefined) throw new Error(`Unknown scene '${name}'.`);
866
+
867
+ this.#hasDepthCoupledOutput = false;
868
+ this.#sceneGeneration += 1;
869
+ // The objects a pending capture armed are leaving the graph; a report about them would be
870
+ // about a scene that no longer exists.
871
+ this.#geometryCapture?.cancel("TN_GEOMETRY_CAPTURE_SCENE_EXIT: the scene changed mid-capture.");
872
+ this.#sceneFrame = undefined;
873
+ this.#afterPhysicsPhase?.clear();
874
+ this.#beforeRenderCallbacks.clear();
875
+ this.#interpolation?.clear();
876
+ this.#interpolation?.track(ctx.camera);
877
+ this.#scene?.exit(ctx);
878
+ this.#pointerEvents?.clear();
879
+ this.#sceneEntered = false;
880
+ this.#scheduler?.clear();
881
+ this.#entities?.clear();
882
+ for (const plugin of this.#config.plugins ?? []) {
883
+ if (typeof plugin !== "function") plugin.sceneExit?.(ctx);
884
+ }
885
+ // The projection holds batches built from the outgoing scene's geometry. Released before the
886
+ // scene is cleared, so a scene change cannot leave the next level drawing the last one's
887
+ // props — and released rather than rebuilt, because every source it referenced is about to go.
888
+ this.#projection?.dispose();
889
+ // Put back anything the cull hid before the outgoing scene is cleared, so a scene change never
890
+ // leaves an object invisible if the game keeps a reference to it.
891
+ this.#cameraCull?.restore();
892
+ clearScene(ctx.scene, this.#computeDriven);
893
+ const scene = new SceneType();
894
+ this.#scene = scene;
895
+ this.#sceneName = name;
896
+ const loaded = scene.load(ctx);
897
+ const transition =
898
+ loaded === undefined
899
+ ? this.#enterTransitionScene(scene, ctx)
900
+ : Promise.resolve(loaded).then(() => this.#enterTransitionScene(scene, ctx));
901
+ const settled = (): void => {
902
+ if (this.#pendingSceneEnter === transition) this.#pendingSceneEnter = undefined;
903
+ };
904
+ // Handled here as well as by the caller: a start scene that navigates inside `enter()` throws
905
+ // its transition away, and the gate below still has to learn that no world arrived. The failure
906
+ // is reported by name: a swallowed rejection left the loading screen up as a "stall" with
907
+ // nothing outstanding (midway-open-pacific on the Wasm engine).
908
+ void transition.then(settled, (error: unknown) => {
909
+ settled();
910
+ reportLaunchFailure({
911
+ kind: "scene-load-failed",
912
+ message: `Scene '${name}' failed to load: ${error instanceof Error ? error.message : String(error)}`,
913
+ });
914
+ });
915
+ this.#pendingSceneEnter = transition;
916
+ return transition;
917
+ }
918
+
919
+ #enterScene(scene: Scene<TState, TPhysics>, ctx: ICtx<TState, TPhysics>): boolean {
920
+ const frame = scene.enter(ctx);
921
+ if (frame !== undefined && typeof frame !== "function") {
922
+ throw new Error("Scene.enter() must return a frame function or undefined.");
923
+ }
924
+ // A boot scene may navigate synchronously; do not replace the frame installed by #goto().
925
+ if (this.#scene !== scene) return false;
926
+ this.#sceneFrame = typeof frame === "function" ? frame : undefined;
927
+ this.#sceneEntered = true;
928
+ // Before the audit, so an opacity the convention made take effect is reported as a warning.
929
+ const opacity = applyOpacityConvention(ctx.scene);
930
+ if (opacity !== undefined) console.warn(opacity);
931
+ for (const line of renderTrapAudit(ctx.scene)) console.error(line);
932
+ // Cutout PBR with no image-based light renders as cardboard, and the compensating tint the
933
+ // author reaches for is invisible in a screenshot review. Once per scene entry, right after
934
+ // `enter()`: `load()` and `enter()` are where the game builds its meshes and sets its own
935
+ // environment, so an earlier read would be a census of an empty scene and a later one would be
936
+ // a census of a scene the author already fixed.
937
+ const unlit = unlitFoliageWarning(ctx.scene);
938
+ if (unlit !== undefined)
939
+ console.warn(`${formatUnlitFoliageWarning(unlit)} ${UNLIT_FOLIAGE_FIX}`);
940
+ return true;
941
+ }
942
+
943
+ async #enterTransitionScene(
944
+ scene: Scene<TState, TPhysics>,
945
+ ctx: ICtx<TState, TPhysics>,
946
+ ): Promise<void> {
947
+ if (!this.#enterScene(scene, ctx)) return;
948
+ const renderer = this.#renderer;
949
+ const nodes = this.#computeDriven.warmupNodes;
950
+ if (renderer === undefined || nodes.length === 0) return;
951
+ this.#sceneEntered = false;
952
+ let report: Awaited<ReturnType<typeof warmUpComputeNodes>> | undefined;
953
+ let failure: string | undefined;
954
+ try {
955
+ report = await warmUpComputeNodes(renderer, nodes, this.#warmUpOptions());
956
+ } catch (error) {
957
+ failure = error instanceof Error ? error.message : String(error);
958
+ }
959
+ console.log(
960
+ `TN_TRANSITION_COMPUTE_WARMUP:${JSON.stringify(
961
+ report === undefined
962
+ ? { failed: failure ?? "unknown" }
963
+ : {
964
+ compiled: report.compiled,
965
+ abandoned: report.abandoned,
966
+ unsupported: report.unsupported,
967
+ timedOut: report.timedOut,
968
+ },
969
+ )}`,
970
+ );
971
+ if (!this.#aborted && this.#scene === scene) this.#sceneEntered = true;
972
+ }
973
+
974
+ start(): Promise<void> {
975
+ if (this.#started) return Promise.resolve();
976
+ if (this.#pendingStart !== undefined) return this.#pendingStart;
977
+ this.#aborted = false;
978
+ const pendingStart = this.#boot().catch((error: unknown) => {
979
+ this.#disconnectUi();
980
+ throw error;
981
+ });
982
+ this.#pendingStart = pendingStart;
983
+ void pendingStart.then(
984
+ () => {
985
+ if (this.#pendingStart === pendingStart) this.#pendingStart = undefined;
986
+ },
987
+ (error: unknown) => {
988
+ if (this.#pendingStart === pendingStart) this.#pendingStart = undefined;
989
+ // Reported by name: a game that writes `void game.start()` otherwise keeps its loading
990
+ // screen up until the stall watcher says "no asset is outstanding".
991
+ reportLaunchFailure({
992
+ kind: "start-failed",
993
+ message: `The game failed to start: ${error instanceof Error ? error.message : String(error)}`,
994
+ });
995
+ },
996
+ );
997
+ return pendingStart;
998
+ }
999
+
1000
+ async #boot(): Promise<void> {
1001
+ const bootSceneName = this.#resumeScene ?? this.#config.start;
1002
+ this.#resumeScene = undefined;
1003
+ const SceneType = this.#config.scenes[bootSceneName];
1004
+ if (SceneType === undefined) throw new Error(`Unknown start scene '${bootSceneName}'.`);
1005
+ this.#connectUi();
1006
+
1007
+ const renderer = await createRenderer({
1008
+ ...this.#config.renderer,
1009
+ canvas: this.#config.canvas ?? this.#config.renderer?.canvas,
1010
+ preferWebGPU: this.#config.render?.preferWebGPU ?? this.#config.renderer?.preferWebGPU,
1011
+ // One rule on both runtimes, decided 2026-09-01 after a HiDPI desktop browser upscaled a
1012
+ // DPR-1 web buffer into visible pixelation: the device's real density, with an explicit
1013
+ // `renderer.pixelRatio` winning over it (the old branch silently clobbered that value).
1014
+ // Headless capture lanes run at DPR 1 and are unaffected; the resolution scaler composes
1015
+ // on top, so a density the GPU cannot afford is trimmed by rungs, not by the developer.
1016
+ pixelRatio: this.#config.renderer?.pixelRatio ?? globalThis.devicePixelRatio ?? 1,
1017
+ antialias: resolveRendererAntialias(
1018
+ this.#config.render,
1019
+ this.#config.renderer?.antialias,
1020
+ getPlatform().os,
1021
+ ),
1022
+ alphaAntialiasing: resolveRendererAlphaAntialiasing(
1023
+ this.#config.render,
1024
+ this.#config.renderer?.alphaAntialiasing,
1025
+ getPlatform().os,
1026
+ ),
1027
+ ...resolveRendererScaleSetting(
1028
+ this.#config.render,
1029
+ this.#config.renderer?.resolutionScale,
1030
+ getPlatform().os,
1031
+ ),
1032
+ source: this.#config.renderer?.source ?? this.#config.platform?.renderer,
1033
+ });
1034
+ if (this.#aborted) {
1035
+ renderer.dispose();
1036
+ return;
1037
+ }
1038
+ this.#renderer = renderer;
1039
+ const canvas = renderer.domElement;
1040
+ const platform = this.#config.platform;
1041
+ if (platform !== undefined) platform.mountCanvas(canvas, this.#config.container);
1042
+ else if (
1043
+ this.#config.container !== undefined &&
1044
+ canvas.parentElement !== this.#config.container
1045
+ )
1046
+ this.#config.container.append(canvas);
1047
+ else if (canvas.parentElement === null && typeof document !== "undefined")
1048
+ document.body.append(canvas);
1049
+
1050
+ const inputTarget =
1051
+ this.#config.inputTarget ??
1052
+ (platform === undefined
1053
+ ? typeof window === "undefined"
1054
+ ? canvas
1055
+ : window
1056
+ : (platform.inputTarget ?? canvas));
1057
+ this.#input = new InputMap(
1058
+ this.#config.input,
1059
+ inputTarget,
1060
+ canvas,
1061
+ platform?.input,
1062
+ this.#config.contextMenu,
1063
+ );
1064
+ this.#state.start();
1065
+ const threeScene = new ThreeScene();
1066
+ const camera = createCamera(this.#config.camera);
1067
+ const interpolation = new PhysicsInterpolation(this.#config.physicsInterpolation);
1068
+ this.#interpolation = interpolation;
1069
+ interpolation.track(camera);
1070
+ const viewport = new Viewport({ camera, renderer: this.#renderer, source: platform?.viewport });
1071
+ const canvasLayer = new CanvasLayer(viewport);
1072
+ this.#viewport = viewport;
1073
+ // The renderer goes to the asset loader so compiled KTX2 textures detect transcoding
1074
+ // support against the real backend; a target that supports none fails right here.
1075
+ const assets = createAssetLoader({ ...this.#config.assets, renderer: renderer.raw });
1076
+ if (assets.compressedTextures !== undefined) await assets.compressedTextures.ready;
1077
+ const entities = new Registry();
1078
+ const random = createRandom(this.#config.seed);
1079
+ const scheduler = new Scheduler();
1080
+ const afterPhysicsPhase = createAfterPhysicsPhase();
1081
+ const input = this.#input;
1082
+ const picker = new ScenePicker({
1083
+ camera,
1084
+ // Input reports window-relative client coordinates; the picker's NDC math is
1085
+ // canvas-relative. Subtract the canvas page offset like replay.ts does for recorded
1086
+ // pointers, or every pick lands displaced by wherever the canvas sits in the layout.
1087
+ pointer: () => {
1088
+ const position = input.raw.pointer.position;
1089
+ const rect = (
1090
+ canvas as { getBoundingClientRect?: () => DOMRect }
1091
+ ).getBoundingClientRect?.();
1092
+ return rect === undefined
1093
+ ? position
1094
+ : new Vector2(position.x - rect.left, position.y - rect.top);
1095
+ },
1096
+ scene: threeScene,
1097
+ viewport,
1098
+ });
1099
+ this.#picker = picker;
1100
+ const pointerEvents = new PointerEvents3D({
1101
+ screen: (position, target) => {
1102
+ const rect = (
1103
+ canvas as { getBoundingClientRect?: () => DOMRect }
1104
+ ).getBoundingClientRect?.();
1105
+ return rect === undefined
1106
+ ? target.copy(position)
1107
+ : target.set(position.x - rect.left, position.y - rect.top);
1108
+ },
1109
+ });
1110
+ this.#pointerEvents = pointerEvents;
1111
+ const loopState: { current?: FixedStepLoop } = {};
1112
+ // The engine owns the world-matrix walk, not three's renderer: on by default it does not recurse
1113
+ // into a hidden subtree, and `renderer.matrixWorld: "all"` restores the every-node walk. The
1114
+ // authored scene is marked once, here, so three never walks it a second time; the mirror scene
1115
+ // is marked at the render site, where whichever root is drawn this frame is known.
1116
+ const matrixWorldPass = new MatrixWorldPass({
1117
+ mode: resolveMatrixWorldMode(this.#config.render),
1118
+ });
1119
+ this.#matrixWorld = matrixWorldPass;
1120
+ threeScene.matrixWorldAutoUpdate = false;
1121
+ // Built before the context because `ctx.startup` reads it: a game asks what the framework's
1122
+ // startup is doing, and the answer is this pass.
1123
+ const projection = new SceneRenderProjection(threeScene, {
1124
+ // The game's `renderer.projection` value verbatim: `false` declines the mirror, an object
1125
+ // names the material check beside accepting it, and the projection owns both readings.
1126
+ projection: this.#config.render?.projection,
1127
+ velocity: () => renderer.renderChainUsesPerObjectVelocity?.() ?? false,
1128
+ matrixWorld: matrixWorldPass,
1129
+ });
1130
+ this.#projection = projection;
1131
+ // Do not submit what the render camera cannot resolve. On by default at a conservative 0.5 px,
1132
+ // and measured whether or not the game narrows or declines it. Its decision is per camera, so
1133
+ // a shadow caster and anything attached to the camera are never dropped on the main view alone.
1134
+ const cameraCull = new RenderCameraCull({
1135
+ minimumPixels: this.#config.render?.minimumProjectedPixels,
1136
+ });
1137
+ this.#cameraCull = cameraCull;
1138
+ let projectionSettled = false;
1139
+ /**
1140
+ * Progress is a high-water mark over the measured load state, never a value that can fall.
1141
+ *
1142
+ * The ratio's denominator grows: a request registered after an earlier one settled shrinks
1143
+ * `settled / requested`, and the file-count and byte branches can disagree across the switch
1144
+ * the first weighed manifest entry triggers. Both make the bar jump backwards, which a player
1145
+ * reads as the load restarting. Measured: a second texture requested after the first settled
1146
+ * took the reported value from 0.7 to 0.35.
1147
+ */
1148
+ let reportedProgress = 0;
1149
+ /** What the load state says right now. This may fall; `startup.progress` is what never does. */
1150
+ const measuredProgress = (): number => {
1151
+ if (projectionSettled) return 1;
1152
+ // A registered hold owns the last tenth. Without this the bar sat at 0.9 for the whole
1153
+ // of the game's own tier and then jumped, which is the reading a player calls frozen.
1154
+ if (startupReadiness.frameworkReady) {
1155
+ const held = startupReadiness.holdReport.length;
1156
+ if (held === 0) return 0.9;
1157
+ const settled = held - startupReadiness.pendingHolds.length;
1158
+ return 0.9 + 0.1 * (settled / held);
1159
+ }
1160
+ if (startupReadiness.compileSettled) return 0.9;
1161
+ if (timeline.enteredMs !== undefined) return 0.8;
1162
+ const { requested, requestedBytes, settled, settledBytes } = assets.progress;
1163
+ // Bytes when the manifest knows them, files when it does not. A file count spends the
1164
+ // same travel on a 4 KB icon as on a 710 MB model, which is how a bar reaches 92% and
1165
+ // then stands still for the rest of the download.
1166
+ if (requestedBytes > 0) return 0.7 * Math.min(1, settledBytes / requestedBytes);
1167
+ return requested === 0 ? 0 : 0.7 * Math.min(1, settled / requested);
1168
+ };
1169
+ let worldRendered = false;
1170
+ let loadingFramePresented = false;
1171
+ let markProjectionSettled: () => void = () => undefined;
1172
+ const projectionReady = new Promise<void>((resolve) => {
1173
+ markProjectionSettled = resolve;
1174
+ });
1175
+ const startupReadiness = new StartupReadiness({
1176
+ /**
1177
+ * The second warm-up: everything a game attached while it held startup.
1178
+ *
1179
+ * The first pass runs at framework readiness, which for a streaming game is before most of
1180
+ * the world exists. Without this, `hold()` buys a complete *picture* and leaves a scene whose
1181
+ * every material still compiles on first sight — which is worse than the pop-in it replaced,
1182
+ * because a compile stall lands while the player is walking rather than while they are
1183
+ * waiting. Measured on a 46,190-instance forest: 8 pipelines warmed, then 28 main-thread
1184
+ * tasks over 40 ms in a minute of play, the worst 267 ms.
1185
+ *
1186
+ * A third of the compile budget, not the whole of it, because this one is spent with the
1187
+ * player already waiting behind a curtain that has been up for seconds. Whatever does not
1188
+ * fit still compiles lazily — the same as before — so the ceiling on the wait is bounded and
1189
+ * the worst case is the behaviour we already had.
1190
+ */
1191
+ afterHolds: async () => {
1192
+ await warmUp("TN_STARTUP_WARMUP_HELD", Math.round(STARTUP_COMPILE_BUDGET_MS / 3), false);
1193
+ },
1194
+ });
1195
+ // Startup readiness does not wait on `ui-ready`, and cannot. The intent proves the page's
1196
+ // script ran, not that a pixel reached the screen, so waiting on it never closed the race it
1197
+ // was added for — it only made the losing side lose later, after up to 45 s of held frames.
1198
+ // The race no longer exists: the native UI is now composited into the game's own frame, so the
1199
+ // cover and the world share one swapchain and there is no second surface left to arrive late.
1200
+ // The held loop starts before an explicit warm-up so the loading surface can animate. A native
1201
+ // frame may therefore arrive while that pass is still awaiting a compile promise; keep first-use
1202
+ // rendering and compute behind the same held boundary until the explicit pass has settled.
1203
+ let explicitWarmUpSettled = !this.#warmUpConfiguredExplicitly();
1204
+ // A web UI is the loading surface on native and on the web. Its bridge must be both attached
1205
+ // and announced ready: an attached but unrendered web view is not a cover the player can see.
1206
+ // Keep this predicate tied to an actually attached and rendered web UI. The render path still
1207
+ // lets a settled world render behind either kind of cover; only the unresolved first-use work
1208
+ // is held, so a persistent HUD cannot stop the world pass after loading.
1209
+ const startupCoverActive = (): boolean =>
1210
+ !startupReadiness.ready &&
1211
+ (canvasLayer.opaque || (this.#uiReady && this.#uiBridge?.hasPeer() === true));
1212
+ const timeline: { -readonly [K in keyof IStartupTimeline]: IStartupTimeline[K] } = {};
1213
+ let warmUpStatus: IStartupStatus["warmup"];
1214
+ const now = (): number => globalThis.performance?.now() ?? Date.now();
1215
+ /**
1216
+ * A launch that stops making progress says so, on the page, instead of leaving a loading
1217
+ * screen up forever. Measured on `midway-open-pacific`: a 104 s launch and then a lost GPU
1218
+ * device, with the only account of either on a terminal the player does not have.
1219
+ */
1220
+ const stopStallWatch = watchStartupStall({
1221
+ pending: () => [...assets.progress.pending, ...startupReadiness.pendingHolds],
1222
+ progress: () => this.#ctx?.startup.progress ?? 0,
1223
+ workProgress: () => assets.progress.settled + startupReadiness.workProgress,
1224
+ stallMs: STARTUP_STALL_MS,
1225
+ });
1226
+ watchDeviceLoss(
1227
+ (
1228
+ renderer.raw as {
1229
+ backend?: { device?: { lost?: Promise<{ reason?: string; message?: string }> } };
1230
+ }
1231
+ ).backend?.device,
1232
+ );
1233
+ // Stamped when the FRAMEWORK is done, which is before `whenReady()` whenever the game has
1234
+ // registered a `startup.hold()`. Two stamps, because one number cannot be both "what the
1235
+ // framework cost" and "what the player waited for", and collapsing them is how a valley that
1236
+ // took 8.8 s to appear reported 1.5 s.
1237
+ void startupReadiness.whenFrameworkReady().then(() => {
1238
+ timeline.compileSettledMs ??= now();
1239
+ timeline.frameworkReadyMs ??= now();
1240
+ });
1241
+ void startupReadiness.whenReady().then(() => {
1242
+ stopStallWatch();
1243
+ // A renderer without first-use compilation settles without running the compile closure
1244
+ // below, so the settle stamp is guaranteed here at the latest.
1245
+ timeline.compileSettledMs ??= now();
1246
+ timeline.frameworkReadyMs ??= now();
1247
+ timeline.readyMs ??= now();
1248
+ projectionSettled = true;
1249
+ markProjectionSettled();
1250
+ // A host capturing a frame has no other way to know the world is on screen. Counting frames
1251
+ // cannot express it: on a software rasteriser the gate resolves on its bounded window rather
1252
+ // than on five in-budget frames, so a fast 300-frame run finishes before the world is shown
1253
+ // and captures the loading state. The native screenshot path waits on this flag.
1254
+ (globalThis as Record<string, unknown>)[STARTUP_READY_GLOBAL] = true;
1255
+ // Again at ready: a world that streams its foliage in under `startup.hold` has none at entry.
1256
+ const unlit = unlitFoliageWarning(threeScene);
1257
+ if (unlit !== undefined)
1258
+ console.warn(`${formatUnlitFoliageWarning(unlit)} ${UNLIT_FOLIAGE_FIX}`);
1259
+ });
1260
+ const warmUp = async (marker: string, budgetMs: number, stamp: boolean): Promise<void> => {
1261
+ if (this.#aborted || this.#renderer === undefined) return;
1262
+ let report: IWarmUpReport | undefined;
1263
+ let failure: string | undefined;
1264
+ try {
1265
+ projection.reconcile();
1266
+ // The frame loop's own walk, run here too because the warm-up draws before that loop does.
1267
+ // Three is told not to walk the scene (`matrixWorldAutoUpdate = false`), and a declined
1268
+ // projection returns from `reconcile()` without walking it, so without this the warm render
1269
+ // compiles every pipeline against stale world matrices and the real frames then build the
1270
+ // rest synchronously -- tens of seconds each on a software adapter, which loses the device.
1271
+ this.#matrixWorld?.apply(projection.root);
1272
+ report = await warmUpScene(renderer, projection.root, camera, {
1273
+ budgetMs,
1274
+ computeNodes: this.#computeDriven.warmupNodes,
1275
+ renderPasses: this.#warmUpOptions().renderPasses,
1276
+ includeHidden: this.#warmUpOptions().includeHidden,
1277
+ });
1278
+ } catch (error) {
1279
+ failure = error instanceof Error ? error.message : String(error);
1280
+ }
1281
+ // With an explicit warm-up, this held pass is only the first half of startup. Stamp after
1282
+ // the explicit pass so its own pipelines remain inside the settled boundary; without one,
1283
+ // this is the only warm-up completion.
1284
+ if (stamp || !this.#warmUpConfiguredExplicitly()) renderer.warmUpSettled?.();
1285
+ warmUpStatus =
1286
+ report === undefined
1287
+ ? { status: "unavailable" }
1288
+ : {
1289
+ attempted: report.attempted,
1290
+ candidates: report.candidates,
1291
+ observed: report.observed,
1292
+ status: report.observed.status,
1293
+ };
1294
+ if (stamp) timeline.compileSettledMs ??= now();
1295
+ console.log(
1296
+ `${marker}:${JSON.stringify(
1297
+ report === undefined
1298
+ ? { failed: failure ?? "unknown" }
1299
+ : {
1300
+ compiled: report.compiled,
1301
+ pipelines: report.pipelines,
1302
+ candidates: report.candidates,
1303
+ attempted: report.attempted,
1304
+ observed: report.observed,
1305
+ slices: report.slices,
1306
+ elapsedMs: Math.round(report.elapsedMs),
1307
+ unsupported: report.unsupported,
1308
+ abandoned: report.abandoned,
1309
+ timedOut: report.timedOut,
1310
+ computeCompiled: report.computeCompiled,
1311
+ computeAbandoned: report.computeAbandoned,
1312
+ computeUnsupported: report.computeUnsupported,
1313
+ computeTimedOut: report.computeTimedOut,
1314
+ passes: report.passes,
1315
+ passPipelines: report.passPipelines,
1316
+ cullingForced: report.cullingForced,
1317
+ visibilityForced: report.visibilityForced,
1318
+ cache: report.cache,
1319
+ },
1320
+ )}`,
1321
+ );
1322
+ };
1323
+ const startupCompile: StartupCompile = async (): Promise<void> => {
1324
+ await warmUp("TN_STARTUP_WARMUP", STARTUP_COMPILE_BUDGET_MS, true);
1325
+ };
1326
+ // The GPU-selected main-pass tally, registered by whichever streamed world is added to the
1327
+ // scene. The frame budget reads it once per window; a world with no sample reports undefined, so
1328
+ // the window carries nothing rather than a zero no frame selected.
1329
+ let gpuTallyProvider:
1330
+ | (() => { readonly instances: number; readonly triangles: number } | undefined)
1331
+ | undefined;
1332
+ const ctx: ICtx<TState, TPhysics> = {
1333
+ get frameTime() {
1334
+ return loopState.current?.frameTime ?? 0;
1335
+ },
1336
+ get alpha() {
1337
+ return loopState.current?.alpha ?? 0;
1338
+ },
1339
+ interpolate: (object) => interpolation.track(object),
1340
+ resetInterpolation: (object) => interpolation.reset(object),
1341
+ add: (object) => {
1342
+ // Narrowed through a plain `Object3D` rather than the type parameter: a type guard applied
1343
+ // to `T` yields `T & IComputeDriven`, which TypeScript will not carry to the registry's
1344
+ // `Object3D & IComputeDriven` without a cast. The local keeps the guard honest and the
1345
+ // return keeps the caller's own type, so a game never casts back what it just built.
1346
+ const node: Object3D = object;
1347
+ threeScene.add(node);
1348
+ if (typeof (node as { aerialPerspective?: unknown }).aerialPerspective === "function") {
1349
+ this.#hasDepthCoupledOutput = true;
1350
+ }
1351
+ if (isComputeDriven(node)) {
1352
+ const activeRenderer = this.#renderer;
1353
+ if (activeRenderer === undefined)
1354
+ throw new Error("Cannot add a compute-driven object before the game starts.");
1355
+ this.#computeDriven.add(node, activeRenderer);
1356
+ }
1357
+ // A streamed world that can say what the GPU selected, so `TN_FRAME_BUDGET` reports the
1358
+ // GPU-selected main-pass count beside its pass record. The tally is asked for only when the
1359
+ // frame budget is on: with it off and no validation, the world adds no readback at all.
1360
+ const tallySource = node as {
1361
+ enableGpuSceneTally?: () => void;
1362
+ gpuSceneTally?: () =>
1363
+ | { readonly instances: number; readonly triangles: number }
1364
+ | undefined;
1365
+ };
1366
+ if (typeof tallySource.gpuSceneTally === "function") {
1367
+ gpuTallyProvider = tallySource.gpuSceneTally.bind(node);
1368
+ if (this.#config.frameBudget !== false) tallySource.enableGpuSceneTally?.();
1369
+ }
1370
+ return object;
1371
+ },
1372
+ assets,
1373
+ after: (delay, callback) => scheduler.after(delay, callback),
1374
+ afterPhysics: (callback) => afterPhysicsPhase.register(callback),
1375
+ beforeRender: (callback) => {
1376
+ if (typeof callback !== "function")
1377
+ throw new Error("beforeRender requires a callback function.");
1378
+ this.#beforeRenderCallbacks.add(callback);
1379
+ return () => this.#beforeRenderCallbacks.delete(callback);
1380
+ },
1381
+ camera,
1382
+ canvasLayer,
1383
+ entities,
1384
+ every: (callback) => scheduler.every(callback),
1385
+ get fps() {
1386
+ return loopState.current?.fps ?? 0;
1387
+ },
1388
+ goto: (name) => this.#goto(name, ctx),
1389
+ input: this.#input,
1390
+ pointer: pointerEvents,
1391
+ physics: undefined as TPhysics,
1392
+ random,
1393
+ raycast: (options) => picker.raycast(options),
1394
+ raycastAll: (options, target) => picker.raycastAll(options, target),
1395
+ startup: {
1396
+ get warmup() {
1397
+ return warmUpStatus;
1398
+ },
1399
+ get phase() {
1400
+ // The projection is reconciled before the first world draw, but readiness is not reported
1401
+ // until first-use work and a sustained in-budget window have completed. An opaque loading
1402
+ // layer cannot turn `whenReady()` into a first-present signal while work is still waiting
1403
+ // behind it.
1404
+ if (projectionSettled) return "ready" as const;
1405
+ return "collapsing" as const;
1406
+ },
1407
+ // True once first-use compilation has settled, which is earlier than `phase === "ready"`
1408
+ // and is the signal a game wants when it must not act during the launch. `phase` cannot
1409
+ // express it: it is binary, and readiness additionally requires a sustained in-budget
1410
+ // frame window that a software rasteriser can only ever let expire. A game gated on
1411
+ // `phase` alone therefore does nothing for ~25s on such a lane — measured as a chase route
1412
+ // of length 0.000000 where 6 was required, because the scenario ended first.
1413
+ get compileSettled() {
1414
+ return startupReadiness.compileSettled;
1415
+ },
1416
+ // Honest and monotonic: the asset ratio carries the first 70% while the start scene
1417
+ // loads, entering the world is 80%, compile settling 90%, and only readiness is 1.
1418
+ // Monotonicity is enforced rather than assumed — see the high-water mark above.
1419
+ get progress() {
1420
+ reportedProgress = Math.max(reportedProgress, measuredProgress());
1421
+ return reportedProgress;
1422
+ },
1423
+ hold: (label, work, budgetMs, progress) => {
1424
+ startupReadiness.hold(label, work, budgetMs, progress);
1425
+ },
1426
+ get timeline() {
1427
+ return { ...timeline };
1428
+ },
1429
+ whenReady: () => projectionReady,
1430
+ whenFrameworkReady: () => startupReadiness.whenFrameworkReady(),
1431
+ },
1432
+ renderer: this.#renderer,
1433
+ viewport,
1434
+ scene: threeScene,
1435
+ state: this.#state,
1436
+ tween: (target, properties, duration, options) =>
1437
+ scheduler.tween(target, properties, duration, options),
1438
+ };
1439
+ this.#ctx = ctx;
1440
+ this.#entities = entities;
1441
+ this.#scheduler = scheduler;
1442
+ this.#afterPhysicsPhase = afterPhysicsPhase;
1443
+ const devToolsHost =
1444
+ platform === undefined
1445
+ ? typeof window === "undefined"
1446
+ ? undefined
1447
+ : window
1448
+ : platform.devToolsHost;
1449
+ this.#cleanup.push(
1450
+ installDevTools(
1451
+ entities,
1452
+ devToolsHost as DevToolsHost | undefined,
1453
+ () => this.#geometryCapture,
1454
+ ),
1455
+ );
1456
+ this.#scene = new SceneType();
1457
+ this.#sceneName = bootSceneName;
1458
+ // The scaler exists whenever the scale is automatic, which now includes a game that said
1459
+ // nothing about it. A pinned number leaves this undefined, which is what makes "pinned" a
1460
+ // guarantee rather than a preference the loop may overrule. `maxFps: 0` removes the ceiling,
1461
+ // and a scaler with no budget is not a scaler with a loose one, so an uncapped game simply
1462
+ // does not get adaptive scaling.
1463
+ const initialTarget = resolveTargetFps(this.#config, getPlatform());
1464
+ let heldTargetFps = initialTarget.targetFps;
1465
+ // Frame-share budgets elsewhere (the world's adaptive LOD) read the target, not the last frame.
1466
+ renderer.noteTargetFps?.(initialTarget.targetFps);
1467
+ const scaler =
1468
+ renderer.surface().scaleSource === "auto" && initialTarget.targetFps > 0
1469
+ ? new ResolutionScaler({
1470
+ // Phones keep the device ladder; a desktop stops before its bottom, where a picture
1471
+ // with nothing reconstructing it stops being a faster frame and becomes a blur.
1472
+ minScale: resolvePlatformResolutionFloor(getPlatform().os),
1473
+ // The adapter family picks the first rung; the first eligible window still decides.
1474
+ start:
1475
+ renderer.gpuClass === undefined
1476
+ ? undefined
1477
+ : RESOLUTION_SCALER.startScaleByGpuClass[renderer.gpuClass.class],
1478
+ targetFps: initialTarget.targetFps,
1479
+ // No floor lift from motion data: consuming velocity is not upscaling. Three's TRAA
1480
+ // accumulates at the canvas's own size, so lifting the floor for it let a forest frame
1481
+ // fall to 0.23 (442x248 on a 1920x1080 canvas). Only a stage that reconstructs a
1482
+ // display-resolution frame may pass `temporalUpscale`, and none ships today.
1483
+ })
1484
+ : undefined;
1485
+ // A class that starts below the ceiling must draw there from the first frame; the scaler only
1486
+ // reports a scale, and nothing else would apply it until a window steps.
1487
+ if (scaler !== undefined && scaler.scale !== 1)
1488
+ renderer.setResolutionScale(scaler.scale, scaler.scaleSource);
1489
+ // The panel's own rate, once a window of presented frames can say it. The native host's
1490
+ // present counter is the only series there that counts displays rather than loop iterations;
1491
+ // on the web one rAF callback is one vblank, so the median presented interval is the period.
1492
+ let measuredRefreshHz: number | undefined;
1493
+ // The world pass's own draw-call count, kept from the last frame of the window so the
1494
+ // projection line can report what the renderer was handed beside what the plan predicted.
1495
+ // A plan and a measurement that disagree is the finding; one number pretending to be both
1496
+ // is how an optimizer reports a win it did not deliver.
1497
+ let lastWorldDrawCalls: number | undefined;
1498
+ // Completion on the last frame must not make an otherwise compiling window look clean.
1499
+ let compilingInWindow = false;
1500
+ let lastCompileCount = renderer.compileCount;
1501
+ const observeCompilation = (): void => {
1502
+ const count = renderer.compileCount;
1503
+ compilingInWindow ||= renderer.compiling === true || count !== lastCompileCount;
1504
+ lastCompileCount = count;
1505
+ };
1506
+ // Built here rather than inside the loop so `frameBudget: false` is a single decision with a
1507
+ // single owner, and so the render phases below feed the same instrument the loop feeds.
1508
+ const frameBudget =
1509
+ this.#config.frameBudget === false
1510
+ ? undefined
1511
+ : new FrameBudget({
1512
+ ...this.#config.frameBudget,
1513
+ simulation: {
1514
+ tick: () => gameLoop.tick(),
1515
+ get step() {
1516
+ return gameLoop.step;
1517
+ },
1518
+ },
1519
+ // The scaler reads the same windows the marker reports, so what it acted on and what
1520
+ // the record shows are the same measurement rather than two sampling paths.
1521
+ onWindow: (reported) => {
1522
+ const sink =
1523
+ this.#config.frameBudget === false ? undefined : this.#config.frameBudget?.report;
1524
+ const reportInfo = sink ?? console.info;
1525
+ const reportWarning = sink ?? console.warn;
1526
+ observeCompilation();
1527
+ const compileObserved = compilingInWindow;
1528
+ compilingInWindow = false;
1529
+ // The display's own rate, read once per window from the cadence the loop already
1530
+ // measured: the host's present counter where there is one, else the median presented
1531
+ // interval, which on the web is the vblank period because rAF is the presentation.
1532
+ measuredRefreshHz =
1533
+ reported.presentedFps ??
1534
+ (reported.presented.p50 > 0 ? 1_000 / reported.presented.p50 : undefined);
1535
+ const target = resolveTargetFps(this.#config, getPlatform(), measuredRefreshHz);
1536
+ renderer.noteTargetFps?.(target.targetFps);
1537
+ if (
1538
+ scaler !== undefined &&
1539
+ target.targetFps > 0 &&
1540
+ target.targetFps !== heldTargetFps
1541
+ ) {
1542
+ heldTargetFps = target.targetFps;
1543
+ scaler.retarget(heldTargetFps);
1544
+ }
1545
+ renderer.observeRenderChainBudget?.(reported);
1546
+ this.#computeDriven.observeBudget(reported);
1547
+ const projection = this.#projection;
1548
+ // Printed every window, projecting or declined. `TN_RENDER_PROJECTION` says once
1549
+ // whether the optimizer engaged; this says, repeatedly, what it is still leaving on
1550
+ // the exact lane and whether the renderer agrees with the plan.
1551
+ if (projection !== undefined) {
1552
+ reportInfo(
1553
+ formatProjectionWindow(
1554
+ projection.report,
1555
+ reported.window,
1556
+ lastWorldDrawCalls,
1557
+ this.#cameraCull?.report,
1558
+ this.#matrixWorld?.report,
1559
+ ),
1560
+ );
1561
+ }
1562
+ if (this.#config.frameBudget !== false)
1563
+ this.#config.frameBudget?.onWindow?.(reported);
1564
+ // The span tree closes on the same window, so the two lines in a log describe the
1565
+ // same frames and a reader can subtract one from the other without a second clock.
1566
+ const spanWindow = spans?.window();
1567
+ if (spanWindow !== undefined) reportInfo(formatSpansWindow(spanWindow));
1568
+ // The scene-shape verdict, on by default, from the census the frame already took.
1569
+ // An agent building a scene of the wrong shape reads it in the log before a human
1570
+ // ever plays the game and calls it slow.
1571
+ const staticCensus = staticTransformCensus();
1572
+ if (staticCensus.roots > 0)
1573
+ reportInfo(`${STATIC_TRANSFORM_MARKER}:${JSON.stringify(staticCensus)}`);
1574
+ const validation = renderListValidator?.report();
1575
+ if (validation !== undefined) reportInfo(formatValidationReport(validation));
1576
+ const warning = sceneWarning(
1577
+ reported,
1578
+ describeSceneShape(reported, this.#cameraCull?.report),
1579
+ target.targetFps,
1580
+ );
1581
+ if (warning !== undefined) reportWarning(formatSceneWarning(warning));
1582
+ // The same sentence goes to the UI on a dev launch, so a human watching the window
1583
+ // and an agent reading the log are told the same thing at the same time. No frame
1584
+ // rate rides it: the loop's own rAF rate reads throttled under a compositor or a
1585
+ // virtual display, so a number drawn from it lies in exactly the sessions where
1586
+ // somebody is trying to measure.
1587
+ if (
1588
+ devMetricsEnabled &&
1589
+ warning !== undefined &&
1590
+ this.#uiBridge?.hasPeer() === true
1591
+ ) {
1592
+ const verdict = describeSceneWarning(warning);
1593
+ if (verdict !== postedVerdict) {
1594
+ postedVerdict = verdict;
1595
+ this.#uiBridge.post({ type: UI_DEV_METRICS_MESSAGE, sceneWarning: verdict });
1596
+ }
1597
+ }
1598
+ if (scaler === undefined) return;
1599
+ // **Not while the world is still arriving.** The scaler judges the game by closed
1600
+ // frame-budget windows, and the windows that close during a launch are not the game:
1601
+ // they are asset decode, scene construction and first-use compilation. Measured on
1602
+ // sandbox/wildwood, a 46,190-instance forest, the first two windows reported 18.8
1603
+ // and 27.3 fps against a 60 fps budget — a deficit large enough that `#rungsToDrop`
1604
+ // crossed three rungs at once and the buffer went from 1600x900 to 976x549 before
1605
+ // the player had control. It then settled at 0.72, which is 52% of the pixels, and
1606
+ // re-probed 0.85 every thirty seconds, missed, and fell back — so the picture went
1607
+ // soft a few seconds in and never fully recovered. The owner's report was "after a
1608
+ // while everything becomes blurry, and keeps getting worse".
1609
+ //
1610
+ // Readiness is the right gate rather than a frame count or a timer: it is the moment
1611
+ // the framework already defines as "the world is safe to show", it now includes
1612
+ // anything the game held startup for, and a host that never reaches it still gets
1613
+ // there on the bounded fallbacks inside `StartupReadiness`.
1614
+ if (!startupReadiness.ready || compileObserved) return;
1615
+ const stepped = scaler.observe(reported);
1616
+ if (stepped !== undefined) renderer.setResolutionScale(stepped, scaler.scaleSource);
1617
+ },
1618
+ // Last, so the engine's own renderer answers this and a game cannot report a
1619
+ // resolution it is not drawing at. The window carries it in both pinned and auto
1620
+ // modes: turning the convention off does not turn its measurement off.
1621
+ readGpuAgeFrames: () => renderer.gpuFrameAge?.(),
1622
+ // The world's own count of what the GPU selected, not `info.render.triangles`' upper
1623
+ // bound over mesh capacity. Absent until the world's first tally lands.
1624
+ readGpuTally: () => gpuTallyProvider?.(),
1625
+ // The resolved budget rides the window rather than a marker of its own, so a harness
1626
+ // reads the target and the frames it was judged against out of one line. It lags the
1627
+ // window by one, because the window is built before this callback runs.
1628
+ readTarget: () => resolveTargetFps(this.#config, getPlatform(), measuredRefreshHz),
1629
+ readSurface: () => {
1630
+ observeCompilation();
1631
+ return {
1632
+ ...renderer.surface(),
1633
+ ...(scaler === undefined ? {} : { atFloor: scaler.atFloor }),
1634
+ compiling: compilingInWindow,
1635
+ };
1636
+ },
1637
+ });
1638
+ this.#frameBudget = frameBudget;
1639
+ // Per-pass draws and triangles ride the frame budget's window by default. The same property
1640
+ // that makes `info.render` an aggregate — one reset per frame before the world render, and
1641
+ // nested shadow/reflection renders sharing that counter — is what this recorder unwinds.
1642
+ const renderPassBudget =
1643
+ frameBudget === undefined
1644
+ ? undefined
1645
+ : RenderPassBudget.install(renderer.raw as Parameters<typeof RenderPassBudget.install>[0]);
1646
+ // Spans are a diagnostic, never a convention: nothing installs them unless `TN_FRAME_SPANS`
1647
+ // asks for them, and every call site below is one guarded return when it does not. They wrap
1648
+ // three's own render path rather than reimplementing it, so what they measure is the path that
1649
+ // ships, and they are removed with the game.
1650
+ const spans = spansRequested() ? new SpanRecorder() : undefined;
1651
+ if (spans !== undefined) setSpanRecorder(spans);
1652
+ const removeSpanProbes =
1653
+ spans === undefined
1654
+ ? undefined
1655
+ : installSpanProbes(renderer.raw as Parameters<typeof installSpanProbes>[0], threeScene);
1656
+ // The boundary counts ride the same flag: they wrap every WebGPU command of the frame, which is
1657
+ // work a shipped build must not pay for a diagnostic it did not ask for.
1658
+ const frameCounters =
1659
+ spans === undefined ? undefined : FrameCounters.install(counterDeviceOf(renderer.raw));
1660
+ // The parity oracle for the static freeze. Off by default and expensive on purpose: it
1661
+ // recomputes every world matrix the long way and throws on the first that disagrees with what
1662
+ // the frame is about to draw.
1663
+ const renderListValidator = renderListValidationRequested()
1664
+ ? new RenderListValidator()
1665
+ : undefined;
1666
+ if (removeSpanProbes !== undefined) {
1667
+ this.#cleanup.push(() => {
1668
+ removeSpanProbes();
1669
+ setSpanRecorder(undefined);
1670
+ });
1671
+ }
1672
+ if (frameCounters !== undefined) this.#cleanup.push(() => frameCounters.uninstall());
1673
+ // Holds no hook and does no work between requests, so an idle game pays nothing for it.
1674
+ const geometryCapture = new GeometryCapture();
1675
+ this.#geometryCapture = geometryCapture;
1676
+ const budgetNow = (): number => globalThis.performance?.now() ?? Date.now();
1677
+ // The dev verdict is decided once per launch, and sent when it changes rather than on a timer:
1678
+ // a chip that re-sent an unchanged sentence four times a second would pay a JSON round trip to
1679
+ // say nothing new.
1680
+ const devMetricsEnabled = isDevLaunch();
1681
+ let postedVerdict: string | undefined;
1682
+ let updates = 0;
1683
+ let renders = 0;
1684
+ let lastGateSkips = 0;
1685
+ const gameLoop: FixedStepLoop = new FixedStepLoop({
1686
+ interpolation,
1687
+ ...(frameBudget === undefined ? {} : { budget: frameBudget }),
1688
+ ...(spans === undefined ? {} : { spans }),
1689
+ maxSteps: this.#config.maxSteps,
1690
+ onBeginFrame: () => {
1691
+ // The engine owns this requestAnimationFrame loop instead of delegating to Three's
1692
+ // setAnimationLoop(). Three's renderer therefore cannot reset its frame counters for us;
1693
+ // a concurrent internal renderer callback can otherwise leave stale work in the first
1694
+ // sample after a held playtest start.
1695
+ resetRendererPerformanceMetrics(renderer.raw);
1696
+ renderer.beginFrame?.();
1697
+ },
1698
+ onRender: (alpha) => {
1699
+ observeCompilation();
1700
+ renderPassBudget?.beginFrame();
1701
+ // Runs on web as well as native, so the two stay one behaviour rather than diverging into
1702
+ // a fast path nobody tests. When the world is drawn, reconciliation happens immediately
1703
+ // before the render, inside the same frame, so a change the game made this tick reaches
1704
+ // the screen this tick instead of the next one. Scenes under its mesh floor get their own
1705
+ // graph back and pay nothing.
1706
+ // A goto clears the graph before its destination enters, and the projection has to drop
1707
+ // those objects on the very next frame. During the first-use hold, however, reconciling a
1708
+ // large scene would be more work before the loader has even presented. Present one
1709
+ // loader-only frame and keep reconciling skipped until first-use work settles; then the
1710
+ // world pass and projection start together behind the still-opaque layer.
1711
+ let worldMetrics: IRenderPerformanceMetrics | undefined;
1712
+ const firstWorldPass = !worldRendered && this.#sceneEntered;
1713
+ const explicitWarmUpPending = this.#warmUpConfiguredExplicitly() && !explicitWarmUpSettled;
1714
+ const loaderHasPixels = canvasLayer.scene.children.length > 0;
1715
+ const mustPresentLoader =
1716
+ firstWorldPass && canvasLayer.opaque && loaderHasPixels && !loadingFramePresented;
1717
+ if (firstWorldPass && !explicitWarmUpPending) {
1718
+ // `startupCompile` is the fallback that compiles inside the readiness gate. When warm-up
1719
+ // is on it has already happened behind the loading screen, so running it again here
1720
+ // would pay the same cost twice.
1721
+ startupReadiness.start(
1722
+ startupCoverActive() && !this.#warmUpConfiguredExplicitly()
1723
+ ? startupCompile
1724
+ : undefined,
1725
+ );
1726
+ }
1727
+ // Ordinary render compute waits for startup readiness. Streaming explicitly opts in
1728
+ // after compilation so a spawn hold can finish behind the curtain. Present the loader
1729
+ // first; charge this admission to the same render phase as normal render compute.
1730
+ if (
1731
+ this.#renderer !== undefined &&
1732
+ this.#sceneEntered &&
1733
+ !explicitWarmUpPending &&
1734
+ !mustPresentLoader &&
1735
+ (!startupCoverActive() || startupReadiness.compileSettled)
1736
+ ) {
1737
+ const computeStart = frameBudget === undefined ? 0 : budgetNow();
1738
+ beginSpan(SPANS.compute);
1739
+ try {
1740
+ // The render camera comes with it, because a render-cadence consumer that culls by the
1741
+ // view — a streamed world's main batches — has to be driven from here and not from a draw
1742
+ // three skips for a mesh that is hidden because it has nothing to draw.
1743
+ this.#computeDriven.processRender(
1744
+ this.#renderer,
1745
+ camera,
1746
+ startupCoverActive() && !startupReadiness.ready,
1747
+ gameLoop,
1748
+ );
1749
+ } finally {
1750
+ endSpan(SPANS.compute);
1751
+ }
1752
+ frameBudget?.addRender(budgetNow() - computeStart);
1753
+ }
1754
+ const waitingForFirstUse =
1755
+ firstWorldPass &&
1756
+ (explicitWarmUpPending || (startupCoverActive() && !startupReadiness.compileSettled));
1757
+ let worldPasses: ReturnType<RenderPassBudget["passes"]> | undefined;
1758
+ if (
1759
+ !mustPresentLoader &&
1760
+ !waitingForFirstUse &&
1761
+ (!canvasLayer.opaque ||
1762
+ (!startupReadiness.ready && canvasLayer.renderWorldDuringStartup) ||
1763
+ canvasLayer.keepWorldRendering)
1764
+ ) {
1765
+ // The projection's own scene when it is faithful, the game's when it is not. Nothing
1766
+ // here branches on which: `root` is the single render input either way, so there is no
1767
+ // second optional render path to leave untested.
1768
+ // The reconcile is bracketed with the render it feeds: its walk, grouping and matrix
1769
+ // sync are render-path work, and a frame budget that hid it in `residual` made the
1770
+ // optimizer's own cost unmeasurable exactly where the optimizer is engaged.
1771
+ const renderStart = frameBudget === undefined ? 0 : budgetNow();
1772
+ // Before anything walks: a frozen subtree whose author moved its root thaws here, so the
1773
+ // walk that follows sees a transform nobody had to remember to announce.
1774
+ refreshStaticTransforms();
1775
+ // Scene prep that must read the frame's last solved state before the projection packs and
1776
+ // the renderer draws. Inside the world-render block it cannot land on a held loader frame.
1777
+ if (this.#beforeRenderCallbacks.size > 0) {
1778
+ let snapshot = this.#beforeRenderSnapshots[this.#beforeRenderDepth];
1779
+ if (snapshot === undefined) {
1780
+ snapshot = [];
1781
+ this.#beforeRenderSnapshots[this.#beforeRenderDepth] = snapshot;
1782
+ }
1783
+ this.#beforeRenderDepth += 1;
1784
+ snapshot.length = 0;
1785
+ for (const callback of this.#beforeRenderCallbacks) snapshot.push(callback);
1786
+ beginSpan(SPANS.beforeRender);
1787
+ try {
1788
+ for (const callback of snapshot) callback();
1789
+ } finally {
1790
+ endSpan(SPANS.beforeRender);
1791
+ this.#beforeRenderDepth -= 1;
1792
+ }
1793
+ }
1794
+ interpolation.render(gameLoop.clockFrozen || this.#paused ? 1 : alpha, () => {
1795
+ // Let a depth-coupled scene update its output node while the scene pass is still the
1796
+ // next render. Ordinary scenes keep the historical hook order and timing.
1797
+ const depthCoupledOutput = this.#hasDepthCoupledOutput;
1798
+ if (depthCoupledOutput && this.#sceneEntered) this.#scene?.render(ctx);
1799
+ // The engine's own walk owns the frame's world matrices, so the count starts here and
1800
+ // covers both applications below: the authored scene the projection reconciles from and
1801
+ // the root the renderer is actually handed.
1802
+ this.#matrixWorld?.beginFrame();
1803
+ if (this.#projection !== undefined) {
1804
+ beginSpan(SPANS.reconcile);
1805
+ try {
1806
+ this.#projection.reconcile();
1807
+ } finally {
1808
+ endSpan(SPANS.reconcile);
1809
+ }
1810
+ }
1811
+ // Virtual geometry ships on by default, so the engine takes the cut rather than waiting
1812
+ // for a game to know it should. It runs here, before the render and after the reconcile,
1813
+ // because an empty cut has to skip its draw rather than submit a zero-count one — and a
1814
+ // scene holding no clustered mesh pays no traversal at all, only the tracked set.
1815
+ beginSpan(SPANS.clustered);
1816
+ try {
1817
+ updateClusteredMeshes(
1818
+ this.#projection?.root ?? threeScene,
1819
+ camera,
1820
+ renderer.surfaceDrawingBufferHeight?.() ?? renderer.surface().drawingBufferHeight,
1821
+ );
1822
+ } finally {
1823
+ endSpan(SPANS.clustered);
1824
+ }
1825
+ // Automatic discrete LOD ships on with the pipeline, so the engine takes the selection
1826
+ // too. It shares the render root and the same drawing-buffer height, and a scene with no
1827
+ // managed mesh pays only the tracked-set walk.
1828
+ beginSpan(SPANS.lod);
1829
+ try {
1830
+ updateModelLods(
1831
+ this.#projection?.root ?? threeScene,
1832
+ camera,
1833
+ renderer.surface().drawingBufferHeight,
1834
+ );
1835
+ } finally {
1836
+ endSpan(SPANS.lod);
1837
+ }
1838
+ // Projected-size cull, per render camera, default on. It writes only `object.visible` —
1839
+ // the one per-frame flag the projection's batch key ignores — and restores what it hid
1840
+ // immediately after the draw, so the authored scene is untouched between frames. The
1841
+ // renderer walks the same root the projection is about to draw, so a declined projection
1842
+ // and an active one both get the gate.
1843
+ const drawingBufferHeight = renderer.surface().drawingBufferHeight;
1844
+ const cullApplyStart = spans === undefined ? 0 : spanNow();
1845
+ this.#cameraCull?.apply(
1846
+ this.#projection?.root ?? threeScene,
1847
+ camera,
1848
+ drawingBufferHeight,
1849
+ );
1850
+ // Added, not bracketed: the render call sits between the apply and the restore, and a
1851
+ // span that contained it would report the world pass as cull work.
1852
+ if (spans !== undefined) addSpan(SPANS.cull, spanNow() - cullApplyStart);
1853
+ const capturing = geometryCapture.armed();
1854
+ if (capturing) {
1855
+ // The mirror is what the renderer sees; arming the authored scene would attribute the
1856
+ // frame to objects that were never submitted.
1857
+ geometryCapture.beginFrame({
1858
+ camera,
1859
+ generation: this.#sceneGeneration,
1860
+ root: this.#projection?.root ?? threeScene,
1861
+ tick: gameLoop.tick(),
1862
+ viewportHeight: renderer.surface().drawingBufferHeight,
1863
+ viewportWidth: renderer.surface().drawingBufferWidth,
1864
+ ...(renderPassBudget === undefined
1865
+ ? {}
1866
+ : { activePassKind: () => renderPassBudget.activeKind() }),
1867
+ ...(this.#projection === undefined
1868
+ ? {}
1869
+ : { ownership: this.#projection.describeOwnership() }),
1870
+ ...(rendererBackendIdentity(renderer.raw) === undefined
1871
+ ? {}
1872
+ : { backend: rendererBackendIdentity(renderer.raw) as string }),
1873
+ });
1874
+ }
1875
+ const renderRoot = this.#projection?.root ?? threeScene;
1876
+ // three's renderer walks whatever scene it is handed, so it is told not to: the pass above
1877
+ // is the walk. Handing it the mirror sets the mirror scene's flag; the authored scene was
1878
+ // marked at construction.
1879
+ renderRoot.matrixWorldAutoUpdate = false;
1880
+ this.#matrixWorld?.apply(renderRoot);
1881
+ renderer.render(renderRoot, camera);
1882
+ renders += 1;
1883
+ // Count declined frames without treating them as drawn-frame render cost.
1884
+ const gateSkips = rendererFrameGateSkips(renderer.raw);
1885
+ if (gateSkips !== undefined) {
1886
+ if (gateSkips > lastGateSkips) frameBudget?.addRenderSkip();
1887
+ lastGateSkips = gateSkips;
1888
+ }
1889
+ // *After* the render, because that is where the draw happened. The matrices read here are
1890
+ // the ones drawn: the walk above refreshed them and `render()` did not touch them. The
1891
+ // frozen roots are passed because the draw root is the projection's mirror when the
1892
+ // engine is collapsing, and validating only that reassured about a scene it never
1893
+ // looked at. `?.` short-circuits before the spread, so `staticRoots()` is not called
1894
+ // at all on a frame without the flag — verified, a million optional calls evaluate the
1895
+ // argument zero times — and this stays a single undefined check in a shipped game.
1896
+ renderListValidator?.frame(renderRoot, ...staticRoots());
1897
+ const cullRestoreStart = spans === undefined ? 0 : spanNow();
1898
+ this.#cameraCull?.restore();
1899
+ if (spans !== undefined) addSpan(SPANS.cull, spanNow() - cullRestoreStart);
1900
+ this.#projection?.commit();
1901
+ renderer.observeRenderChainFrame?.();
1902
+ frameBudget?.addRender(budgetNow() - renderStart);
1903
+ // Read the split before the overlay renders: the overlay is its own draw, not part of the
1904
+ // world pass, and the budget window already accounts for it in its own phase.
1905
+ worldPasses = renderPassBudget?.passes();
1906
+ if (worldPasses !== undefined && worldPasses.length > 0)
1907
+ frameBudget?.addRenderPasses(worldPasses);
1908
+ // After the passes are read, so the rows reconcile against this frame's own totals.
1909
+ if (capturing) geometryCapture.finishFrame(worldPasses ?? []);
1910
+ // Resolve the GPU timestamps every frame, not once per reported window.
1911
+ //
1912
+ // `trackTimestamp` spends two queries per render pass, and three's pool holds 2048.
1913
+ // A scene with a post-processing chain runs tens of passes per frame — a cathedral
1914
+ // with SSGI, denoise, godrays, SSR and bloom measured 27 — so the pool fills in
1915
+ // 2048 / (2 x 27) = 38 frames. The resolve used to be wired to the frame-budget
1916
+ // window boundary, 300 frames by default, which is eight times too slow: three
1917
+ // warned `Maximum number of queries exceeded`, stopped recording, and every window
1918
+ // after the first reported `gpuMs: undefined`. The one instrument that exists so the
1919
+ // GPU record is not wall-clock algebra was reading nothing.
1920
+ //
1921
+ // This does not put the GPU on the frame path. `resolveTimestampsAsync` is
1922
+ // fire-and-forget and already catch-guarded, which was the original cadence's only
1923
+ // stated concern.
1924
+ // Deliberately unspanned. The resolve runs *after* `addRender` closed the render phase,
1925
+ // so its milliseconds are in the frame's `residual`, not in `render`. A span for it was
1926
+ // measured on the native smoke game at 0.18 ms and showed up as exactly that much
1927
+ // negative residual — the tree reporting, correctly, that it had been handed a term from
1928
+ // outside the phase it is dividing up. The frame budget already carries this cost.
1929
+ renderer.resolveGpuFrame();
1930
+ frameBudget?.addGpuPyramidMs(renderer.gpuPyramidMs?.());
1931
+ // The budget's GPU series is fed every frame, not read once per reported window. A
1932
+ // single window-close read is one instantaneous, lagged `info.render.timestamp` — the
1933
+ // sample that made a 17.6 ms frame read as 2.98–10.40 ms. The sample carries the
1934
+ // resolved frame id so a resolve still in flight is counted stale, not measured twice.
1935
+ //
1936
+ // The reading is the frame's own passes out of three's per-pass map, handed out one
1937
+ // resolved frame per presented frame. Three's resolve answers with one number for the
1938
+ // batch — the last frame in it — so reading that instead dropped every frame a batch
1939
+ // caught up on, and because the resolve is asked for on the same 1-in-8 stride the
1940
+ // sampler uses, how many frames a batch caught up on was a function of frame rate.
1941
+ // The pass recorder is what reads three's per-pass map back into per-frame numbers; a
1942
+ // renderer it cannot instrument falls back to the batch's own single number, which is the
1943
+ // reading there was before — one sample per resolve rather than one per sampled frame.
1944
+ const gpuFrame = renderPassBudget?.nextGpuFrame();
1945
+ const gpuSample = gpuFrame === undefined ? renderer.gpuFrameSample?.() : undefined;
1946
+ frameBudget?.addGpuMs(
1947
+ gpuFrame?.total ?? gpuSample?.ms,
1948
+ gpuFrame?.frame ?? gpuSample?.frame,
1949
+ );
1950
+ // Where one resolved frame's GPU time went: main and shadow come from the pass
1951
+ // recorder's per-uid query results, and everything else in that pool (post chain,
1952
+ // reflections, HUD) is the remainder. Compute is its own pool.
1953
+ if (gpuFrame !== undefined) {
1954
+ const computeMs = renderer.gpuComputeMs?.();
1955
+ // The recorder hands out a frame only when every pass it recorded resolved, so `total`
1956
+ // is the whole frame and never a partial sum; `main` and `shadow` are whole or zero.
1957
+ // `other` is the remainder of the frame (post chain, reflection, HUD). `shadowPasses`
1958
+ // rides along so a consumer can tell a frame that rendered a shadow from one that drew
1959
+ // none, since a real render can resolve to 0 ms.
1960
+ frameBudget?.addGpuBucketMs({
1961
+ main: gpuFrame.main,
1962
+ shadow: gpuFrame.shadow,
1963
+ shadowPasses: gpuFrame.shadowPasses,
1964
+ other: Math.max(0, gpuFrame.total - gpuFrame.main - gpuFrame.shadow),
1965
+ ...(computeMs === undefined ? {} : { compute: computeMs }),
1966
+ });
1967
+ // The main pass's own GPU series, for the adaptive LOD control loop: the frame
1968
+ // budget's `gpuMain` bucket is the record, and this is the same number smoothed on the
1969
+ // renderer so a world holding only the renderer can read it. Fed per delivered frame,
1970
+ // fresh or not.
1971
+ renderer.noteGpuMainMs?.(gpuFrame.main, gpuFrame.frame);
1972
+ } else {
1973
+ renderer.noteGpuMainMs?.(undefined);
1974
+ }
1975
+ if (!depthCoupledOutput && this.#sceneEntered) this.#scene?.render(ctx);
1976
+ if (this.#sceneEntered) {
1977
+ if (!worldRendered) gameLoop.clearRuntimeDiagnostics();
1978
+ worldRendered = true;
1979
+ }
1980
+ if (this.#renderMetricsEnabled) {
1981
+ const metrics = rendererPerformanceMetrics(renderer.raw);
1982
+ worldMetrics =
1983
+ worldPasses === undefined || worldPasses.length === 0
1984
+ ? metrics
1985
+ : { ...metrics, passes: worldPasses.map((pass) => ({ ...pass })) };
1986
+ }
1987
+ // Read whether or not the game asked for render metrics: the projection line reports
1988
+ // the measured draw count, and a convention's measurement does not switch off with the
1989
+ // convention that happens to sit beside it.
1990
+ lastWorldDrawCalls = rendererDrawCallCount(renderer.raw);
1991
+ });
1992
+ }
1993
+ if (mustPresentLoader) loadingFramePresented = true;
1994
+ // Include state written by beforeRender and Scene.render in this frame's UI snapshot.
1995
+ if (this.#config.stateFlushMs === undefined) this.#state.flush();
1996
+ // Every frame, including one whose canvas layer is empty: the native UI is composited into
1997
+ // the game's own frame whether or not the game draws a HUD of its own, so a frame that
1998
+ // skipped this would report work it did pay as `residual`. The host reports what the
1999
+ // *previous* frame's composite cost — the only reading that exists when a frame begins —
2000
+ // so this charges the phase to the frame that paid it, one frame late rather than never.
2001
+ // Absent on the web target and on any host with no overlay, where the work is zero rather
2002
+ // than unknown, so an absent global must read as zero and not as a missing measurement.
2003
+ // The boundary counts ride the span flag, but the simulation tick does not need them: it is
2004
+ // fed every frame so a plain `TN_FRAME_BUDGET` log can join a window's start and end ticks
2005
+ // without `TN_FRAME_SPANS`. `addCounters` keeps the last tick a caller did provide.
2006
+ frameBudget?.addCounters({
2007
+ ...(frameCounters?.read() ?? {}),
2008
+ simulationTick: gameLoop.tick(),
2009
+ });
2010
+ const uiHost = globalThis as { __tnUiCompositeMs?: () => number };
2011
+ frameBudget?.addUi(
2012
+ typeof uiHost.__tnUiCompositeMs === "function" ? (uiHost.__tnUiCompositeMs() ?? 0) : 0,
2013
+ );
2014
+ if (canvasLayer.scene.children.length > 0) {
2015
+ const overlayStart = frameBudget === undefined ? 0 : budgetNow();
2016
+ // The overlay is its own render call and its own frame-budget phase. The span probes sit
2017
+ // on `render`, so without this they would charge the HUD's draw to the render phase the
2018
+ // spans are explaining — measured on the native smoke game as `coverage 1.03` and a
2019
+ // residual of −0.37 ms, two render calls per frame where the phase paid for one. The
2020
+ // recorder is unhooked rather than flagged, so every probe takes the same guarded return
2021
+ // it takes in a shipped build and the span stack cannot be left half-open.
2022
+ if (spans !== undefined) setSpanRecorder(undefined);
2023
+ try {
2024
+ renderer.renderOverlay(canvasLayer.scene, canvasLayer.camera);
2025
+ } finally {
2026
+ if (spans !== undefined) setSpanRecorder(spans);
2027
+ }
2028
+ frameBudget?.addOverlay(budgetNow() - overlayStart);
2029
+ if (!this.#renderMetricsEnabled) return undefined;
2030
+ const overlayMetrics = rendererPerformanceMetrics(renderer.raw);
2031
+ return combineRenderPerformanceMetrics(renderer.kind, worldMetrics, overlayMetrics);
2032
+ }
2033
+ return this.#renderMetricsEnabled ? worldMetrics : undefined;
2034
+ },
2035
+ onAfterPhysics: (dt) => {
2036
+ if (this.#paused) return;
2037
+ afterPhysicsPhase.run(dt);
2038
+ },
2039
+ onUpdate: (dt) => {
2040
+ if (this.#paused) return;
2041
+ this.#input?.tick();
2042
+ scheduler.tick(dt);
2043
+ pointerEvents.tick(input.raw.pointers, picker, input.raw.pointer, input.raw.pointerEdges);
2044
+ for (const plugin of this.#activePlugins) plugin.beforeUpdate?.(ctx, dt);
2045
+ const scene = this.#scene;
2046
+ const frame = this.#sceneFrame;
2047
+ if (frame !== undefined) {
2048
+ frame(ctx, dt);
2049
+ updates += 1;
2050
+ }
2051
+ // An async goto() installs the incoming scene before its load resolves; until enter()
2052
+ // has run there is no gameplay to step and a game-overridden update() would run against
2053
+ // a cleared graph.
2054
+ else if (this.#sceneEntered && scene !== undefined) {
2055
+ scene.update(ctx, dt);
2056
+ updates += 1;
2057
+ }
2058
+ if (this.#scene !== scene || this.#sceneFrame !== frame) return;
2059
+ for (const plugin of this.#activePlugins) plugin.update?.(ctx, dt);
2060
+ this.#entities?.sweep();
2061
+ if (this.#renderer !== undefined && this.#sceneEntered)
2062
+ this.#computeDriven.process(this.#renderer);
2063
+ },
2064
+ onFrame: (frameMs) => startupReadiness.observe(frameMs),
2065
+ step: this.#config.step,
2066
+ });
2067
+ loopState.current = gameLoop;
2068
+ this.#loop = gameLoop;
2069
+ const startGates: Array<{
2070
+ readonly gate: Promise<void>;
2071
+ readonly rejectEntered: (error: unknown) => void;
2072
+ readonly resolveEntered: () => void;
2073
+ }> = [];
2074
+ const runtime: IGamePluginRuntime = {
2075
+ fixedStep: (ticks, options) => gameLoop.advance(ticks, options),
2076
+ frameCounts: () => ({ updates, renders }),
2077
+ frameBudgetWindow: () => this.#frameBudget?.window(),
2078
+ freezeClock: () => gameLoop.freezeClock(),
2079
+ renderCurrent: () => gameLoop.renderCurrentFrame(),
2080
+ enableRuntimeDiagnostics: () => {
2081
+ this.#renderMetricsEnabled = true;
2082
+ gameLoop.setCollectMetrics(true);
2083
+ },
2084
+ holdStart: (gate) => {
2085
+ let rejectEntered: (error: unknown) => void = () => undefined;
2086
+ let resolveEntered: () => void = () => undefined;
2087
+ const entered = new Promise<void>((resolve, reject) => {
2088
+ rejectEntered = reject;
2089
+ resolveEntered = resolve;
2090
+ });
2091
+ startGates.push({ gate, rejectEntered, resolveEntered });
2092
+ return entered;
2093
+ },
2094
+ geometryCapture: (request) => geometryCapture.request(request),
2095
+ observations: createRuntimeObservations(),
2096
+ ...(renderer.pipelineCensus === undefined ? {} : { pipelineCensus: renderer.pipelineCensus }),
2097
+ tick: gameLoop.tick,
2098
+ random,
2099
+ rapier: null,
2100
+ seed: this.#config.seed ?? null,
2101
+ startupCompileSettled: () => startupReadiness.compileSettled,
2102
+ startupTimeline: () => ({ ...timeline }),
2103
+ step: gameLoop.step,
2104
+ runtimeDiagnosticsSeries: () => gameLoop.runtimeDiagnosticsSeries(),
2105
+ };
2106
+ Object.assign(runtime, {
2107
+ _setClockMode: (mode: "fixed-step" | "wall-clock") => gameLoop._setClockMode(mode),
2108
+ });
2109
+ // A boot that throws must end exactly like an aborted boot: every cleanup attempted, every
2110
+ // resource released — and the original error rethrown, not a teardown error standing in
2111
+ // for it. The abort branches below stay outside these guards: they tear down themselves.
2112
+ for (const plugin of this.#config.plugins ?? []) {
2113
+ let cleanup: PluginCleanup | undefined;
2114
+ try {
2115
+ cleanup = typeof plugin === "function" ? plugin(ctx) : await plugin.setup?.(ctx, runtime);
2116
+ } catch (error) {
2117
+ this.#teardown(ctx);
2118
+ throw error;
2119
+ }
2120
+ if (typeof plugin !== "function") this.#activePlugins.push(plugin);
2121
+ if (this.#aborted) {
2122
+ if (cleanup !== undefined) this.#cleanup.push(cleanup);
2123
+ this.#teardown(ctx);
2124
+ return;
2125
+ }
2126
+ if (cleanup !== undefined) this.#cleanup.push(cleanup);
2127
+ }
2128
+ const scene = this.#scene;
2129
+ if (scene === undefined) {
2130
+ this.#teardown(ctx);
2131
+ return;
2132
+ }
2133
+ // Held: the loop renders every frame from here but steps nothing. On native the render loop
2134
+ // is the only thing that can put pixels on the screen, so an async load starts it before the
2135
+ // await; a synchronous load has already completed and starts it after the call. Holding rather
2136
+ // than simply starting keeps the determinism contract intact: no tick advances and no elapsed
2137
+ // time is banked before the release below.
2138
+ const startHeldLoop = (): void => {
2139
+ gameLoop.setHeld(true);
2140
+ gameLoop.start();
2141
+ };
2142
+ try {
2143
+ timeline.loadStartedMs ??= now();
2144
+ const loaded = scene.load(ctx);
2145
+ startHeldLoop();
2146
+ if (loaded !== undefined) await loaded;
2147
+ } catch (error) {
2148
+ this.#teardown(ctx);
2149
+ throw error;
2150
+ }
2151
+ if (this.#aborted) {
2152
+ this.#teardown(ctx);
2153
+ return;
2154
+ }
2155
+ // Plugins that need to mutate scene-load placeholders hold here. Setup must land before
2156
+ // Scene.enter() transfers those values into authoritative physics/gameplay state.
2157
+ if (startGates.length > 0) {
2158
+ try {
2159
+ await Promise.all(startGates.map(({ gate }) => gate));
2160
+ } catch (error) {
2161
+ for (const startGate of startGates) startGate.rejectEntered(error);
2162
+ this.#teardown(ctx);
2163
+ throw error;
2164
+ }
2165
+ if (this.#aborted) {
2166
+ const error = new Error("Game start was aborted before the start scene entered.");
2167
+ for (const startGate of startGates) startGate.rejectEntered(error);
2168
+ this.#teardown(ctx);
2169
+ return;
2170
+ }
2171
+ }
2172
+ try {
2173
+ this.#enterScene(scene, ctx);
2174
+ timeline.enteredMs ??= now();
2175
+ // A start scene that navigates inside `enter()` — every `boot` template does — has handed the
2176
+ // run a world that is still in `load()`, and the entity registry is empty until it enters.
2177
+ // Releasing the gate there described a game that had not been built yet, so every
2178
+ // entity-derived capability was read off nothing. The gate follows the scene that entered.
2179
+ const worldEntered = this.#pendingSceneEnter;
2180
+ const entered = (): void => {
2181
+ for (const startGate of startGates) startGate.resolveEntered();
2182
+ };
2183
+ if (worldEntered === undefined) entered();
2184
+ else
2185
+ void worldEntered.then(entered, (error: unknown) => {
2186
+ for (const startGate of startGates) startGate.rejectEntered(error);
2187
+ });
2188
+ } catch (error) {
2189
+ for (const startGate of startGates) startGate.rejectEntered(error);
2190
+ this.#teardown(ctx);
2191
+ throw error;
2192
+ }
2193
+ if (this.#aborted) {
2194
+ this.#teardown(ctx);
2195
+ return;
2196
+ }
2197
+ // The scene is built and the loop is still held, which is the only window where compiling can
2198
+ // cost frames nobody is playing. Warming up here rather than letting the first real frame do
2199
+ // it is what keeps a launch from freezing inside one 24-second frame. PRD-218.
2200
+ if (this.#warmUpConfiguredExplicitly() && this.#renderer !== undefined) {
2201
+ // Never fatal, and never able to hang the launch. This block sits between "the scene is
2202
+ // built" and "the game may start", so anything it does wrong is something the player
2203
+ // experiences as the game not starting -- which is exactly what the first version did: a
2204
+ // `compileAsync` that never resolved on a Pixel 8 left this `await` pending forever, the
2205
+ // loop stayed held, the simulation never advanced, and the game sat on its loading screen
2206
+ // with no error anywhere. A warm-up that fails must cost the launch its speed, never its
2207
+ // start, so the failure is reported and boot carries on.
2208
+ let report: IWarmUpReport | undefined;
2209
+ let failure: string | undefined;
2210
+ try {
2211
+ projection.reconcile();
2212
+ // Same walk as the held warm-up above: the explicit warm-up also draws before the frame
2213
+ // loop's own matrix pass, and a declined projection left the scene un-walked.
2214
+ this.#matrixWorld?.apply(projection.root);
2215
+ const warmUpOptions: IWarmUpOptions = this.#warmUpOptions();
2216
+ report = await warmUpScene(this.#renderer, projection.root, camera, {
2217
+ ...warmUpOptions,
2218
+ computeNodes: [...(warmUpOptions.computeNodes ?? []), ...this.#computeDriven.warmupNodes],
2219
+ });
2220
+ } catch (error) {
2221
+ failure = error instanceof Error ? error.message : String(error);
2222
+ }
2223
+ this.#renderer.warmUpSettled?.();
2224
+ warmUpStatus =
2225
+ report === undefined
2226
+ ? { status: "unavailable" }
2227
+ : {
2228
+ attempted: report.attempted,
2229
+ candidates: report.candidates,
2230
+ observed: report.observed,
2231
+ status: report.observed.status,
2232
+ };
2233
+ // One greppable line on every platform, so a device lane reads what the warm-up did without
2234
+ // instrumenting anything -- including the cases where it could do nothing, ran out of
2235
+ // budget, or threw.
2236
+ console.log(
2237
+ `TN_WARMUP:${JSON.stringify(
2238
+ report === undefined
2239
+ ? { failed: failure ?? "unknown" }
2240
+ : {
2241
+ compiled: report.compiled,
2242
+ pipelines: report.pipelines,
2243
+ candidates: report.candidates,
2244
+ attempted: report.attempted,
2245
+ observed: report.observed,
2246
+ slices: report.slices,
2247
+ elapsedMs: Math.round(report.elapsedMs),
2248
+ unsupported: report.unsupported,
2249
+ abandoned: report.abandoned,
2250
+ timedOut: report.timedOut,
2251
+ computeCompiled: report.computeCompiled,
2252
+ computeAbandoned: report.computeAbandoned,
2253
+ computeUnsupported: report.computeUnsupported,
2254
+ computeTimedOut: report.computeTimedOut,
2255
+ passes: report.passes,
2256
+ passPipelines: report.passPipelines,
2257
+ cullingForced: report.cullingForced,
2258
+ visibilityForced: report.visibilityForced,
2259
+ cache: report.cache,
2260
+ },
2261
+ )}`,
2262
+ );
2263
+ explicitWarmUpSettled = true;
2264
+ if (this.#aborted) {
2265
+ this.#teardown(ctx);
2266
+ return;
2267
+ }
2268
+ }
2269
+ this.#started = true;
2270
+ // Every gate has resolved and the scene has entered, so the simulation may move. The first
2271
+ // tick after this reads a single frame's dt, not one spanning the load.
2272
+ gameLoop.setHeld(false);
2273
+ gameLoop.start();
2274
+ }
2275
+ pause(): void {
2276
+ this.#paused = true;
2277
+ }
2278
+
2279
+ resume(): void {
2280
+ this.#paused = false;
2281
+ }
2282
+
2283
+ stop(): void {
2284
+ this.#aborted = true;
2285
+ this.#geometryCapture?.cancel("TN_GEOMETRY_CAPTURE_STOPPED: the game stopped mid-capture.");
2286
+ this.#teardown();
2287
+ }
2288
+
2289
+ #disposePlugin(plugin: IGamePluginHooks<TState, TPhysics>, ctx: ICtx<TState, TPhysics>): void {
2290
+ if (this.#disposedPlugins.has(plugin)) return;
2291
+ this.#disposedPlugins.add(plugin);
2292
+ plugin.dispose?.(ctx);
2293
+ }
2294
+
2295
+ #teardown(startingCtx?: ICtx<TState, TPhysics>): void {
2296
+ const ctx = this.#ctx ?? startingCtx;
2297
+ // Teardown is failure-atomic: one throwing release must not strand the resources after it.
2298
+ // Every attempt runs, errors are collected, and the first — the original cause — is thrown
2299
+ // once all attempts and the final leak check have completed.
2300
+ const failures: unknown[] = [];
2301
+ this.#disconnectUi();
2302
+ this.#loop?.stop();
2303
+ this.#frameBudget?.dispose();
2304
+ this.#afterPhysicsPhase?.clear();
2305
+ this.#beforeRenderCallbacks.clear();
2306
+ this.#interpolation?.clear();
2307
+ this.#interpolation = undefined;
2308
+ if (this.#sceneEntered && ctx !== undefined) {
2309
+ try {
2310
+ this.#scene?.exit(ctx);
2311
+ } catch (error) {
2312
+ failures.push(error);
2313
+ }
2314
+ }
2315
+ this.#sceneFrame = undefined;
2316
+ this.#sceneEntered = false;
2317
+ this.#scheduler?.clear();
2318
+ this.#entities?.clear();
2319
+ this.#entities = undefined;
2320
+ if (ctx !== undefined)
2321
+ for (const plugin of this.#activePlugins) {
2322
+ try {
2323
+ this.#disposePlugin(plugin, ctx);
2324
+ } catch (error) {
2325
+ failures.push(error);
2326
+ }
2327
+ }
2328
+ this.#activePlugins = [];
2329
+ for (const cleanup of this.#cleanup.splice(0)) {
2330
+ try {
2331
+ cleanup();
2332
+ } catch (error) {
2333
+ failures.push(error);
2334
+ }
2335
+ }
2336
+ if (ctx !== undefined) clearScene(ctx.scene, this.#computeDriven);
2337
+ this.#cameraCull?.dispose();
2338
+ this.#cameraCull = undefined;
2339
+ this.#matrixWorld?.dispose();
2340
+ this.#matrixWorld = undefined;
2341
+ this.#input?.dispose();
2342
+ this.#state.stop();
2343
+ ctx?.canvasLayer.dispose();
2344
+ this.#viewport?.dispose();
2345
+ const renderer = this.#renderer;
2346
+ renderer?.dispose();
2347
+ if (renderer !== undefined) {
2348
+ if (this.#config.platform === undefined) renderer.domElement.remove?.();
2349
+ else this.#config.platform.unmountCanvas(renderer.domElement);
2350
+ }
2351
+ this.#renderer = undefined;
2352
+ this.#viewport = undefined;
2353
+ this.#input = undefined;
2354
+ this.#scene = undefined;
2355
+ this.#ctx = undefined;
2356
+ this.#hasDepthCoupledOutput = false;
2357
+ this.#loop = undefined;
2358
+ this.#pointerEvents?.dispose();
2359
+ this.#pointerEvents = undefined;
2360
+ this.#picker?.dispose();
2361
+ this.#picker = undefined;
2362
+ this.#scheduler = undefined;
2363
+ this.#afterPhysicsPhase = undefined;
2364
+ this.#disposedPlugins.clear();
2365
+ this.#paused = false;
2366
+ this.#started = false;
2367
+ // Runs even when releases above failed; its verdict loses to a real cleanup error, which is
2368
+ // the more actionable diagnosis of what went wrong while stopping.
2369
+ if ((ctx?.scene.children.length ?? 0) > 0)
2370
+ failures.push(new Error("IGame teardown leaked scene objects."));
2371
+ if (failures.length > 0) throw failures[0];
2372
+ }
2373
+ }
2374
+
2375
+ function createRuntimeObservations(): IGameRuntimeObservations {
2376
+ const contributions = new Set<IGameObservationContribution>();
2377
+ return {
2378
+ contribute: (contribution) => {
2379
+ contributions.add(contribution);
2380
+ return () => contributions.delete(contribution);
2381
+ },
2382
+ contributions: () => [...contributions],
2383
+ };
2384
+ }
2385
+
2386
+ export function defineGame<TState extends Record<string, unknown>, TPhysics = undefined>(
2387
+ config: IGameConfig<TState, TPhysics>,
2388
+ ): IGame<TState, TPhysics> {
2389
+ return new GameImpl<TState, TPhysics>(config);
2390
+ }