@threenative/core 0.3.4 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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-Bj8G1wmD.d.ts} +102 -11
  5. package/dist/hot.d.ts +4 -4
  6. package/dist/index.d.ts +712 -118
  7. package/dist/index.js +12423 -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 +47 -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 +2390 -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 +564 -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 +839 -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
@@ -0,0 +1,839 @@
1
+ import {
2
+ type IPlaytestBridgeDescription,
3
+ type IPlaytestBridgeV1,
4
+ type IPlaytestContactObservation,
5
+ type IPlaytestGameplayObservation,
6
+ type IPlaytestObservationSnapshot,
7
+ type IPlaytestSampleRequest,
8
+ type IPlaytestStrideObservation,
9
+ type IPlaytestWorldObservation,
10
+ type JsonPrimitive,
11
+ type JsonValue,
12
+ PLAYTEST_CLOCK_GLOBAL,
13
+ PLAYTEST_PROTOCOL_LIMITS,
14
+ type PlaytestClockMode,
15
+ assertJsonSafe,
16
+ requestedPlaytestClockMode,
17
+ } from "@threenative/playtest/protocol";
18
+ import { type IThreePlaytestEntity, installThreePlaytestBridge } from "@threenative/playtest/three";
19
+ import { Object3D, type Object3D as ThreeObject3D, type Vector2 } from "three";
20
+ import type { IAssetLoader } from "./assets.js";
21
+ import { audioRuntimeSnapshot } from "./audio.js";
22
+ import type { EntitySnapshot } from "./entities.js";
23
+ import type { IGameObservationContribution, IGamePluginHooks, IGamePluginRuntime } from "./game.js";
24
+ import { GEOMETRY_CAPTURE_CAPABILITY } from "./geometry-capture.js";
25
+ import { PIPELINE_CENSUS_CAPABILITY } from "./pipeline-census.js";
26
+ import { readRenderChainObservation } from "./render/chain.js";
27
+ import type { ICtx } from "./scene.js";
28
+ import { CORE_VERSION } from "./version.js";
29
+
30
+ const currentAgent = typeof navigator === "undefined" ? "node" : navigator.userAgent;
31
+
32
+ /**
33
+ * Install the playtest bridge into a portable game.
34
+ * @situation expose movement and world observations to a playtest
35
+ * @situation connect a game to the ThreeNative scenario runner
36
+ * @constraint install once in the game's plugin list
37
+ * @example const game = defineGame({ plugins: [playtest()] });
38
+ */
39
+ export function playtest<
40
+ TState extends Record<string, unknown> = Record<string, unknown>,
41
+ TPhysics = undefined,
42
+ >(options: IPlaytestOptions = {}): IGamePluginHooks<TState, TPhysics> {
43
+ let dispose: (() => void) | undefined;
44
+ let attached: Promise<void> | undefined;
45
+ let startSceneEntered: Promise<void> | undefined;
46
+ let disposePipelineCensus: (() => void) | undefined;
47
+ let disposeGeometryCapture: (() => void) | undefined;
48
+ let contactHistory: IPlaytestContactObservation[] = [];
49
+ // The tick a contact happened on, and the tick a published value changed on, are the two
50
+ // halves of "the door opened because the plate was pressed". Both are drained per tick rather
51
+ // than per sample: a sample is a step boundary, and a win arriving 199 ticks into a 200-tick
52
+ // step is indistinguishable at that granularity from one arriving with the contact.
53
+ const watcher = createTransitionWatcher();
54
+ let readTick: (() => number) | undefined;
55
+ return {
56
+ sceneExit: () => {
57
+ contactHistory = [];
58
+ watcher.reset();
59
+ },
60
+ update: (ctx) => {
61
+ const tick = readTick?.();
62
+ if (tick === undefined) return;
63
+ drainContacts(ctx, contactHistory, tick);
64
+ watcher.observe(ctx, tick);
65
+ },
66
+ setup: async (ctx, runtime) => {
67
+ readTick = runtime?.tick;
68
+ const seed = runtime?.seed ?? null;
69
+ // One decision, named once, for both consumers: the freeze below and the bridge's verdict on
70
+ // `advance`. Handing the bridge only a *requested* mode and letting it derive the rest is what
71
+ // let the two disagree — a frozen loop reported as the wall clock publishes a frame rate for a
72
+ // game that was not playing. The deterministic answer is therefore stated rather than derived,
73
+ // and stays `undefined` only when there is no tick producer to be fixed-step about.
74
+ let clockMode: PlaytestClockMode | undefined =
75
+ requestedPlaytestClockMode() ?? (runtime === undefined ? undefined : "fixed-step");
76
+ const wallClock = clockMode === "wall-clock";
77
+ const replayRuntime: IPlaytestWorldObservation["runtime"] =
78
+ runtime?.seed === null || runtime?.seed === undefined
79
+ ? undefined
80
+ : {
81
+ agent: currentAgent,
82
+ core: CORE_VERSION,
83
+ randomState: ctx.random.state,
84
+ rapier: runtime.rapier ?? null,
85
+ step: runtime.step,
86
+ };
87
+ const clockRuntime = runtime as
88
+ | (IGamePluginRuntime & {
89
+ _setClockMode?: (mode: "fixed-step" | "wall-clock") => void;
90
+ })
91
+ | undefined;
92
+ const liveAdvance = runtime === undefined ? undefined : wallClockAdvance(runtime);
93
+ const bridgeOptions: Parameters<typeof installThreePlaytestBridge>[0] = {
94
+ camera: ctx.camera,
95
+ ...(clockMode === undefined ? {} : { clockMode }),
96
+ entities: () => bridgeEntities(ctx),
97
+ components: () => componentObservations(ctx.entities.snapshot()),
98
+ // The live clock has to be driven by the host's own frame pump, so a live run's `advance`
99
+ // waits the span of wall time the count names and reports the ticks that pump ran.
100
+ ...(runtime === undefined
101
+ ? {}
102
+ : {
103
+ fixedStep: (ticks, options) =>
104
+ clockMode === "wall-clock" && liveAdvance !== undefined
105
+ ? liveAdvance(ticks)
106
+ : runtime.fixedStep(ticks, options),
107
+ tick: runtime.tick,
108
+ }),
109
+ ...(runtime?.runtimeDiagnosticsSeries === undefined
110
+ ? {}
111
+ : { runtimeDiagnosticsSeries: runtime.runtimeDiagnosticsSeries }),
112
+ // A driven native loop presents nothing between ticks; the render-only operation lets a
113
+ // desktop screenshot draw the standing world without spending a simulation step.
114
+ ...(runtime?.renderCurrent === undefined
115
+ ? {}
116
+ : { renderCurrent: () => runtime.renderCurrent?.() }),
117
+ ...(options.events === undefined ? {} : { events: options.events }),
118
+ gameplay: () => gameplayObservations(ctx, contactHistory, seed, replayRuntime, watcher),
119
+ gameplayChannels: () => gameplayChannels(ctx),
120
+ renderer: ctx.renderer.raw as { getDrawingBufferSize(target: Vector2): Vector2 },
121
+ renderChain: () => {
122
+ const observation = readRenderChainObservation(ctx.renderer);
123
+ return observation === undefined
124
+ ? undefined
125
+ : {
126
+ ...observation,
127
+ contributions: observation.contributions.map((contribution) => ({
128
+ ...contribution,
129
+ })),
130
+ dropped: observation.dropped.map((stage) => ({ ...stage })),
131
+ requested: [...observation.requested],
132
+ stages: [...observation.stages],
133
+ velocity: { ...observation.velocity },
134
+ };
135
+ },
136
+ resources: stateResources(ctx, runtime),
137
+ scene: ctx.scene,
138
+ // A runner advances ticks far faster than a launch completes, and compute dispatch and
139
+ // the first world present are both held behind an opaque loading layer. Published so the
140
+ // runner waits for the world rather than observing a frozen simulation behind a loader.
141
+ startup: () => ({
142
+ phase: ctx.startup.phase,
143
+ progress: ctx.startup.progress,
144
+ ...(ctx.startup.warmup === undefined ? {} : { warmup: ctx.startup.warmup }),
145
+ ...(runtime?.startupCompileSettled === undefined
146
+ ? {}
147
+ : { compileSettled: runtime.startupCompileSettled() }),
148
+ // Wall-clock milestones, so a scenario asserts startup time as an observation instead
149
+ // of reading it off a console marker after the fact.
150
+ ...(runtime?.startupTimeline === undefined
151
+ ? {}
152
+ : { timeline: runtime.startupTimeline() }),
153
+ }),
154
+ };
155
+ const installation = installThreePlaytestBridge(bridgeOptions);
156
+ let clockDisposed = false;
157
+ const clockControl = {
158
+ _clockEpoch: 0,
159
+ _setClockMode: (mode: unknown) => {
160
+ if (clockDisposed) throw new Error("Playtest clock is disposed.");
161
+ if (mode !== "fixed-step" && mode !== "wall-clock")
162
+ throw new Error("Unknown clock mode.");
163
+ clockRuntime?._setClockMode?.(mode);
164
+ if (mode !== clockMode) clockControl._clockEpoch += 1;
165
+ clockMode = mode;
166
+ bridgeOptions.clockMode = mode;
167
+ return { mode, tick: runtime?.tick(), epoch: clockControl._clockEpoch };
168
+ },
169
+ };
170
+ if (clockRuntime?._setClockMode !== undefined) {
171
+ Object.assign(installation.bridge, { _setClockMode: clockControl._setClockMode });
172
+ Object.defineProperty(installation.bridge, "_clockEpoch", {
173
+ get: () => clockControl._clockEpoch,
174
+ });
175
+ }
176
+ const pipelineCensus = runtime?.pipelineCensus;
177
+ if (runtime !== undefined && pipelineCensus !== undefined) {
178
+ disposePipelineCensus = runtime.observations.contribute({
179
+ capabilities: [PIPELINE_CENSUS_CAPABILITY],
180
+ sample: () => ({ pipelineCensus: pipelineCensus() as unknown as JsonValue }),
181
+ });
182
+ }
183
+ const geometryCapture = runtime?.geometryCapture;
184
+ if (runtime !== undefined && geometryCapture !== undefined) {
185
+ disposeGeometryCapture = runtime.observations.contribute({
186
+ capabilities: [GEOMETRY_CAPTURE_CAPABILITY],
187
+ // Nothing is armed, walked or hooked unless this request asked for a capture: the
188
+ // capability says the runtime can answer, not that every sample pays for one.
189
+ sample: async (request) =>
190
+ request.geometry === undefined
191
+ ? {}
192
+ : { geometry: (await geometryCapture(request.geometry)) as unknown as JsonValue },
193
+ });
194
+ }
195
+ installRuntimeChannels(installation.bridge, runtime);
196
+ // A runner announced itself: it is the one consumer of per-frame render samples, so
197
+ // collection turns on exactly for playtest runs and stays off for every plain `pnpm dev`
198
+ // frame. It reads the same predicate as the boot hold below, because gating collection on
199
+ // the browser's half alone left every device and desktop run with an empty
200
+ // `runtimeDiagnosticsSeries` under an advertised `runtime.performance` — a native host
201
+ // announces itself through `TN_PLAYTEST_ENDPOINT`, not through the expected global.
202
+ if (runnerAnnounced()) {
203
+ runtime?.enableRuntimeDiagnostics?.();
204
+ // Same predicate, same reason, one window later. The hold below covers the boot, and the
205
+ // hold ends the moment the runner attaches -- but the runner then pumps live frames for
206
+ // the rAF warmup and for the whole startup wait before it takes its first observation, and
207
+ // every one of those frames advanced the game on the wall clock. So the simulation time a
208
+ // tick-counting scenario sees before its own first tick was a function of how fast the
209
+ // machine booted. The loop is frozen here instead: from the first frame of the run, ticks
210
+ // are the only clock, which is what the run is already counting.
211
+ //
212
+ // A run that asked for the wall clock is the one consumer that wants the opposite: it
213
+ // measures a frame rate for a game, and the frozen loop's presented frames repeat a
214
+ // standing state while the scenario's ticks arrive in bursts — a profile of a game that is
215
+ // not playing. It asked by name, so it is not frozen.
216
+ if (!wallClock) runtime?.freezeClock?.();
217
+ }
218
+ dispose = installation.dispose;
219
+ attached = holdUntilAttached(installation.bridge, options, () => startSceneEntered);
220
+ const cleanup = () => {
221
+ if (!clockDisposed && clockRuntime?._setClockMode !== undefined)
222
+ clockControl._setClockMode("fixed-step");
223
+ clockDisposed = true;
224
+ disposePipelineCensus?.();
225
+ disposePipelineCensus = undefined;
226
+ disposeGeometryCapture?.();
227
+ disposeGeometryCapture = undefined;
228
+ dispose?.();
229
+ dispose = undefined;
230
+ attached = undefined;
231
+ startSceneEntered = undefined;
232
+ contactHistory = [];
233
+ readTick = undefined;
234
+ watcher.reset();
235
+ };
236
+ // Hand the hold to the game rather than blocking this plugin's setup. The game waits after
237
+ // load() has registered setup placeholders but before enter() transfers them into live state.
238
+ // describe() releases a no-setup run and waits for the returned scene-enter signal before it
239
+ // reads entity-derived capabilities.
240
+ if (attached !== undefined) {
241
+ const gate = attached.catch((error: unknown) => {
242
+ cleanup();
243
+ throw error;
244
+ });
245
+ if (runtime?.holdStart === undefined) await gate;
246
+ else {
247
+ startSceneEntered = runtime.holdStart(gate);
248
+ // describe() awaits the same promise when called. Attach a rejection handler now so a
249
+ // setup failure cannot become an unhandled rejection when the runner stops at applySetup.
250
+ void startSceneEntered.catch(() => undefined);
251
+ }
252
+ }
253
+ return cleanup;
254
+ },
255
+ };
256
+ }
257
+
258
+ export const PLAYTEST_ATTACH_TIMEOUT_MS = 30_000;
259
+
260
+ /**
261
+ * Resolves when a runner first calls `describe()`, the handshake every runner performs before
262
+ * it observes anything.
263
+ *
264
+ * Without this, a scenario races the game: a proof that does finite work at startup can finish
265
+ * before the runner takes its first observation, and the assertion then reports
266
+ * TN_PLAYTEST_ASSERTION_TRIVIAL or a zero-delta failure depending only on how fast the device
267
+ * booted. Opt-in, because a game that holds for a runner that never arrives is worse than the
268
+ * race for every non-test caller.
269
+ *
270
+ * Fails closed: if no runner attaches within the timeout, setup throws rather than quietly
271
+ * starting anyway and reproducing the race it was added to remove.
272
+ */
273
+ /** The global a playtest runner sets before the page loads, so a game can tell one is coming. */
274
+ export const PLAYTEST_RUNNER_EXPECTED_GLOBAL = "__THREENATIVE_PLAYTEST_RUNNER_EXPECTED__";
275
+
276
+ /**
277
+ * The clock a consumer asks this game to run on, named in the protocol's own vocabulary. Set before
278
+ * the game module evaluates — a production profile does it in the instrumentation it injects ahead
279
+ * of the bundle, on the browser and on native alike, and the browser runner's `--live-clock` does it
280
+ * in an `addInitScript` ahead of every page script.
281
+ *
282
+ * The read and its failure live in the protocol beside the mode they name, so the loop's clock, the
283
+ * bridge's verdict on it and the producer a game installs itself cannot disagree about it.
284
+ */
285
+ export { PLAYTEST_CLOCK_GLOBAL };
286
+
287
+ /**
288
+ * How long a live advance waits for the pump's own tick past the span its ticks name.
289
+ *
290
+ * The room this buys has to be wall time, not a number of fixed slices, because the thing being
291
+ * waited for is a frame and a frame costs what the machine costs: four slices is 33 ms, which is half
292
+ * a frame on the 15 fps host the old bound claimed to cover and a fraction of one on anything
293
+ * slower — and the 2026-10-04 CI host measured 55-59 ms, where those four slices ended at 50.0 ms
294
+ * and read that slow pump as a dead one. Eight slices only bought 83.3 ms, which is still named
295
+ * against a machine the runner was about to measure. The runner counts a wait in ten-tick pieces, so
296
+ * each piece named a 166 ms span and then a few more slices — and Machinefall's map-walk standing
297
+ * scene died on exactly that at load average 142, with the world plainly drawing at 20 fps in the
298
+ * windows either side. A measurement whose subject is a slow machine cannot refuse to measure one.
299
+ *
300
+ * A one-tick request names exactly one frame interval, so a wait that ended on that boundary ran
301
+ * just before the host's next frame and observed nothing: the 2026-09-28 desktop pair failed on
302
+ * that at 58 mean fps. The tick has to come from the pump, and only a pump that has genuinely
303
+ * stopped may end the wait without one.
304
+ */
305
+ const WALL_CLOCK_PUMP_TIMEOUT_MS = 1_000;
306
+
307
+ const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
308
+
309
+ /**
310
+ * The live-clock stand-in for `runtime.fixedStep`: deliver the span of wall time `ticks` fixed steps
311
+ * would cover, and report the ticks the host's own frame pump ran in it.
312
+ *
313
+ * Waiting rather than stepping is the whole point. The loop is not frozen on this path, so the host
314
+ * keeps presenting frames for the whole span and every one of them advances the game at the fixed
315
+ * step's own rate — a run whose simulation rate is the machine's frame rate, which is what a
316
+ * profile is for. It also means the runner needs nothing new: it still asks for tick counts and
317
+ * still batches them, and a burst costs the wall time it always claimed to cost.
318
+ */
319
+ function wallClockAdvance(runtime: IGamePluginRuntime): (ticks: number) => Promise<number> {
320
+ const stepMs = runtime.step * 1_000;
321
+ return async (ticks) => {
322
+ const before = runtime.tick();
323
+ await sleep(ticks * stepMs);
324
+ // The span is the floor, not the end: a host whose next frame lands just after it has still
325
+ // presented nothing to report. Keep waiting for the pump's own tick, in half-step slices, and
326
+ // never take one here — the loop is the host's, and a tick invented here would be the profile
327
+ // measuring itself. The deadline is the bound, so a pump that has stopped is a fast failure
328
+ // carrying zero rather than a wait that never ends.
329
+ const deadline = Date.now() + WALL_CLOCK_PUMP_TIMEOUT_MS;
330
+ while (runtime.tick() === before && Date.now() < deadline) await sleep(stepMs / 2);
331
+ return runtime.tick() - before;
332
+ };
333
+ }
334
+
335
+ /**
336
+ * Hold when told to, and by default whenever a browser or native runner announced itself.
337
+ *
338
+ * Without it a scenario races the boot, and how much simulation elapses before the first
339
+ * observation depends on how fast the machine renders — measured on action-rpg's combat
340
+ * scenario, player health 90 on SwiftShader and 95 on a real GPU from the same build. Keyed off
341
+ * the runner rather than off the plugin being installed, because every template installs
342
+ * `playtest()` unconditionally and a game that holds for a runner who never arrives is broken
343
+ * for whoever ran `pnpm dev`. Browser runners set the expected global before navigation; native
344
+ * hosts expose `TN_PLAYTEST_ENDPOINT` when a device/desktop transport is attached.
345
+ */
346
+ function shouldHoldUntilAttached(options: IPlaytestOptions): boolean {
347
+ if (options.holdUntilAttached !== undefined) return options.holdUntilAttached;
348
+ return runnerAnnounced();
349
+ }
350
+
351
+ /**
352
+ * Whether a runner announced itself, whichever lane it came from.
353
+ *
354
+ * Browser runners set the expected global before navigation; a native host exposes
355
+ * `TN_PLAYTEST_ENDPOINT` when a device or desktop transport is attached. Both decisions that
356
+ * depend on an announcement — holding the boot, and turning per-frame render collection on — read
357
+ * this one predicate: they were written separately once, and the collection half shipped with only
358
+ * the browser branch, so every device and desktop run answered an advertised
359
+ * `runtime.performance` with an empty series.
360
+ */
361
+ function runnerAnnounced(): boolean {
362
+ const host = globalThis as Record<string, unknown>;
363
+ return host[PLAYTEST_RUNNER_EXPECTED_GLOBAL] === true || host.TN_PLAYTEST_ENDPOINT !== undefined;
364
+ }
365
+
366
+ function holdUntilAttached(
367
+ bridge: IPlaytestBridgeV1,
368
+ options: IPlaytestOptions,
369
+ startSceneEntered: () => Promise<void> | undefined,
370
+ ): Promise<void> | undefined {
371
+ if (!shouldHoldUntilAttached(options)) return undefined;
372
+ const timeoutMs = options.attachTimeoutMs ?? PLAYTEST_ATTACH_TIMEOUT_MS;
373
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
374
+ throw new Error(`TN_PLAYTEST_ATTACH_TIMEOUT_INVALID: ${String(options.attachTimeoutMs)}`);
375
+ }
376
+ const describe = bridge.describe;
377
+ const applySetup = bridge.applySetup;
378
+ return new Promise<void>((resolve, reject) => {
379
+ let settled = false;
380
+ const timer = setTimeout(() => {
381
+ settled = true;
382
+ reject(
383
+ new Error(
384
+ `TN_PLAYTEST_ATTACH_TIMEOUT: no playtest runner applied setup or called describe() within ${timeoutMs}ms.`,
385
+ ),
386
+ );
387
+ }, timeoutMs);
388
+ // Node keeps the process alive for a pending timer; a held game must not outlive its host.
389
+ timer.unref?.();
390
+ const release = () => {
391
+ if (settled) return;
392
+ settled = true;
393
+ clearTimeout(timer);
394
+ resolve();
395
+ };
396
+ const fail = (error: unknown) => {
397
+ if (settled) return;
398
+ settled = true;
399
+ clearTimeout(timer);
400
+ reject(error);
401
+ };
402
+ if (applySetup !== undefined) {
403
+ bridge.applySetup = async (request) => {
404
+ try {
405
+ const confirmation = await applySetup(request);
406
+ release();
407
+ return confirmation;
408
+ } catch (error) {
409
+ fail(error);
410
+ throw error;
411
+ }
412
+ };
413
+ }
414
+ bridge.describe = async () => {
415
+ release();
416
+ await startSceneEntered();
417
+ return describe();
418
+ };
419
+ });
420
+ }
421
+
422
+ export interface IPlaytestOptions {
423
+ readonly events?: () => JsonValue[];
424
+ /**
425
+ * Hold start-scene entry until a runner attaches. Defaults on for an announced runner.
426
+ */
427
+ readonly holdUntilAttached?: boolean;
428
+ /** Milliseconds to wait when `holdUntilAttached` is set. Default {@link PLAYTEST_ATTACH_TIMEOUT_MS}. */
429
+ readonly attachTimeoutMs?: number;
430
+ }
431
+
432
+ function installRuntimeChannels(
433
+ bridge: IPlaytestBridgeV1,
434
+ runtime: IGamePluginRuntime | undefined,
435
+ ): void {
436
+ const describe = bridge.describe;
437
+ bridge.describe = () =>
438
+ Promise.resolve(describe()).then((description) =>
439
+ addRuntimeCapabilities(description, runtime?.observations.contributions() ?? []),
440
+ );
441
+ const sample = bridge.sample;
442
+ bridge.sample = (request) =>
443
+ Promise.resolve(sample(request)).then((snapshot) =>
444
+ addRuntimeObservations(snapshot, request, runtime?.observations.contributions() ?? []),
445
+ );
446
+ }
447
+ function addRuntimeCapabilities(
448
+ description: IPlaytestBridgeDescription,
449
+ contributions: readonly IGameObservationContribution[],
450
+ ): IPlaytestBridgeDescription {
451
+ const capabilities = [...description.capabilities];
452
+ const contributed = contributions.flatMap(({ capabilities }) => capabilities);
453
+ for (const capability of ["runtime.audio", "runtime.world", ...contributed]) {
454
+ if (!capabilities.includes(capability)) capabilities.push(capability);
455
+ }
456
+ return { ...description, capabilities };
457
+ }
458
+ async function addRuntimeObservations(
459
+ snapshot: IPlaytestObservationSnapshot,
460
+ request: IPlaytestSampleRequest,
461
+ contributions: readonly IGameObservationContribution[],
462
+ ): Promise<IPlaytestObservationSnapshot> {
463
+ const result: Record<string, unknown> = { ...snapshot };
464
+ for (const contribution of contributions) {
465
+ // Awaited in order: an observation that waits for a presented frame — a geometry capture —
466
+ // cannot be produced inside the request that asked for it, and the collision check below has
467
+ // to see the slices in a stable order.
468
+ const slice = await contribution.sample(request);
469
+ if (typeof slice !== "object" || slice === null || Array.isArray(slice)) {
470
+ throw new TypeError("A runtime observation contribution must return a top-level object.");
471
+ }
472
+ assertJsonSafe(slice, "$.runtimeContribution");
473
+ for (const [key, value] of Object.entries(slice)) {
474
+ if (Object.hasOwn(result, key)) {
475
+ throw new Error(
476
+ `TN_PLAYTEST_OBSERVATION_COLLISION: top-level key '${key}' already exists.`,
477
+ );
478
+ }
479
+ result[key] = value;
480
+ }
481
+ }
482
+ // quality-allow: every contributed value is validated as JSON-safe immediately above.
483
+ return result as unknown as IPlaytestObservationSnapshot;
484
+ }
485
+ function runtimeObservation(
486
+ seed: number | null,
487
+ replayRuntime: IPlaytestWorldObservation["runtime"],
488
+ ): { audio: ReturnType<typeof audioRuntimeSnapshot>; world: IPlaytestWorldObservation } {
489
+ return {
490
+ audio: audioRuntimeSnapshot(),
491
+ world: {
492
+ seed,
493
+ ...(replayRuntime === undefined ? {} : { runtime: replayRuntime }),
494
+ },
495
+ };
496
+ }
497
+ function bridgeEntities<TState extends Record<string, unknown>, TPhysics>(
498
+ ctx: ICtx<TState, TPhysics>,
499
+ ): IThreePlaytestEntity[] {
500
+ return [
501
+ { id: "camera.main", object: ctx.camera },
502
+ ...Object.keys(ctx.entities.snapshot()).flatMap((id) => {
503
+ const object = entityObject(ctx.entities.get(id));
504
+ return object === undefined ? [] : [{ id, object }];
505
+ }),
506
+ ];
507
+ }
508
+ function entityObject(entity: object | undefined): ThreeObject3D | undefined {
509
+ if (entity instanceof Object3D) return entity;
510
+ const candidate =
511
+ (entity as { mesh?: unknown; object?: unknown } | undefined)?.mesh ??
512
+ (entity as { mesh?: unknown; object?: unknown } | undefined)?.object;
513
+ return candidate instanceof Object3D ? candidate : undefined;
514
+ }
515
+ function gameplayObservations<TState extends Record<string, unknown>, TPhysics>(
516
+ ctx: ICtx<TState, TPhysics>,
517
+ contactHistory: IPlaytestContactObservation[],
518
+ seed: number | null,
519
+ replayRuntime: IPlaytestWorldObservation["runtime"],
520
+ watcher: ITransitionWatcher,
521
+ ): IPlaytestGameplayObservation {
522
+ const animation: IPlaytestGameplayObservation["animation"] = {};
523
+ const states: IPlaytestGameplayObservation["states"] = {};
524
+ const snapshot = ctx.entities.snapshot();
525
+ for (const id of Object.keys(snapshot)) {
526
+ const entity = ctx.entities.get(id) as
527
+ | {
528
+ animation?: {
529
+ advancedFrames?: unknown;
530
+ current?: unknown;
531
+ finished?: unknown;
532
+ stride?: unknown;
533
+ };
534
+ state?: unknown;
535
+ }
536
+ | undefined;
537
+ const finished =
538
+ typeof entity?.animation?.finished === "boolean" ? entity.animation.finished : undefined;
539
+ if (
540
+ typeof entity?.animation?.current === "string" &&
541
+ typeof entity.animation.advancedFrames === "number"
542
+ ) {
543
+ const stride = strideObservation(entity.animation.stride);
544
+ animation[id] = {
545
+ advancedFrames: entity.animation.advancedFrames,
546
+ clip: entity.animation.current,
547
+ ...(finished === undefined ? {} : { finished }),
548
+ ...(stride === undefined ? {} : { stride }),
549
+ };
550
+ }
551
+ if (typeof entity?.state === "string") states[id] = entity.state;
552
+ }
553
+ const channels = gameplayChannels(ctx);
554
+ // The per-tick update hook has already drained everything that happened since the last sample
555
+ // and stamped each event with its tick. This final drain catches a run whose bridge is sampled
556
+ // without the loop having ticked — a paused game, a wall-clock scenario — and stamps those with
557
+ // the tick the loop last reported. Contacts are never dropped for want of a tick.
558
+ const contacts = channels.includes("runtime.contacts")
559
+ ? drainContacts(ctx, contactHistory, watcher.lastTick())
560
+ : undefined;
561
+ const tags = channels.includes("runtime.tags") ? tagCounts(snapshot) : undefined;
562
+ const transitions = watcher.read();
563
+ return {
564
+ animation,
565
+ ...(contacts === undefined ? {} : { contacts }),
566
+ states,
567
+ ...(tags === undefined ? {} : { tags }),
568
+ ...(transitions === undefined ? {} : { transitions }),
569
+ ...runtimeObservation(seed, replayRuntime),
570
+ };
571
+ }
572
+ /**
573
+ * Read an animation player's stride report, or report nothing.
574
+ *
575
+ * A partially shaped report is dropped whole rather than filled in: a stride number the producer
576
+ * did not measure would be read downstream as a measurement, and the one thing this harness may
577
+ * never do is hand back an unmeasured zero. `strideSync: false` still reports — that is the
578
+ * override being honest about what it turned off.
579
+ */
580
+ function strideObservation(value: unknown): IPlaytestStrideObservation | undefined {
581
+ if (typeof value !== "object" || value === null) return undefined;
582
+ const report = value as Record<string, unknown>;
583
+ const numbers = ["clipGroundSpeed", "groundSpeed", "rate"] as const;
584
+ const flags = ["overridden", "synced"] as const;
585
+ if (!numbers.every((key) => typeof report[key] === "number" && Number.isFinite(report[key])))
586
+ return undefined;
587
+ if (!flags.every((key) => typeof report[key] === "boolean")) return undefined;
588
+ return {
589
+ clipGroundSpeed: report.clipGroundSpeed as number,
590
+ groundSpeed: report.groundSpeed as number,
591
+ overridden: report.overridden as boolean,
592
+ rate: report.rate as number,
593
+ synced: report.synced as boolean,
594
+ };
595
+ }
596
+
597
+ type GameplayChannel = "runtime.contacts" | "runtime.tags" | "runtime.transitions";
598
+ interface IContactEvent {
599
+ /** The area that observed the contact, when the source reports one. */
600
+ readonly area?: object;
601
+ readonly body: object;
602
+ readonly entity?: string;
603
+ readonly started: boolean;
604
+ }
605
+ interface IContactSource {
606
+ drainContacts(): readonly IContactEvent[];
607
+ }
608
+
609
+ function gameplayChannels<TState extends Record<string, unknown>, TPhysics>(
610
+ _ctx: ICtx<TState, TPhysics>,
611
+ ): GameplayChannel[] {
612
+ return ["runtime.contacts", "runtime.tags", "runtime.transitions"];
613
+ }
614
+ function drainContacts<TState extends Record<string, unknown>, TPhysics>(
615
+ ctx: ICtx<TState, TPhysics>,
616
+ history: IPlaytestContactObservation[],
617
+ tick: number | undefined,
618
+ ): IPlaytestContactObservation[] {
619
+ // Build the value→id index without extracting debug fields. First id wins per value, matching
620
+ // the insertion-order find it replaced.
621
+ const idsByEntity = new Map<object, string>();
622
+ ctx.entities.forEach((id, registered) => {
623
+ for (const value of objectGraphValues(registered))
624
+ if (!idsByEntity.has(value)) idsByEntity.set(value, id);
625
+ });
626
+ ctx.entities.forEach((_id, registered) => {
627
+ for (const source of entitySources(registered)) {
628
+ for (const event of source.drainContacts()) {
629
+ const entity = idsByEntity.get(event.body);
630
+ // The area's own `entity` option names the far side of the contact. A game that
631
+ // registered the area under a scene-registry id has already named it, and requiring the
632
+ // option again meant a demonstrably firing trigger reported no contact at all — a green
633
+ // `contacts` assertion over a run whose own state proved the overlap happened.
634
+ const other =
635
+ event.entity ??
636
+ (event.area === undefined ? undefined : idsByEntity.get(event.area)) ??
637
+ idsByEntity.get(source);
638
+ if (entity === undefined || other === undefined) continue;
639
+ history.push({
640
+ entity,
641
+ kind: event.started ? "trigger" : "trigger.exit",
642
+ ...(tick === undefined ? {} : { tick }),
643
+ with: other,
644
+ });
645
+ if (history.length > PLAYTEST_PROTOCOL_LIMITS.maxEventsPerDrain) history.shift();
646
+ }
647
+ }
648
+ });
649
+ return [...history];
650
+ }
651
+ /**
652
+ * When a published value changed, and to what — the other half of "because".
653
+ *
654
+ * A run has always been able to say *a contact happened* and *the state reads `won`*. Nothing
655
+ * related the two, and a scenario could only compare at step boundaries, where a win arriving one
656
+ * tick after the contact and a win arriving 199 ticks later inside the same step are the same
657
+ * observation. That is exactly the shape of a game whose terminal state comes from a timer or a
658
+ * distance check and merely happens to land near a contact.
659
+ *
660
+ * The watcher diffs the published surface once per tick and records every change with the tick it
661
+ * happened on. It watches what a scenario can name: each registered entity's `state`, and the
662
+ * top-level primitive fields of the game's own published state. A deeper path is not watched, and
663
+ * an assertion about one fails closed rather than being answered from a value nobody diffed.
664
+ */
665
+ export const PLAYTEST_TRANSITION_LOG_LIMIT = 512;
666
+
667
+ export interface IPlaytestTransition {
668
+ from: JsonPrimitive;
669
+ /** `states.<entity>` for a registered entity, or `state.<field>` for a published field. */
670
+ path: string;
671
+ tick: number;
672
+ to: JsonPrimitive;
673
+ }
674
+
675
+ interface ITransitionWatcher {
676
+ lastTick(): number | undefined;
677
+ observe<TState extends Record<string, unknown>, TPhysics>(
678
+ ctx: ICtx<TState, TPhysics>,
679
+ tick: number,
680
+ ): void;
681
+ read(): IPlaytestTransition[] | undefined;
682
+ reset(): void;
683
+ }
684
+
685
+ function primitiveOrUndefined(value: unknown): JsonPrimitive | undefined {
686
+ if (value === null) return null;
687
+ if (typeof value === "string" || typeof value === "boolean") return value;
688
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
689
+ }
690
+
691
+ function createTransitionWatcher(): ITransitionWatcher {
692
+ let previous = new Map<string, JsonPrimitive>();
693
+ let log: IPlaytestTransition[] = [];
694
+ let seen = false;
695
+ let tickSeen: number | undefined;
696
+ const record = (path: string, to: JsonPrimitive, tick: number): void => {
697
+ const had = previous.has(path);
698
+ const from = previous.get(path);
699
+ previous.set(path, to);
700
+ // The first value a path ever reports is its initial value, not a transition. Recording it as
701
+ // one would make every scenario's `neverBefore` fail against the game's own starting state.
702
+ if (!had || from === to) return;
703
+ log.push({ from: from as JsonPrimitive, path, tick, to });
704
+ if (log.length > PLAYTEST_TRANSITION_LOG_LIMIT) log.shift();
705
+ };
706
+ return {
707
+ lastTick: () => tickSeen,
708
+ observe: (ctx, tick) => {
709
+ tickSeen = tick;
710
+ seen = true;
711
+ ctx.entities.forEach((id, entity) => {
712
+ const candidate = entity as { state?: unknown };
713
+ if (typeof candidate.state === "string") record(`states.${id}`, candidate.state, tick);
714
+ });
715
+ // The store is read without flushing: a flush is a publish to the UI, and an observer must
716
+ // not change when the game's own subscribers run.
717
+ const state = ctx.state.getState() as Record<string, unknown>;
718
+ for (const key of Object.keys(state)) {
719
+ const value = primitiveOrUndefined(state[key]);
720
+ if (value !== undefined) record(`state.${key}`, value, tick);
721
+ }
722
+ },
723
+ // Absent until the loop has ticked at least once. A run that never ticked has not observed
724
+ // that nothing changed; it has observed nothing, and an assertion against it must say so.
725
+ read: () => (seen ? log.map((entry) => ({ ...entry })) : undefined),
726
+ reset: () => {
727
+ previous = new Map();
728
+ log = [];
729
+ seen = false;
730
+ tickSeen = undefined;
731
+ },
732
+ };
733
+ }
734
+
735
+ function entitySources(entity: object | undefined): IContactSource[] {
736
+ return objectGraphValues(entity).filter(
737
+ (value): value is IContactSource =>
738
+ "drainContacts" in value &&
739
+ typeof (value as { drainContacts?: unknown }).drainContacts === "function",
740
+ );
741
+ }
742
+
743
+ /** Walk registered fields far enough to reach the physics adapter without traversing Three's graph. */
744
+ function objectGraphValues(root: object | undefined): object[] {
745
+ if (root === undefined) return [];
746
+ const values: object[] = [];
747
+ const visited = new Set<object>();
748
+ const visit = (value: unknown, depth: number): void => {
749
+ if (value === null || typeof value !== "object" || visited.has(value)) return;
750
+ visited.add(value);
751
+ values.push(value);
752
+ if (depth >= 4 || value instanceof Object3D) return;
753
+ for (const child of Object.values(value)) visit(child, depth + 1);
754
+ };
755
+ visit(root, 0);
756
+ return values;
757
+ }
758
+
759
+ function tagCounts(snapshot: EntitySnapshot): Record<string, { count: number }> {
760
+ const counts: Record<string, { count: number }> = {};
761
+ for (const fields of Object.values(snapshot)) {
762
+ for (const tag of fields.tags ?? []) counts[tag] = { count: (counts[tag]?.count ?? 0) + 1 };
763
+ }
764
+ return counts;
765
+ }
766
+
767
+ function componentObservations(
768
+ snapshot: EntitySnapshot,
769
+ ): Record<string, Record<string, JsonValue>> {
770
+ const components: Record<string, Record<string, JsonValue>> = {};
771
+ for (const [id, fields] of Object.entries(snapshot)) {
772
+ if (Object.keys(fields).length === 0) continue;
773
+ assertJsonSafe(fields, `$.components.${id}`);
774
+ components[id] = fields as Record<string, JsonValue>;
775
+ }
776
+ return components;
777
+ }
778
+
779
+ function stateResources<TState extends Record<string, unknown>, TPhysics>(
780
+ ctx: ICtx<TState, TPhysics>,
781
+ runtime: IGamePluginRuntime | undefined,
782
+ ) {
783
+ return {
784
+ read: () => {
785
+ ctx.state.flush();
786
+ const state = ctx.state.getState();
787
+ assertJsonSafe(state);
788
+ // A bridge sample is an observation, not a live view. The store's current object is
789
+ // mutated in place by later patches and scene resets; returning it directly makes an
790
+ // earlier `before` sample change when a menu navigates to the next scene.
791
+ const value = cloneJsonValue(state) as Record<string, JsonValue>;
792
+ return Object.fromEntries([
793
+ // `state` is canonical. Keep `GameState` as a compatibility alias until published
794
+ // scenarios have migrated, then remove the alias in a future breaking release.
795
+ ["state", value],
796
+ ["GameState", value],
797
+ // Where every asset was actually served from, on every target and not only in a browser
798
+ // console log: a game whose manifest never loaded runs on the uncompiled source directory
799
+ // and looks healthy, and without this nothing observable says so.
800
+ ["assets", assetResolutions(ctx.assets)],
801
+ ...(runtime?.frameCounts === undefined
802
+ ? []
803
+ : [["__threenativeFrameCounts", runtime.frameCounts()]]),
804
+ ]);
805
+ },
806
+ };
807
+ }
808
+
809
+ /**
810
+ * The asset loader's `resolved` ledger, nested on the dots of each logical path.
811
+ *
812
+ * An observation path addresses a value with dots, so a logical path — which is itself dotted —
813
+ * cannot be a key here without being split first. Nesting keeps it lossless and makes
814
+ * `path: "native-proof.png.via"` read as what it is.
815
+ */
816
+ function assetResolutions(assets: IAssetLoader): Record<string, JsonValue> {
817
+ const nested: Record<string, JsonValue> = {};
818
+ for (const [logical, record] of assets.resolved) {
819
+ const parts = logical.split(".");
820
+ let node = nested;
821
+ for (const part of parts.slice(0, -1)) {
822
+ const child = (node[part] ?? {}) as Record<string, JsonValue>;
823
+ node[part] = child;
824
+ node = child;
825
+ }
826
+ node[parts.at(-1) ?? logical] = { url: record.url, via: record.via };
827
+ }
828
+ return nested;
829
+ }
830
+
831
+ function cloneJsonValue(value: JsonValue): JsonValue {
832
+ if (Array.isArray(value)) return value.map((item) => cloneJsonValue(item));
833
+ if (typeof value === "object" && value !== null) {
834
+ return Object.fromEntries(
835
+ Object.entries(value).map(([key, item]) => [key, cloneJsonValue(item)]),
836
+ );
837
+ }
838
+ return value;
839
+ }