@threenative/core 0.3.6 → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/README.md +3 -5
  2. package/capabilities.json +739 -50
  3. package/dist/{assets-CqvE429w.d.ts → assets-YUbXa3-Y.d.ts} +101 -2
  4. package/dist/{canvas-layer-C1-5CviZ.d.ts → canvas-layer-vCtanIeB.d.ts} +1 -1
  5. package/dist/{game-Jz4Fdoeb.d.ts → game-cb99J-YE.d.ts} +100 -31
  6. package/dist/hot.d.ts +4 -4
  7. package/dist/hot.js +23 -5
  8. package/dist/index.d.ts +1742 -29
  9. package/dist/index.js +22443 -12423
  10. package/dist/{model-lod-BDAUYgsS.d.ts → model-lod-CTpZ6imz.d.ts} +1 -1
  11. package/dist/net.js +39 -12
  12. package/dist/playtest.d.ts +4 -4
  13. package/dist/playtest.js +48 -9
  14. package/dist/react-css.js +23 -0
  15. package/dist/react.d.ts +2 -2
  16. package/dist/{renderer-9yEo9hPa.d.ts → renderer-rZm0hVqq.d.ts} +178 -5
  17. package/dist/ui-layer.d.ts +11 -2
  18. package/dist/ui-layer.js +76 -4
  19. package/dist/worker.d.ts +36 -0
  20. package/dist/worker.js +1088 -0
  21. package/dist/world.d.ts +11 -3
  22. package/dist/world.js +1117 -197
  23. package/mcp/animation-server.mjs +265 -0
  24. package/mcp/animation.mjs +22 -0
  25. package/mcp/call.mjs +105 -0
  26. package/mcp/devtools.mjs +5 -0
  27. package/mcp/engine-server.mjs +713 -37
  28. package/mcp/launch.mjs +3 -2
  29. package/mcp/servers.d.mts +2 -0
  30. package/mcp/servers.mjs +33 -8
  31. package/package.json +12 -8
  32. package/patches/three@0.185.1-prd269-upgrade.patch +308 -0
  33. package/patches/three@0.185.1.patch +481 -272
  34. package/src/animation-packet-state.ts +88 -0
  35. package/src/animation-pose-packet.ts +537 -0
  36. package/src/animation.ts +779 -31
  37. package/src/asset-cache.ts +719 -0
  38. package/src/assets.ts +521 -152
  39. package/src/audio.ts +29 -3
  40. package/src/auto-batch.ts +792 -0
  41. package/src/config.ts +2 -0
  42. package/src/frame-budget.ts +268 -2
  43. package/src/game.ts +525 -105
  44. package/src/grounding.ts +7 -6
  45. package/src/hot.ts +19 -5
  46. package/src/index.ts +381 -6
  47. package/src/input.ts +21 -2
  48. package/src/interpolation.ts +19 -1
  49. package/src/launch-diagnostics.ts +7 -2
  50. package/src/look/ao-multibounce.ts +29 -0
  51. package/src/look/ao-reach.ts +39 -0
  52. package/src/look/auto-exposure.ts +264 -0
  53. package/src/look/default-tone-mapping.ts +44 -0
  54. package/src/look/exposure-graph.ts +208 -0
  55. package/src/look/exposure-readback.ts +97 -0
  56. package/src/look/exposure-settings.ts +132 -0
  57. package/src/look/filmic-tone-mapping.ts +852 -0
  58. package/src/look/gi-registry.ts +55 -0
  59. package/src/look/local-exposure.ts +507 -0
  60. package/src/look/look-diagnostics.ts +24 -0
  61. package/src/look/motion-blur.ts +42 -0
  62. package/src/look/quality.ts +309 -0
  63. package/src/look/reflection-trace.ts +344 -0
  64. package/src/look/unreal-bloom.ts +295 -0
  65. package/src/look/vignette.ts +14 -0
  66. package/src/look/world-environment.ts +2033 -0
  67. package/src/loop.ts +25 -1
  68. package/src/merge-parts.ts +25 -10
  69. package/src/model-lod.ts +14 -0
  70. package/src/net-session.ts +58 -14
  71. package/src/ocean/spectral.ts +41 -7
  72. package/src/picking.ts +72 -5
  73. package/src/platform.ts +29 -1
  74. package/src/playtest.ts +54 -8
  75. package/src/profiling/FrameCounters.ts +166 -5
  76. package/src/profiling/FrameStages.ts +289 -0
  77. package/src/profiling/Spans.ts +39 -25
  78. package/src/profiling/debug-telemetry.ts +312 -0
  79. package/src/profiling/scene-warning.ts +42 -6
  80. package/src/projection-apply.ts +11 -3
  81. package/src/projection-content.ts +189 -0
  82. package/src/projection-marker.ts +6 -2
  83. package/src/projection-plan.ts +279 -28
  84. package/src/projection-skinned.ts +620 -5
  85. package/src/projection-stability.ts +16 -0
  86. package/src/projection-uniform.ts +5 -1
  87. package/src/quiet-markers.ts +56 -0
  88. package/src/render/budget-ladder.ts +256 -0
  89. package/src/render/chain.ts +89 -7
  90. package/src/render/exposure-units.ts +59 -0
  91. package/src/render/frame-time-budget.ts +162 -0
  92. package/src/render/gi-budget.ts +231 -0
  93. package/src/render/gi-visualize.ts +49 -0
  94. package/src/render/material-key.ts +1 -0
  95. package/src/render/probe-volume.ts +196 -36
  96. package/src/render/rough-diffuse.ts +177 -0
  97. package/src/render/scene-trace.ts +532 -0
  98. package/src/render/shadow-filter-budget.ts +237 -0
  99. package/src/render/sky-capture.ts +194 -0
  100. package/src/render/soft-shadow.ts +607 -0
  101. package/src/render/surface-cache.ts +418 -0
  102. package/src/render/traced-reflections.ts +408 -0
  103. package/src/render/two-sided-foliage.ts +120 -0
  104. package/src/render/virtual-shadow-pages.ts +112 -12
  105. package/src/render/virtual-shadow.ts +386 -38
  106. package/src/render-camera-cull.ts +536 -31
  107. package/src/render-pass-budget.ts +140 -22
  108. package/src/renderProjection.ts +65 -9
  109. package/src/renderer-config.ts +3 -2
  110. package/src/renderer.ts +289 -14
  111. package/src/resolution-scaler.ts +65 -7
  112. package/src/skeletal-mesh.ts +4 -0
  113. package/src/snow-field.ts +46 -0
  114. package/src/softbody.ts +6 -5
  115. package/src/startup-offscreen-bytes.ts +168 -0
  116. package/src/startup-readiness.ts +137 -2
  117. package/src/ui-bridge.ts +38 -0
  118. package/src/ui-hit-regions.ts +6 -2
  119. package/src/ui-layer.ts +1 -0
  120. package/src/ui-state.ts +32 -3
  121. package/src/version.ts +1 -1
  122. package/src/viewport.ts +8 -5
  123. package/src/warmup.ts +76 -10
  124. package/src/worker-audio.ts +579 -0
  125. package/src/worker.ts +842 -0
  126. package/src/world-cells.ts +4 -1
  127. package/gpl/LICENSE.GPL +0 -117
  128. package/gpl/convert.py +0 -192
  129. package/gpl/fixtures/make_world_fixture.py +0 -184
  130. package/gpl/recipes/_common.py +0 -180
  131. package/gpl/recipes/bake_ao.py +0 -111
  132. package/gpl/recipes/decimate.py +0 -70
  133. package/gpl/recipes/export_world.py +0 -699
  134. package/gpl/recipes/retarget.py +0 -131
  135. package/gpl/recipes/unwrap.py +0 -71
  136. package/mcp/blender-server.mjs +0 -689
  137. package/mcp/blender.mjs +0 -26
