@threenative/core 0.3.4 → 0.3.6

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 (176) hide show
  1. package/capabilities.json +1505 -79
  2. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  3. package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  4. package/dist/{game-CljaDv4D.d.ts → game-Jz4Fdoeb.d.ts} +114 -11
  5. package/dist/hot.d.ts +4 -4
  6. package/dist/index.d.ts +712 -118
  7. package/dist/index.js +12437 -4955
  8. package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
  9. package/dist/playtest.d.ts +6 -10
  10. package/dist/playtest.js +57 -24
  11. package/dist/react-css.d.ts +62 -0
  12. package/dist/react-css.js +591 -0
  13. package/dist/react.d.ts +2 -2
  14. package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
  15. package/dist/terrain-jobs-worker.d.ts +2 -0
  16. package/dist/terrain-jobs-worker.js +130 -0
  17. package/dist/ui-layer.js +59 -8
  18. package/dist/world.d.ts +766 -73
  19. package/dist/world.js +9307 -3543
  20. package/gpl/recipes/export_world.py +18 -1
  21. package/mcp/blender-server.mjs +7 -4
  22. package/mcp/blender.mjs +3 -4
  23. package/mcp/engine-server.mjs +2 -2
  24. package/mcp/servers.mjs +4 -4
  25. package/package.json +15 -9
  26. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  27. package/patches/three@0.185.1.patch +6594 -700
  28. package/scripts/apply-three-patch.mjs +62 -4
  29. package/src/animation-blend.ts +264 -0
  30. package/src/animation-composition.ts +362 -0
  31. package/src/animation-layers.ts +260 -0
  32. package/src/animation-root-motion.ts +283 -0
  33. package/src/animation.ts +896 -0
  34. package/src/assets.ts +1303 -0
  35. package/src/atmosphere/index.ts +335 -0
  36. package/src/atmosphere/luts.ts +298 -0
  37. package/src/atmosphere/params.ts +323 -0
  38. package/src/audio.ts +912 -0
  39. package/src/billboard.ts +124 -0
  40. package/src/bone-lengths.ts +157 -0
  41. package/src/camera-shake.ts +116 -0
  42. package/src/canvas-layer.ts +47 -0
  43. package/src/clip-audit.ts +401 -0
  44. package/src/clustered-batch.ts +492 -0
  45. package/src/clustered-mesh.ts +638 -0
  46. package/src/compute-driven.ts +176 -0
  47. package/src/compute-timing.ts +318 -0
  48. package/src/config.ts +593 -0
  49. package/src/debug.ts +82 -0
  50. package/src/engine-render-hook.ts +25 -0
  51. package/src/entities.ts +79 -0
  52. package/src/entity-snapshot.ts +53 -0
  53. package/src/flight.ts +683 -0
  54. package/src/fluid-field.ts +748 -0
  55. package/src/fluid-particles.ts +1253 -0
  56. package/src/frame-budget.ts +1368 -0
  57. package/src/game.ts +2408 -0
  58. package/src/geometry-capture.ts +1098 -0
  59. package/src/gpu-class.ts +160 -0
  60. package/src/gpu-frame-observation.ts +424 -0
  61. package/src/gpu-readback.ts +143 -0
  62. package/src/gpu-scene-bvh.ts +464 -0
  63. package/src/grounding.ts +100 -0
  64. package/src/hot.ts +161 -0
  65. package/src/import-meta.d.ts +13 -0
  66. package/src/index.ts +1536 -0
  67. package/src/input.ts +690 -0
  68. package/src/instanced-batch-lod.ts +283 -0
  69. package/src/instanced-batch.ts +274 -0
  70. package/src/interpolation.ts +129 -0
  71. package/src/launch-diagnostics.ts +161 -0
  72. package/src/loop.ts +574 -0
  73. package/src/matrix-world.ts +245 -0
  74. package/src/merge-parts.ts +812 -0
  75. package/src/model-lod.ts +1315 -0
  76. package/src/net-protocol.ts +333 -0
  77. package/src/net-session.ts +477 -0
  78. package/src/net.ts +80 -0
  79. package/src/ocean/fft.ts +72 -0
  80. package/src/ocean/spectral.ts +728 -0
  81. package/src/particle-significance.ts +102 -0
  82. package/src/particles.ts +648 -0
  83. package/src/path-follow.ts +175 -0
  84. package/src/picking.ts +250 -0
  85. package/src/pipeline-census.ts +1566 -0
  86. package/src/platform.ts +210 -0
  87. package/src/playtest.ts +850 -0
  88. package/src/pointer-events.ts +411 -0
  89. package/src/pose-measure.ts +435 -0
  90. package/src/profiling/FrameCounters.ts +231 -0
  91. package/src/profiling/Spans.ts +548 -0
  92. package/src/profiling/opacity-convention.ts +21 -0
  93. package/src/profiling/render-list-validate.ts +175 -0
  94. package/src/profiling/render-trap-audit.ts +84 -0
  95. package/src/profiling/scene-warning.ts +190 -0
  96. package/src/profiling/span-probes.ts +191 -0
  97. package/src/profiling/unlit-foliage-warning.ts +149 -0
  98. package/src/projection-apply.ts +1529 -0
  99. package/src/projection-marker.ts +142 -0
  100. package/src/projection-plan.ts +1258 -0
  101. package/src/projection-skinned.ts +419 -0
  102. package/src/projection-stability.ts +409 -0
  103. package/src/projection-uniform.ts +328 -0
  104. package/src/random.ts +41 -0
  105. package/src/react-css.ts +604 -0
  106. package/src/react-glyphs.ts +114 -0
  107. package/src/react-host.ts +576 -0
  108. package/src/react-layout.ts +265 -0
  109. package/src/react.ts +60 -0
  110. package/src/render/alpha-antialiasing.ts +159 -0
  111. package/src/render/batched-velocity.ts +126 -0
  112. package/src/render/chain.ts +1021 -0
  113. package/src/render/daylight.ts +189 -0
  114. package/src/render/depth-pyramid.ts +596 -0
  115. package/src/render/foliage-alpha.ts +166 -0
  116. package/src/render/material-key.ts +60 -0
  117. package/src/render/mesh-pool.ts +144 -0
  118. package/src/render/probe-volume.ts +1668 -0
  119. package/src/render/resolution-subrect.ts +253 -0
  120. package/src/render/velocity.ts +442 -0
  121. package/src/render/virtual-shadow-pages.ts +827 -0
  122. package/src/render/virtual-shadow-partial.ts +174 -0
  123. package/src/render/virtual-shadow.ts +3330 -0
  124. package/src/render/world-impostor-surface.ts +722 -0
  125. package/src/render/world-impostor.ts +558 -0
  126. package/src/render-camera-cull.ts +441 -0
  127. package/src/render-pass-budget.ts +501 -0
  128. package/src/renderProjection.ts +758 -0
  129. package/src/renderer-config.ts +127 -0
  130. package/src/renderer.ts +1847 -0
  131. package/src/replay-protocol.ts +85 -0
  132. package/src/replay.ts +205 -0
  133. package/src/resolution-scaler.ts +819 -0
  134. package/src/rig-preparation.ts +271 -0
  135. package/src/ripple-field.ts +432 -0
  136. package/src/scale.ts +109 -0
  137. package/src/scene.ts +239 -0
  138. package/src/schedule.ts +155 -0
  139. package/src/skeletal-mesh.ts +61 -0
  140. package/src/skeleton.ts +100 -0
  141. package/src/snow-field.ts +744 -0
  142. package/src/softbody-topology.ts +269 -0
  143. package/src/softbody.ts +516 -0
  144. package/src/sprite-animator.ts +222 -0
  145. package/src/startup-readiness.ts +386 -0
  146. package/src/state.ts +66 -0
  147. package/src/static-transform.ts +274 -0
  148. package/src/storage-buffer.ts +253 -0
  149. package/src/streaming.ts +308 -0
  150. package/src/target-fps.ts +92 -0
  151. package/src/terrain-jobs-worker.ts +17 -0
  152. package/src/terrain-jobs.ts +353 -0
  153. package/src/textures.ts +39 -0
  154. package/src/tracers.ts +237 -0
  155. package/src/ui-bridge.ts +368 -0
  156. package/src/ui-hit-regions.ts +380 -0
  157. package/src/ui-layer.ts +83 -0
  158. package/src/ui-state.ts +220 -0
  159. package/src/version.ts +2 -0
  160. package/src/viewport.ts +253 -0
  161. package/src/warmup.ts +1357 -0
  162. package/src/water-surface.ts +384 -0
  163. package/src/wave-field.ts +524 -0
  164. package/src/world-capabilities.ts +131 -0
  165. package/src/world-cell-proxy.ts +392 -0
  166. package/src/world-cells.ts +10564 -0
  167. package/src/world-gpu-scene.ts +3354 -0
  168. package/src/world-heightmap.ts +82 -0
  169. package/src/world-package.ts +469 -0
  170. package/src/world-passes.ts +582 -0
  171. package/src/world-region.ts +17 -0
  172. package/src/world-terrain-splat.ts +564 -0
  173. package/src/world-tiles.ts +3826 -0
  174. package/src/world-topology.ts +370 -0
  175. package/src/world-validate.ts +48 -0
  176. package/src/world.ts +805 -0
