@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,1368 @@
1
+ /**
2
+ * Per-presented-frame cost attribution, on by default, for every platform.
3
+ *
4
+ * A device once read 18.3 fps with nothing in the repository able to say where the frame went;
5
+ * the answer took a hand-written 468-line probe that monkey-patched `requestAnimationFrame` and
6
+ * `renderer.render` from inside the game. That probe had to guess the phase boundaries because it
7
+ * lived outside the loop. This lives inside the loop, so it knows them: the framework owns the
8
+ * simulation/render split, the render call and the frame's start and end, and no game should ever
9
+ * write this again.
10
+ *
11
+ * Two consumers, one measurement:
12
+ *
13
+ * - a windowed `TN_FRAME_BUDGET` marker line, printed periodically on stdout (and therefore in
14
+ * logcat on Android), so a cold agent reading standard device-lane output sees the attribution
15
+ * without instrumenting anything;
16
+ * - a per-frame sample carried into the playtest render series, so `assert.performance` can bound
17
+ * an fps floor and a per-phase ceiling and a mobile regression is a red gate rather than a vibe.
18
+ *
19
+ * Fail closed: malformed options throw at construction rather than silently disabling the budget,
20
+ * and a phase that was never measured reports zero samples so a consumer asserting on it fails
21
+ * instead of skipping.
22
+ */
23
+
24
+ import type { IFrameCounters } from "./profiling/FrameCounters.js";
25
+ import {
26
+ FRAME_PASS_KINDS,
27
+ type FramePassKind,
28
+ type IRenderPassSample,
29
+ MAIN_DRAW_SOURCES,
30
+ type MainDrawSource,
31
+ } from "./render-pass-budget.js";
32
+ import type { ITargetFps, TargetFpsSource } from "./target-fps.js";
33
+
34
+ const TARGET_FPS_SOURCES: readonly TargetFpsSource[] = [
35
+ "config",
36
+ "display",
37
+ "fallback",
38
+ "mobile-default",
39
+ ];
40
+
41
+ /**
42
+ * Fail closed: a resolved budget nobody can act on is not a budget. A rate that is not a
43
+ * non-negative number, or a source that names no rule, would be read as an answer.
44
+ */
45
+ function requireTarget(target: ITargetFps): ITargetFps {
46
+ if (!Number.isFinite(target.targetFps) || target.targetFps < 0)
47
+ throw new Error(
48
+ `Frame budget targetFps must be a non-negative number, received ${String(target.targetFps)}.`,
49
+ );
50
+ if (!TARGET_FPS_SOURCES.includes(target.source))
51
+ throw new Error(
52
+ `Frame budget targetSource must name how the target was chosen, received ${String(target.source)}.`,
53
+ );
54
+ return target;
55
+ }
56
+
57
+ /** Marker printed once per report window. */
58
+ export const FRAME_BUDGET_MARKER = "TN_FRAME_BUDGET";
59
+ /** Marker printed the moment a gap between presented frames exceeds `hitchMs`. */
60
+ export const FRAME_HITCH_MARKER = "TN_FRAME_HITCH";
61
+
62
+ /**
63
+ * The named parts of one presented frame. They partition the frame: `hostGap` is the time before
64
+ * the callback (present wait plus whatever the host did between callbacks), and `update`,
65
+ * `render`, `overlay`, `ui` and `residual` sum to the callback's own duration.
66
+ *
67
+ * `overlay` and `ui` are two different draws that happen to sit next to each other. `overlay` is
68
+ * the three.js HUD pass; `ui` is the native UI layer's composite of the page's pixels into the
69
+ * game's own frame — one upload and one quad — which is why it is a phase of its own and not part
70
+ * of `overlay`.
71
+ */
72
+ export const FRAME_BUDGET_PHASES = [
73
+ "hostGap",
74
+ "update",
75
+ "render",
76
+ "overlay",
77
+ "ui",
78
+ "residual",
79
+ ] as const;
80
+
81
+ export type FrameBudgetPhase = (typeof FRAME_BUDGET_PHASES)[number];
82
+
83
+ /** One frame's cost, split by phase. Every field is milliseconds. */
84
+ export interface IFramePhaseSample {
85
+ readonly hostGap: number;
86
+ readonly update: number;
87
+ readonly render: number;
88
+ readonly overlay: number;
89
+ readonly ui: number;
90
+ readonly residual: number;
91
+ }
92
+
93
+ /**
94
+ * What the frame the window measured was actually drawn at.
95
+ *
96
+ * A resolution number without its sample count does not describe an image, and neither of them
97
+ * describes anything at all unless the window that carries the fps also carries them. This is
98
+ * reported whether the scale was pinned by the game or chosen by the engine: turning the
99
+ * convention off does not turn its measurement off.
100
+ */
101
+ export interface IFrameSurfaceState {
102
+ readonly resolutionSubrect?: boolean;
103
+ /** The applied drawing-buffer scale, in `(0, 1]`. */
104
+ readonly resolutionScale: number;
105
+ /**
106
+ * `"pinned"` when the game fixed the number, `"auto"` when the engine chose it, and
107
+ * `"auto-pinned"` when the engine chose it and then stopped moving it — the oscillation guard
108
+ * holding a rung is a different state from a game that pinned one, and reads as one.
109
+ */
110
+ readonly scaleSource: "pinned" | "auto" | "auto-pinned";
111
+ /** Multisample count of the 3D drawing buffer; 1 when sampling is off. */
112
+ readonly sampleCount: number;
113
+ readonly drawingBufferWidth: number;
114
+ readonly drawingBufferHeight: number;
115
+ /**
116
+ * True when the scaler is at its lowest rung and the tail is still over budget.
117
+ *
118
+ * A window that reports 0.23 and nothing else reads as a met budget at a low resolution. It is
119
+ * the opposite: the engine ran out of room and the game is still missing its target. Always
120
+ * false under a pinned scale, which has no floor to reach.
121
+ */
122
+ readonly atFloor: boolean;
123
+ /** Compilation overlapped the measured window; automatic scaling waits for a clean window. */
124
+ readonly compiling?: boolean;
125
+ }
126
+
127
+ const SCALE_SOURCES: readonly IFrameSurfaceState["scaleSource"][] = [
128
+ "pinned",
129
+ "auto",
130
+ "auto-pinned",
131
+ ];
132
+
133
+ /** Fail closed: a surface that cannot describe an image is never reported as one. */
134
+ function requireSurface(surface: IFrameSurfaceState): IFrameSurfaceState {
135
+ const {
136
+ atFloor,
137
+ compiling,
138
+ drawingBufferHeight,
139
+ drawingBufferWidth,
140
+ resolutionSubrect,
141
+ resolutionScale,
142
+ sampleCount,
143
+ scaleSource,
144
+ } = surface;
145
+ if (compiling !== undefined && typeof compiling !== "boolean")
146
+ throw new Error("Frame budget surface compiling must be a boolean when observed.");
147
+ if (resolutionSubrect !== undefined && typeof resolutionSubrect !== "boolean")
148
+ throw new Error("Frame budget surface resolutionSubrect must be a boolean when observed.");
149
+ if (typeof atFloor !== "boolean")
150
+ throw new Error(
151
+ `Frame budget surface atFloor must say whether the scaler had room left, received ${String(atFloor)}.`,
152
+ );
153
+ if (!Number.isFinite(resolutionScale) || resolutionScale <= 0 || resolutionScale > 1)
154
+ throw new Error(
155
+ `Frame budget surface resolutionScale must be within (0, 1], received ${String(resolutionScale)}.`,
156
+ );
157
+ if (!SCALE_SOURCES.includes(scaleSource))
158
+ throw new Error(
159
+ `Frame budget surface scaleSource must name how the scale was chosen, received ${String(scaleSource)}.`,
160
+ );
161
+ if (!Number.isInteger(sampleCount) || sampleCount < 1)
162
+ throw new Error(
163
+ `Frame budget surface sampleCount must be an integer of at least one, received ${String(sampleCount)}.`,
164
+ );
165
+ for (const [name, value] of [
166
+ ["drawingBufferWidth", drawingBufferWidth],
167
+ ["drawingBufferHeight", drawingBufferHeight],
168
+ ] as const) {
169
+ if (!Number.isInteger(value) || value < 1)
170
+ throw new Error(
171
+ `Frame budget surface ${name} must be an integer of at least one, received ${String(value)}.`,
172
+ );
173
+ }
174
+ return {
175
+ atFloor,
176
+ ...(compiling === undefined ? {} : { compiling }),
177
+ drawingBufferHeight,
178
+ drawingBufferWidth,
179
+ ...(resolutionSubrect === undefined ? {} : { resolutionSubrect }),
180
+ resolutionScale,
181
+ sampleCount,
182
+ scaleSource,
183
+ };
184
+ }
185
+
186
+ export interface IFrameBudgetSummary {
187
+ readonly samples: number;
188
+ readonly mean: number;
189
+ readonly p50: number;
190
+ readonly p95: number;
191
+ readonly p99: number;
192
+ readonly max: number;
193
+ }
194
+
195
+ /** Where one resolved frame's GPU milliseconds went. Closed on purpose, like the phases. */
196
+ export const FRAME_GPU_BUCKETS = ["main", "shadow", "other", "compute"] as const;
197
+
198
+ export type FrameGpuBucket = (typeof FRAME_GPU_BUCKETS)[number];
199
+
200
+ /** One frame's GPU milliseconds per bucket; a bucket the device did not resolve is absent. */
201
+ export type IFrameGpuBucketSample = Partial<Record<FrameGpuBucket, number>> & {
202
+ /**
203
+ * Shadow passes the frame recorded, from the producer. `0` means the frame drew no shadow and its
204
+ * `shadow` bucket is a known zero; `> 0` means it rendered one. Absent when the source cannot say,
205
+ * and no frame is then counted as rendered.
206
+ */
207
+ readonly shadowPasses?: number;
208
+ };
209
+
210
+ /**
211
+ * One render-pass kind's submissions across a window, so a change that trades triangles for CPU is
212
+ * visible in the same report as the milliseconds it traded for.
213
+ */
214
+ export interface IFrameBudgetPassSummary {
215
+ readonly draws: IFrameBudgetSummary;
216
+ /**
217
+ * The main pass's own draws per origin, summarised like every other series in this window.
218
+ *
219
+ * The per-frame counts sum to `draws` exactly, which is the invariant the split exists to answer;
220
+ * the percentiles below do not have to, because a source that draws on some frames and not others
221
+ * has a median over its own frames rather than over the window's. A source no frame drew is
222
+ * absent. Absent altogether — never a set of zeros — when the renderer named no object behind one
223
+ * of the pass's draws, which is the same rule the pass record itself follows. One exception to the
224
+ * sum: a world with bundles on counts its replays here, and three never traverses a replay, so the
225
+ * sources can exceed `draws`; the sum holds for the sources that went through the per-draw path.
226
+ */
227
+ readonly drawsBySource?: Readonly<Partial<Record<MainDrawSource, IFrameBudgetSummary>>>;
228
+ /** Frames in the window that submitted a pass of this kind. */
229
+ readonly frames: number;
230
+ /**
231
+ * Three's CPU figure: `instanceCount * count / 3` per draw, where an indirect batch's `count` is
232
+ * the merged geometry's capacity. An upper bound over what the GPU could select.
233
+ */
234
+ readonly triangles: IFrameBudgetSummary;
235
+ /**
236
+ * What the GPU selected, main pass only: the streamed world's own indirect tally, beside the
237
+ * figure above so a reader of the pass record can tell which of the two it is holding. Absent
238
+ * rather than zero when the world reported no tally — see `mainGpuTriangles`.
239
+ */
240
+ readonly gpuTriangles?: number;
241
+ }
242
+
243
+ /**
244
+ * One reported window of the frame meter.
245
+ *
246
+ * **The cadence here is the loop's, not necessarily the display's.** `endFrame` is called once per
247
+ * frame the game's loop runs, and on the web that is one `requestAnimationFrame` per vblank, so the
248
+ * interval is a presented frame's. On a native host the loop's dispatch is what drives it — the host
249
+ * says so itself: "the JavaScript budget reads the same interval as presentedDelta"
250
+ * (`runtime-native/src/runtime.cpp`, `executeAnimationFrameCallbacks`). Its presentation cap paces
251
+ * the **present**, never the loop, so a loop that outruns 60 Hz iterates many times per present and
252
+ * this window's `fps` is inflated by exactly that ratio. Measured on midway's native launch:
253
+ * `fps 2631.58` beside the host's own `TN_PRESENTS_TICK:{"frames":1740,"presents":133,"capHz":60}`.
254
+ * The display's rate is the host's series; a reader that has both must not print this one as though
255
+ * it were a player's — `threenative-playtest perf` refuses to (`TN_PERF_VIRTUAL_DISPLAY`).
256
+ */
257
+ export interface IFrameBudgetWindow {
258
+ /** Browser Long Tasks, independent of vsync/GPU waits. Unavailable on hosts without this API. */
259
+ readonly longTasks:
260
+ | { readonly available: false }
261
+ | {
262
+ readonly available: true;
263
+ readonly count: number;
264
+ readonly longestMs: number;
265
+ readonly afterFirstFrameMs: number;
266
+ };
267
+ /** 1 for the first reported window, incrementing thereafter. */
268
+ readonly window: number;
269
+ /** Loop frames counted in this window, hitches excluded — one per present on the web. */
270
+ readonly frames: number;
271
+ /** Fixed simulation ticks in this window multiplied by the loop's step, when supplied. */
272
+ readonly simulatedSeconds?: number;
273
+ /** Frames excluded from the window because their present gap exceeded `hitchMs`. */
274
+ readonly hitches: number;
275
+ /**
276
+ * Derived from the mean interval between loop frames. The number a player would read off a
277
+ * counter only where the loop's cadence is the display's, as it is on the web via rAF.
278
+ */
279
+ readonly fps: number;
280
+ /**
281
+ * Frames that reached the display in this window, when the host reports them.
282
+ *
283
+ * Absent on the web, where rAF *is* the display's cadence and a second number would be the same
284
+ * one. On a native host the presentation cap lets the loop dispatch many times per present, so
285
+ * this is the count a player saw and `fps` is not. **Zero is a reading**: a window of loop frames
286
+ * can be shorter than one present period, and the display genuinely showed nothing in it.
287
+ */
288
+ readonly presents?: number;
289
+ /**
290
+ * Presents per second over this window's own duration. Absent when the window counted none —
291
+ * a rate needs at least one present, and a window too short to contain one carries no rate to
292
+ * assess rather than a zero.
293
+ */
294
+ readonly presentedFps?: number;
295
+ /** Interval between loop frames — the honest frame period where the loop presents every frame. */
296
+ readonly presented: IFrameBudgetSummary;
297
+ /** Duration of the frame callback itself, entry to exit. */
298
+ readonly frame: IFrameBudgetSummary;
299
+ /** Fixed simulation steps executed in the callback. */
300
+ readonly substeps: IFrameBudgetSummary;
301
+ readonly phases: Readonly<Record<FrameBudgetPhase, IFrameBudgetSummary>>;
302
+ /** Each phase's mean as a fraction of the mean presented interval. */
303
+ readonly shares: Readonly<Record<FrameBudgetPhase, number>>;
304
+ /**
305
+ * Draw calls and triangles submitted per render pass, when a pass recorder was installed.
306
+ *
307
+ * Absent rather than defaulted: a renderer whose submissions nothing measured and a frame that
308
+ * submitted nothing are different facts, and a zero would merge them. A kind no frame submitted
309
+ * is absent; `frames` says how many frames did.
310
+ */
311
+ readonly passes?: Readonly<Partial<Record<FramePassKind, IFrameBudgetPassSummary>>>;
312
+ /**
313
+ * Instances and triangles the GPU actually selected in the main pass, from the streamed world's
314
+ * own indirect-args tally when it has one.
315
+ *
316
+ * These are the honest counterpart of `passes.main`: three's `renderer.info.render.triangles`
317
+ * counts a mesh's CPU window/capacity for an indirect draw, so `passes.main.triangles` is an upper
318
+ * bound over what the GPU could draw, while `mainGpuTriangles` is the sum over the indirect
319
+ * records of `instanceCount x indexCount / 3` — what the kernel selected. Main pass only: shadow
320
+ * passes are not tallied. Absent, never zero, before the first sample lands.
321
+ */
322
+ readonly mainGpuInstances?: number;
323
+ readonly mainGpuTriangles?: number;
324
+ /**
325
+ * The resolution and sampling this window's frames were drawn at, when the loop reported one.
326
+ * Absent rather than defaulted: a consumer asserting on it must fail loudly instead of reading
327
+ * a fabricated `1.0` that no frame was ever drawn at.
328
+ */
329
+ readonly surface?: IFrameSurfaceState;
330
+ /**
331
+ * The rate the loop is holding, and what decided it, when the engine resolved one.
332
+ *
333
+ * Two fields rather than an object, and a harness reads them without unwrapping anything: a
334
+ * number nobody can place (`targetSource: "fallback"`) is the difference between a game holding
335
+ * its panel and a game settling for 60, and only this line says which one happened.
336
+ */
337
+ readonly targetFps?: number;
338
+ readonly targetSource?: TargetFpsSource;
339
+ /**
340
+ * Frames in this window that ran past the target frame (`1000 / targetFps`, the target this
341
+ * window started with): `render` over every counted frame's render phase, `gpu` over the frames
342
+ * with a resolved GPU sample. A pooled p95 is under the target exactly when at most 5 % of the
343
+ * pooled frames are, which window quantiles can only bound (PRD-478). Absent until a target is
344
+ * known.
345
+ */
346
+ readonly overTarget?: { readonly frameMs: number; readonly gpu: number; readonly render: number };
347
+ /**
348
+ * GPU milliseconds per resolved frame in this window, from `timestamp-query`, summarised like a
349
+ * phase — mean/p50/p95/p99/max over the frames the device actually reported.
350
+ *
351
+ * A single instantaneous `info.render.timestamp` read is lagged by up to `gpuAgeFrames` and
352
+ * spread 3.5x between consecutive reads of one steady frame, so it is not the frame's GPU cost
353
+ * and is not what this reports. Absent rather than zero when no frame resolved a reading: an
354
+ * adapter without timestamps and a frame that genuinely cost no GPU time are different facts,
355
+ * and a zero would merge them.
356
+ */
357
+ readonly gpu?: IFrameBudgetSummary;
358
+ /**
359
+ * Frames in the window whose GPU reading had not advanced since the previous frame, or was
360
+ * absent. `gpu.samples + gpuStale` is the frames the device was asked about; a window where
361
+ * every frame is stale reports `gpu` absent rather than the last reading looking current.
362
+ */
363
+ readonly gpuStale: number;
364
+ /**
365
+ * Frames in the window the renderer declined to draw (the Wasm web engine holds at most two drawn
366
+ * frames on the GPU). Their render phase is near zero, so `phases.render` over the window reads
367
+ * cheaper than the frames that were drawn; divide by `frames - renderSkips` for a drawn frame's cost.
368
+ * Absent, not zero, when the renderer drew every frame.
369
+ */
370
+ readonly renderSkips?: number;
371
+ /**
372
+ * The window mean of `gpu`, when present. The scalar the resolution scaler reads.
373
+ *
374
+ * It is the same number as `gpu.mean`; a single field keeps the scaler and the perf report on
375
+ * one series rather than a second instantaneous read.
376
+ */
377
+ readonly gpuMs?: number;
378
+ /** Resolved renderer-frame range behind this window; unavailable for unframed samples. */
379
+ readonly gpuFrames?: { readonly first: number; readonly last: number };
380
+ /** Age of the most recent resolved GPU timestamp in Three.js frame IDs; absent means unobservable. */
381
+ readonly gpuAgeFrames?: number;
382
+ /**
383
+ * GPU milliseconds per resolved frame, split by where the device spent them: the main scene
384
+ * pass, every shadow pass, everything else in the render pool (post chain, reflections, HUD) and
385
+ * the compute pool. Each is the window's p50 over the frames that resolved it, one decimal.
386
+ *
387
+ * `gpu` is their sum's series; these say which pass owns it. Absent rather than zero when that
388
+ * bucket never resolved — an unmeasured pass and a free one are different facts — so
389
+ * `gpuMain + gpuShadow + gpuOther` reconciles with `gpuMs` only when all three are present.
390
+ */
391
+ readonly gpuMain?: number;
392
+ readonly gpuShadow?: number;
393
+ readonly gpuOther?: number;
394
+ readonly gpuCompute?: number;
395
+ /**
396
+ * The shadow bucket's p95 and coverage over **every** frame that resolved a shadow reading,
397
+ * known-zero frames included, so the p95 can sit at zero while the shadow renders are expensive.
398
+ * Kept for compatibility beside {@link gpuShadowRendered}, which is the same tail over the frames
399
+ * that actually rendered a shadow — the distribution the phase comparison should read.
400
+ */
401
+ readonly gpuShadowP95?: number;
402
+ readonly gpuShadowSamples?: number;
403
+ /**
404
+ * The shadow bucket's distribution over the frames that **actually rendered a shadow**, distinct
405
+ * from the known-zero frames the p50 and all-frame p95 above include.
406
+ *
407
+ * `samples` is how many frames rendered one, so observed renders are tellable from frames that
408
+ * drew none (`gpuShadowSamples - gpuShadowRendered.samples`). Absent, never a zeroed summary, when
409
+ * no rendered shadow resolved: a render that cost 0 ms is still a render, and only the producer's
410
+ * own `shadowPasses` record says one happened, so the count is not guessed from `shadow > 0`.
411
+ */
412
+ readonly gpuShadowRendered?: IFrameBudgetSummary;
413
+ /** Pyramid build GPU milliseconds per resolved build, including the depth copy/resolve. */
414
+ readonly gpuPyramid?: IFrameBudgetSummary;
415
+ /**
416
+ * The frame's boundary counts, when something counted them, plus the simulation tick the window
417
+ * closed on when the loop fed one.
418
+ *
419
+ * Each boundary series is absent when nothing measured it, and a series present with zero samples
420
+ * is not possible: an uncounted frame and a frame that crossed the boundary zero times are
421
+ * different facts, and a fabricated zero merges them. `hostCalls` and `gpuBytes` come from
422
+ * `FrameCounters`; `jsAllocBytes` needs a platform that publishes `performance.memory`.
423
+ * `simulationTick` is not a platform reading — it is the loop's latest fixed-step count, so the
424
+ * object is present whenever `addCounters` carried a tick even with no boundary field measured.
425
+ */
426
+ readonly counters?: {
427
+ readonly hostCalls?: IFrameBudgetSummary;
428
+ readonly gpuBytes?: IFrameBudgetSummary;
429
+ readonly jsAllocBytes?: IFrameBudgetSummary;
430
+ readonly simulationTick?: number;
431
+ };
432
+ }
433
+
434
+ export interface IFrameBudgetSimulation {
435
+ readonly tick: () => number;
436
+ readonly step: number;
437
+ }
438
+
439
+ export interface IFrameBudgetOptions {
440
+ /** Simulation ticks per report window when a clock is supplied, otherwise presented frames. Default 300. */
441
+ readonly reportEvery?: number;
442
+ /** Minimum measured rendered frames per report window. Default 1. */
443
+ readonly minFrames?: number;
444
+ readonly simulation?: IFrameBudgetSimulation;
445
+ /** A present gap at or above this is a hitch, not a frame. Default 2000 ms. */
446
+ readonly hitchMs?: number;
447
+ /** Ring capacity per series. Default 1024. */
448
+ readonly capacity?: number;
449
+ /** Where marker lines go. Default `console.log`. In defineGame, also receives all window telemetry; without a custom sink its existing info/warn severities remain. */
450
+ readonly report?: (line: string) => void;
451
+ /** Wall clock for hitch markers. Default `Date.now`. */
452
+ readonly wallClock?: () => number;
453
+ /**
454
+ * Called with each completed window, after its marker line. A HUD reads it to show the split
455
+ * on screen; a measurement run reads it to advance in lockstep with the instrument instead of
456
+ * guessing when a window closed.
457
+ */
458
+ readonly onWindow?: (window: IFrameBudgetWindow) => void;
459
+ /**
460
+ * Reads what the frames were drawn at, called once per reported window. Wired by the frame
461
+ * loop, which is the only place that knows both the renderer and the window boundary.
462
+ */
463
+ readonly readSurface?: () => IFrameSurfaceState;
464
+ /**
465
+ * The engine's resolved frame budget, read once per reported window.
466
+ *
467
+ * Wired by the game, which owns the rule and the panel measurement behind it. A window with no
468
+ * resolver reports no target rather than a default that looks measured.
469
+ */
470
+ readonly readTarget?: () => ITargetFps | undefined;
471
+ /**
472
+ * Frames the display has presented so far, when the platform can say.
473
+ *
474
+ * Defaults to the native host's `__tnPresentedCount`, whose presence is the whole signal: the
475
+ * web has no such seam and needs none. A counter that goes backwards or non-finite is ignored
476
+ * for the window rather than reported as a negative rate.
477
+ */
478
+ readonly readPresentCount?: () => number | undefined;
479
+ /** Reads the successful GPU query frame age, not the age of the last resolve attempt. */
480
+ readonly readGpuAgeFrames?: () => number | undefined;
481
+ /**
482
+ * The GPU-selected main-pass instance and triangle count, read once per reported window.
483
+ *
484
+ * Wired by the game from the streamed world's own tally; `undefined` until its first sample lands
485
+ * or when the world has none, so a window reports absent rather than a fabricated zero.
486
+ */
487
+ readonly readGpuTally?: () =>
488
+ | { readonly instances: number; readonly triangles: number }
489
+ | undefined;
490
+ }
491
+
492
+ const DEFAULT_REPORT_EVERY = 300;
493
+ const DEFAULT_HITCH_MS = 2_000;
494
+ const DEFAULT_CAPACITY = 1_024;
495
+
496
+ function requirePositiveInteger(value: number | undefined, fallback: number, name: string): number {
497
+ if (value === undefined) return fallback;
498
+ if (!Number.isInteger(value) || value < 1)
499
+ throw new Error(
500
+ `Frame budget ${name} must be an integer of at least one, received ${String(value)}.`,
501
+ );
502
+ return value;
503
+ }
504
+
505
+ function requirePositiveNumber(value: number | undefined, fallback: number, name: string): number {
506
+ if (value === undefined) return fallback;
507
+ if (!Number.isFinite(value) || value <= 0)
508
+ throw new Error(
509
+ `Frame budget ${name} must be a finite number greater than zero, received ${String(value)}.`,
510
+ );
511
+ return value;
512
+ }
513
+
514
+ /** A fixed-capacity ring of milliseconds. Never allocates after construction. */
515
+ class Ring {
516
+ readonly #buffer: Float64Array;
517
+ #count = 0;
518
+ #cursor = 0;
519
+ #total = 0;
520
+
521
+ constructor(capacity: number) {
522
+ this.#buffer = new Float64Array(capacity);
523
+ }
524
+
525
+ push(value: number): void {
526
+ // A non-finite sample means a clock the host did not deliver; dropping it silently would
527
+ // manufacture a clean percentile out of a broken measurement.
528
+ if (!Number.isFinite(value))
529
+ throw new Error(`Frame budget received a non-finite sample: ${String(value)}.`);
530
+ const capacity = this.#buffer.length;
531
+ const index = this.#cursor % capacity;
532
+ if (this.#count === capacity) this.#total -= this.#buffer[index] ?? 0;
533
+ this.#buffer[index] = value;
534
+ this.#total += value;
535
+ this.#cursor += 1;
536
+ if (this.#count < capacity) this.#count += 1;
537
+ }
538
+
539
+ /** Samples currently held. A series with none is reported absent rather than summarised to zero. */
540
+ get count(): number {
541
+ return this.#count;
542
+ }
543
+
544
+ reset(): void {
545
+ this.#count = 0;
546
+ this.#cursor = 0;
547
+ this.#total = 0;
548
+ }
549
+
550
+ summarize(scratch: Float64Array): IFrameBudgetSummary {
551
+ const count = this.#count;
552
+ if (count === 0) return { max: 0, mean: 0, p50: 0, p95: 0, p99: 0, samples: 0 };
553
+ for (let index = 0; index < count; index += 1) scratch[index] = this.#buffer[index] ?? 0;
554
+ const view = scratch.subarray(0, count);
555
+ view.sort();
556
+ const rank = (fraction: number): number =>
557
+ round(view[Math.min(count - 1, Math.ceil(fraction * count) - 1)] ?? 0);
558
+ return {
559
+ max: round(view[count - 1] ?? 0),
560
+ mean: round(this.#total / count),
561
+ p50: rank(0.5),
562
+ p95: rank(0.95),
563
+ p99: rank(0.99),
564
+ samples: count,
565
+ };
566
+ }
567
+ }
568
+
569
+ /**
570
+ * The native host's presented-frame counter, when this build has one.
571
+ *
572
+ * `__tnPresentedCount` is a private diagnostic seam beside `__tnPresentationCap`; its *presence* is
573
+ * the signal, so the web returns `undefined` here and the window reports no present series at all
574
+ * rather than a zero. Read through a property lookup once, at construction: a per-frame lookup of a
575
+ * global is a per-frame megamorphic access for no gain.
576
+ */
577
+ function hostPresentCountReader(): (() => number | undefined) | undefined {
578
+ const host = globalThis as { __tnPresentedCount?: unknown };
579
+ if (typeof host.__tnPresentedCount !== "function") return undefined;
580
+ const read = host.__tnPresentedCount as () => unknown;
581
+ return () => {
582
+ const value = read();
583
+ return typeof value === "number" ? value : undefined;
584
+ };
585
+ }
586
+
587
+ /** Whether a per-source key names a source this window counts. */
588
+ function isMainDrawSource(source: string): source is MainDrawSource {
589
+ return (MAIN_DRAW_SOURCES as readonly string[]).includes(source);
590
+ }
591
+
592
+ function round(value: number): number {
593
+ return Math.round(value * 100) / 100;
594
+ }
595
+
596
+ /** One decimal, for the per-bucket GPU line the harness prints as `<ms>` with a single place. */
597
+ function round1(value: number): number {
598
+ return Math.round(value * 10) / 10;
599
+ }
600
+
601
+ /**
602
+ * Accumulates one frame at a time and reports windowed attribution.
603
+ *
604
+ * The caller is the frame loop; the sequence per frame is
605
+ * `beginFrame` → `markSimulationEnd` → (`addRender` / `addOverlay` / `addUi`) → `endFrame`.
606
+ * Calling them out of order throws rather than producing a plausible-looking split. The one
607
+ * exception is `addSimulation`, which reports simulation that ran outside any frame — see it.
608
+ */
609
+ export class FrameBudget {
610
+ #taskObserver: PerformanceObserver | undefined;
611
+ #taskCount = 0;
612
+ #longestTaskMs = 0;
613
+ #afterFirstFrameTaskMs = 0;
614
+ readonly reportEvery: number;
615
+ readonly minFrames: number;
616
+ readonly hitchMs: number;
617
+ readonly #simulation: IFrameBudgetSimulation | undefined;
618
+ #windowStartTick: number | undefined;
619
+ #report: (line: string) => void;
620
+ #wallClock: () => number;
621
+ #onWindow: ((window: IFrameBudgetWindow) => void) | undefined;
622
+ #readSurface: (() => IFrameSurfaceState) | undefined;
623
+ #readTarget: (() => ITargetFps | undefined) | undefined;
624
+ #readGpuAgeFrames: (() => number | undefined) | undefined;
625
+ #readGpuTally:
626
+ | (() => { readonly instances: number; readonly triangles: number } | undefined)
627
+ | undefined;
628
+ #scratch: Float64Array;
629
+ #presented: Ring;
630
+ #frame: Ring;
631
+ #substeps: Ring;
632
+ #phaseRings: Record<FrameBudgetPhase, Ring>;
633
+ #gpu: Ring;
634
+ #gpuPyramid: Ring;
635
+ #gpuBucketRings: Record<FrameGpuBucket, Ring>;
636
+ #gpuBucketThisFrame: IFrameGpuBucketSample = {};
637
+ /** Shadow milliseconds of this frame's frames that recorded a shadow pass, not its known zeros. */
638
+ #gpuShadowRendered: Ring;
639
+ /** The shadow pass count the producer reported for this frame; `undefined` when it reported none. */
640
+ #gpuShadowPassesThisFrame: number | undefined;
641
+ #passDrawRings: Record<FramePassKind, Ring>;
642
+ #passDrawSourceRings: Record<MainDrawSource, Ring>;
643
+ #passTriangleRings: Record<FramePassKind, Ring>;
644
+ #passFrames: Record<FramePassKind, number> = { main: 0, nested: 0, reflection: 0, shadow: 0 };
645
+ #passesThisFrame: IRenderPassSample[] = [];
646
+ #hostCalls: Ring;
647
+ #gpuBytes: Ring;
648
+ #jsAllocBytes: Ring;
649
+ #countersThisFrame: IFrameCounters | undefined;
650
+ // The latest tick fed this window. It is not a boundary count and does not sum across frames: it
651
+ // is the loop's fixed-step count at the last frame that fed one, so consecutive window closes read
652
+ // a start tick and an end tick and the join is independent of how many frames rendered.
653
+ #simulationTick: number | undefined;
654
+ #lastRenderMs: number | undefined;
655
+ // The resolved frame the last sample belonged to, so a reading still in flight is not measured
656
+ // twice. It survives a window boundary: the first frame of a new window can still be showing the
657
+ // previous window's resolved frame.
658
+ #lastGpuFrame: number | undefined;
659
+ #gpuThisFrame: number | undefined;
660
+ #gpuFrameThisFrame: number | undefined;
661
+ #gpuFirstFrame = Number.POSITIVE_INFINITY;
662
+ #gpuLastFrame = Number.NEGATIVE_INFINITY;
663
+ #gpuUnframed = false;
664
+ #gpuStaleThisFrame = false;
665
+ #gpuStaleInWindow = 0;
666
+ #renderSkippedThisFrame = false;
667
+ #renderSkipsInWindow = 0;
668
+ #open = false;
669
+ #frameStart = 0;
670
+ #simulationEnd: number | undefined;
671
+ #renderMs = 0;
672
+ #overlayMs = 0;
673
+ #uiMs = 0;
674
+ #substepCount = 0;
675
+ #hostGap = 0;
676
+ #presentedDelta = 0;
677
+ #lastTimestamp: number | undefined;
678
+ #lastFrameEnd: number | undefined;
679
+ #framesInWindow = 0;
680
+ #hitchesInWindow = 0;
681
+ /** The target frame this window counts against, and its two counts; see `overTarget`. */
682
+ #targetFrameMs: number | undefined;
683
+ #renderOverTarget = 0;
684
+ #gpuOverTarget = 0;
685
+ #windowIndex = 0;
686
+ #readPresentCount: (() => number | undefined) | undefined;
687
+ #lastPresentCount: number | undefined;
688
+ #presentsInWindow = 0;
689
+ #firstFrameStart: number | undefined;
690
+ #firstTaskFrameStart: number | undefined;
691
+
692
+ constructor(options: IFrameBudgetOptions = {}) {
693
+ this.#simulation = options.simulation;
694
+ this.reportEvery = requirePositiveInteger(
695
+ options.reportEvery,
696
+ DEFAULT_REPORT_EVERY,
697
+ "reportEvery",
698
+ );
699
+ this.minFrames = requirePositiveInteger(options.minFrames, 1, "minFrames");
700
+ this.hitchMs = requirePositiveNumber(options.hitchMs, DEFAULT_HITCH_MS, "hitchMs");
701
+ const capacity = requirePositiveInteger(options.capacity, DEFAULT_CAPACITY, "capacity");
702
+ this.#report = options.report ?? ((line) => console.log(line));
703
+ this.#wallClock = options.wallClock ?? (() => Date.now());
704
+ this.#onWindow = options.onWindow;
705
+ this.#readSurface = options.readSurface;
706
+ this.#readTarget = options.readTarget;
707
+ this.#readPresentCount = options.readPresentCount ?? hostPresentCountReader();
708
+ this.#readGpuAgeFrames = options.readGpuAgeFrames;
709
+ this.#readGpuTally = options.readGpuTally;
710
+ if (globalThis.PerformanceObserver?.supportedEntryTypes.includes("longtask")) {
711
+ this.#taskObserver = new PerformanceObserver((list) => {
712
+ for (const entry of list.getEntries()) {
713
+ this.#taskCount++;
714
+ this.#longestTaskMs = Math.max(this.#longestTaskMs, entry.duration);
715
+ if (
716
+ this.#firstTaskFrameStart !== undefined &&
717
+ entry.startTime >= this.#firstTaskFrameStart
718
+ )
719
+ this.#afterFirstFrameTaskMs = Math.max(this.#afterFirstFrameTaskMs, entry.duration);
720
+ }
721
+ });
722
+ this.#taskObserver.observe({ type: "longtask", buffered: true });
723
+ }
724
+ this.#scratch = new Float64Array(capacity);
725
+ this.#presented = new Ring(capacity);
726
+ this.#frame = new Ring(capacity);
727
+ this.#substeps = new Ring(capacity);
728
+ this.#gpu = new Ring(capacity);
729
+ this.#gpuPyramid = new Ring(capacity);
730
+ this.#gpuShadowRendered = new Ring(capacity);
731
+ this.#gpuBucketRings = {
732
+ compute: new Ring(capacity),
733
+ main: new Ring(capacity),
734
+ other: new Ring(capacity),
735
+ shadow: new Ring(capacity),
736
+ };
737
+ this.#hostCalls = new Ring(capacity);
738
+ this.#gpuBytes = new Ring(capacity);
739
+ this.#jsAllocBytes = new Ring(capacity);
740
+ this.#phaseRings = {
741
+ hostGap: new Ring(capacity),
742
+ overlay: new Ring(capacity),
743
+ render: new Ring(capacity),
744
+ residual: new Ring(capacity),
745
+ ui: new Ring(capacity),
746
+ update: new Ring(capacity),
747
+ };
748
+ this.#passDrawRings = {
749
+ main: new Ring(capacity),
750
+ nested: new Ring(capacity),
751
+ reflection: new Ring(capacity),
752
+ shadow: new Ring(capacity),
753
+ };
754
+ this.#passDrawSourceRings = {
755
+ bundles: new Ring(capacity),
756
+ chunks: new Ring(capacity),
757
+ gpuScene: new Ring(capacity),
758
+ instanced: new Ring(capacity),
759
+ other: new Ring(capacity),
760
+ proxies: new Ring(capacity),
761
+ sky: new Ring(capacity),
762
+ terrain: new Ring(capacity),
763
+ };
764
+ this.#passTriangleRings = {
765
+ main: new Ring(capacity),
766
+ nested: new Ring(capacity),
767
+ reflection: new Ring(capacity),
768
+ shadow: new Ring(capacity),
769
+ };
770
+ }
771
+
772
+ /**
773
+ * @param timestampMs the frame timestamp the host handed the callback — the presented-frame
774
+ * clock, which is not the same as `nowMs` and is what the interval between frames comes from.
775
+ * @param nowMs the monotonic clock at callback entry.
776
+ */
777
+ dispose(): void {
778
+ this.#taskObserver?.disconnect();
779
+ this.#taskObserver = undefined;
780
+ }
781
+
782
+ beginFrame(timestampMs: number, nowMs: number): void {
783
+ if (this.#open)
784
+ throw new Error("FrameBudget.beginFrame called before the previous frame ended.");
785
+ this.#open = true;
786
+ this.#windowStartTick ??= this.#simulation?.tick();
787
+ this.#frameStart = nowMs;
788
+ if (this.#firstFrameStart === undefined) this.#firstFrameStart = nowMs;
789
+ this.#firstTaskFrameStart ??= nowMs;
790
+ this.#simulationEnd = undefined;
791
+ this.#renderMs = 0;
792
+ this.#overlayMs = 0;
793
+ this.#uiMs = 0;
794
+ this.#substepCount = 0;
795
+ this.#gpuThisFrame = undefined;
796
+ this.#gpuFrameThisFrame = undefined;
797
+ this.#gpuStaleThisFrame = false;
798
+ this.#renderSkippedThisFrame = false;
799
+ this.#gpuBucketThisFrame = {};
800
+ this.#gpuShadowPassesThisFrame = undefined;
801
+ this.#hostGap = this.#lastFrameEnd === undefined ? 0 : Math.max(0, nowMs - this.#lastFrameEnd);
802
+ this.#presentedDelta =
803
+ this.#lastTimestamp === undefined ? 0 : Math.max(0, timestampMs - this.#lastTimestamp);
804
+ this.#lastTimestamp = timestampMs;
805
+ }
806
+
807
+ /** The boundary between the fixed-step simulation and everything the render phase does. */
808
+ markSimulationEnd(nowMs: number, substeps: number): void {
809
+ if (!this.#open) throw new Error("FrameBudget.markSimulationEnd called outside a frame.");
810
+ this.#simulationEnd = nowMs;
811
+ // Accumulated, not assigned: `addSimulation` may already have charged a counted batch that ran
812
+ // inside this frame, and that batch's steps are this frame's.
813
+ this.#substepCount += substeps;
814
+ }
815
+
816
+ /**
817
+ * Charges one counted simulation batch — the loop's `advance(ticks)`, which is how a tick-counted
818
+ * playtest run simulates at all — to this window's `update` and `substeps`.
819
+ *
820
+ * A batch is not a frame. It presents nothing, so it must not count as one: no frame in the
821
+ * window, no present interval, no GPU sample, no hitch however long it blocked, and no window
822
+ * boundary. Opening a metered frame around it instead put half of a fixed-step run's windows into
823
+ * the frame and render percentiles as zero-millisecond frames that drew nothing, and closed a
824
+ * "300-frame" window on 300 metered frames rather than 300 presented ones — which is how a
825
+ * 300-frame window came to hold ~20 GPU timestamp samples instead of ~37.
826
+ *
827
+ * Inside a live frame — the frozen prime's settle, which is `advance()` called from inside the
828
+ * frame that armed it — the batch's milliseconds are already inside that frame's own measurement
829
+ * and are not charged a second time; only its steps are added, so the frame reports it exactly
830
+ * once. Its blocking cost reaches the window either way: through the enclosing frame's `update`,
831
+ * or here.
832
+ */
833
+ addSimulation(ms: number, ticks: number): void {
834
+ if (!Number.isFinite(ms) || ms < 0)
835
+ throw new Error(
836
+ `Frame budget simulation ms must be a non-negative number, received ${String(ms)}.`,
837
+ );
838
+ if (!Number.isInteger(ticks) || ticks < 0)
839
+ throw new Error(
840
+ `Frame budget simulation ticks must be a non-negative integer, received ${String(ticks)}.`,
841
+ );
842
+ if (this.#open) {
843
+ this.#substepCount += ticks;
844
+ return;
845
+ }
846
+ this.#phaseRings.update.push(ms);
847
+ this.#substeps.push(ticks);
848
+ }
849
+
850
+ addRender(ms: number): void {
851
+ if (!this.#open) throw new Error("FrameBudget.addRender called outside a frame.");
852
+ this.#renderMs += ms;
853
+ }
854
+
855
+ /** The renderer returned without drawing this frame; counted once per frame in the window's `renderSkips`. */
856
+ addRenderSkip(): void {
857
+ if (!this.#open) throw new Error("FrameBudget.addRenderSkip called outside a frame.");
858
+ this.#renderSkippedThisFrame = true;
859
+ }
860
+
861
+ addOverlay(ms: number): void {
862
+ if (!this.#open) throw new Error("FrameBudget.addOverlay called outside a frame.");
863
+ this.#overlayMs += ms;
864
+ }
865
+
866
+ addUi(ms: number): void {
867
+ if (!this.#open) throw new Error("FrameBudget.addUi called outside a frame.");
868
+ this.#uiMs += ms;
869
+ }
870
+
871
+ /**
872
+ * Records one presented frame's GPU duration, from a resolved `timestamp-query`.
873
+ *
874
+ * `ms` is `undefined` when the device reported no reading for the frame. `frame` is the
875
+ * Three.js frame id the duration belongs to — `gpuFrameSample`/`gpuFrameAge` on the renderer.
876
+ * A reading whose `frame` has not advanced since the previous frame is the previous frame's
877
+ * resolve still in flight, so it is counted as stale and not pushed again; that repetition was
878
+ * what made one lagged sample read as the current frame's cost. Without a `frame` a reading is
879
+ * always taken as fresh, since there is nothing to tell repeats from a genuine re-measurement.
880
+ *
881
+ * Once per frame. A window with no reading at all reports `gpu` absent, never a zero.
882
+ */
883
+ addGpuMs(ms: number | undefined, frame?: number): void {
884
+ if (!this.#open) throw new Error("FrameBudget.addGpuMs called outside a frame.");
885
+ if (ms === undefined) {
886
+ this.#gpuStaleThisFrame = true;
887
+ return;
888
+ }
889
+ if (!Number.isFinite(ms) || ms < 0) {
890
+ throw new Error(`Frame budget gpuMs must be a non-negative number, received ${String(ms)}.`);
891
+ }
892
+ if (frame !== undefined) {
893
+ if (!Number.isInteger(frame) || frame < 0) {
894
+ throw new Error(
895
+ `Frame budget gpu frame must be a non-negative integer, received ${String(frame)}.`,
896
+ );
897
+ }
898
+ if (frame === this.#lastGpuFrame) {
899
+ this.#gpuStaleThisFrame = true;
900
+ return;
901
+ }
902
+ this.#lastGpuFrame = frame;
903
+ }
904
+ this.#gpuThisFrame = ms;
905
+ this.#gpuFrameThisFrame = frame;
906
+ }
907
+
908
+ /** Record one freshly resolved pyramid build, independently of the render pool's cadence. */
909
+ addGpuPyramidMs(ms: number | undefined): void {
910
+ if (!this.#open) throw new Error("FrameBudget.addGpuPyramidMs called outside a frame.");
911
+ if (ms === undefined) return;
912
+ if (ms < 0) throw new Error("Frame budget gpu pyramid must be non-negative.");
913
+ this.#gpuPyramid.push(ms);
914
+ }
915
+
916
+ /**
917
+ * Records where one resolved frame's GPU time went, from the per-pass timestamp split.
918
+ *
919
+ * Alongside `addGpuMs`, once per frame. A bucket the producer could not attribute is left out
920
+ * rather than passed as zero: an unmeasured pass and a free one are different facts, and the
921
+ * p50 of a bucket that was never measured is absent from the window. An unknown bucket name
922
+ * throws rather than being dropped, the same fail-closed rule as a phase.
923
+ */
924
+ addGpuBucketMs(sample: IFrameGpuBucketSample): void {
925
+ if (!this.#open) throw new Error("FrameBudget.addGpuBucketMs called outside a frame.");
926
+ const shadowPasses = sample.shadowPasses;
927
+ if (shadowPasses !== undefined) {
928
+ if (!Number.isInteger(shadowPasses) || shadowPasses < 0)
929
+ throw new Error(
930
+ `Frame budget gpu shadowPasses must be a non-negative integer, received ${String(shadowPasses)}.`,
931
+ );
932
+ this.#gpuShadowPassesThisFrame = shadowPasses;
933
+ }
934
+ for (const bucket of FRAME_GPU_BUCKETS) {
935
+ const ms = sample[bucket];
936
+ if (ms === undefined) continue;
937
+ if (!Number.isFinite(ms) || ms < 0)
938
+ throw new Error(
939
+ `Frame budget gpu ${bucket} must be a non-negative number, received ${String(ms)}.`,
940
+ );
941
+ this.#gpuBucketThisFrame[bucket] = ms;
942
+ }
943
+ }
944
+
945
+ /**
946
+ * Records the frame's host-boundary counts, from `FrameCounters` or any other source.
947
+ *
948
+ * At most one call per frame; a second replaces the first rather than summing, because the
949
+ * counter's own reader already returns the frame's totals and summing two reads of one frame
950
+ * would double it. A field the platform cannot report is left out of the series entirely.
951
+ *
952
+ * `simulationTick`, when present, must be a finite non-negative integer and is stored as the
953
+ * window's latest tick — never summed, and never cleared by a later call that omits it, so a
954
+ * plain `TN_FRAME_BUDGET` log can join a window's start and end ticks.
955
+ */
956
+ addCounters(counters: IFrameCounters): void {
957
+ if (!this.#open) throw new Error("FrameBudget.addCounters called outside a frame.");
958
+ for (const [name, value] of [
959
+ ["hostCalls", counters.hostCalls],
960
+ ["gpuBytes", counters.gpuBytes],
961
+ ["jsAllocBytes", counters.jsAllocBytes],
962
+ ] as const) {
963
+ if (value === undefined) continue;
964
+ if (!Number.isFinite(value) || value < 0)
965
+ throw new Error(
966
+ `Frame budget counter ${name} must be a non-negative number, received ${String(value)}.`,
967
+ );
968
+ }
969
+ const tick = counters.simulationTick;
970
+ if (tick !== undefined) {
971
+ if (!Number.isInteger(tick) || tick < 0)
972
+ throw new Error(
973
+ `Frame budget counter simulationTick must be a non-negative integer, received ${String(tick)}.`,
974
+ );
975
+ this.#simulationTick = tick;
976
+ }
977
+ this.#countersThisFrame = counters;
978
+ }
979
+
980
+ /**
981
+ * Records the frame's per-pass submissions, from `RenderPassBudget` or any other source. At most
982
+ * one entry per kind per frame is meaningful; a second of the same kind is summed by the caller.
983
+ * An unknown kind throws rather than being dropped, the same fail-closed rule as a phase.
984
+ */
985
+ addRenderPasses(passes: readonly IRenderPassSample[]): void {
986
+ if (!this.#open) throw new Error("FrameBudget.addRenderPasses called outside a frame.");
987
+ for (const pass of passes) {
988
+ if (!(FRAME_PASS_KINDS as readonly string[]).includes(pass.kind))
989
+ throw new Error(
990
+ `FrameBudget received an unknown pass kind: ${String(pass.kind)}. Expected one of: ${FRAME_PASS_KINDS.join(", ")}.`,
991
+ );
992
+ this.#passesThisFrame.push(pass);
993
+ }
994
+ }
995
+
996
+ /**
997
+ * Closes the frame and returns its phase split, or `undefined` when the frame was a hitch and
998
+ * therefore excluded — a 27-second startup stall is not a frame time and must not enter a
999
+ * percentile anybody is asked to act on.
1000
+ *
1001
+ * `wantSample` is false when the caller is going to discard the split, which is the default
1002
+ * shipping configuration. The object is small but it escapes this method, so V8 cannot scalar-
1003
+ * replace it, and building one per frame is one dead allocation per frame in every game. The
1004
+ * window meters below are pushed either way: turning the sample off must not turn measurement
1005
+ * off, and `window()` reads the same numbers whichever way this is called.
1006
+ */
1007
+ endFrame(nowMs: number, wantSample = true): IFramePhaseSample | undefined {
1008
+ if (!this.#open) throw new Error("FrameBudget.endFrame called outside a frame.");
1009
+ this.#open = false;
1010
+ this.#lastRenderMs = undefined;
1011
+ const simulationEnd = this.#simulationEnd ?? this.#frameStart;
1012
+ const frameMs = Math.max(0, nowMs - this.#frameStart);
1013
+ this.#lastFrameEnd = nowMs;
1014
+
1015
+ this.#countPresents();
1016
+
1017
+ const isHitch = this.#presentedDelta >= this.hitchMs;
1018
+ if (isHitch) {
1019
+ this.#passesThisFrame.length = 0;
1020
+ this.#hitchesInWindow += 1;
1021
+ this.#report(
1022
+ `${FRAME_HITCH_MARKER}:${JSON.stringify({
1023
+ gapMs: round(this.#presentedDelta),
1024
+ uptimeMs: round(nowMs),
1025
+ wallClock: this.#wallClock(),
1026
+ })}`,
1027
+ );
1028
+ this.#maybeReport();
1029
+ return undefined;
1030
+ }
1031
+
1032
+ const update = Math.max(0, simulationEnd - this.#frameStart);
1033
+ const tail = Math.max(0, nowMs - simulationEnd);
1034
+ const residual = Math.max(0, tail - this.#renderMs - this.#overlayMs - this.#uiMs);
1035
+ const sample: IFramePhaseSample | undefined = wantSample
1036
+ ? {
1037
+ hostGap: round(this.#hostGap),
1038
+ overlay: round(this.#overlayMs),
1039
+ render: round(this.#renderMs),
1040
+ residual: round(residual),
1041
+ ui: round(this.#uiMs),
1042
+ update: round(update),
1043
+ }
1044
+ : undefined;
1045
+ this.#frame.push(frameMs);
1046
+ this.#substeps.push(this.#substepCount);
1047
+ // The first frame has no predecessor, so it has neither an interval nor a host gap; pushing a
1048
+ // zero there would drag every percentile toward a frame that never happened.
1049
+ if (this.#presentedDelta > 0) this.#presented.push(this.#presentedDelta);
1050
+ if (this.#hostGap > 0) this.#phaseRings.hostGap.push(this.#hostGap);
1051
+ this.#phaseRings.update.push(update);
1052
+ this.#phaseRings.render.push(this.#renderMs);
1053
+ if (this.#targetFrameMs !== undefined && this.#renderMs > this.#targetFrameMs)
1054
+ this.#renderOverTarget += 1;
1055
+ this.#lastRenderMs = this.#renderMs;
1056
+ this.#phaseRings.overlay.push(this.#overlayMs);
1057
+ this.#phaseRings.residual.push(residual);
1058
+ this.#phaseRings.ui.push(this.#uiMs);
1059
+ if (this.#gpuThisFrame !== undefined) {
1060
+ this.#gpu.push(this.#gpuThisFrame);
1061
+ if (this.#gpuFrameThisFrame === undefined) this.#gpuUnframed = true;
1062
+ else {
1063
+ this.#gpuFirstFrame = Math.min(this.#gpuFirstFrame, this.#gpuFrameThisFrame);
1064
+ this.#gpuLastFrame = Math.max(this.#gpuLastFrame, this.#gpuFrameThisFrame);
1065
+ }
1066
+ if (this.#targetFrameMs !== undefined && this.#gpuThisFrame > this.#targetFrameMs)
1067
+ this.#gpuOverTarget += 1;
1068
+ }
1069
+ for (const bucket of FRAME_GPU_BUCKETS) {
1070
+ const ms = this.#gpuBucketThisFrame[bucket];
1071
+ if (ms !== undefined && this.#gpuThisFrame !== undefined)
1072
+ this.#gpuBucketRings[bucket].push(ms);
1073
+ }
1074
+ // The shadow tail over frames that actually rendered a shadow, separate from the known-zero
1075
+ // frames the ring above also holds: only the producer's count says a render happened, because a
1076
+ // real render can resolve to 0 ms and a `shadow > 0` guess would drop it.
1077
+ const renderedShadow = this.#gpuBucketThisFrame.shadow;
1078
+ if ((this.#gpuShadowPassesThisFrame ?? 0) > 0 && renderedShadow !== undefined)
1079
+ this.#gpuShadowRendered.push(renderedShadow);
1080
+ this.#gpuShadowPassesThisFrame = undefined;
1081
+ this.#gpuBucketThisFrame = {};
1082
+ if (this.#gpuStaleThisFrame) this.#gpuStaleInWindow += 1;
1083
+ if (this.#renderSkippedThisFrame) this.#renderSkipsInWindow += 1;
1084
+ for (const pass of this.#passesThisFrame) {
1085
+ this.#passDrawRings[pass.kind].push(pass.draws);
1086
+ this.#passTriangleRings[pass.kind].push(pass.triangles);
1087
+ // The main pass's per-origin counts, one sample per source the frame drew. A source the
1088
+ // frame did not draw contributes no sample, so its percentiles describe the frames that had
1089
+ // it — the same rule every other series here follows.
1090
+ if (pass.drawsBySource !== undefined)
1091
+ for (const [source, count] of Object.entries(pass.drawsBySource)) {
1092
+ if (!isMainDrawSource(source))
1093
+ throw new Error(
1094
+ `FrameBudget received an unknown main draw source: ${source}. Expected one of: ${MAIN_DRAW_SOURCES.join(", ")}.`,
1095
+ );
1096
+ this.#passDrawSourceRings[source].push(count);
1097
+ }
1098
+ this.#passFrames[pass.kind] += 1;
1099
+ }
1100
+ this.#passesThisFrame.length = 0;
1101
+ const counters = this.#countersThisFrame;
1102
+ this.#countersThisFrame = undefined;
1103
+ if (counters?.hostCalls !== undefined) this.#hostCalls.push(counters.hostCalls);
1104
+ if (counters?.gpuBytes !== undefined) this.#gpuBytes.push(counters.gpuBytes);
1105
+ if (counters?.jsAllocBytes !== undefined) this.#jsAllocBytes.push(counters.jsAllocBytes);
1106
+ this.#framesInWindow += 1;
1107
+ this.#maybeReport();
1108
+ return sample;
1109
+ }
1110
+
1111
+ /** Reads the window in progress without disturbing it. */
1112
+ window(): IFrameBudgetWindow {
1113
+ const presented = this.#presented.summarize(this.#scratch);
1114
+ const phases = {
1115
+ hostGap: this.#phaseRings.hostGap.summarize(this.#scratch),
1116
+ overlay: this.#phaseRings.overlay.summarize(this.#scratch),
1117
+ render: this.#phaseRings.render.summarize(this.#scratch),
1118
+ residual: this.#phaseRings.residual.summarize(this.#scratch),
1119
+ ui: this.#phaseRings.ui.summarize(this.#scratch),
1120
+ update: this.#phaseRings.update.summarize(this.#scratch),
1121
+ };
1122
+ const share = (value: number): number =>
1123
+ presented.mean === 0 ? 0 : Math.round((value / presented.mean) * 1_000) / 1_000;
1124
+ const passes: Partial<Record<FramePassKind, IFrameBudgetPassSummary>> = {};
1125
+ const gpuTally = this.#readGpuTally?.();
1126
+ for (const kind of FRAME_PASS_KINDS) {
1127
+ if (this.#passFrames[kind] === 0) continue;
1128
+ // The split belongs to `main` alone, and it is the only kind the recorder attributes: the
1129
+ // rings are per source rather than per kind and per source, so a summary that attached them
1130
+ // to a shadow pass would report the main pass's origins under a nested pass's name.
1131
+ const drawsBySource: Partial<Record<MainDrawSource, IFrameBudgetSummary>> = {};
1132
+ if (kind === "main")
1133
+ for (const source of MAIN_DRAW_SOURCES) {
1134
+ const ring = this.#passDrawSourceRings[source];
1135
+ if (ring.count > 0) drawsBySource[source] = ring.summarize(this.#scratch);
1136
+ }
1137
+ passes[kind] = {
1138
+ draws: this.#passDrawRings[kind].summarize(this.#scratch),
1139
+ ...(Object.keys(drawsBySource).length === 0 ? {} : { drawsBySource }),
1140
+ frames: this.#passFrames[kind],
1141
+ triangles: this.#passTriangleRings[kind].summarize(this.#scratch),
1142
+ // Main pass only, and beside three's CPU figure rather than instead of it: the same window
1143
+ // that says `triangles 338,000,000` has to say what the kernel actually selected.
1144
+ ...(kind === "main" && gpuTally !== undefined ? { gpuTriangles: gpuTally.triangles } : {}),
1145
+ };
1146
+ }
1147
+ const surface =
1148
+ this.#readSurface === undefined ? undefined : requireSurface(this.#readSurface());
1149
+ const gpuAgeFrames = this.#readGpuAgeFrames?.();
1150
+ if (gpuAgeFrames !== undefined && (!Number.isInteger(gpuAgeFrames) || gpuAgeFrames < 0))
1151
+ throw new Error(
1152
+ `Frame budget gpuAgeFrames must be a non-negative integer, received ${String(gpuAgeFrames)}.`,
1153
+ );
1154
+ // The window's own duration, for a rate built from presents rather than from loop intervals.
1155
+ const windowSpanMs = this.#windowSpanMs;
1156
+ // A seam plus one readable sample: zero presents is a reading, absent is no seam. The
1157
+ // unreadable flag clears itself on the next good sample, so a transient gap does not end the
1158
+ // series for the rest of the run.
1159
+ const presentCounted =
1160
+ this.#readPresentCount !== undefined && this.#lastPresentCount !== undefined;
1161
+ const hostCalls =
1162
+ this.#hostCalls.count === 0 ? undefined : this.#hostCalls.summarize(this.#scratch);
1163
+ const gpuBytes =
1164
+ this.#gpuBytes.count === 0 ? undefined : this.#gpuBytes.summarize(this.#scratch);
1165
+ const jsAllocBytes =
1166
+ this.#jsAllocBytes.count === 0 ? undefined : this.#jsAllocBytes.summarize(this.#scratch);
1167
+ const simulationTick = this.#simulationTick;
1168
+ const counters =
1169
+ hostCalls === undefined &&
1170
+ gpuBytes === undefined &&
1171
+ jsAllocBytes === undefined &&
1172
+ simulationTick === undefined
1173
+ ? undefined
1174
+ : {
1175
+ ...(gpuBytes === undefined ? {} : { gpuBytes }),
1176
+ ...(hostCalls === undefined ? {} : { hostCalls }),
1177
+ ...(jsAllocBytes === undefined ? {} : { jsAllocBytes }),
1178
+ ...(simulationTick === undefined ? {} : { simulationTick }),
1179
+ };
1180
+ const gpuSummary = this.#gpu.summarize(this.#scratch);
1181
+ const gpu = gpuSummary.samples === 0 ? undefined : gpuSummary;
1182
+ const gpuBucket = (bucket: FrameGpuBucket): number | undefined => {
1183
+ const summary = this.#gpuBucketRings[bucket].summarize(this.#scratch);
1184
+ return summary.samples === 0 ? undefined : round1(summary.p50);
1185
+ };
1186
+ const gpuMain = gpuBucket("main");
1187
+ const gpuShadow = gpuBucket("shadow");
1188
+ const gpuOther = gpuBucket("other");
1189
+ const gpuCompute = gpuBucket("compute");
1190
+ const shadowBucket = this.#gpuBucketRings.shadow.summarize(this.#scratch);
1191
+ const shadowRendered = this.#gpuShadowRendered.summarize(this.#scratch);
1192
+ const gpuPyramid = this.#gpuPyramid.summarize(this.#scratch);
1193
+ const target = this.#readTarget === undefined ? undefined : (this.#readTarget() ?? undefined);
1194
+ const resolvedTarget = target === undefined ? undefined : requireTarget(target);
1195
+ const overTarget =
1196
+ this.#targetFrameMs === undefined
1197
+ ? undefined
1198
+ : {
1199
+ frameMs: round(this.#targetFrameMs),
1200
+ gpu: this.#gpuOverTarget,
1201
+ render: this.#renderOverTarget,
1202
+ };
1203
+ // The next window counts against the target this one reports.
1204
+ this.#targetFrameMs =
1205
+ resolvedTarget !== undefined && resolvedTarget.targetFps > 0
1206
+ ? 1_000 / resolvedTarget.targetFps
1207
+ : undefined;
1208
+ return {
1209
+ longTasks:
1210
+ this.#taskObserver === undefined
1211
+ ? { available: false }
1212
+ : {
1213
+ available: true,
1214
+ count: this.#taskCount,
1215
+ longestMs: this.#longestTaskMs,
1216
+ afterFirstFrameMs: this.#afterFirstFrameTaskMs,
1217
+ },
1218
+ fps: presented.mean === 0 ? 0 : round(1_000 / presented.mean),
1219
+ frame: this.#frame.summarize(this.#scratch),
1220
+ frames: this.#framesInWindow,
1221
+ ...(this.#simulation === undefined
1222
+ ? {}
1223
+ : {
1224
+ simulatedSeconds:
1225
+ (this.#simulation.tick() - (this.#windowStartTick ?? this.#simulation.tick())) *
1226
+ this.#simulation.step,
1227
+ }),
1228
+ hitches: this.#hitchesInWindow,
1229
+ phases,
1230
+ presented,
1231
+ ...(presentCounted ? { presents: this.#presentsInWindow } : {}),
1232
+ ...(presentCounted && this.#presentsInWindow > 0 && windowSpanMs > 0
1233
+ ? { presentedFps: round((this.#presentsInWindow * 1_000) / windowSpanMs) }
1234
+ : {}),
1235
+ shares: {
1236
+ hostGap: share(phases.hostGap.mean),
1237
+ overlay: share(phases.overlay.mean),
1238
+ render: share(phases.render.mean),
1239
+ residual: share(phases.residual.mean),
1240
+ ui: share(phases.ui.mean),
1241
+ update: share(phases.update.mean),
1242
+ },
1243
+ substeps: this.#substeps.summarize(this.#scratch),
1244
+ ...(Object.keys(passes).length === 0 ? {} : { passes }),
1245
+ // The GPU-selected main-pass count, beside the pass record it refines: absent until the
1246
+ // world's tally has a sample, so a reader never sees a zero that no frame selected.
1247
+ ...(gpuTally === undefined
1248
+ ? {}
1249
+ : { mainGpuInstances: gpuTally.instances, mainGpuTriangles: gpuTally.triangles }),
1250
+ // One series, two readers: `gpu` is the distribution and `gpuMs` is its mean for the scaler
1251
+ // and the perf record, which want a single number.
1252
+ ...(gpu === undefined ? {} : { gpu }),
1253
+ gpuStale: this.#gpuStaleInWindow,
1254
+ ...(this.#renderSkipsInWindow > 0 ? { renderSkips: this.#renderSkipsInWindow } : {}),
1255
+ ...(gpu === undefined ? {} : { gpuMs: gpu.mean }),
1256
+ ...(gpu === undefined || this.#gpuUnframed
1257
+ ? {}
1258
+ : { gpuFrames: { first: this.#gpuFirstFrame, last: this.#gpuLastFrame } }),
1259
+ ...(gpuAgeFrames === undefined ? {} : { gpuAgeFrames }),
1260
+ ...(resolvedTarget === undefined
1261
+ ? {}
1262
+ : { targetFps: resolvedTarget.targetFps, targetSource: resolvedTarget.source }),
1263
+ ...(overTarget === undefined ? {} : { overTarget }),
1264
+ ...(surface === undefined ? {} : { surface }),
1265
+ ...(counters === undefined ? {} : { counters }),
1266
+ window: this.#windowIndex + 1,
1267
+ // Appended after every existing field so a parser that reads this line as JSON keeps the
1268
+ // keys it already knew; the per-bucket p50s are the only additions.
1269
+ ...(gpuMain === undefined ? {} : { gpuMain }),
1270
+ ...(gpuShadow === undefined ? {} : { gpuShadow }),
1271
+ ...(gpuOther === undefined ? {} : { gpuOther }),
1272
+ ...(gpuCompute === undefined ? {} : { gpuCompute }),
1273
+ ...(shadowBucket.samples === 0
1274
+ ? {}
1275
+ : { gpuShadowP95: round1(shadowBucket.p95), gpuShadowSamples: shadowBucket.samples }),
1276
+ ...(shadowRendered.samples === 0 ? {} : { gpuShadowRendered: shadowRendered }),
1277
+ ...(gpuPyramid.samples === 0 ? {} : { gpuPyramid }),
1278
+ };
1279
+ }
1280
+
1281
+ /**
1282
+ * The render phase of the frame that just closed, or `undefined` when that frame was a hitch and
1283
+ * therefore not counted.
1284
+ *
1285
+ * It exists because the phase split object is optional — `endFrame` builds one only when a
1286
+ * consumer asked for per-frame samples, which shipping games do not — and a reader that needs
1287
+ * the number must not be forced to turn that allocation on to get it. Reading a measurement and
1288
+ * collecting a sample are different requests.
1289
+ */
1290
+ get lastRenderMs(): number | undefined {
1291
+ return this.#lastRenderMs;
1292
+ }
1293
+
1294
+ /**
1295
+ * Folds the display's own present counter into this window.
1296
+ *
1297
+ * Read once per frame, at the frame's close, so the delta covers what the display did during it.
1298
+ * A counter that went backwards (a host restarting its numbering) or is not finite is treated as
1299
+ * a gap in the reading rather than as a negative rate; the window then reports no presents at all
1300
+ * rather than a number built from a discontinuity.
1301
+ */
1302
+ /** Duration of the window's loop frames, first start to last end. */
1303
+ get #windowSpanMs(): number {
1304
+ if (this.#firstFrameStart === undefined || this.#lastFrameEnd === undefined) return 0;
1305
+ return Math.max(0, this.#lastFrameEnd - this.#firstFrameStart);
1306
+ }
1307
+
1308
+ #countPresents(): void {
1309
+ const read = this.#readPresentCount;
1310
+ if (read === undefined) return;
1311
+ const count = read();
1312
+ if (count === undefined || !Number.isFinite(count)) {
1313
+ // One unreadable sample is not a broken counter: the reading resumes on the next frame, and
1314
+ // the window still says what it counted.
1315
+ this.#lastPresentCount = undefined;
1316
+ return;
1317
+ }
1318
+ const previous = this.#lastPresentCount;
1319
+ this.#lastPresentCount = count;
1320
+ if (previous === undefined || count < previous) return; // first sample, or a restarted counter
1321
+ this.#presentsInWindow += count - previous;
1322
+ }
1323
+
1324
+ #maybeReport(): void {
1325
+ // Callers without a loop clock retain presented-frame window boundaries.
1326
+ const elapsed =
1327
+ this.#simulation === undefined
1328
+ ? this.#framesInWindow
1329
+ : this.#simulation.tick() - (this.#windowStartTick ?? this.#simulation.tick());
1330
+ if (elapsed < this.reportEvery || this.#framesInWindow < this.minFrames) return;
1331
+ const completed = this.window();
1332
+ this.#report(`${FRAME_BUDGET_MARKER}:${JSON.stringify(completed)}`);
1333
+ this.#windowIndex += 1;
1334
+ this.#presented.reset();
1335
+ this.#frame.reset();
1336
+ this.#substeps.reset();
1337
+ this.#gpu.reset();
1338
+ this.#gpuFirstFrame = Number.POSITIVE_INFINITY;
1339
+ this.#gpuLastFrame = Number.NEGATIVE_INFINITY;
1340
+ this.#gpuUnframed = false;
1341
+ this.#gpuPyramid.reset();
1342
+ for (const bucket of FRAME_GPU_BUCKETS) this.#gpuBucketRings[bucket].reset();
1343
+ this.#gpuShadowRendered.reset();
1344
+ this.#hostCalls.reset();
1345
+ this.#gpuBytes.reset();
1346
+ this.#jsAllocBytes.reset();
1347
+ this.#simulationTick = undefined;
1348
+ this.#gpuStaleInWindow = 0;
1349
+ this.#renderSkipsInWindow = 0;
1350
+ for (const phase of FRAME_BUDGET_PHASES) this.#phaseRings[phase].reset();
1351
+ for (const kind of FRAME_PASS_KINDS) {
1352
+ this.#passDrawRings[kind].reset();
1353
+ this.#passTriangleRings[kind].reset();
1354
+ this.#passFrames[kind] = 0;
1355
+ }
1356
+ for (const source of MAIN_DRAW_SOURCES) this.#passDrawSourceRings[source].reset();
1357
+ this.#framesInWindow = 0;
1358
+ this.#windowStartTick = this.#simulation?.tick();
1359
+ this.#hitchesInWindow = 0;
1360
+ this.#renderOverTarget = 0;
1361
+ this.#gpuOverTarget = 0;
1362
+ this.#presentsInWindow = 0;
1363
+ this.#firstFrameStart = undefined;
1364
+ // After the reset, so a consumer that changes the scene from this callback changes it for the
1365
+ // window that starts now rather than for the one just reported.
1366
+ this.#onWindow?.(completed);
1367
+ }
1368
+ }