package/src/config.ts CHANGED
@@ -303,6 +303,8 @@ export interface IThreeNativePerformanceBudget {
303
303
  readonly maxDrawCalls?: number;
304
304
  /** Maximum nearest-rank 95th-percentile frame time in milliseconds. */
305
305
  readonly maxFrameMsP95?: number;
306
+ /** Why this profile cannot hold 60 fps; the harness requires it when `maxFrameMsP95` is above 16.7. */
307
+ readonly maxFrameMsReason?: string;
306
308
  /** Maximum renderer triangle count across every pass combined. */
307
309
  readonly maxTriangles?: number;
308
310
  /** Frame-budget floor: the median presented frame must sustain at least this many frames a second. */
@@ -22,6 +22,13 @@
22
22
  */
23
23
 
24
24
  import type { IFrameCounters } from "./profiling/FrameCounters.js";
25
+ import { type IFrameStageSample, RENDER_STAGES, STAGE_PARTS } from "./profiling/FrameStages.js";
26
+ import {
27
+ countDebug,
28
+ debugHotCalls,
29
+ debugRequested,
30
+ formatDebugReport,
31
+ } from "./profiling/debug-telemetry.js";
25
32
  import {
26
33
  FRAME_PASS_KINDS,
27
34
  type FramePassKind,
@@ -255,19 +262,29 @@ export interface IFrameBudgetPassSummary {
255
262
  * it were a player's — `threenative-playtest perf` refuses to (`TN_PERF_VIRTUAL_DISPLAY`).
256
263
  */
257
264
  export interface IFrameBudgetWindow {
258
- /** Browser Long Tasks, independent of vsync/GPU waits. Unavailable on hosts without this API. */
265
+ /**
266
+ * Browser Long Tasks, independent of vsync/GPU waits. Unavailable on hosts without this API.
267
+ * `count` and `longestMs` describe this window; `afterFirstFrameMs` is the run's startup figure.
268
+ */
259
269
  readonly longTasks:
260
270
  | { readonly available: false }
261
271
  | {
262
272
  readonly available: true;
273
+ /** Long Tasks observed inside this window, not since the page started. */
263
274
  readonly count: number;
275
+ /** This window's longest Long Task; 0 when it saw none. */
264
276
  readonly longestMs: number;
277
+ /** The run's longest task after the first frame: a startup number, not this window's. */
265
278
  readonly afterFirstFrameMs: number;
266
279
  };
267
280
  /** 1 for the first reported window, incrementing thereafter. */
268
281
  readonly window: number;
282
+ /** The web engine's job pool: `on (N)` workers, or `off (<reason>)`; absent off the Wasm engine. */
283
+ readonly threads?: string;
269
284
  /** Loop frames counted in this window, hitches excluded — one per present on the web. */
270
285
  readonly frames: number;
286
+ /** Debug-only elapsed time between completed report boundaries; absent on the first window. */
287
+ readonly durationMs?: number;
271
288
  /** Fixed simulation ticks in this window multiplied by the loop's step, when supplied. */
272
289
  readonly simulatedSeconds?: number;
273
290
  /** Frames excluded from the window because their present gap exceeded `hitchMs`. */
@@ -294,6 +311,16 @@ export interface IFrameBudgetWindow {
294
311
  readonly presentedFps?: number;
295
312
  /** Interval between loop frames — the honest frame period where the loop presents every frame. */
296
313
  readonly presented: IFrameBudgetSummary;
314
+ /**
315
+ * Interval between frames the renderer drew. A declined frame (`renderSkips`) adds its time to the
316
+ * next drawn frame's interval, because the display showed the previous image for both. Reported
317
+ * beside `presented`, which gates keep reading; on the web this is what the player saw.
318
+ */
319
+ readonly drawn: IFrameBudgetSummary;
320
+ /** Loop frames the renderer drew: `frames - renderSkips`. */
321
+ readonly drawnFrames: number;
322
+ /** Derived from the mean `drawn` interval: drawn frames per second. */
323
+ readonly drawnFps: number;
297
324
  /** Duration of the frame callback itself, entry to exit. */
298
325
  readonly frame: IFrameBudgetSummary;
299
326
  /** Fixed simulation steps executed in the callback. */
@@ -389,6 +416,8 @@ export interface IFrameBudgetWindow {
389
416
  * `gpuMain + gpuShadow + gpuOther` reconciles with `gpuMs` only when all three are present.
390
417
  */
391
418
  readonly gpuMain?: number;
419
+ /** Fresh frames in the same main-bucket ring as gpuMain; absent when unmeasured. */
420
+ readonly gpuMainSamples?: number;
392
421
  readonly gpuShadow?: number;
393
422
  readonly gpuOther?: number;
394
423
  readonly gpuCompute?: number;
@@ -427,8 +456,31 @@ export interface IFrameBudgetWindow {
427
456
  readonly hostCalls?: IFrameBudgetSummary;
428
457
  readonly gpuBytes?: IFrameBudgetSummary;
429
458
  readonly jsAllocBytes?: IFrameBudgetSummary;
459
+ /** JS->Wasm crossings per frame, when the back end counts them (`createCrossingReader`). */
460
+ readonly bridgeCrossings?: IFrameBudgetSummary;
461
+ readonly dirtyTransforms?: IFrameBudgetSummary;
462
+ readonly castersMoving?: IFrameBudgetSummary;
463
+ /** Engine work counts per frame by name, when a playtest asked for them (`createEngineCounterReader`). */
464
+ readonly engine?: Readonly<Record<string, IFrameBudgetSummary>>;
430
465
  readonly simulationTick?: number;
431
466
  };
467
+ /**
468
+ * Where the callback's frame went (PRD-771), per stage in ms, one series per name. The render phase's
469
+ * stages (`RENDER_STAGES`) plus the `update`, `overlay`, `ui` and `residual` phases partition `frame`;
470
+ * `stageSum` is each frame's sum of those, so a window whose `stageSum` trails `frame` says how much
471
+ * time no stage named. `STAGE_PARTS` are pieces of `wasmPlan`, published beside it and not in the sum.
472
+ * Absent until a frame reported stages, and a name nothing measured is absent, never zero.
473
+ */
474
+ readonly stages?: Readonly<Record<string, IFrameBudgetSummary>>;
475
+ readonly stageSum?: IFrameBudgetSummary;
476
+ /**
477
+ * The mean of each stage over the window's slowest frames, the ones whose `stageSum` reaches its own p95: where
478
+ * the p95 frame goes, to read beside the stage's p50. `frames` is how many that was.
479
+ */
480
+ readonly stagesAtP95?: {
481
+ readonly frames: number;
482
+ readonly stages: Readonly<Record<string, number>>;
483
+ };
432
484
  }
433
485
 
434
486
  export interface IFrameBudgetSimulation {
@@ -493,6 +545,16 @@ const DEFAULT_REPORT_EVERY = 300;
493
545
  const DEFAULT_HITCH_MS = 2_000;
494
546
  const DEFAULT_CAPACITY = 1_024;
495
547
 
548
+ /** The series a window's `stages` can hold: the render stages, the parts of `wasmPlan`, then the phases that complete the frame. */
549
+ const STAGE_NAMES = [
550
+ ...RENDER_STAGES,
551
+ ...STAGE_PARTS,
552
+ "update",
553
+ "overlay",
554
+ "ui",
555
+ "residual",
556
+ ] as const;
557
+
496
558
  function requirePositiveInteger(value: number | undefined, fallback: number, name: string): number {
497
559
  if (value === undefined) return fallback;
498
560
  if (!Number.isInteger(value) || value < 1)
@@ -547,6 +609,18 @@ class Ring {
547
609
  this.#total = 0;
548
610
  }
549
611
 
612
+ /** Mean of this series over the frames where `gate` reaches `floor`. The rings fill and reset in step, so a slot is one frame. */
613
+ meanWhere(gate: Ring, floor: number): { readonly frames: number; readonly mean: number } {
614
+ let frames = 0;
615
+ let total = 0;
616
+ for (let index = 0; index < this.#count; index += 1) {
617
+ if ((gate.#buffer[index] ?? 0) < floor) continue;
618
+ frames += 1;
619
+ total += this.#buffer[index] ?? 0;
620
+ }
621
+ return { frames, mean: frames === 0 ? 0 : total / frames };
622
+ }
623
+
550
624
  summarize(scratch: Float64Array): IFrameBudgetSummary {
551
625
  const count = this.#count;
552
626
  if (count === 0) return { max: 0, mean: 0, p50: 0, p95: 0, p99: 0, samples: 0 };
@@ -607,6 +681,8 @@ function round1(value: number): number {
607
681
  * exception is `addSimulation`, which reports simulation that ran outside any frame — see it.
608
682
  */
609
683
  export class FrameBudget {
684
+ readonly #debug = debugRequested();
685
+ #debugWindowBoundary: number | undefined;
610
686
  #taskObserver: PerformanceObserver | undefined;
611
687
  #taskCount = 0;
612
688
  #longestTaskMs = 0;
@@ -627,6 +703,8 @@ export class FrameBudget {
627
703
  | undefined;
628
704
  #scratch: Float64Array;
629
705
  #presented: Ring;
706
+ #drawn: Ring;
707
+ #drawnInWindow = 0;
630
708
  #frame: Ring;
631
709
  #substeps: Ring;
632
710
  #phaseRings: Record<FrameBudgetPhase, Ring>;
@@ -646,6 +724,15 @@ export class FrameBudget {
646
724
  #hostCalls: Ring;
647
725
  #gpuBytes: Ring;
648
726
  #jsAllocBytes: Ring;
727
+ #bridgeCrossings: Ring;
728
+ #dirtyTransforms: Ring;
729
+ #castersMoving: Ring;
730
+ #engine = new Map<string, Ring>();
731
+ /** One ring per name in `STAGE_NAMES`, made on the first `addStages` so a meter-off run allocates none. */
732
+ #stageRings: Ring[] | undefined;
733
+ #stageSumRing: Ring | undefined;
734
+ #stagesThisFrame: IFrameStageSample | undefined;
735
+ readonly #capacity: number;
649
736
  #countersThisFrame: IFrameCounters | undefined;
650
737
  // The latest tick fed this window. It is not a boundary count and does not sum across frames: it
651
738
  // is the loop's fixed-step count at the last frame that fed one, so consecutive window closes read
@@ -675,6 +762,9 @@ export class FrameBudget {
675
762
  #hostGap = 0;
676
763
  #presentedDelta = 0;
677
764
  #lastTimestamp: number | undefined;
765
+ #frameTimestamp = 0;
766
+ /** The last drawn frame's timestamp; a declined frame leaves it, so the next drawn interval spans it. */
767
+ #lastDrawnTimestamp: number | undefined;
678
768
  #lastFrameEnd: number | undefined;
679
769
  #framesInWindow = 0;
680
770
  #hitchesInWindow = 0;
@@ -699,6 +789,7 @@ export class FrameBudget {
699
789
  this.minFrames = requirePositiveInteger(options.minFrames, 1, "minFrames");
700
790
  this.hitchMs = requirePositiveNumber(options.hitchMs, DEFAULT_HITCH_MS, "hitchMs");
701
791
  const capacity = requirePositiveInteger(options.capacity, DEFAULT_CAPACITY, "capacity");
792
+ this.#capacity = capacity;
702
793
  this.#report = options.report ?? ((line) => console.log(line));
703
794
  this.#wallClock = options.wallClock ?? (() => Date.now());
704
795
  this.#onWindow = options.onWindow;
@@ -710,6 +801,10 @@ export class FrameBudget {
710
801
  if (globalThis.PerformanceObserver?.supportedEntryTypes.includes("longtask")) {
711
802
  this.#taskObserver = new PerformanceObserver((list) => {
712
803
  for (const entry of list.getEntries()) {
804
+ if (this.#debug) {
805
+ countDebug("longTasks", 1, "host", "PerformanceObserver.longtask");
806
+ countDebug("longTaskMs", entry.duration, "host", "PerformanceObserver.longtask", "ms");
807
+ }
713
808
  this.#taskCount++;
714
809
  this.#longestTaskMs = Math.max(this.#longestTaskMs, entry.duration);
715
810
  if (
@@ -723,6 +818,7 @@ export class FrameBudget {
723
818
  }
724
819
  this.#scratch = new Float64Array(capacity);
725
820
  this.#presented = new Ring(capacity);
821
+ this.#drawn = new Ring(capacity);
726
822
  this.#frame = new Ring(capacity);
727
823
  this.#substeps = new Ring(capacity);
728
824
  this.#gpu = new Ring(capacity);
@@ -737,6 +833,9 @@ export class FrameBudget {
737
833
  this.#hostCalls = new Ring(capacity);
738
834
  this.#gpuBytes = new Ring(capacity);
739
835
  this.#jsAllocBytes = new Ring(capacity);
836
+ this.#bridgeCrossings = new Ring(capacity);
837
+ this.#dirtyTransforms = new Ring(capacity);
838
+ this.#castersMoving = new Ring(capacity);
740
839
  this.#phaseRings = {
741
840
  hostGap: new Ring(capacity),
742
841
  overlay: new Ring(capacity),
@@ -802,6 +901,7 @@ export class FrameBudget {
802
901
  this.#presentedDelta =
803
902
  this.#lastTimestamp === undefined ? 0 : Math.max(0, timestampMs - this.#lastTimestamp);
804
903
  this.#lastTimestamp = timestampMs;
904
+ this.#frameTimestamp = timestampMs;
805
905
  }
806
906
 
807
907
  /** The boundary between the fixed-step simulation and everything the render phase does. */
@@ -955,10 +1055,18 @@ export class FrameBudget {
955
1055
  */
956
1056
  addCounters(counters: IFrameCounters): void {
957
1057
  if (!this.#open) throw new Error("FrameBudget.addCounters called outside a frame.");
1058
+ if (this.#debug)
1059
+ for (const [name, value] of Object.entries(counters.engine ?? {})) {
1060
+ if (!Number.isFinite(value) || value < 0)
1061
+ throw new Error(`Frame budget engine counter ${name} must be non-negative and finite.`);
1062
+ }
958
1063
  for (const [name, value] of [
959
1064
  ["hostCalls", counters.hostCalls],
960
1065
  ["gpuBytes", counters.gpuBytes],
961
1066
  ["jsAllocBytes", counters.jsAllocBytes],
1067
+ ["bridgeCrossings", counters.bridgeCrossings],
1068
+ ["dirtyTransforms", counters.dirtyTransforms],
1069
+ ["castersMoving", counters.castersMoving],
962
1070
  ] as const) {
963
1071
  if (value === undefined) continue;
964
1072
  if (!Number.isFinite(value) || value < 0)
@@ -993,6 +1101,15 @@ export class FrameBudget {
993
1101
  }
994
1102
  }
995
1103
 
1104
+ /**
1105
+ * Records the frame's render-phase stages, from `createStageReader`. At most one call per frame; the
1106
+ * object is read at `endFrame`, so a caller may reuse one sample across frames.
1107
+ */
1108
+ addStages(stages: IFrameStageSample): void {
1109
+ if (!this.#open) throw new Error("FrameBudget.addStages called outside a frame.");
1110
+ this.#stagesThisFrame = stages;
1111
+ }
1112
+
996
1113
  /**
997
1114
  * Closes the frame and returns its phase split, or `undefined` when the frame was a hitch and
998
1115
  * therefore excluded — a 27-second startup stall is not a frame time and must not enter a
@@ -1014,9 +1131,19 @@ export class FrameBudget {
1014
1131
 
1015
1132
  this.#countPresents();
1016
1133
 
1134
+ const drawn = !this.#renderSkippedThisFrame;
1135
+ const drawnDelta =
1136
+ drawn && this.#lastDrawnTimestamp !== undefined
1137
+ ? Math.max(0, this.#frameTimestamp - this.#lastDrawnTimestamp)
1138
+ : 0;
1139
+ if (drawn) this.#lastDrawnTimestamp = this.#frameTimestamp;
1140
+
1017
1141
  const isHitch = this.#presentedDelta >= this.hitchMs;
1018
1142
  if (isHitch) {
1143
+ // The gap is excluded, so the next drawn interval must not start before it.
1144
+ if (!drawn) this.#lastDrawnTimestamp = undefined;
1019
1145
  this.#passesThisFrame.length = 0;
1146
+ this.#stagesThisFrame = undefined;
1020
1147
  this.#hitchesInWindow += 1;
1021
1148
  this.#report(
1022
1149
  `${FRAME_HITCH_MARKER}:${JSON.stringify({
@@ -1047,6 +1174,8 @@ export class FrameBudget {
1047
1174
  // The first frame has no predecessor, so it has neither an interval nor a host gap; pushing a
1048
1175
  // zero there would drag every percentile toward a frame that never happened.
1049
1176
  if (this.#presentedDelta > 0) this.#presented.push(this.#presentedDelta);
1177
+ if (drawnDelta > 0) this.#drawn.push(drawnDelta);
1178
+ if (drawn) this.#drawnInWindow += 1;
1050
1179
  if (this.#hostGap > 0) this.#phaseRings.hostGap.push(this.#hostGap);
1051
1180
  this.#phaseRings.update.push(update);
1052
1181
  this.#phaseRings.render.push(this.#renderMs);
@@ -1056,6 +1185,7 @@ export class FrameBudget {
1056
1185
  this.#phaseRings.overlay.push(this.#overlayMs);
1057
1186
  this.#phaseRings.residual.push(residual);
1058
1187
  this.#phaseRings.ui.push(this.#uiMs);
1188
+ this.#pushStages(update, residual);
1059
1189
  if (this.#gpuThisFrame !== undefined) {
1060
1190
  this.#gpu.push(this.#gpuThisFrame);
1061
1191
  if (this.#gpuFrameThisFrame === undefined) this.#gpuUnframed = true;
@@ -1103,6 +1233,19 @@ export class FrameBudget {
1103
1233
  if (counters?.hostCalls !== undefined) this.#hostCalls.push(counters.hostCalls);
1104
1234
  if (counters?.gpuBytes !== undefined) this.#gpuBytes.push(counters.gpuBytes);
1105
1235
  if (counters?.jsAllocBytes !== undefined) this.#jsAllocBytes.push(counters.jsAllocBytes);
1236
+ if (counters?.bridgeCrossings !== undefined)
1237
+ this.#bridgeCrossings.push(counters.bridgeCrossings);
1238
+ if (counters?.dirtyTransforms !== undefined)
1239
+ this.#dirtyTransforms.push(counters.dirtyTransforms);
1240
+ if (counters?.castersMoving !== undefined) this.#castersMoving.push(counters.castersMoving);
1241
+ for (const [name, value] of Object.entries(counters?.engine ?? {})) {
1242
+ let ring = this.#engine.get(name);
1243
+ if (ring === undefined) {
1244
+ ring = new Ring(this.#capacity);
1245
+ this.#engine.set(name, ring);
1246
+ }
1247
+ ring.push(value);
1248
+ }
1106
1249
  this.#framesInWindow += 1;
1107
1250
  this.#maybeReport();
1108
1251
  return sample;
@@ -1111,6 +1254,7 @@ export class FrameBudget {
1111
1254
  /** Reads the window in progress without disturbing it. */
1112
1255
  window(): IFrameBudgetWindow {
1113
1256
  const presented = this.#presented.summarize(this.#scratch);
1257
+ const drawn = this.#drawn.summarize(this.#scratch);
1114
1258
  const phases = {
1115
1259
  hostGap: this.#phaseRings.hostGap.summarize(this.#scratch),
1116
1260
  overlay: this.#phaseRings.overlay.summarize(this.#scratch),
@@ -1164,26 +1308,63 @@ export class FrameBudget {
1164
1308
  this.#gpuBytes.count === 0 ? undefined : this.#gpuBytes.summarize(this.#scratch);
1165
1309
  const jsAllocBytes =
1166
1310
  this.#jsAllocBytes.count === 0 ? undefined : this.#jsAllocBytes.summarize(this.#scratch);
1311
+ const bridgeCrossings =
1312
+ this.#bridgeCrossings.count === 0
1313
+ ? undefined
1314
+ : this.#bridgeCrossings.summarize(this.#scratch);
1315
+ const dirtyTransforms =
1316
+ this.#dirtyTransforms.count === 0
1317
+ ? undefined
1318
+ : this.#dirtyTransforms.summarize(this.#scratch);
1319
+ const castersMoving =
1320
+ this.#castersMoving.count === 0 ? undefined : this.#castersMoving.summarize(this.#scratch);
1167
1321
  const simulationTick = this.#simulationTick;
1168
1322
  const counters =
1169
1323
  hostCalls === undefined &&
1170
1324
  gpuBytes === undefined &&
1171
1325
  jsAllocBytes === undefined &&
1326
+ bridgeCrossings === undefined &&
1327
+ dirtyTransforms === undefined &&
1328
+ castersMoving === undefined &&
1329
+ this.#engine.size === 0 &&
1172
1330
  simulationTick === undefined
1173
1331
  ? undefined
1174
1332
  : {
1333
+ ...(bridgeCrossings === undefined ? {} : { bridgeCrossings }),
1334
+ ...(castersMoving === undefined ? {} : { castersMoving }),
1335
+ ...(dirtyTransforms === undefined ? {} : { dirtyTransforms }),
1336
+ ...(this.#engine.size === 0
1337
+ ? {}
1338
+ : {
1339
+ engine: Object.fromEntries(
1340
+ [...this.#engine].map(([name, ring]) => [name, ring.summarize(this.#scratch)]),
1341
+ ),
1342
+ }),
1175
1343
  ...(gpuBytes === undefined ? {} : { gpuBytes }),
1176
1344
  ...(hostCalls === undefined ? {} : { hostCalls }),
1177
1345
  ...(jsAllocBytes === undefined ? {} : { jsAllocBytes }),
1178
1346
  ...(simulationTick === undefined ? {} : { simulationTick }),
1179
1347
  };
1348
+ const stageRings = this.#stageRings;
1349
+ const stages =
1350
+ stageRings === undefined || (stageRings[0]?.count ?? 0) === 0
1351
+ ? undefined
1352
+ : Object.fromEntries(
1353
+ STAGE_NAMES.flatMap((name, index) => {
1354
+ const ring = stageRings[index];
1355
+ return ring === undefined || ring.count === 0
1356
+ ? []
1357
+ : [[name, ring.summarize(this.#scratch)]];
1358
+ }),
1359
+ );
1180
1360
  const gpuSummary = this.#gpu.summarize(this.#scratch);
1181
1361
  const gpu = gpuSummary.samples === 0 ? undefined : gpuSummary;
1182
1362
  const gpuBucket = (bucket: FrameGpuBucket): number | undefined => {
1183
1363
  const summary = this.#gpuBucketRings[bucket].summarize(this.#scratch);
1184
1364
  return summary.samples === 0 ? undefined : round1(summary.p50);
1185
1365
  };
1186
- const gpuMain = gpuBucket("main");
1366
+ const mainBucket = this.#gpuBucketRings.main.summarize(this.#scratch);
1367
+ const gpuMain = mainBucket.samples === 0 ? undefined : round1(mainBucket.p50);
1187
1368
  const gpuShadow = gpuBucket("shadow");
1188
1369
  const gpuOther = gpuBucket("other");
1189
1370
  const gpuCompute = gpuBucket("compute");
@@ -1218,6 +1399,13 @@ export class FrameBudget {
1218
1399
  fps: presented.mean === 0 ? 0 : round(1_000 / presented.mean),
1219
1400
  frame: this.#frame.summarize(this.#scratch),
1220
1401
  frames: this.#framesInWindow,
1402
+ ...(this.#debug && this.#debugWindowBoundary !== undefined && this.#lastFrameEnd !== undefined
1403
+ ? { durationMs: Math.max(0, this.#lastFrameEnd - this.#debugWindowBoundary) }
1404
+ : {}),
1405
+ // The Wasm engine's job pool (PRD-752 phase 4), as its facade reports it: `on (N)` or `off (<reason>)`.
1406
+ ...(typeof (globalThis as { __tnWebThreads?: unknown }).__tnWebThreads === "string"
1407
+ ? { threads: (globalThis as { __tnWebThreads?: string }).__tnWebThreads }
1408
+ : {}),
1221
1409
  ...(this.#simulation === undefined
1222
1410
  ? {}
1223
1411
  : {
@@ -1228,6 +1416,9 @@ export class FrameBudget {
1228
1416
  hitches: this.#hitchesInWindow,
1229
1417
  phases,
1230
1418
  presented,
1419
+ drawn,
1420
+ drawnFrames: this.#drawnInWindow,
1421
+ drawnFps: drawn.mean === 0 ? 0 : round(1_000 / drawn.mean),
1231
1422
  ...(presentCounted ? { presents: this.#presentsInWindow } : {}),
1232
1423
  ...(presentCounted && this.#presentsInWindow > 0 && windowSpanMs > 0
1233
1424
  ? { presentedFps: round((this.#presentsInWindow * 1_000) / windowSpanMs) }
@@ -1263,6 +1454,13 @@ export class FrameBudget {
1263
1454
  ...(overTarget === undefined ? {} : { overTarget }),
1264
1455
  ...(surface === undefined ? {} : { surface }),
1265
1456
  ...(counters === undefined ? {} : { counters }),
1457
+ ...(stages === undefined || this.#stageSumRing === undefined
1458
+ ? {}
1459
+ : {
1460
+ stages,
1461
+ stageSum: this.#stageSumRing.summarize(this.#scratch),
1462
+ stagesAtP95: this.#stagesAtP95(this.#stageSumRing, stageRings),
1463
+ }),
1266
1464
  window: this.#windowIndex + 1,
1267
1465
  // Appended after every existing field so a parser that reads this line as JSON keeps the
1268
1466
  // keys it already knew; the per-bucket p50s are the only additions.
@@ -1275,6 +1473,7 @@ export class FrameBudget {
1275
1473
  : { gpuShadowP95: round1(shadowBucket.p95), gpuShadowSamples: shadowBucket.samples }),
1276
1474
  ...(shadowRendered.samples === 0 ? {} : { gpuShadowRendered: shadowRendered }),
1277
1475
  ...(gpuPyramid.samples === 0 ? {} : { gpuPyramid }),
1476
+ ...(mainBucket.samples === 0 ? {} : { gpuMainSamples: mainBucket.samples }),
1278
1477
  };
1279
1478
  }
1280
1479
 
@@ -1305,6 +1504,57 @@ export class FrameBudget {
1305
1504
  return Math.max(0, this.#lastFrameEnd - this.#firstFrameStart);
1306
1505
  }
1307
1506
 
1507
+ /** The stages' means over the frames at or above the sum's p95 (see `IFrameBudgetWindow.stagesAtP95`). */
1508
+ #stagesAtP95(
1509
+ sumRing: Ring,
1510
+ stageRings: readonly Ring[] | undefined,
1511
+ ): NonNullable<IFrameBudgetWindow["stagesAtP95"]> {
1512
+ const floor = sumRing.summarize(this.#scratch).p95;
1513
+ const stages: Record<string, number> = {};
1514
+ let frames = 0;
1515
+ for (let index = 0; index < STAGE_NAMES.length; index += 1) {
1516
+ const ring = stageRings?.[index];
1517
+ // A ring that missed frames is out of step with the sum, so its slots are not this tail's frames.
1518
+ if (ring === undefined || ring.count === 0 || ring.count !== sumRing.count) continue;
1519
+ const at = ring.meanWhere(sumRing, floor);
1520
+ frames = at.frames;
1521
+ stages[STAGE_NAMES[index] as string] = round(at.mean);
1522
+ }
1523
+ return { frames, stages };
1524
+ }
1525
+
1526
+ /** Pushes this frame's stages, with the phases that complete the partition of `frame`. */
1527
+ #pushStages(update: number, residual: number): void {
1528
+ const sample = this.#stagesThisFrame;
1529
+ this.#stagesThisFrame = undefined;
1530
+ if (sample === undefined) return;
1531
+ let rings = this.#stageRings;
1532
+ if (rings === undefined) {
1533
+ rings = STAGE_NAMES.map(() => new Ring(this.#capacity));
1534
+ this.#stageRings = rings;
1535
+ this.#stageSumRing = new Ring(this.#capacity);
1536
+ }
1537
+ let sum = 0;
1538
+ for (let index = 0; index < STAGE_NAMES.length; index += 1) {
1539
+ const name = STAGE_NAMES[index] as (typeof STAGE_NAMES)[number];
1540
+ const value =
1541
+ name === "update"
1542
+ ? update
1543
+ : name === "overlay"
1544
+ ? this.#overlayMs
1545
+ : name === "ui"
1546
+ ? this.#uiMs
1547
+ : name === "residual"
1548
+ ? residual
1549
+ : sample[name];
1550
+ // A stage the engine did not measure this frame has no sample: absent, never zero.
1551
+ if (value === undefined) continue;
1552
+ rings[index]?.push(value);
1553
+ if (!(STAGE_PARTS as readonly string[]).includes(name)) sum += value;
1554
+ }
1555
+ this.#stageSumRing?.push(sum);
1556
+ }
1557
+
1308
1558
  #countPresents(): void {
1309
1559
  const read = this.#readPresentCount;
1310
1560
  if (read === undefined) return;
@@ -1330,8 +1580,16 @@ export class FrameBudget {
1330
1580
  if (elapsed < this.reportEvery || this.#framesInWindow < this.minFrames) return;
1331
1581
  const completed = this.window();
1332
1582
  this.#report(`${FRAME_BUDGET_MARKER}:${JSON.stringify(completed)}`);
1583
+ if (this.#debug) {
1584
+ this.#report(formatDebugReport(completed));
1585
+ const hotCalls = debugHotCalls(completed);
1586
+ if (hotCalls !== undefined) this.#report(hotCalls);
1587
+ }
1333
1588
  this.#windowIndex += 1;
1589
+ if (this.#debug) this.#debugWindowBoundary = this.#lastFrameEnd;
1334
1590
  this.#presented.reset();
1591
+ this.#drawn.reset();
1592
+ this.#drawnInWindow = 0;
1335
1593
  this.#frame.reset();
1336
1594
  this.#substeps.reset();
1337
1595
  this.#gpu.reset();
@@ -1344,6 +1602,12 @@ export class FrameBudget {
1344
1602
  this.#hostCalls.reset();
1345
1603
  this.#gpuBytes.reset();
1346
1604
  this.#jsAllocBytes.reset();
1605
+ this.#bridgeCrossings.reset();
1606
+ this.#dirtyTransforms.reset();
1607
+ this.#castersMoving.reset();
1608
+ this.#engine.clear();
1609
+ for (const ring of this.#stageRings ?? []) ring.reset();
1610
+ this.#stageSumRing?.reset();
1347
1611
  this.#simulationTick = undefined;
1348
1612
  this.#gpuStaleInWindow = 0;
1349
1613
  this.#renderSkipsInWindow = 0;
@@ -1357,6 +1621,8 @@ export class FrameBudget {
1357
1621
  this.#framesInWindow = 0;
1358
1622
  this.#windowStartTick = this.#simulation?.tick();
1359
1623
  this.#hitchesInWindow = 0;
1624
+ this.#taskCount = 0;
1625
+ this.#longestTaskMs = 0;
1360
1626
  this.#renderOverTarget = 0;
1361
1627
  this.#gpuOverTarget = 0;
1362
1628
  this.#presentsInWindow = 0;