package/src/loop.ts ADDED
@@ -0,0 +1,574 @@
1
+ import type { FrameBudget, IFramePhaseSample } from "./frame-budget.js";
2
+ import type { PhysicsInterpolation } from "./interpolation.js";
3
+ import type { SpanRecorder } from "./profiling/Spans.js";
4
+ import type { FramePassKind, IRenderPassSample } from "./render-pass-budget.js";
5
+
6
+ export type AfterPhysicsCallback = (dt: number) => void;
7
+
8
+ export interface IAfterPhysicsContext {
9
+ readonly afterPhysics: (callback: AfterPhysicsCallback) => () => void;
10
+ }
11
+
12
+ export interface IAfterPhysicsPhase {
13
+ clear(): void;
14
+ register(callback: AfterPhysicsCallback): () => void;
15
+ run(dt: number): void;
16
+ }
17
+
18
+ export function createAfterPhysicsPhase(): IAfterPhysicsPhase {
19
+ const callbacks = new Set<AfterPhysicsCallback>();
20
+ // Snapshot storage reused across frames, with one array per nesting level so a dispatch
21
+ // started from inside a running callback cannot clobber its parent's snapshot.
22
+ const snapshots: AfterPhysicsCallback[][] = [];
23
+ let depth = 0;
24
+ return {
25
+ clear: () => callbacks.clear(),
26
+ register: (callback) => {
27
+ if (typeof callback !== "function")
28
+ throw new Error("afterPhysics requires a callback function.");
29
+ callbacks.add(callback);
30
+ return () => callbacks.delete(callback);
31
+ },
32
+ run: (dt) => {
33
+ if (!Number.isFinite(dt) || dt <= 0)
34
+ throw new Error(`afterPhysics requires a positive finite dt, received ${String(dt)}.`);
35
+ if (callbacks.size === 0) return;
36
+ let snapshot = snapshots[depth];
37
+ if (snapshot === undefined) {
38
+ snapshot = [];
39
+ snapshots[depth] = snapshot;
40
+ }
41
+ depth += 1;
42
+ snapshot.length = 0;
43
+ // Snapshot before running: a callback that registers or removes work affects the next
44
+ // dispatch, not this one, and one already snapshotted still runs after a later removal.
45
+ for (const callback of callbacks) snapshot.push(callback);
46
+ try {
47
+ for (let index = 0; index < snapshot.length; index += 1) snapshot[index]?.(dt);
48
+ } finally {
49
+ depth -= 1;
50
+ }
51
+ },
52
+ };
53
+ }
54
+
55
+ /** Register work that reads transforms after every simulation step and before the frame renders. */
56
+ export function afterPhysics(
57
+ context: IAfterPhysicsContext,
58
+ callback: AfterPhysicsCallback,
59
+ ): () => void {
60
+ if (typeof context?.afterPhysics !== "function")
61
+ throw new Error("afterPhysics requires a game context.");
62
+ return context.afterPhysics(callback);
63
+ }
64
+
65
+ export interface IFixedStepLoopOptions {
66
+ readonly interpolation?: PhysicsInterpolation;
67
+ readonly step?: number;
68
+ readonly maxSteps?: number;
69
+ /** Collect per-frame render samples for diagnostics consumers. Default false. */
70
+ readonly collectMetrics?: boolean;
71
+ /** Runs once per presented frame, before any fixed-step simulation dispatches. */
72
+ readonly onBeginFrame?: () => void;
73
+ readonly onUpdate: (dt: number) => void;
74
+ /** Runs after `onUpdate` has completed and before `onRender` starts. */
75
+ readonly onAfterPhysics?: (dt: number) => void;
76
+ readonly onRender?: (alpha: number) => undefined | IRenderPerformanceMetrics;
77
+ /** Actual wall time spent in one simulation+render callback, for startup gates and diagnostics. */
78
+ readonly onFrame?: (frameMs: number) => void;
79
+ readonly requestFrame?: (callback: (time: number) => void) => number;
80
+ readonly cancelFrame?: (handle: number) => void;
81
+ /**
82
+ * Per-frame cost attribution. The loop is the only place that knows where the simulation phase
83
+ * ends and the render phase begins, so it is the only honest place to measure them; a game
84
+ * wrapping `requestAnimationFrame` from outside has to guess that boundary.
85
+ */
86
+ readonly budget?: FrameBudget;
87
+ /**
88
+ * The render-phase span tree, when `TN_FRAME_SPANS` asked for one.
89
+ *
90
+ * The loop is where the frame budget's own phase split becomes a number, so it is the only place
91
+ * that can close the span tree against the same render phase the meter charged. A tree closed
92
+ * anywhere else would be arithmetic against a second, slightly different interval.
93
+ */
94
+ readonly spans?: SpanRecorder;
95
+ /** Monotonic clock for phase boundaries. Defaults to `performance.now`. */
96
+ readonly now?: () => number;
97
+ }
98
+
99
+ export interface IRenderPerformanceMetrics {
100
+ readonly drawCalls?: number;
101
+ readonly passes?: readonly IRenderPassSample[];
102
+ readonly triangles?: number;
103
+ }
104
+
105
+ export interface IRenderPerformanceSample extends IRenderPerformanceMetrics {
106
+ readonly frameMs: number;
107
+ /** Successful render-callback completion ID; absolute across clears and retention. */
108
+ readonly sequence?: number;
109
+ /** Completion boundary from the monotonic phase clock, not the rAF timestamp or render-body cost. */
110
+ readonly completedAtMs?: number;
111
+ /** Where this frame's milliseconds went. Present whenever a frame budget is installed. */
112
+ readonly phases?: IFramePhaseSample;
113
+ }
114
+
115
+ const MAX_RENDER_PERFORMANCE_SAMPLES = 1_024;
116
+
117
+ /**
118
+ * One entry per pass kind, summed, for a retained sample.
119
+ *
120
+ * `RenderPassBudget` records one entry per `render()` call, which is what the frame budget and the
121
+ * geometry capture need to attribute a submission to the innermost call. A retained sample does
122
+ * not: it is a 1,024-frame window shipped to the playtest bridge under a 1 MB payload ceiling, and
123
+ * a frame with 30 nested calls made that window ~1.4 MB, so `assert.performance` failed with
124
+ * TN_PLAYTEST_PAYLOAD_TOO_LARGE before frame 0. Consumers read per-kind values, and taking the
125
+ * first of N silently undercounted every lane past its first call.
126
+ */
127
+ function aggregatePassesByKind(passes: readonly IRenderPassSample[]): IRenderPassSample[] {
128
+ const totals = new Map<FramePassKind, IRenderPassSample>();
129
+ for (const pass of passes) {
130
+ const total = totals.get(pass.kind);
131
+ totals.set(pass.kind, {
132
+ draws: (total?.draws ?? 0) + pass.draws,
133
+ kind: pass.kind,
134
+ triangles: (total?.triangles ?? 0) + pass.triangles,
135
+ });
136
+ }
137
+ return [...totals.values()];
138
+ }
139
+
140
+ /**
141
+ * How many fixed steps a frozen clock runs once, before the run's first observation.
142
+ *
143
+ * This is the settling the boot used to do by accident, counted instead of measured. Live frames
144
+ * during the startup compile wait advanced the simulation at whatever rate the machine managed —
145
+ * 59 ticks before the first sample on a quiet one, thousands on a loaded one — and games leaned on
146
+ * that: the platformer character captures its visual-attachment baseline on its first grounded
147
+ * contact, so a run that started at tick 0 read `visualAttached: false` where a run that started at
148
+ * tick 59 read `true`, from the same build. A fixed count is the same settling with the machine out
149
+ * of it, and one second is what the quiet machine actually delivered. A run's own steps are
150
+ * unaffected: this happens once, before the runner takes its first tick, and `#tick` counts it, so
151
+ * the report says how old the simulation is.
152
+ */
153
+ const FROZEN_SETTLE_STEPS = 60;
154
+
155
+ export class FixedStepLoop {
156
+ readonly step: number;
157
+ readonly maxSteps: number;
158
+ #onBeginFrame: (() => void) | undefined;
159
+ #onUpdate: (dt: number) => void;
160
+ #onAfterPhysics: (dt: number) => void;
161
+ #onRender: (alpha: number) => undefined | IRenderPerformanceMetrics;
162
+ #onFrame: (frameMs: number) => void;
163
+ #requestFrame: (callback: (time: number) => void) => number;
164
+ #cancelFrame: (handle: number) => void;
165
+ readonly #interpolation: PhysicsInterpolation | undefined;
166
+ #accumulator = 0;
167
+ #lastTime: number | undefined;
168
+ #frameTime = 0;
169
+ #frameHandle: number | undefined;
170
+ #running = false;
171
+ #held = false;
172
+ #clockFrozen = false;
173
+ #driven = false;
174
+ #primePending = false;
175
+ #settleSteps = FROZEN_SETTLE_STEPS;
176
+ #tick = 0;
177
+ #fps = 0;
178
+ #lastRenderTime: number | undefined;
179
+ #renderPerformanceSamples: IRenderPerformanceSample[] = [];
180
+ #renderCompletionSequence = 0;
181
+ #frameCallback: (time: number) => void;
182
+ #budget: FrameBudget | undefined;
183
+ #spans: SpanRecorder | undefined;
184
+ #now: () => number;
185
+ // Sample collection is opt-in because nothing outside a diagnostics consumer reads the series:
186
+ // collecting unconditionally spent allocations on every rendered frame of every game.
187
+ #collectMetrics: boolean;
188
+
189
+ constructor(options: IFixedStepLoopOptions) {
190
+ const step = options.step ?? 1 / 60;
191
+ if (!Number.isFinite(step) || step <= 0) {
192
+ throw new Error(
193
+ `FixedStepLoop step must be a finite number of seconds greater than zero, received ${String(options.step)}.`,
194
+ );
195
+ }
196
+ this.step = step;
197
+ this.#interpolation = options.interpolation;
198
+ // A maxSteps below one passed the while-loop bound `updates < maxSteps` zero
199
+ // times per frame: the game rendered but never simulated, silently.
200
+ const maxSteps = options.maxSteps ?? 5;
201
+ if (!Number.isInteger(maxSteps) || maxSteps < 1) {
202
+ throw new Error(
203
+ `FixedStepLoop maxSteps must be an integer of at least one, received ${String(options.maxSteps)}.`,
204
+ );
205
+ }
206
+ this.maxSteps = maxSteps;
207
+ this.#collectMetrics = options.collectMetrics ?? false;
208
+ this.#budget = options.budget;
209
+ this.#spans = options.spans;
210
+ this.#now = options.now ?? (() => globalThis.performance?.now() ?? Date.now());
211
+ this.#onBeginFrame = options.onBeginFrame;
212
+ this.#onUpdate = options.onUpdate;
213
+ this.#onAfterPhysics = options.onAfterPhysics ?? (() => undefined);
214
+ this.#onRender = options.onRender ?? (() => undefined);
215
+ this.#onFrame = options.onFrame ?? (() => undefined);
216
+ this.#requestFrame =
217
+ options.requestFrame ??
218
+ ((callback) =>
219
+ typeof globalThis.requestAnimationFrame === "function"
220
+ ? globalThis.requestAnimationFrame(callback)
221
+ : 0);
222
+ this.#cancelFrame =
223
+ options.cancelFrame ??
224
+ ((handle) => {
225
+ if (typeof globalThis.cancelAnimationFrame === "function")
226
+ globalThis.cancelAnimationFrame(handle);
227
+ });
228
+ this.#frameCallback = (time) => this.#frame(time);
229
+ }
230
+
231
+ /** Frame callback timestamp in milliseconds. */
232
+ get frameTime(): number {
233
+ return this.#frameTime;
234
+ }
235
+
236
+ /** Fraction of the next fixed step accumulated for this presented frame. */
237
+ get alpha(): number {
238
+ return Math.max(0, Math.min(1 - Number.EPSILON, this.#accumulator / this.step));
239
+ }
240
+
241
+ get running(): boolean {
242
+ return this.#running;
243
+ }
244
+ get fps(): number {
245
+ return this.#fps;
246
+ }
247
+ runtimeDiagnosticsSeries(): readonly IRenderPerformanceSample[] {
248
+ return this.#renderPerformanceSamples.map((sample) => ({ ...sample }));
249
+ }
250
+ /**
251
+ * Forget the render samples taken so far. The game calls it once, when the world first draws:
252
+ * the frames before it are the boot — held behind the startup compile, drawing nothing — and a
253
+ * steady-state window that keeps them fails `maxDrawCalls` closed on frames that have no draw
254
+ * count and puts seconds of compile into the frame-time percentile.
255
+ */
256
+ clearRuntimeDiagnostics(): void {
257
+ this.#renderPerformanceSamples = [];
258
+ }
259
+ /** The frame budget this loop feeds, when one is installed. */
260
+ get budget(): FrameBudget | undefined {
261
+ return this.#budget;
262
+ }
263
+ /** Turns sample collection on for the rest of the run; a diagnostics consumer asking for the series is the only caller. */
264
+ setCollectMetrics(enabled: boolean): void {
265
+ this.#collectMetrics = enabled;
266
+ }
267
+ /** True while the loop renders without simulating. */
268
+ get held(): boolean {
269
+ return this.#held;
270
+ }
271
+ /**
272
+ * Render without simulating.
273
+ *
274
+ * Boot needs frames on the screen before the start scene has finished loading: on native the
275
+ * render loop is the only thing that can draw, so a loop that starts after `load()` resolves
276
+ * leaves the screen black for the whole asset load and a loading screen never appears. A held
277
+ * loop draws and does nothing else -- `onUpdate` is never called, `tick()` still reads zero,
278
+ * and the hold banks no time, so the first tick after release gets one frame of `dt` rather
279
+ * than one covering the entire load.
280
+ */
281
+ setHeld(held: boolean): void {
282
+ this.#held = held;
283
+ }
284
+ /** Reserved playtest seam: transition without banking elapsed wall time. */
285
+ _setClockMode(mode: "fixed-step" | "wall-clock"): void {
286
+ if (mode !== "fixed-step" && mode !== "wall-clock") throw new Error("Unknown clock mode.");
287
+ const frozen = mode === "fixed-step";
288
+ if (this.#clockFrozen === frozen) return;
289
+ this.#clockFrozen = frozen;
290
+ this.#primePending = false;
291
+ this.#accumulator = 0;
292
+ this.#lastTime = frozen ? Number.POSITIVE_INFINITY : undefined;
293
+ this.#lastRenderTime = undefined;
294
+ this.#driven = false;
295
+ this.clearRuntimeDiagnostics();
296
+ if (this.#running && this.#frameHandle === undefined)
297
+ this.#frameHandle = this.#requestFrame(this.#frameCallback);
298
+ }
299
+
300
+ /**
301
+ * Stop the live clock: from here a rendered frame draws and simulates nothing, and banks no
302
+ * time. `advance()` is then the only thing that moves the simulation.
303
+ *
304
+ * This is the whole-run form of the hold above, and it exists because the hold is undone by the
305
+ * first tick while the clock is not. A tick-counting playtest run banks real wall-clock seconds
306
+ * into the same simulation its ticks measure: the runner pumps live frames for the rAF warmup
307
+ * and then for the whole startup wait -- compile settlement is 30s+ on a software adapter and
308
+ * is itself a function of how loaded the machine is -- and every one of those frames advanced
309
+ * the game. Measured on the racing template's `racing-finish-behind-rival-is-dnf`: 164 ticks
310
+ * (2.73s of race time) elapsed before the scenario pressed a key on a fast machine with a real
311
+ * GPU, and that scenario's third lap lands at 47.0s against a 90s in-game race limit, so the
312
+ * 42.7s of headroom is spent by boot time rather than by the scenario. The same scenario then
313
+ * fails its `completedLaps` assertion on a loaded runner and passes on a quiet one, from the
314
+ * same build. Idempotent, and implied by `advance()`.
315
+ *
316
+ * Frozen stops *time*, not the frame function: the loop still settles the world with a fixed
317
+ * number of steps — see `#primeFrame`. A game lays out per-frame state in `update` (action-rpg's
318
+ * touch overlay places itself against the viewport there and is parented to the camera), and a
319
+ * run reads its first observation before it takes its first tick, so a freeze that skipped
320
+ * updates outright left that state at its constructed pose: the overlay sat on the camera's own
321
+ * origin and `point.project` divided by a zero w, which is `NaN` bounds in the entity observation
322
+ * and took the scenario down before it asserted anything.
323
+ *
324
+ * @param settleSteps Fixed steps to run once the loop is live. Defaults to one second; zero
325
+ * leaves the world exactly as the game built it.
326
+ */
327
+ freezeClock(settleSteps = FROZEN_SETTLE_STEPS): void {
328
+ // Armed by the *transition* into frozen, so `advance()` — which implies the freeze — does not
329
+ // re-arm it and spend a settling pass after every tick-counted step the runner takes.
330
+ if (!Number.isInteger(settleSteps) || settleSteps < 0)
331
+ throw new Error("settleSteps must be a non-negative integer.");
332
+ if (!this.#clockFrozen) this.#primePending = true;
333
+ this.#clockFrozen = true;
334
+ this.#settleSteps = settleSteps;
335
+ this.#lastTime = Number.POSITIVE_INFINITY;
336
+ }
337
+ /** True once the live clock no longer drives the simulation. */
338
+ get clockFrozen(): boolean {
339
+ return this.#clockFrozen;
340
+ }
341
+ readonly tick = (): number => this.#tick;
342
+ start(now = globalThis.performance?.now() ?? 0): void {
343
+ if (this.#running) return;
344
+ this.#running = true;
345
+ this.#driven = false;
346
+ // A freeze asked for before the loop ran outranks the start timestamp, or a playtest bridge
347
+ // that installs first would be undone by the boot it is supposed to cover.
348
+ this.#lastTime = this.#clockFrozen ? Number.POSITIVE_INFINITY : now;
349
+ this.#lastRenderTime = undefined;
350
+ this.#tick = 0;
351
+ this.#fps = 0;
352
+ this.#renderPerformanceSamples = [];
353
+ this.#frameHandle = this.#requestFrame(this.#frameCallback);
354
+ }
355
+ stop(): void {
356
+ this.#running = false;
357
+ if (this.#frameHandle !== undefined) this.#cancelFrame(this.#frameHandle);
358
+ this.#frameHandle = undefined;
359
+ this.#lastTime = undefined;
360
+ this.#accumulator = 0;
361
+ }
362
+
363
+ #advanceSimulation(now: number): number {
364
+ if (this.#held || this.#clockFrozen) {
365
+ // The whole accumulate-and-update block is skipped rather than just the callback: `#tick`
366
+ // advances inside that loop, and a held frame that moved the tick would break the
367
+ // determinism contract every playtest hold depends on. The clock still moves forward so
368
+ // the hold banks no time.
369
+ this.#lastTime = Math.max(this.#lastTime ?? now, now);
370
+ this.#primeFrame();
371
+ return 0;
372
+ }
373
+ const elapsed = Math.max(0, (now - (this.#lastTime ?? now)) / 1000);
374
+ this.#lastTime = Math.max(this.#lastTime ?? now, now);
375
+ this.#accumulator += elapsed;
376
+ let updates = 0;
377
+ while (this.#accumulator + Number.EPSILON >= this.step && updates < this.maxSteps) {
378
+ this.#interpolation?.beginTick();
379
+ this.#onUpdate(this.step);
380
+ this.#onAfterPhysics(this.step);
381
+ this.#interpolation?.endTick();
382
+ this.#tick += 1;
383
+ this.#accumulator -= this.step;
384
+ updates += 1;
385
+ }
386
+ if (updates === this.maxSteps && this.#accumulator >= this.step) this.#accumulator = 0;
387
+ return updates;
388
+ }
389
+
390
+ /**
391
+ * Settle the world once, on the first live frame after the clock froze.
392
+ *
393
+ * `freezeClock` means the wall clock stops moving the simulation, not that the game stops being
394
+ * called: a scene computes per-frame state in `update` — action-rpg's touch overlay measures the
395
+ * viewport and parents itself to the camera there — and a playtest run reads its first
396
+ * observation before it takes its first tick. Without this pass that state is still whatever its
397
+ * constructor left it, which for a camera-parented overlay is a 72-unit ring sitting on the
398
+ * camera's own origin: `point.project` divides by a zero `w`, and the observation the run reads
399
+ * carries `NaN` bounds, which takes the scenario down before it asserts anything.
400
+ *
401
+ * It is `advance()` over a fixed count, so it is a tick-counted settle rather than a timed one:
402
+ * what it costs is a constant no machine speed can change, and `#tick` moves with it, because the
403
+ * simulation really is that many steps old and the run's report should say so. `FROZEN_SETTLE_STEPS`
404
+ * is where the count comes from.
405
+ *
406
+ * A held boot frame cannot spend it: the scene has not entered yet, so there is nothing of the
407
+ * game's to settle, and the arm survives the hold to fire when the loop is genuinely live. Once,
408
+ * because a second pass would repeat input edge detection and per-frame bookkeeping for nothing.
409
+ */
410
+ #primeFrame(): void {
411
+ if (!this.#primePending || this.#held) return;
412
+ this.#primePending = false;
413
+ if (this.#settleSteps > 0) this.advance(this.#settleSteps);
414
+ }
415
+
416
+ #recordFrameTiming(now: number): number | undefined {
417
+ if (!Number.isFinite(now)) return undefined;
418
+ const frameMs = this.#lastRenderTime === undefined ? undefined : now - this.#lastRenderTime;
419
+ if (frameMs !== undefined && frameMs > 0) this.#fps += (1_000 / frameMs - this.#fps) * 0.1;
420
+ this.#lastRenderTime = now;
421
+ return frameMs;
422
+ }
423
+
424
+ stepFrame(now: number, driven: boolean | "render-only" = false): number {
425
+ this.#frameTime = now;
426
+ const callbackStartedAt = this.#now();
427
+ const budget = this.#budget;
428
+ budget?.beginFrame(now, this.#now());
429
+ let updates = 0;
430
+ let frameMs: number | undefined;
431
+ let callbackMs: number | undefined;
432
+ let callbackFinishedAt = Number.NaN;
433
+ let metrics: IRenderPerformanceMetrics | undefined;
434
+ let phases: IFramePhaseSample | undefined;
435
+ try {
436
+ this.#onBeginFrame?.();
437
+ if (driven === true) {
438
+ this.#onUpdate(this.step);
439
+ this.#onAfterPhysics(this.step);
440
+ this.#tick += 1;
441
+ updates = 1;
442
+ } else if (driven !== "render-only") updates = this.#advanceSimulation(now);
443
+ budget?.markSimulationEnd(this.#now(), updates);
444
+ frameMs = this.#recordFrameTiming(now);
445
+ // onRender does the rendering itself; only its metrics return value is optional.
446
+ metrics = this.#onRender(this.alpha);
447
+ } finally {
448
+ // A renderer can throw before it returns (for example, when SwiftShader rejects a buffer).
449
+ // Close the budget before propagating that error so later frames report the real failure
450
+ // instead of flooding the console with beginFrame calls against a poisoned budget.
451
+ phases = budget?.endFrame(this.#now(), this.#collectMetrics);
452
+ // Closed against the meter's own render phase, so the tree's residual is arithmetic against
453
+ // the number the window reports rather than against a second measurement of the same work.
454
+ // A frame that threw keeps its half-open stack out of the window instead of contributing a
455
+ // fabricated zero.
456
+ const spans = this.#spans;
457
+ if (spans !== undefined) {
458
+ // From the meter's own reading, never from the optional phase sample: `endFrame` builds a
459
+ // sample only when a consumer asked for one, and shipping games do not, so closing the
460
+ // tree on `phases` abandoned every frame and the span window never appeared.
461
+ const renderMs = budget?.lastRenderMs;
462
+ if (renderMs !== undefined && spans.depth === 0) spans.endFrame(renderMs);
463
+ else spans.abandonFrame();
464
+ }
465
+ callbackFinishedAt = this.#now();
466
+ if (Number.isFinite(callbackStartedAt) && Number.isFinite(callbackFinishedAt)) {
467
+ callbackMs = Math.max(0, callbackFinishedAt - callbackStartedAt);
468
+ }
469
+ }
470
+ // Reached only after successful rendering; IDs also reveal gaps across disabled collection.
471
+ const sequence = ++this.#renderCompletionSequence;
472
+ if (callbackMs !== undefined) this.#onFrame(callbackMs);
473
+ if (this.#collectMetrics && frameMs !== undefined && frameMs > 0) {
474
+ const sample: IRenderPerformanceSample = {
475
+ frameMs,
476
+ sequence,
477
+ completedAtMs: callbackFinishedAt,
478
+ ...(metrics === undefined || metrics.drawCalls === undefined
479
+ ? {}
480
+ : { drawCalls: metrics.drawCalls }),
481
+ ...(metrics?.passes === undefined || metrics.passes.length === 0
482
+ ? {}
483
+ : { passes: aggregatePassesByKind(metrics.passes) }),
484
+ ...(phases === undefined ? {} : { phases }),
485
+ ...(metrics === undefined || metrics.triangles === undefined
486
+ ? {}
487
+ : { triangles: metrics.triangles }),
488
+ };
489
+ this.#renderPerformanceSamples.push(sample);
490
+ if (this.#renderPerformanceSamples.length > MAX_RENDER_PERFORMANCE_SAMPLES)
491
+ this.#renderPerformanceSamples.shift();
492
+ }
493
+ return updates;
494
+ }
495
+
496
+ /**
497
+ * Run `ticks` fixed steps now and return how many ran. `until` is asked after each tick and ends
498
+ * the batch early when it answers true, so a caller can stop where an asynchronous change began.
499
+ */
500
+ advance(ticks: number, options?: { render?: boolean; until?: () => boolean }): number {
501
+ if (!this.#running) throw new Error("Cannot advance a stopped loop.");
502
+ if (!Number.isInteger(ticks) || ticks <= 0)
503
+ throw new Error("advance ticks must be a positive integer.");
504
+ // Driving one tick is a statement that the run counts ticks, so it also stops the live clock
505
+ // racing it. `freezeClock()` exists for the frames *before* that statement, which is where a
506
+ // boot's wall clock used to reach the simulation. The prime is not armed from here: this line
507
+ // has just delivered a real update, so the game has had its pass, and arming it would spend
508
+ // one more zero-dt update after every step a run counts. For the same reason a settle still
509
+ // pending is spent: it would otherwise land inside a later counted step as extra ticks.
510
+ this.#primePending = false;
511
+ this.#clockFrozen = true;
512
+ this.#lastTime = Number.POSITIVE_INFINITY;
513
+ if (options?.render === true && !this.#held) {
514
+ // Held startup still needs automatic loading/warmup frames.
515
+ this.#driven = true;
516
+ if (this.#frameHandle !== undefined) this.#cancelFrame(this.#frameHandle);
517
+ this.#frameHandle = undefined;
518
+ for (let index = 0; index < ticks; index += 1) {
519
+ this.stepFrame(this.#now(), true);
520
+ if (options.until?.() === true) return index + 1;
521
+ }
522
+ return ticks;
523
+ }
524
+ // A counted batch is metered, because a tick-counted run — which is what a playtest run is — is
525
+ // simulated entirely by `advance()` and reported `update 0 ms`, `substeps 0` and one boot window
526
+ // followed by nothing but hitches, a blocking batch having pushed the next live timestamp past
527
+ // `hitchMs`. It is charged as simulation, not as a frame: it presents nothing, so counting it as
528
+ // one put zero-millisecond frames that drew nothing into half of every window's frame and render
529
+ // percentiles. `addSimulation` decides which it is from the frame it lands in, so an `advance()`
530
+ // from inside a live frame — the frozen prime's settle — is charged there exactly once.
531
+ const startedAt = this.#now();
532
+ let ran = 0;
533
+ while (ran < ticks) {
534
+ this.#interpolation?.beginTick();
535
+ this.#onUpdate(this.step);
536
+ this.#onAfterPhysics(this.step);
537
+ this.#interpolation?.endTick();
538
+ this.#tick += 1;
539
+ ran += 1;
540
+ if (options?.until?.() === true) break;
541
+ }
542
+ const finishedAt = this.#now();
543
+ const budget = this.#budget;
544
+ if (budget !== undefined && Number.isFinite(startedAt) && Number.isFinite(finishedAt))
545
+ budget.addSimulation(Math.max(0, finishedAt - startedAt), ran);
546
+ return ran;
547
+ }
548
+
549
+ /**
550
+ * Draw the world once without stepping it, for a native deterministic screenshot: the automatic
551
+ * frame pump is off between ticks, so nothing presents and a desktop capture would time out.
552
+ * `render-only` runs the render hooks but skips the frozen startup settle, so the copy is the
553
+ * standing world rather than a simulation change; a live clock fails closed.
554
+ */
555
+ renderCurrentFrame(): number {
556
+ if (!this.#running) throw new Error("Cannot render a stopped loop.");
557
+ if (!this.#clockFrozen)
558
+ throw new Error(
559
+ "renderCurrentFrame requires a frozen clock; a live loop advances through its own frames.",
560
+ );
561
+ return this.stepFrame(this.#now(), "render-only");
562
+ }
563
+
564
+ #frame(time: number): void {
565
+ if (!this.#running || this.#driven) return;
566
+ try {
567
+ this.stepFrame(time);
568
+ } finally {
569
+ if (this.#running && !this.#driven) {
570
+ this.#frameHandle = this.#requestFrame(this.#frameCallback);
571
+ }
572
+ }
573
+ }
574
+ }