@threenative/core 0.3.11 → 0.3.13

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