@threenative/core 0.3.5 → 0.3.8

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 (137) hide show
  1. package/README.md +3 -5
  2. package/capabilities.json +739 -50
  3. package/dist/{assets-CqvE429w.d.ts → assets-YUbXa3-Y.d.ts} +101 -2
  4. package/dist/{canvas-layer-C1-5CviZ.d.ts → canvas-layer-vCtanIeB.d.ts} +1 -1
  5. package/dist/{game-Bj8G1wmD.d.ts → game-cb99J-YE.d.ts} +112 -31
  6. package/dist/hot.d.ts +4 -4
  7. package/dist/hot.js +23 -5
  8. package/dist/index.d.ts +1742 -29
  9. package/dist/index.js +22445 -12411
  10. package/dist/{model-lod-BDAUYgsS.d.ts → model-lod-CTpZ6imz.d.ts} +1 -1
  11. package/dist/net.js +39 -12
  12. package/dist/playtest.d.ts +4 -4
  13. package/dist/playtest.js +59 -10
  14. package/dist/react-css.js +23 -0
  15. package/dist/react.d.ts +2 -2
  16. package/dist/{renderer-9yEo9hPa.d.ts → renderer-rZm0hVqq.d.ts} +178 -5
  17. package/dist/ui-layer.d.ts +11 -2
  18. package/dist/ui-layer.js +76 -4
  19. package/dist/worker.d.ts +36 -0
  20. package/dist/worker.js +1088 -0
  21. package/dist/world.d.ts +11 -3
  22. package/dist/world.js +1117 -197
  23. package/mcp/animation-server.mjs +265 -0
  24. package/mcp/animation.mjs +22 -0
  25. package/mcp/call.mjs +105 -0
  26. package/mcp/devtools.mjs +5 -0
  27. package/mcp/engine-server.mjs +713 -37
  28. package/mcp/launch.mjs +3 -2
  29. package/mcp/servers.d.mts +2 -0
  30. package/mcp/servers.mjs +33 -8
  31. package/package.json +12 -8
  32. package/patches/three@0.185.1-prd269-upgrade.patch +308 -0
  33. package/patches/three@0.185.1.patch +481 -272
  34. package/src/animation-packet-state.ts +88 -0
  35. package/src/animation-pose-packet.ts +537 -0
  36. package/src/animation.ts +779 -31
  37. package/src/asset-cache.ts +719 -0
  38. package/src/assets.ts +521 -152
  39. package/src/audio.ts +29 -3
  40. package/src/auto-batch.ts +792 -0
  41. package/src/config.ts +2 -0
  42. package/src/frame-budget.ts +268 -2
  43. package/src/game.ts +544 -106
  44. package/src/grounding.ts +7 -6
  45. package/src/hot.ts +19 -5
  46. package/src/index.ts +381 -6
  47. package/src/input.ts +21 -2
  48. package/src/interpolation.ts +19 -1
  49. package/src/launch-diagnostics.ts +7 -2
  50. package/src/look/ao-multibounce.ts +29 -0
  51. package/src/look/ao-reach.ts +39 -0
  52. package/src/look/auto-exposure.ts +264 -0
  53. package/src/look/default-tone-mapping.ts +44 -0
  54. package/src/look/exposure-graph.ts +208 -0
  55. package/src/look/exposure-readback.ts +97 -0
  56. package/src/look/exposure-settings.ts +132 -0
  57. package/src/look/filmic-tone-mapping.ts +852 -0
  58. package/src/look/gi-registry.ts +55 -0
  59. package/src/look/local-exposure.ts +507 -0
  60. package/src/look/look-diagnostics.ts +24 -0
  61. package/src/look/motion-blur.ts +42 -0
  62. package/src/look/quality.ts +309 -0
  63. package/src/look/reflection-trace.ts +344 -0
  64. package/src/look/unreal-bloom.ts +295 -0
  65. package/src/look/vignette.ts +14 -0
  66. package/src/look/world-environment.ts +2033 -0
  67. package/src/loop.ts +40 -6
  68. package/src/merge-parts.ts +25 -10
  69. package/src/model-lod.ts +14 -0
  70. package/src/net-session.ts +58 -14
  71. package/src/ocean/spectral.ts +41 -7
  72. package/src/picking.ts +72 -5
  73. package/src/platform.ts +29 -1
  74. package/src/playtest.ts +69 -12
  75. package/src/profiling/FrameCounters.ts +166 -5
  76. package/src/profiling/FrameStages.ts +289 -0
  77. package/src/profiling/Spans.ts +39 -25
  78. package/src/profiling/debug-telemetry.ts +312 -0
  79. package/src/profiling/scene-warning.ts +42 -6
  80. package/src/projection-apply.ts +11 -3
  81. package/src/projection-content.ts +189 -0
  82. package/src/projection-marker.ts +6 -2
  83. package/src/projection-plan.ts +279 -28
  84. package/src/projection-skinned.ts +620 -5
  85. package/src/projection-stability.ts +16 -0
  86. package/src/projection-uniform.ts +5 -1
  87. package/src/quiet-markers.ts +56 -0
  88. package/src/render/budget-ladder.ts +256 -0
  89. package/src/render/chain.ts +89 -7
  90. package/src/render/exposure-units.ts +59 -0
  91. package/src/render/frame-time-budget.ts +162 -0
  92. package/src/render/gi-budget.ts +231 -0
  93. package/src/render/gi-visualize.ts +49 -0
  94. package/src/render/material-key.ts +1 -0
  95. package/src/render/probe-volume.ts +196 -36
  96. package/src/render/rough-diffuse.ts +177 -0
  97. package/src/render/scene-trace.ts +532 -0
  98. package/src/render/shadow-filter-budget.ts +237 -0
  99. package/src/render/sky-capture.ts +194 -0
  100. package/src/render/soft-shadow.ts +607 -0
  101. package/src/render/surface-cache.ts +418 -0
  102. package/src/render/traced-reflections.ts +408 -0
  103. package/src/render/two-sided-foliage.ts +120 -0
  104. package/src/render/virtual-shadow-pages.ts +112 -12
  105. package/src/render/virtual-shadow.ts +386 -38
  106. package/src/render-camera-cull.ts +536 -31
  107. package/src/render-pass-budget.ts +140 -22
  108. package/src/renderProjection.ts +65 -9
  109. package/src/renderer-config.ts +3 -2
  110. package/src/renderer.ts +289 -14
  111. package/src/resolution-scaler.ts +65 -7
  112. package/src/skeletal-mesh.ts +4 -0
  113. package/src/snow-field.ts +46 -0
  114. package/src/softbody.ts +6 -5
  115. package/src/startup-offscreen-bytes.ts +168 -0
  116. package/src/startup-readiness.ts +137 -2
  117. package/src/ui-bridge.ts +38 -0
  118. package/src/ui-hit-regions.ts +6 -2
  119. package/src/ui-layer.ts +1 -0
  120. package/src/ui-state.ts +32 -3
  121. package/src/version.ts +1 -1
  122. package/src/viewport.ts +8 -5
  123. package/src/warmup.ts +76 -10
  124. package/src/worker-audio.ts +579 -0
  125. package/src/worker.ts +842 -0
  126. package/src/world-cells.ts +4 -1
  127. package/gpl/LICENSE.GPL +0 -117
  128. package/gpl/convert.py +0 -192
  129. package/gpl/fixtures/make_world_fixture.py +0 -184
  130. package/gpl/recipes/_common.py +0 -180
  131. package/gpl/recipes/bake_ao.py +0 -111
  132. package/gpl/recipes/decimate.py +0 -70
  133. package/gpl/recipes/export_world.py +0 -699
  134. package/gpl/recipes/retarget.py +0 -131
  135. package/gpl/recipes/unwrap.py +0 -71
  136. package/mcp/blender-server.mjs +0 -689
  137. package/mcp/blender.mjs +0 -26
package/src/game.ts CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  Vector2,
8
8
  } from "three";
9
9
  import { type IAssetLoaderOptions, createAssetLoader } from "./assets.js";
10
+ import { AutoBatch, type IAutoBatchConfig } from "./auto-batch.js";
10
11
  import { CanvasLayer } from "./canvas-layer.js";
11
12
  import { updateClusteredMeshes } from "./clustered-mesh.js";
12
13
  import { ComputeDrivenRegistry, isComputeDriven } from "./compute-driven.js";
@@ -33,9 +34,19 @@ import { MatrixWorldPass } from "./matrix-world.js";
33
34
  import { updateModelLods } from "./model-lod.js";
34
35
  import { ScenePicker } from "./picking.js";
35
36
  import type { IPipelineCensus } from "./pipeline-census.js";
36
- import { getPlatform } from "./platform.js";
37
+ import { getPlatform, hostDocument, hostWindow } from "./platform.js";
37
38
  import { PointerEvents3D } from "./pointer-events.js";
38
- import { FrameCounters, counterDeviceOf } from "./profiling/FrameCounters.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";
39
50
  import {
40
51
  SPANS,
41
52
  SpanRecorder,
@@ -47,6 +58,12 @@ import {
47
58
  spanNow,
48
59
  spansRequested,
49
60
  } from "./profiling/Spans.js";
61
+ import {
62
+ countDebug,
63
+ debugRequested,
64
+ measureDebug,
65
+ observeDebugGc,
66
+ } from "./profiling/debug-telemetry.js";
50
67
  import { applyOpacityConvention } from "./profiling/opacity-convention.js";
51
68
  import {
52
69
  RenderListValidator,
@@ -67,6 +84,7 @@ import {
67
84
  unlitFoliageWarning,
68
85
  } from "./profiling/unlit-foliage-warning.js";
69
86
  import { formatProjectionWindow } from "./projection-marker.js";
87
+ import { installQuietMarkers, uninstallQuietMarkers } from "./quiet-markers.js";
70
88
  import { type IRandom, createRandom } from "./random.js";
71
89
  import { RenderCameraCull } from "./render-camera-cull.js";
72
90
  import { RenderPassBudget } from "./render-pass-budget.js";
@@ -83,6 +101,8 @@ import {
83
101
  type IRendererOptions,
84
102
  type RendererKind,
85
103
  createRenderer,
104
+ rendererFrameGateSkips,
105
+ rendererWorldPresented,
86
106
  } from "./renderer.js";
87
107
  import { RESOLUTION_SCALER, ResolutionScaler } from "./resolution-scaler.js";
88
108
  import type {
@@ -95,7 +115,14 @@ import type {
95
115
  } from "./scene.js";
96
116
  import { Scheduler } from "./schedule.js";
97
117
  import {
118
+ type IStartupOffscreenBytes,
119
+ STARTUP_OFFSCREEN_BYTES_MARKER,
120
+ measureStartupOffscreenBytes,
121
+ } from "./startup-offscreen-bytes.js";
122
+ import {
123
+ type IStartupImageState,
98
124
  STARTUP_COMPILE_BUDGET_MS,
125
+ STARTUP_STABLE_WINDOW_MS,
99
126
  STARTUP_STALL_MS,
100
127
  type StartupCompile,
101
128
  StartupReadiness,
@@ -112,6 +139,7 @@ import {
112
139
  type IUiBridge,
113
140
  UI_DEV_METRICS_MESSAGE,
114
141
  UI_READY_INTENT,
142
+ UI_STARTUP_MESSAGE,
115
143
  connectUiBridge,
116
144
  } from "./ui-bridge.js";
117
145
  import { type IUiStatePublisher, onUiIntent, publishUiState } from "./ui-state.js";
@@ -119,6 +147,8 @@ import { type IViewportOptions, Viewport } from "./viewport.js";
119
147
  import {
120
148
  type IWarmUpOptions,
121
149
  type IWarmUpReport,
150
+ prepareSceneEnvironment,
151
+ sceneNeedsEnvironmentPreparation,
122
152
  warmUpComputeNodes,
123
153
  warmUpScene,
124
154
  } from "./warmup.js";
@@ -151,7 +181,19 @@ export interface IGameRuntimeObservations {
151
181
  }
152
182
 
153
183
  export interface IGamePluginRuntime {
184
+ /**
185
+ * Runs `ticks` fixed steps and returns how many ran. Fewer than asked when a `goto()` began
186
+ * inside the batch: the ticks after it belong to the destination scene, which does not exist
187
+ * until `sceneTransition()` settles.
188
+ */
154
189
  readonly fixedStep: (ticks: number, options?: { render?: boolean }) => number;
190
+ /**
191
+ * The `goto()` in flight, or undefined when no scene is loading. Settles once the destination
192
+ * scene has loaded and entered, and never rejects: a failed load is reported as a launch
193
+ * failure. A runner that counts ticks awaits it before spending more, exactly as it awaits
194
+ * `holdStart` at boot, so a restart cannot be outrun by the ticks that follow it.
195
+ */
196
+ readonly sceneTransition?: () => Promise<void> | undefined;
155
197
  /** Completed scene updates and primary world render requests, independent of budget windows. */
156
198
  readonly frameCounts?: () => { updates: number; renders: number };
157
199
  /**
@@ -188,6 +230,12 @@ export interface IGamePluginRuntime {
188
230
  * they read are the ones the world actually has. The frame loop remains held throughout.
189
231
  */
190
232
  readonly holdStart?: (gate: Promise<void>) => Promise<void>;
233
+ /**
234
+ * Settles when the start scene's `load()` has finished, so its entities are registered. A runner's
235
+ * pre-entry setup awaits it: setup names entities `load()` adds, and an async `load()` (a texture
236
+ * or a model fetch) is still pending when the runner first attaches. Rejects when `load()` throws.
237
+ */
238
+ readonly startSceneLoaded?: () => Promise<void>;
191
239
  readonly observations: IGameRuntimeObservations;
192
240
  readonly tick: () => number;
193
241
  readonly runtimeDiagnosticsSeries?: () => readonly IRenderPerformanceSample[];
@@ -203,8 +251,12 @@ export interface IGamePluginRuntime {
203
251
  * must be reported rather than inferred from a phase that cannot distinguish the two.
204
252
  */
205
253
  readonly startupCompileSettled?: () => boolean;
254
+ /** The loading cover has lifted: the startup hand-off finished and page UI shows state. */
255
+ readonly startupRevealed?: () => boolean;
206
256
  /** When the startup milestones happened, for the playtest bridge's startup observation. */
207
257
  readonly startupTimeline?: () => IStartupTimeline;
258
+ /** What the reveal waited for that the spawn camera does not show; absent until the reveal. */
259
+ readonly startupOffscreenBytes?: () => IStartupOffscreenBytes | undefined;
208
260
  /** The renderer-owned bounded pipeline capture, when the renderer has not been opted out. */
209
261
  readonly pipelineCensus?: () => IPipelineCensus;
210
262
  /**
@@ -344,6 +396,15 @@ export type GamePlugin<
344
396
  */
345
397
  const STARTUP_READY_GLOBAL = "__TN_STARTUP_READY__";
346
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
+
347
408
  export interface IGameConfig<
348
409
  TState extends Record<string, unknown> = Record<string, unknown>,
349
410
  TPhysics = undefined,
@@ -367,6 +428,13 @@ export interface IGameConfig<
367
428
  * assertion, because turning a convention off must not turn its measurement off.
368
429
  */
369
430
  readonly frameBudget?: IFrameBudgetOptions | false;
431
+ /**
432
+ * Static meshes that share a material merge into one draw once the scene has settled, on by
433
+ * default and reported as `TN_AUTO_BATCH`. A mesh the game later moves, hides or re-materials
434
+ * comes back at once. `false` turns the pass off; `userData.batch = "off"` on a mesh or any
435
+ * ancestor keeps just that subtree out.
436
+ */
437
+ readonly autoBatch?: boolean | IAutoBatchConfig;
370
438
  readonly initialState?: TState;
371
439
  /**
372
440
  * The **pre-start** shader warm-up. Off by default, and that is not the same as no warm-up.
@@ -492,8 +560,11 @@ export interface IGame<
492
560
  readonly ui: IGameUi;
493
561
  /** Rebuilds the requested scene from its initial state, then merges an optional carry patch. */
494
562
  goto(name: string, options?: IGotoOptions<TState>): Promise<void>;
495
- /** Boot into `name` instead of `config.start` on the next `start()`. Hot reload's restore path. */
496
- resumeScene(name: string): void;
563
+ /**
564
+ * Boot into `name` instead of `config.start` on the next `start()`. Hot reload's restore path.
565
+ * `revealed`: the session already showed its HUD, so the restarted game keeps the cover lifted.
566
+ */
567
+ resumeScene(name: string, options?: { readonly revealed?: boolean }): void;
497
568
  start(): Promise<void>;
498
569
  pause(): void;
499
570
  resume(): void;
@@ -577,13 +648,6 @@ function rendererDrawCallCount(raw: unknown): number | undefined {
577
648
  return typeof calls === "number" && Number.isFinite(calls) && calls >= 0 ? calls : undefined;
578
649
  }
579
650
 
580
- /** Cumulative render() calls the renderer declined to draw (the Wasm web engine's frame gate), when it counts them. */
581
- function rendererFrameGateSkips(raw: unknown): number | undefined {
582
- const info = (raw as { info?: { engine?: { frameGateSkips?: unknown } } } | null)?.info;
583
- const skips = info?.engine?.frameGateSkips;
584
- return typeof skips === "number" && Number.isFinite(skips) ? skips : undefined;
585
- }
586
-
587
651
  function rendererPerformanceMetrics(raw: unknown): {
588
652
  drawCalls?: number;
589
653
  triangles?: number;
@@ -710,6 +774,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
710
774
  #loop: FixedStepLoop | undefined;
711
775
  #interpolation: PhysicsInterpolation | undefined;
712
776
  #projection: SceneRenderProjection | undefined;
777
+ #autoBatch: AutoBatch | undefined;
713
778
  #cameraCull: RenderCameraCull | undefined;
714
779
  #matrixWorld: MatrixWorldPass | undefined;
715
780
  #cleanup: Array<() => void> = [];
@@ -734,19 +799,19 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
734
799
  #pendingStart: Promise<void> | undefined;
735
800
  #aborted = false;
736
801
  #sceneEntered = false;
737
- /**
738
- * The scene a `goto()` is loading right now, or undefined when none is.
739
- *
740
- * Between a `goto()` and its `enter()` the registry is cleared and nothing owns the world, so a
741
- * reader that needs the world's entities has to wait for this rather than for the scene it
742
- * navigated from. The playtest handshake reads exactly that.
743
- */
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. */
744
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;
745
808
  #paused = false;
746
809
  #started = false;
747
810
  #uiBridge: IUiBridge | undefined;
748
811
  #uiPublisher: IUiStatePublisher | undefined;
749
812
  #uiReady = false;
813
+ /** The loading cover has lifted and page UI may show state; see `UI_STARTUP_MESSAGE`. */
814
+ #uiRevealed = false;
750
815
  // Flipped only by a diagnostics consumer announcing itself; see enableRuntimeDiagnostics().
751
816
  #renderMetricsEnabled = false;
752
817
  // Depth-coupled output needs the scene hook before its pass; ordinary scenes retain the
@@ -793,9 +858,15 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
793
858
  * available here: it throws before `start()`, and it resets state to the destination's
794
859
  * `initialState`, which would discard the very state being restored.
795
860
  */
796
- resumeScene(name: string): void {
861
+ resumeScene(name: string, options?: { readonly revealed?: boolean }): void {
797
862
  if (this.#config.scenes[name] === undefined) throw new Error(`Unknown scene '${name}'.`);
798
863
  this.#resumeScene = name;
864
+ // An edit restarts the game, and its HUD would blank until this startup lifted the cover
865
+ // again: seconds after every save on a slow GPU. A session that showed its HUD keeps it.
866
+ // The updated module may have connected its UI already and told a waiting HUD to hide.
867
+ if (options?.revealed !== true) return;
868
+ this.#uiRevealed = true;
869
+ if (this.#uiBridge?.hasPeer()) this.#postUiStartup();
799
870
  }
800
871
 
801
872
  get state(): GameStore<TState> {
@@ -824,10 +895,15 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
824
895
  this.#uiBridge = bridge;
825
896
  // The store already coalesces writes at flush. Deferring this again waits for the native
826
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();
827
900
  this.#uiPublisher = publishUiState(bridge, this.#state, { schedule: (flush) => flush() });
828
901
  onUiIntent(bridge, (intent) => {
829
902
  if (intent !== UI_READY_INTENT) return;
830
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();
831
907
  // Publish immediately: the UI has just rendered against nothing, and waiting for the store's
832
908
  // next change would leave a HUD showing its initial values for up to a tick.
833
909
  this.#uiPublisher?.publish();
@@ -835,7 +911,15 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
835
911
  return bridge;
836
912
  }
837
913
 
914
+ #postUiStartup(): void {
915
+ this.#uiBridge?.post({
916
+ type: UI_STARTUP_MESSAGE,
917
+ phase: this.#uiRevealed ? "ready" : "covered",
918
+ });
919
+ }
920
+
838
921
  #disconnectUi(): void {
922
+ this.#uiRevealed = false;
839
923
  this.#uiPublisher?.stop();
840
924
  this.#uiPublisher = undefined;
841
925
  this.#uiReady = false;
@@ -889,6 +973,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
889
973
  // Put back anything the cull hid before the outgoing scene is cleared, so a scene change never
890
974
  // leaves an object invisible if the game keeps a reference to it.
891
975
  this.#cameraCull?.restore();
976
+ this.#autoBatch?.reset();
892
977
  clearScene(ctx.scene, this.#computeDriven);
893
978
  const scene = new SceneType();
894
979
  this.#scene = scene;
@@ -925,6 +1010,10 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
925
1010
  if (this.#scene !== scene) return false;
926
1011
  this.#sceneFrame = typeof frame === "function" ? frame : undefined;
927
1012
  this.#sceneEntered = true;
1013
+ // What `enter()` built is what the warm-up compiles and the first frame draws, so it merges
1014
+ // now, before either: no frame is ever drawn unmerged, and the compile counts merged meshes,
1015
+ // not every source. Anything that moves afterwards is given back by the guard.
1016
+ this.#autoBatch?.settleNow();
928
1017
  // Before the audit, so an opacity the convention made take effect is reported as a warning.
929
1018
  const opacity = applyOpacityConvention(ctx.scene);
930
1019
  if (opacity !== undefined) console.warn(opacity);
@@ -937,6 +1026,9 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
937
1026
  const unlit = unlitFoliageWarning(ctx.scene);
938
1027
  if (unlit !== undefined)
939
1028
  console.warn(`${formatUnlitFoliageWarning(unlit)} ${UNLIT_FOLIAGE_FIX}`);
1029
+ const entered = this.#onStartSceneEntered;
1030
+ this.#onStartSceneEntered = undefined;
1031
+ entered?.();
940
1032
  return true;
941
1033
  }
942
1034
 
@@ -944,27 +1036,62 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
944
1036
  scene: Scene<TState, TPhysics>,
945
1037
  ctx: ICtx<TState, TPhysics>,
946
1038
  ): Promise<void> {
1039
+ // A load can finish after the game moved on or stopped. Check before `enter()`, because an
1040
+ // entry hook mutates the live Three.js scene and no later check can undo that. The check
1041
+ // inside `#enterScene` stays: an entry hook may itself navigate.
1042
+ if (this.#aborted || this.#ctx !== ctx || this.#scene !== scene) return;
947
1043
  if (!this.#enterScene(scene, ctx)) return;
948
1044
  const renderer = this.#renderer;
949
1045
  const nodes = this.#computeDriven.warmupNodes;
950
- if (renderer === undefined || nodes.length === 0) return;
1046
+ // Before startup readiness has begun, its own warm-up bakes the entered scene's environment.
1047
+ // Baking here too held the world pass for the whole bake: the runner kit's Boot calls
1048
+ // goto("run") from enter(), the bake took 35 s on SwiftShader (about 50 s on CI), the startup
1049
+ // warm-up then prepared it again, and the launch sat at 80% until TN_STARTUP_STALLED. An
1050
+ // explicit warm-up runs once, right after the start scene, so a transition keeps its bake.
1051
+ const hasEnvironment =
1052
+ ctx.scene.environment?.isTexture === true &&
1053
+ (this.#startupGateStarted || this.#warmUpConfiguredExplicitly());
1054
+ if (renderer === undefined || (nodes.length === 0 && !hasEnvironment)) return;
951
1055
  this.#sceneEntered = false;
952
1056
  let report: Awaited<ReturnType<typeof warmUpComputeNodes>> | undefined;
1057
+ let environmentPrepared: boolean | undefined;
953
1058
  let failure: string | undefined;
954
1059
  try {
955
- report = await warmUpComputeNodes(renderer, nodes, this.#warmUpOptions());
1060
+ const options = this.#warmUpOptions();
1061
+ if (hasEnvironment) {
1062
+ const projection = this.#projection;
1063
+ projection?.reconcile();
1064
+ const root = projection?.root ?? ctx.scene;
1065
+ this.#matrixWorld?.apply(root);
1066
+ // A new environment skips world draws until its retained bake has completed. Only the bake:
1067
+ // a whole-scene warm-up here held the runner kit's first frame for its 45 s budget on
1068
+ // SwiftShader, and the first world frame's startup warm-up compiles the scene anyway.
1069
+ const now = globalThis.performance?.now() ?? Date.now();
1070
+ environmentPrepared = await prepareSceneEnvironment(
1071
+ renderer,
1072
+ root,
1073
+ ctx.camera,
1074
+ now + (options.budgetMs ?? STARTUP_COMPILE_BUDGET_MS),
1075
+ );
1076
+ }
1077
+ if (nodes.length > 0) report = await warmUpComputeNodes(renderer, nodes, options);
956
1078
  } catch (error) {
957
1079
  failure = error instanceof Error ? error.message : String(error);
958
1080
  }
959
1081
  console.log(
960
- `TN_TRANSITION_COMPUTE_WARMUP:${JSON.stringify(
961
- report === undefined
1082
+ `${hasEnvironment ? "TN_TRANSITION_WARMUP" : "TN_TRANSITION_COMPUTE_WARMUP"}:${JSON.stringify(
1083
+ failure !== undefined || (report === undefined && environmentPrepared === undefined)
962
1084
  ? { failed: failure ?? "unknown" }
963
1085
  : {
964
- compiled: report.compiled,
965
- abandoned: report.abandoned,
966
- unsupported: report.unsupported,
967
- timedOut: report.timedOut,
1086
+ ...(environmentPrepared === undefined ? {} : { environmentPrepared }),
1087
+ ...(report === undefined
1088
+ ? {}
1089
+ : {
1090
+ compiled: report.compiled,
1091
+ abandoned: report.abandoned,
1092
+ unsupported: report.unsupported,
1093
+ timedOut: report.timedOut,
1094
+ }),
968
1095
  },
969
1096
  )}`,
970
1097
  );
@@ -975,6 +1102,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
975
1102
  if (this.#started) return Promise.resolve();
976
1103
  if (this.#pendingStart !== undefined) return this.#pendingStart;
977
1104
  this.#aborted = false;
1105
+ installQuietMarkers();
978
1106
  const pendingStart = this.#boot().catch((error: unknown) => {
979
1107
  this.#disconnectUi();
980
1108
  throw error;
@@ -997,7 +1125,19 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
997
1125
  return pendingStart;
998
1126
  }
999
1127
 
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
+ );
1137
+ }
1138
+
1000
1139
  async #boot(): Promise<void> {
1140
+ const debug = debugRequested();
1001
1141
  const bootSceneName = this.#resumeScene ?? this.#config.start;
1002
1142
  this.#resumeScene = undefined;
1003
1143
  const SceneType = this.#config.scenes[bootSceneName];
@@ -1029,31 +1169,33 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1029
1169
  this.#config.renderer?.resolutionScale,
1030
1170
  getPlatform().os,
1031
1171
  ),
1032
- source: this.#config.renderer?.source ?? this.#config.platform?.renderer,
1172
+ source: this.#config.renderer?.source ?? this.#platform?.renderer,
1033
1173
  });
1034
1174
  if (this.#aborted) {
1035
1175
  renderer.dispose();
1036
1176
  return;
1037
1177
  }
1038
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));
1039
1185
  const canvas = renderer.domElement;
1040
- const platform = this.#config.platform;
1186
+ const platform = this.#platform;
1187
+ const page = hostDocument();
1041
1188
  if (platform !== undefined) platform.mountCanvas(canvas, this.#config.container);
1042
1189
  else if (
1043
1190
  this.#config.container !== undefined &&
1044
1191
  canvas.parentElement !== this.#config.container
1045
1192
  )
1046
1193
  this.#config.container.append(canvas);
1047
- else if (canvas.parentElement === null && typeof document !== "undefined")
1048
- document.body.append(canvas);
1194
+ else if (canvas.parentElement === null && page !== undefined) page.body.append(canvas);
1049
1195
 
1050
1196
  const inputTarget =
1051
1197
  this.#config.inputTarget ??
1052
- (platform === undefined
1053
- ? typeof window === "undefined"
1054
- ? canvas
1055
- : window
1056
- : (platform.inputTarget ?? canvas));
1198
+ (platform === undefined ? (hostWindow() ?? canvas) : (platform.inputTarget ?? canvas));
1057
1199
  this.#input = new InputMap(
1058
1200
  this.#config.input,
1059
1201
  inputTarget,
@@ -1063,6 +1205,8 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1063
1205
  );
1064
1206
  this.#state.start();
1065
1207
  const threeScene = new ThreeScene();
1208
+ if (debug && "__debugTelemetry" in threeScene)
1209
+ (threeScene as ThreeScene & { __debugTelemetry: boolean }).__debugTelemetry = true;
1066
1210
  const camera = createCamera(this.#config.camera);
1067
1211
  const interpolation = new PhysicsInterpolation(this.#config.physicsInterpolation);
1068
1212
  this.#interpolation = interpolation;
@@ -1074,6 +1218,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1074
1218
  // support against the real backend; a target that supports none fails right here.
1075
1219
  const assets = createAssetLoader({ ...this.#config.assets, renderer: renderer.raw });
1076
1220
  if (assets.compressedTextures !== undefined) await assets.compressedTextures.ready;
1221
+ this.#cleanup.push(() => assets.dispose());
1077
1222
  const entities = new Registry();
1078
1223
  const random = createRandom(this.#config.seed);
1079
1224
  const scheduler = new Scheduler();
@@ -1120,14 +1265,28 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1120
1265
  threeScene.matrixWorldAutoUpdate = false;
1121
1266
  // Built before the context because `ctx.startup` reads it: a game asks what the framework's
1122
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;
1123
1271
  const projection = new SceneRenderProjection(threeScene, {
1124
1272
  // The game's `renderer.projection` value verbatim: `false` declines the mirror, an object
1125
1273
  // names the material check beside accepting it, and the projection owns both readings.
1126
1274
  projection: this.#config.render?.projection,
1127
- velocity: () => renderer.renderChainUsesPerObjectVelocity?.() ?? false,
1275
+ velocity: () => !ownedEngine && (renderer.renderChainUsesPerObjectVelocity?.() ?? false),
1128
1276
  matrixWorld: matrixWorldPass,
1129
1277
  });
1130
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;
1131
1290
  // Do not submit what the render camera cannot resolve. On by default at a conservative 0.5 px,
1132
1291
  // and measured whether or not the game narrows or declines it. Its decision is per camera, so
1133
1292
  // a shadow caster and anything attached to the camera are never dropped on the main view alone.
@@ -1136,6 +1295,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1136
1295
  });
1137
1296
  this.#cameraCull = cameraCull;
1138
1297
  let projectionSettled = false;
1298
+ let offscreenBytes: IStartupOffscreenBytes | undefined;
1139
1299
  /**
1140
1300
  * Progress is a high-water mark over the measured load state, never a value that can fall.
1141
1301
  *
@@ -1168,6 +1328,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1168
1328
  };
1169
1329
  let worldRendered = false;
1170
1330
  let loadingFramePresented = false;
1331
+ let stateHandOffFrames = 0;
1171
1332
  let markProjectionSettled: () => void = () => undefined;
1172
1333
  const projectionReady = new Promise<void>((resolve) => {
1173
1334
  markProjectionSettled = resolve;
@@ -1191,6 +1352,24 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1191
1352
  afterHolds: async () => {
1192
1353
  await warmUp("TN_STARTUP_WARMUP_HELD", Math.round(STARTUP_COMPILE_BUDGET_MS / 3), false);
1193
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
+ },
1194
1373
  });
1195
1374
  // Startup readiness does not wait on `ui-ready`, and cannot. The intent proves the page's
1196
1375
  // script ran, not that a pixel reached the screen, so waiting on it never closed the race it
@@ -1209,6 +1388,13 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1209
1388
  const startupCoverActive = (): boolean =>
1210
1389
  !startupReadiness.ready &&
1211
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
+ };
1212
1398
  const timeline: { -readonly [K in keyof IStartupTimeline]: IStartupTimeline[K] } = {};
1213
1399
  let warmUpStatus: IStartupStatus["warmup"];
1214
1400
  const now = (): number => globalThis.performance?.now() ?? Date.now();
@@ -1218,17 +1404,23 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1218
1404
  * device, with the only account of either on a terminal the player does not have.
1219
1405
  */
1220
1406
  const stopStallWatch = watchStartupStall({
1221
- pending: () => [...assets.progress.pending, ...startupReadiness.pendingHolds],
1407
+ pending: () => [
1408
+ ...assets.progress.pending,
1409
+ ...startupReadiness.pendingHolds,
1410
+ ...startupReadiness.pendingImage,
1411
+ ],
1222
1412
  progress: () => this.#ctx?.startup.progress ?? 0,
1223
1413
  workProgress: () => assets.progress.settled + startupReadiness.workProgress,
1224
1414
  stallMs: STARTUP_STALL_MS,
1225
1415
  });
1416
+ this.#cleanup.push(stopStallWatch);
1226
1417
  watchDeviceLoss(
1227
1418
  (
1228
1419
  renderer.raw as {
1229
1420
  backend?: { device?: { lost?: Promise<{ reason?: string; message?: string }> } };
1230
1421
  }
1231
1422
  ).backend?.device,
1423
+ () => this.#aborted || this.#renderer !== renderer,
1232
1424
  );
1233
1425
  // Stamped when the FRAMEWORK is done, which is before `whenReady()` whenever the game has
1234
1426
  // registered a `startup.hold()`. Two stamps, because one number cannot be both "what the
@@ -1246,12 +1438,34 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1246
1438
  timeline.frameworkReadyMs ??= now();
1247
1439
  timeline.readyMs ??= now();
1248
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;
1249
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();
1250
1451
  // A host capturing a frame has no other way to know the world is on screen. Counting frames
1251
1452
  // cannot express it: on a software rasteriser the gate resolves on its bounded window rather
1252
1453
  // than on five in-budget frames, so a fast 300-frame run finishes before the world is shown
1253
1454
  // and captures the loading state. The native screenshot path waits on this flag.
1254
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
+ }
1255
1469
  // Again at ready: a world that streams its foliage in under `startup.hold` has none at entry.
1256
1470
  const unlit = unlitFoliageWarning(threeScene);
1257
1471
  if (unlit !== undefined)
@@ -1270,6 +1484,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1270
1484
  // rest synchronously -- tens of seconds each on a software adapter, which loses the device.
1271
1485
  this.#matrixWorld?.apply(projection.root);
1272
1486
  report = await warmUpScene(renderer, projection.root, camera, {
1487
+ afterCoveredDraw: repaintCover,
1273
1488
  budgetMs,
1274
1489
  computeNodes: this.#computeDriven.warmupNodes,
1275
1490
  renderPasses: this.#warmUpOptions().renderPasses,
@@ -1323,6 +1538,21 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1323
1538
  const startupCompile: StartupCompile = async (): Promise<void> => {
1324
1539
  await warmUp("TN_STARTUP_WARMUP", STARTUP_COMPILE_BUDGET_MS, true);
1325
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
+ };
1326
1556
  // The GPU-selected main-pass tally, registered by whichever streamed world is added to the
1327
1557
  // scene. The frame budget reads it once per window; a world with no sample reports undefined, so
1328
1558
  // the window carries nothing rather than a zero no frame selected.
@@ -1440,12 +1670,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1440
1670
  this.#entities = entities;
1441
1671
  this.#scheduler = scheduler;
1442
1672
  this.#afterPhysicsPhase = afterPhysicsPhase;
1443
- const devToolsHost =
1444
- platform === undefined
1445
- ? typeof window === "undefined"
1446
- ? undefined
1447
- : window
1448
- : platform.devToolsHost;
1673
+ const devToolsHost = platform === undefined ? hostWindow() : platform.devToolsHost;
1449
1674
  this.#cleanup.push(
1450
1675
  installDevTools(
1451
1676
  entities,
@@ -1464,24 +1689,25 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1464
1689
  let heldTargetFps = initialTarget.targetFps;
1465
1690
  // Frame-share budgets elsewhere (the world's adaptive LOD) read the target, not the last frame.
1466
1691
  renderer.noteTargetFps?.(initialTarget.targetFps);
1467
- const scaler =
1468
- renderer.surface().scaleSource === "auto" && initialTarget.targetFps > 0
1692
+ const automaticScale = renderer.surface().scaleSource === "auto";
1693
+ const createScaler = () =>
1694
+ automaticScale && heldTargetFps > 0
1469
1695
  ? new ResolutionScaler({
1470
1696
  // Phones keep the device ladder; a desktop stops before its bottom, where a picture
1471
1697
  // with nothing reconstructing it stops being a faster frame and becomes a blur.
1472
1698
  minScale: resolvePlatformResolutionFloor(getPlatform().os),
1473
1699
  // The adapter family picks the first rung; the first eligible window still decides.
1474
1700
  start:
1475
- renderer.gpuClass === undefined
1701
+ renderer.temporalUpscaleStartScale?.() ??
1702
+ (renderer.gpuClass === undefined
1476
1703
  ? undefined
1477
- : RESOLUTION_SCALER.startScaleByGpuClass[renderer.gpuClass.class],
1478
- targetFps: initialTarget.targetFps,
1479
- // No floor lift from motion data: consuming velocity is not upscaling. Three's TRAA
1480
- // accumulates at the canvas's own size, so lifting the floor for it let a forest frame
1481
- // fall to 0.23 (442x248 on a 1920x1080 canvas). Only a stage that reconstructs a
1482
- // display-resolution frame may pass `temporalUpscale`, and none ships today.
1704
+ : RESOLUTION_SCALER.startScaleByGpuClass[renderer.gpuClass.class]),
1705
+ targetFps: heldTargetFps,
1706
+ temporalUpscale: () => renderer.temporalUpscale?.() === true,
1483
1707
  })
1484
1708
  : undefined;
1709
+ let scaler = createScaler();
1710
+ let temporalStartApplied = renderer.temporalUpscale?.() === true;
1485
1711
  // A class that starts below the ceiling must draw there from the first frame; the scaler only
1486
1712
  // reports a scale, and nothing else would apply it until a window steps.
1487
1713
  if (scaler !== undefined && scaler.scale !== 1)
@@ -1551,7 +1777,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1551
1777
  if (projection !== undefined) {
1552
1778
  reportInfo(
1553
1779
  formatProjectionWindow(
1554
- projection.report,
1780
+ projection.windowReport,
1555
1781
  reported.window,
1556
1782
  lastWorldDrawCalls,
1557
1783
  this.#cameraCull?.report,
@@ -1565,19 +1791,22 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1565
1791
  // same frames and a reader can subtract one from the other without a second clock.
1566
1792
  const spanWindow = spans?.window();
1567
1793
  if (spanWindow !== undefined) reportInfo(formatSpansWindow(spanWindow));
1568
- // The scene-shape verdict, on by default, from the census the frame already took.
1569
- // An agent building a scene of the wrong shape reads it in the log before a human
1570
- // ever plays the game and calls it slow.
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.
1571
1797
  const staticCensus = staticTransformCensus();
1572
1798
  if (staticCensus.roots > 0)
1573
1799
  reportInfo(`${STATIC_TRANSFORM_MARKER}:${JSON.stringify(staticCensus)}`);
1574
1800
  const validation = renderListValidator?.report();
1575
1801
  if (validation !== undefined) reportInfo(formatValidationReport(validation));
1576
- const warning = sceneWarning(
1577
- reported,
1578
- describeSceneShape(reported, this.#cameraCull?.report),
1579
- target.targetFps,
1580
- );
1802
+ const warning = devMetricsEnabled
1803
+ ? sceneWarning(
1804
+ reported,
1805
+ describeSceneShape(reported, this.#cameraCull?.report),
1806
+ target.targetFps,
1807
+ renderer.gpuClass?.class,
1808
+ )
1809
+ : undefined;
1581
1810
  if (warning !== undefined) reportWarning(formatSceneWarning(warning));
1582
1811
  // The same sentence goes to the UI on a dev launch, so a human watching the window
1583
1812
  // and an agent reading the log are told the same thing at the same time. No frame
@@ -1657,6 +1886,12 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1657
1886
  // work a shipped build must not pay for a diagnostic it did not ask for.
1658
1887
  const frameCounters =
1659
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();
1660
1895
  // The parity oracle for the static freeze. Off by default and expensive on purpose: it
1661
1896
  // recomputes every world matrix the long way and throws on the first that disagrees with what
1662
1897
  // the frame is about to draw.
@@ -1670,10 +1905,22 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1670
1905
  });
1671
1906
  }
1672
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
+ }
1673
1912
  // Holds no hook and does no work between requests, so an idle game pays nothing for it.
1674
1913
  const geometryCapture = new GeometryCapture();
1675
1914
  this.#geometryCapture = geometryCapture;
1676
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;
1677
1924
  // The dev verdict is decided once per launch, and sent when it changes rather than on a timer:
1678
1925
  // a chip that re-sent an unchanged sentence four times a second would pay a JSON round trip to
1679
1926
  // say nothing new.
@@ -1682,6 +1929,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1682
1929
  let updates = 0;
1683
1930
  let renders = 0;
1684
1931
  let lastGateSkips = 0;
1932
+ let readinessGateSkips = 0;
1685
1933
  const gameLoop: FixedStepLoop = new FixedStepLoop({
1686
1934
  interpolation,
1687
1935
  ...(frameBudget === undefined ? {} : { budget: frameBudget }),
@@ -1697,6 +1945,13 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1697
1945
  },
1698
1946
  onRender: (alpha) => {
1699
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
+ }
1700
1955
  renderPassBudget?.beginFrame();
1701
1956
  // Runs on web as well as native, so the two stay one behaviour rather than diverging into
1702
1957
  // a fast path nobody tests. When the world is drawn, reconciliation happens immediately
@@ -1715,13 +1970,16 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1715
1970
  const mustPresentLoader =
1716
1971
  firstWorldPass && canvasLayer.opaque && loaderHasPixels && !loadingFramePresented;
1717
1972
  if (firstWorldPass && !explicitWarmUpPending) {
1973
+ this.#startupGateStarted = true;
1718
1974
  // `startupCompile` is the fallback that compiles inside the readiness gate. When warm-up
1719
1975
  // is on it has already happened behind the loading screen, so running it again here
1720
1976
  // would pay the same cost twice.
1721
1977
  startupReadiness.start(
1722
- startupCoverActive() && !this.#warmUpConfiguredExplicitly()
1723
- ? startupCompile
1724
- : undefined,
1978
+ this.#warmUpConfiguredExplicitly()
1979
+ ? undefined
1980
+ : startupCoverActive()
1981
+ ? startupCompile
1982
+ : startupEnvironment(),
1725
1983
  );
1726
1984
  }
1727
1985
  // Ordinary render compute waits for startup readiness. Streaming explicitly opts in
@@ -1735,6 +1993,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1735
1993
  (!startupCoverActive() || startupReadiness.compileSettled)
1736
1994
  ) {
1737
1995
  const computeStart = frameBudget === undefined ? 0 : budgetNow();
1996
+ computeStageMs = 0;
1738
1997
  beginSpan(SPANS.compute);
1739
1998
  try {
1740
1999
  // The render camera comes with it, because a render-cadence consumer that culls by the
@@ -1749,13 +2008,20 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1749
2008
  } finally {
1750
2009
  endSpan(SPANS.compute);
1751
2010
  }
1752
- frameBudget?.addRender(budgetNow() - computeStart);
2011
+ computeStageMs = frameBudget === undefined ? 0 : budgetNow() - computeStart;
2012
+ frameBudget?.addRender(computeStageMs);
1753
2013
  }
1754
2014
  const waitingForFirstUse =
1755
2015
  firstWorldPass &&
1756
2016
  (explicitWarmUpPending || (startupCoverActive() && !startupReadiness.compileSettled));
1757
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.
1758
2023
  if (
2024
+ (this.#sceneEntered || canvasLayer.opaque) &&
1759
2025
  !mustPresentLoader &&
1760
2026
  !waitingForFirstUse &&
1761
2027
  (!canvasLayer.opaque ||
@@ -1772,6 +2038,17 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1772
2038
  // Before anything walks: a frozen subtree whose author moved its root thaws here, so the
1773
2039
  // walk that follows sees a transform nobody had to remember to announce.
1774
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);
1775
2052
  // Scene prep that must read the frame's last solved state before the projection packs and
1776
2053
  // the renderer draws. Inside the world-render block it cannot land on a held loader frame.
1777
2054
  if (this.#beforeRenderCallbacks.size > 0) {
@@ -1785,7 +2062,16 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1785
2062
  for (const callback of this.#beforeRenderCallbacks) snapshot.push(callback);
1786
2063
  beginSpan(SPANS.beforeRender);
1787
2064
  try {
1788
- for (const callback of snapshot) callback();
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
+ }
1789
2075
  } finally {
1790
2076
  endSpan(SPANS.beforeRender);
1791
2077
  this.#beforeRenderDepth -= 1;
@@ -1835,12 +2121,17 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1835
2121
  } finally {
1836
2122
  endSpan(SPANS.lod);
1837
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);
1838
2130
  // Projected-size cull, per render camera, default on. It writes only `object.visible` —
1839
2131
  // the one per-frame flag the projection's batch key ignores — and restores what it hid
1840
2132
  // immediately after the draw, so the authored scene is untouched between frames. The
1841
2133
  // renderer walks the same root the projection is about to draw, so a declined projection
1842
2134
  // and an active one both get the gate.
1843
- const drawingBufferHeight = renderer.surface().drawingBufferHeight;
1844
2135
  const cullApplyStart = spans === undefined ? 0 : spanNow();
1845
2136
  this.#cameraCull?.apply(
1846
2137
  this.#projection?.root ?? threeScene,
@@ -1872,13 +2163,16 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1872
2163
  : { backend: rendererBackendIdentity(renderer.raw) as string }),
1873
2164
  });
1874
2165
  }
1875
- const renderRoot = this.#projection?.root ?? threeScene;
1876
- // three's renderer walks whatever scene it is handed, so it is told not to: the pass above
1877
- // is the walk. Handing it the mirror sets the mirror scene's flag; the authored scene was
1878
- // marked at construction.
1879
- renderRoot.matrixWorldAutoUpdate = false;
1880
- this.#matrixWorld?.apply(renderRoot);
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();
1881
2174
  renderer.render(renderRoot, camera);
2175
+ const engineEnd = readStages === undefined ? 0 : budgetNow();
1882
2176
  renders += 1;
1883
2177
  // Count declined frames without treating them as drawn-frame render cost.
1884
2178
  const gateSkips = rendererFrameGateSkips(renderer.raw);
@@ -1899,7 +2193,17 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1899
2193
  if (spans !== undefined) addSpan(SPANS.cull, spanNow() - cullRestoreStart);
1900
2194
  this.#projection?.commit();
1901
2195
  renderer.observeRenderChainFrame?.();
1902
- frameBudget?.addRender(budgetNow() - renderStart);
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;
1903
2207
  // Read the split before the overlay renders: the overlay is its own draw, not part of the
1904
2208
  // world pass, and the budget window already accounts for it in its own phase.
1905
2209
  worldPasses = renderPassBudget?.passes();
@@ -1992,7 +2296,8 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
1992
2296
  }
1993
2297
  if (mustPresentLoader) loadingFramePresented = true;
1994
2298
  // Include state written by beforeRender and Scene.render in this frame's UI snapshot.
1995
- if (this.#config.stateFlushMs === undefined) this.#state.flush();
2299
+ if (this.#config.stateFlushMs === undefined && stateHandOffFrames === 0)
2300
+ this.#state.flush();
1996
2301
  // Every frame, including one whose canvas layer is empty: the native UI is composited into
1997
2302
  // the game's own frame whether or not the game draws a HUD of its own, so a frame that
1998
2303
  // skipped this would report work it did pay as `residual`. The host reports what the
@@ -2003,8 +2308,31 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2003
2308
  // The boundary counts ride the span flag, but the simulation tick does not need them: it is
2004
2309
  // fed every frame so a plain `TN_FRAME_BUDGET` log can join a window's start and end ticks
2005
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);
2006
2331
  frameBudget?.addCounters({
2007
- ...(frameCounters?.read() ?? {}),
2332
+ ...(work ?? {}),
2333
+ ...(boundary ?? {}),
2334
+ ...(crossings === undefined ? {} : { bridgeCrossings: crossings }),
2335
+ ...(engine === undefined ? {} : { engine }),
2008
2336
  simulationTick: gameLoop.tick(),
2009
2337
  });
2010
2338
  const uiHost = globalThis as { __tnUiCompositeMs?: () => number };
@@ -2034,34 +2362,127 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2034
2362
  },
2035
2363
  onAfterPhysics: (dt) => {
2036
2364
  if (this.#paused) return;
2037
- afterPhysicsPhase.run(dt);
2365
+ if (debug)
2366
+ measureDebug("afterPhysics", "update", "afterPhysicsPhase.run", () =>
2367
+ afterPhysicsPhase.run(dt),
2368
+ );
2369
+ else afterPhysicsPhase.run(dt);
2038
2370
  },
2039
2371
  onUpdate: (dt) => {
2040
2372
  if (this.#paused) return;
2041
- this.#input?.tick();
2042
- scheduler.tick(dt);
2043
- pointerEvents.tick(input.raw.pointers, picker, input.raw.pointer, input.raw.pointerEdges);
2044
- for (const plugin of this.#activePlugins) plugin.beforeUpdate?.(ctx, dt);
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
+ }
2045
2399
  const scene = this.#scene;
2046
2400
  const frame = this.#sceneFrame;
2047
- if (frame !== undefined) {
2048
- frame(ctx, dt);
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);
2049
2410
  updates += 1;
2050
2411
  }
2051
2412
  // An async goto() installs the incoming scene before its load resolves; until enter()
2052
2413
  // has run there is no gameplay to step and a game-overridden update() would run against
2053
2414
  // a cleared graph.
2054
2415
  else if (this.#sceneEntered && scene !== undefined) {
2055
- scene.update(ctx, dt);
2416
+ if (debug)
2417
+ measureDebug("sceneCallbacks", "update", `${scene.constructor.name}.update`, () =>
2418
+ scene.update(ctx, dt),
2419
+ );
2420
+ else scene.update(ctx, dt);
2056
2421
  updates += 1;
2057
2422
  }
2058
2423
  if (this.#scene !== scene || this.#sceneFrame !== frame) return;
2059
- for (const plugin of this.#activePlugins) plugin.update?.(ctx, dt);
2060
- this.#entities?.sweep();
2061
- if (this.#renderer !== undefined && this.#sceneEntered)
2062
- this.#computeDriven.process(this.#renderer);
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
+ }
2063
2485
  },
2064
- onFrame: (frameMs) => startupReadiness.observe(frameMs),
2065
2486
  step: this.#config.step,
2066
2487
  });
2067
2488
  loopState.current = gameLoop;
@@ -2071,8 +2492,21 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2071
2492
  readonly rejectEntered: (error: unknown) => void;
2072
2493
  readonly resolveEntered: () => void;
2073
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);
2074
2501
  const runtime: IGamePluginRuntime = {
2075
- fixedStep: (ticks, options) => gameLoop.advance(ticks, options),
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
+ ),
2076
2510
  frameCounts: () => ({ updates, renders }),
2077
2511
  frameBudgetWindow: () => this.#frameBudget?.window(),
2078
2512
  freezeClock: () => gameLoop.freezeClock(),
@@ -2099,7 +2533,9 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2099
2533
  rapier: null,
2100
2534
  seed: this.#config.seed ?? null,
2101
2535
  startupCompileSettled: () => startupReadiness.compileSettled,
2536
+ startupRevealed: () => this.#uiRevealed,
2102
2537
  startupTimeline: () => ({ ...timeline }),
2538
+ startupOffscreenBytes: () => offscreenBytes,
2103
2539
  step: gameLoop.step,
2104
2540
  runtimeDiagnosticsSeries: () => gameLoop.runtimeDiagnosticsSeries(),
2105
2541
  };
@@ -2144,7 +2580,9 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2144
2580
  const loaded = scene.load(ctx);
2145
2581
  startHeldLoop();
2146
2582
  if (loaded !== undefined) await loaded;
2583
+ settleLoaded();
2147
2584
  } catch (error) {
2585
+ settleLoaded(error);
2148
2586
  this.#teardown(ctx);
2149
2587
  throw error;
2150
2588
  }
@@ -2170,21 +2608,16 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2170
2608
  }
2171
2609
  }
2172
2610
  try {
2173
- this.#enterScene(scene, ctx);
2174
- timeline.enteredMs ??= now();
2175
- // A start scene that navigates inside `enter()` — every `boot` template does — has handed the
2176
- // run a world that is still in `load()`, and the entity registry is empty until it enters.
2177
- // Releasing the gate there described a game that had not been built yet, so every
2178
- // entity-derived capability was read off nothing. The gate follows the scene that entered.
2179
- const worldEntered = this.#pendingSceneEnter;
2180
- const entered = (): void => {
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 = () => {
2181
2614
  for (const startGate of startGates) startGate.resolveEntered();
2182
2615
  };
2183
- if (worldEntered === undefined) entered();
2184
- else
2185
- void worldEntered.then(entered, (error: unknown) => {
2186
- for (const startGate of startGates) startGate.rejectEntered(error);
2187
- });
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
+ });
2188
2621
  } catch (error) {
2189
2622
  for (const startGate of startGates) startGate.rejectEntered(error);
2190
2623
  this.#teardown(ctx);
@@ -2214,6 +2647,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2214
2647
  this.#matrixWorld?.apply(projection.root);
2215
2648
  const warmUpOptions: IWarmUpOptions = this.#warmUpOptions();
2216
2649
  report = await warmUpScene(this.#renderer, projection.root, camera, {
2650
+ afterCoveredDraw: repaintCover,
2217
2651
  ...warmUpOptions,
2218
2652
  computeNodes: [...(warmUpOptions.computeNodes ?? []), ...this.#computeDriven.warmupNodes],
2219
2653
  });
@@ -2284,6 +2718,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2284
2718
  this.#aborted = true;
2285
2719
  this.#geometryCapture?.cancel("TN_GEOMETRY_CAPTURE_STOPPED: the game stopped mid-capture.");
2286
2720
  this.#teardown();
2721
+ uninstallQuietMarkers();
2287
2722
  }
2288
2723
 
2289
2724
  #disposePlugin(plugin: IGamePluginHooks<TState, TPhysics>, ctx: ICtx<TState, TPhysics>): void {
@@ -2293,6 +2728,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2293
2728
  }
2294
2729
 
2295
2730
  #teardown(startingCtx?: ICtx<TState, TPhysics>): void {
2731
+ this.#onStartSceneEntered = undefined;
2296
2732
  const ctx = this.#ctx ?? startingCtx;
2297
2733
  // Teardown is failure-atomic: one throwing release must not strand the resources after it.
2298
2734
  // Every attempt runs, errors are collected, and the first — the original cause — is thrown
@@ -2333,6 +2769,7 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2333
2769
  failures.push(error);
2334
2770
  }
2335
2771
  }
2772
+ this.#autoBatch?.reset();
2336
2773
  if (ctx !== undefined) clearScene(ctx.scene, this.#computeDriven);
2337
2774
  this.#cameraCull?.dispose();
2338
2775
  this.#cameraCull = undefined;
@@ -2345,8 +2782,9 @@ class GameImpl<TState extends Record<string, unknown>, TPhysics>
2345
2782
  const renderer = this.#renderer;
2346
2783
  renderer?.dispose();
2347
2784
  if (renderer !== undefined) {
2348
- if (this.#config.platform === undefined) renderer.domElement.remove?.();
2349
- else this.#config.platform.unmountCanvas(renderer.domElement);
2785
+ const platform = this.#platform;
2786
+ if (platform === undefined) renderer.domElement.remove?.();
2787
+ else platform.unmountCanvas(renderer.domElement);
2350
2788
  }
2351
2789
  this.#renderer = undefined;
2352
2790
  this.#viewport = undefined;