@vgai/engine 0.5.8 → 0.5.9

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 (43) hide show
  1. package/dist/adapter/ingest/contract-debug-adapter.d.ts +35 -0
  2. package/dist/adapter/ingest/contract-debug-adapter.d.ts.map +1 -0
  3. package/dist/adapter/ingest/contract-debug-adapter.js +90 -0
  4. package/dist/adapter/ingest/game-contract.d.ts +60 -1
  5. package/dist/adapter/ingest/game-contract.d.ts.map +1 -1
  6. package/dist/adapter/ingest/game-contract.js +1 -1
  7. package/dist/adapter/setup-three-root-adapter.d.ts.map +1 -1
  8. package/dist/adapter/setup-three-root-adapter.js +94 -2
  9. package/dist/dev/performance-profiler.d.ts +13 -7
  10. package/dist/dev/performance-profiler.d.ts.map +1 -1
  11. package/dist/dev/performance-profiler.js +31 -3
  12. package/dist/dev/register-render-vitals.d.ts +95 -0
  13. package/dist/dev/register-render-vitals.d.ts.map +1 -0
  14. package/dist/dev/register-render-vitals.js +182 -0
  15. package/dist/dev/render-census.d.ts +135 -0
  16. package/dist/dev/render-census.d.ts.map +1 -0
  17. package/dist/dev/render-census.js +257 -0
  18. package/dist/dev/render-vitals.d.ts +181 -0
  19. package/dist/dev/render-vitals.d.ts.map +1 -0
  20. package/dist/dev/render-vitals.js +232 -0
  21. package/dist/dev/static-batch-advisor.d.ts +106 -0
  22. package/dist/dev/static-batch-advisor.d.ts.map +1 -0
  23. package/dist/dev/static-batch-advisor.js +141 -0
  24. package/dist/render/render-batch-system.d.ts.map +1 -1
  25. package/dist/render/render-batch-system.js +7 -18
  26. package/dist/render/structural-signature.d.ts +148 -0
  27. package/dist/render/structural-signature.d.ts.map +1 -0
  28. package/dist/render/structural-signature.js +193 -0
  29. package/dist/runtime/dev-layers.d.ts.map +1 -1
  30. package/dist/runtime/dev-layers.js +6 -0
  31. package/package.json +1 -1
  32. package/schemas/engine-capabilities.json +5 -5
  33. package/src/adapter/ingest/contract-debug-adapter.ts +110 -0
  34. package/src/adapter/ingest/game-contract.ts +63 -1
  35. package/src/adapter/setup-three-root-adapter.ts +94 -2
  36. package/src/dev/performance-profiler.ts +47 -12
  37. package/src/dev/register-render-vitals.ts +249 -0
  38. package/src/dev/render-census.ts +351 -0
  39. package/src/dev/render-vitals.ts +338 -0
  40. package/src/dev/static-batch-advisor.ts +186 -0
  41. package/src/render/render-batch-system.ts +16 -19
  42. package/src/render/structural-signature.ts +231 -0
  43. package/src/runtime/dev-layers.ts +7 -1
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Projects a game's DECLARED system surface (`window.vgaiGame.systems`, see
3
+ * `game-contract.ts`) onto the host's existing {@link DebugAdapter} — the one
4
+ * seam `game.commands()` / `game.state()` / `game.providers()` already read
5
+ * through for first-party content (`command-listener.ts`'s
6
+ * `dispatchBridgeMethod` → `getActiveSystems().debug`).
7
+ *
8
+ * Why a projection rather than a second door: an agent driving an ingested
9
+ * game must not have to learn a parallel vocabulary. A first-party game
10
+ * registers verbs with `ctx.debug.registerCommand`; an ingested game declares
11
+ * them in its entry shim. Both arrive at the SAME `DebugAdapter`, so every
12
+ * consumer downstream — the CLI's `vgai eval`, `@vgai/e2e`'s `GameClient`, the
13
+ * editor's Debug Console and State Watch panels — works unchanged and unaware
14
+ * of the provenance.
15
+ *
16
+ * What this deliberately does NOT do:
17
+ * - **Validate arguments.** The first-party path validates against a declared
18
+ * Zod tuple; a shim beside a foreign game is plain JS and has none. A verb
19
+ * validates itself and throws its own error, which surfaces wrapped as
20
+ * `DEBUG_COMMAND_FAILED` — the host never invents a schema to check against.
21
+ * - **Fabricate an event ring.** There is no tick loop behind an ingested
22
+ * game's declarations, so `events()` is empty. That is accurate (nothing was
23
+ * emitted), not a stub standing in for a missing feature.
24
+ */
25
+
26
+ import { DebugError } from '../../runtime/debug-registry';
27
+ import type { DebugAdapter, DebugCommandInfo, TickStampedEvent } from '../system-adapter';
28
+ import type { VgaiGameSystems } from './game-contract';
29
+
30
+ /**
31
+ * Build a {@link DebugAdapter} over a declared system surface, or `null` when
32
+ * the game declared no verbs and no state. `null` is the honest floor: the
33
+ * bridge then reports `DEBUG_ADAPTER_UNAVAILABLE` exactly as it did before,
34
+ * rather than serving an empty adapter that reads as "this game has no state"
35
+ * when the truth is "this game declared nothing".
36
+ */
37
+ export function createContractDebugAdapter(
38
+ systems: VgaiGameSystems | undefined | null,
39
+ ): DebugAdapter | null {
40
+ const commandList = systems?.commands ?? [];
41
+ const providerList = systems?.state ?? [];
42
+ if (commandList.length === 0 && providerList.length === 0) return null;
43
+
44
+ // Snapshot into name-keyed maps once. A later duplicate shadows an earlier
45
+ // one and the listing de-duplicates with it, so `commands()` can never
46
+ // advertise a name `invoke()` would resolve differently.
47
+ const byCommand = new Map(commandList.map((c) => [c.name, c]));
48
+ const byProvider = new Map(providerList.map((p) => [p.name, p]));
49
+
50
+ return {
51
+ providers: () =>
52
+ [...byProvider.values()].map((p) => ({ name: p.name, tier: p.tier ?? 'observable' })),
53
+
54
+ state: (name: string): unknown => {
55
+ const provider = byProvider.get(name);
56
+ if (!provider) {
57
+ throw new DebugError(
58
+ 'STATE_PROVIDER_NOT_FOUND',
59
+ `No state provider named "${name}" is declared by this game.`,
60
+ { registered: [...byProvider.keys()] },
61
+ );
62
+ }
63
+ return provider.read();
64
+ },
65
+
66
+ stateAll: (): Record<string, unknown> => {
67
+ const out: Record<string, unknown> = {};
68
+ for (const [name, provider] of byProvider) {
69
+ // One throwing provider must not cost the caller every other reading —
70
+ // the same per-key isolation the first-party registry gives.
71
+ try {
72
+ out[name] = provider.read();
73
+ } catch (err) {
74
+ out[name] = { __error: String(err) };
75
+ }
76
+ }
77
+ return out;
78
+ },
79
+
80
+ commands: (): DebugCommandInfo[] =>
81
+ [...byCommand.values()].map((c) => ({
82
+ name: c.name,
83
+ description: c.description,
84
+ argsJsonSchema: c.argsJsonSchema,
85
+ // An ingested game runs entirely in the browser realm the host mounted
86
+ // it in; there is no server leg for its verbs to route to.
87
+ locus: 'client' as const,
88
+ })),
89
+
90
+ invoke: async (name: string, args: unknown[]): Promise<unknown> => {
91
+ const command = byCommand.get(name);
92
+ if (!command) {
93
+ throw new DebugError(
94
+ 'DEBUG_COMMAND_NOT_REGISTERED',
95
+ `No command named "${name}" is declared by this game.`,
96
+ { registered: [...byCommand.keys()] },
97
+ );
98
+ }
99
+ try {
100
+ return await command.run(...args);
101
+ } catch (err) {
102
+ throw new DebugError('DEBUG_COMMAND_FAILED', `Command "${name}" threw: ${String(err)}`, {
103
+ name,
104
+ });
105
+ }
106
+ },
107
+
108
+ events: (): TickStampedEvent[] => [],
109
+ };
110
+ }
@@ -15,7 +15,7 @@
15
15
  * endpoint by endpoint: capture infers what it can (the scene), the game
16
16
  * declares what inference can't reach (its DOM root, its session lifecycle).
17
17
  *
18
- * Origin (root), F17+F21 (lifecycle).
18
+ * Origin (root), F17+F21 (lifecycle), WO-SYS1 (systems).
19
19
  */
20
20
 
21
21
  /**
@@ -34,6 +34,62 @@ export interface VgaiGameLifecycle {
34
34
  resume?(): void;
35
35
  }
36
36
 
37
+ /**
38
+ * One invokable verb the game exposes. Deliberately the SAME listing shape a
39
+ * first-party game gets from `ctx.debug.registerCommand`
40
+ * (`DebugCommandInfo`/`DebugAdapter.invoke` in `adapter/system-adapter.ts`) —
41
+ * an ingested game's verbs must enumerate through `game.commands()` and run
42
+ * through `game.command(...)` with no second vocabulary for agents to learn.
43
+ *
44
+ * `run` receives the positional argument list exactly as invoked. There is no
45
+ * host-side validation: the contract is plain JS declared beside a foreign
46
+ * game, so it cannot carry a Zod tuple the way `registerCommand` does.
47
+ * `argsJsonSchema` is therefore DOCUMENTATION for listing surfaces, not a
48
+ * gate — a verb validates its own arguments and throws its own errors.
49
+ */
50
+ export interface VgaiGameCommand {
51
+ name: string;
52
+ description?: string;
53
+ /** JSON-Schema projection of the argument list, when the game declares one. */
54
+ argsJsonSchema?: unknown;
55
+ run(...args: unknown[]): unknown | Promise<unknown>;
56
+ }
57
+
58
+ /**
59
+ * One named, JSON-serializable state read — the `ctx.debug.registerStateProvider`
60
+ * shape. `tier` carries the same meaning as the first-party one: `observable`
61
+ * is a value the game already computes, `assisted` is one the shim derives.
62
+ */
63
+ export interface VgaiGameStateProvider {
64
+ name: string;
65
+ tier?: 'observable' | 'assisted';
66
+ read(): unknown;
67
+ }
68
+
69
+ /**
70
+ * The game's SYSTEM surface: what its content actually IS, as opposed to how
71
+ * it renders. An ingested game's content is not always its scene graph — in a
72
+ * system-driven game the authorable content lives in the game's own model and
73
+ * is reached through the game's own verbs, which `root`/`lifecycle` could not
74
+ * express.
75
+ *
76
+ * Both members are read by exactly one consumer,
77
+ * `adapter/ingest/contract-debug-adapter.ts`, which projects them onto the
78
+ * host's ordinary `DebugAdapter` (`adapter/system-adapter.ts`) — so
79
+ * `game.commands()`/`game.state()` reach an ingested game through the same
80
+ * bridge first-party content uses, with no second vocabulary for agents to
81
+ * learn. That is deliberate scope: this
82
+ * interface describes what a foreign game's entry shim may declare, so every
83
+ * member here is a promise the host must already keep. A member nothing reads
84
+ * would be a shim author implementing a hook that is never called.
85
+ */
86
+ export interface VgaiGameSystems {
87
+ /** Verbs, enumerated by `game.commands()` and run by `game.command(...)`. */
88
+ commands?: VgaiGameCommand[];
89
+ /** State reads, enumerated by `game.providers()` and read by `game.state(...)`. */
90
+ state?: VgaiGameStateProvider[];
91
+ }
92
+
37
93
  export interface VgaiGameContract {
38
94
  /** Bump only on breaking shape changes; additive endpoints keep version 1. */
39
95
  contractVersion: 1;
@@ -45,6 +101,12 @@ export interface VgaiGameContract {
45
101
  */
46
102
  root?: HTMLElement;
47
103
  lifecycle?: VgaiGameLifecycle;
104
+ /**
105
+ * The game's own systems. Absent means "this game declared no system
106
+ * surface" — every dependent editor surface then shows a named absence, not
107
+ * an empty pretend-palette.
108
+ */
109
+ systems?: VgaiGameSystems;
48
110
  }
49
111
 
50
112
  /**
@@ -33,12 +33,14 @@ import {
33
33
  import { createSimClock, getSimClock, type SimClockInternal } from '../core/sim-clock';
34
34
  import { createSystemRunner } from '../core/system-runner';
35
35
  import { createDebugDraw } from '../dev/debug-draw';
36
+ import { type RenderVitalsRegistration, registerRenderVitals } from '../dev/register-render-vitals';
36
37
  import {
37
38
  createRenderDebugAdapter,
38
39
  frameCaptureContextFor,
39
40
  type RenderDebugWiring,
40
41
  } from '../dev/render-debug-adapter';
41
42
  import { collectRenderMemory } from '../dev/render-memory';
43
+ import { RENDER_SUBMIT_PHASE } from '../dev/render-vitals';
42
44
  import { createWebGLFrameCapture } from '../dev/webgl-frame-capture';
43
45
  import { createWebGLGpuTimer } from '../dev/webgl-gpu-timer';
44
46
  import { createSceneIndex } from '../ecs/scene-index';
@@ -61,6 +63,7 @@ import {
61
63
  type DebugRegistry,
62
64
  getDebugRegistry,
63
65
  } from '../runtime/debug-registry';
66
+ import { devLayersEnabled } from '../runtime/dev-layers';
64
67
  import { disposeDebrisSubtree, type RootFrameHooks } from '../runtime/game';
65
68
  import type { EditorPreview, GameCleanup, GameContext, GameSetupFn } from '../runtime/types';
66
69
  import { type AudioContext as GameAudio, setupAudio } from '../setup/setup-audio';
@@ -237,6 +240,10 @@ export class SetupThreeRootAdapter implements RootAdapter {
237
240
  : null;
238
241
  const viewportShading = new ViewportShadingRenderer();
239
242
  let viewportShadingMode: ViewportShadingMode = 'solid';
243
+ /** Top-level `renderer.render()` calls the last presentation cost — written
244
+ * by the render system, read by `postFrame`. See both for why the count is
245
+ * latched rather than differenced at report time. */
246
+ let lastPresentationPasses = 0;
240
247
 
241
248
  // --- System runner (engine-level systems) ---
242
249
  const systems = createSystemRunner(host.game?.profiler.systemObserver, 'three');
@@ -296,7 +303,8 @@ export class SetupThreeRootAdapter implements RootAdapter {
296
303
  systems.add(
297
304
  'render',
298
305
  (dt) => {
299
- if (host.game?.profiler.enabled) gpuTimer?.begin();
306
+ const profiler = host.game?.profiler;
307
+ if (profiler?.enabled) gpuTimer?.begin();
300
308
  if (sparkRenderer) scene.add(sparkRenderer);
301
309
  // W4b: arm-gated frame capture wraps the real draw calls. beginPass
302
310
  // is a no-op unless a captureFrame() armed it; afterRender delivers
@@ -304,6 +312,21 @@ export class SetupThreeRootAdapter implements RootAdapter {
304
312
  // patched context — in the SAME finally as gpuTimer.end(). Spark is
305
313
  // added before this so its draws fall inside the captured frame.
306
314
  renderDebugWiring?.beforeRender();
315
+ // Issue #1504: CPU render submission, bracketed as its OWN profiler
316
+ // phase nested inside the frame's enclosing `render` phase. This is
317
+ // the frame's only isolated measurement of "how long did it take to
318
+ // hand the draws to the driver" — the `render` phase around it also
319
+ // contains physics-debug redraw and every other world's render work,
320
+ // and a system span would key the reading to this adapter's system
321
+ // NAME. The profiler's phase clock is a stack precisely so this
322
+ // bracket cannot truncate its parent (`dev/performance-profiler.ts`).
323
+ // It is also what makes a frame a PRESENTATION as far as the vitals
324
+ // fold is concerned: no draw, no bracket, no display frame.
325
+ profiler?.beginPhase();
326
+ // `info.render.frame` counts top-level renderer.render() calls and
327
+ // survives `info.reset()`, so its delta across the draw is how many
328
+ // passes the composer chain (plus shadows) actually cost.
329
+ const passesBefore = renderer.info.render.frame;
307
330
  try {
308
331
  viewportShading.render(
309
332
  scene,
@@ -315,6 +338,8 @@ export class SetupThreeRootAdapter implements RootAdapter {
315
338
  (mesh) => camera.layers.test(mesh.layers),
316
339
  );
317
340
  } finally {
341
+ profiler?.endPhase(RENDER_SUBMIT_PHASE);
342
+ lastPresentationPasses = renderer.info.render.frame - passesBefore;
318
343
  renderDebugWiring?.afterRender();
319
344
  sparkRenderer?.removeFromParent();
320
345
  gpuTimer?.end();
@@ -336,13 +361,25 @@ export class SetupThreeRootAdapter implements RootAdapter {
336
361
 
337
362
  const postFrame = () => {
338
363
  if (ownsInput) input.endFrame();
339
- if (host.game?.profiler.enabled) {
364
+ // `renderer.info` is checked, not assumed: a headless/stub renderer
365
+ // supplies only what the runtime needs to mount, and a mount with no
366
+ // counters must report NOTHING rather than throw once per frame. This
367
+ // used to be unreachable because only the editor ever enabled the
368
+ // profiler; the engine enables it itself under the dev gate now (see the
369
+ // render-vitals seed below), so the assumption has to be paid for.
370
+ if (host.game?.profiler.enabled && renderer.info) {
340
371
  host.game.profiler.reportRender({
341
372
  gpuMs: gpuTimer?.poll() ?? null,
342
373
  drawCalls: renderer.info.render.calls,
343
374
  triangles: renderer.info.render.triangles,
344
375
  geometries: renderer.info.memory.geometries,
345
376
  textures: renderer.info.memory.textures,
377
+ // The LAST presentation's pass count, not a delta taken here: under
378
+ // the display-rate loop this hook runs once per fixed SUBSTEP, so a
379
+ // delta measured at this point would read as 0 on every substep that
380
+ // did not draw. Same one-frame-warm semantics as the renderer.info
381
+ // counters beside it.
382
+ renderPasses: lastPresentationPasses,
346
383
  });
347
384
  }
348
385
  };
@@ -538,6 +575,48 @@ export class SetupThreeRootAdapter implements RootAdapter {
538
575
  (host.game ? getSeededRandom(host.game) : null) ??
539
576
  createSeededRandom(DEFAULT_SEEDED_RANDOM_SEED);
540
577
 
578
+ // --- Live render vitals (issue #1504) -------------------------------------
579
+ // Engine-owned and first-party, seeded HERE like `renderDebug` above: a
580
+ // running game must be able to explain its own frame cost through the debug
581
+ // registry, with no capability to install and nothing for a game to write.
582
+ //
583
+ // THE GATE, in one place. Three conditions, and the reason for each:
584
+ // 1. `devLayersEnabled()` — the ONE owner of "is this a dev/editor
585
+ // context" (`runtime/dev-layers.ts`). A ship build registers nothing,
586
+ // subscribes to nothing, and never enables the profiler.
587
+ // 2. a `Game` shell exists — the readings are folded out of that game's
588
+ // profiler frames, and a bare mount has no profiler to fold.
589
+ // 3. not headless — a headless mount registers no render system at all,
590
+ // so it never brackets a submission and never presents a frame. Its
591
+ // vitals could only ever read empty, and registering a door that is
592
+ // structurally incapable of answering is worse than not having one.
593
+ //
594
+ // The enabled-gating question, resolved: the profiler is AUTO-ENABLED here
595
+ // rather than given a second, cheaper always-on counter tier. A counter
596
+ // tier would be a parallel measurement path — exactly the side ledger this
597
+ // work exists to avoid — and the profiler already has the one property
598
+ // that made the choice: `enabled` is a plain flag whose cost is per-frame
599
+ // bookkeeping the editor ALREADY pays (it sets `profiler.enabled = true`
600
+ // on play, `CenterDocuments.tsx`), so under the dev gate this is not a new
601
+ // cost, it is the same cost arriving a little earlier. Nothing here ever
602
+ // turns it OFF: the profiler's other owners (the Performance panel,
603
+ // `render-control.ts`'s perfSample) save and restore the prior state, so a
604
+ // dev session that enabled it at mount keeps it enabled.
605
+ let renderVitals: RenderVitalsRegistration | null = null;
606
+ const seedRenderVitals = (): void => {
607
+ if (!host.game || headless || !devLayersEnabled()) return;
608
+ renderVitals?.dispose();
609
+ host.game.profiler.enabled = true;
610
+ renderVitals = registerRenderVitals({
611
+ registry: debugRegistry,
612
+ worldId: this.id,
613
+ profiler: host.game.profiler,
614
+ scene,
615
+ renderer,
616
+ });
617
+ };
618
+ seedRenderVitals();
619
+
541
620
  // Snapshot of the engine-owned adapter kinds, taken right after seeding
542
621
  // and before any setup() has had a chance to run. `hotReload`/`disposeGame`
543
622
  // use this to strip every GAME-registered kind (including an override of a
@@ -740,6 +819,13 @@ export class SetupThreeRootAdapter implements RootAdapter {
740
819
  safeStep('debugRegistry.strip', () =>
741
820
  host.game ? debugRegistry.strip(this.id) : debugRegistry.strip(),
742
821
  );
822
+ // The strip above removes the vitals REGISTRATIONS (their provenance is
823
+ // this world). This ends the fold's profiler subscription — the one
824
+ // resource `registerRenderVitals` allocates that a strip cannot reach.
825
+ safeStep('renderVitals.dispose', () => {
826
+ renderVitals?.dispose();
827
+ renderVitals = null;
828
+ });
743
829
 
744
830
  // Release analyser taps BEFORE the audio teardown below. A consumer
745
831
  // (the editor's meter poll) should dispose its own handle, but Stop must
@@ -855,6 +941,12 @@ export class SetupThreeRootAdapter implements RootAdapter {
855
941
  // every react-door registration (whose `useEffect` cleanup never
856
942
  // re-fires to restore them after someone else's strip).
857
943
  safeStep('debugRegistry.strip', () => debugRegistry.strip(this.id));
944
+ // The strip above takes the ENGINE's own vitals registrations with it
945
+ // (they carry this world's provenance, which is what makes the game's
946
+ // own re-seed silent). Re-seed them before the incoming setup runs, so a
947
+ // warm restart does not silently cost a game its render vitals — and so
948
+ // the fold starts clean rather than carrying the outgoing game's frames.
949
+ safeStep('renderVitals re-seed', seedRenderVitals);
858
950
 
859
951
  currentCleanup = await newSetup(ctx, newEditorPreview);
860
952
  };
@@ -35,6 +35,15 @@ export interface PerformanceRenderStats {
35
35
  readonly triangles: number;
36
36
  readonly geometries: number;
37
37
  readonly textures: number;
38
+ /**
39
+ * How many top-level `renderer.render()` submissions the last presentation
40
+ * took (`renderer.info.render.frame`'s delta across one draw) — a composer
41
+ * chain, a shadow pass and a post stack each cost one. `null` (never a
42
+ * fabricated 0, same rule as `gpuMs`) when no reporter counted them: a
43
+ * reporter that omits `renderPasses` is saying it does not know, which is
44
+ * different from saying nothing was drawn.
45
+ */
46
+ readonly renderPasses: number | null;
38
47
  }
39
48
 
40
49
  export interface PerformanceFrame {
@@ -75,13 +84,7 @@ export interface PerformanceSnapshot {
75
84
  readonly phases: readonly PerformanceTiming[];
76
85
  readonly systems: readonly PerformanceTiming[];
77
86
  readonly components: readonly PerformanceTiming[];
78
- readonly render: {
79
- readonly gpuMs: number | null;
80
- readonly drawCalls: number;
81
- readonly triangles: number;
82
- readonly geometries: number;
83
- readonly textures: number;
84
- };
87
+ readonly render: PerformanceRenderStats;
85
88
  }
86
89
 
87
90
  const now = () => globalThis.performance?.now() ?? Date.now();
@@ -110,15 +113,27 @@ export function createPerformanceProfiler(initiallyEnabled = false) {
110
113
  let frameId = 0;
111
114
  let frameStart = 0;
112
115
  let lastFrameStart = 0;
113
- let phaseStart = 0;
116
+ /**
117
+ * Phase start times, innermost last. A STACK rather than the single slot
118
+ * this used to be, because phases NEST: the three adapter brackets its CPU
119
+ * render submission as its own phase (`render.submit`,
120
+ * `dev/render-vitals.ts`) from inside the frame's enclosing `render` phase.
121
+ * With one slot the inner `beginPhase()` overwrote the outer's start, so the
122
+ * outer `endPhase('render')` measured only the tail after the inner phase —
123
+ * silently under-reporting the very phase the inner one was decomposing.
124
+ * Balanced callers are unaffected; `endPhase` with an empty stack falls back
125
+ * to `frameStart` rather than a stale start from a previous frame.
126
+ */
127
+ const phaseStack: number[] = [];
114
128
  let systemStart = 0;
115
129
  let componentStart = 0;
116
- let render = {
117
- gpuMs: null as number | null,
130
+ let render: PerformanceRenderStats = {
131
+ gpuMs: null,
118
132
  drawCalls: 0,
119
133
  triangles: 0,
120
134
  geometries: 0,
121
135
  textures: 0,
136
+ renderPasses: null,
122
137
  };
123
138
  let snapshot: PerformanceSnapshot = {
124
139
  enabled,
@@ -188,15 +203,28 @@ export function createPerformanceProfiler(initiallyEnabled = false) {
188
203
  currentComponents.clear();
189
204
  frameSystems = [];
190
205
  frameComponents = [];
191
- render = { gpuMs: null, drawCalls: 0, triangles: 0, geometries: 0, textures: 0 };
206
+ // A frame that threw mid-phase leaves entries on the stack; a fresh
207
+ // frame starts from nothing rather than inheriting them.
208
+ phaseStack.length = 0;
209
+ render = {
210
+ gpuMs: null,
211
+ drawCalls: 0,
212
+ triangles: 0,
213
+ geometries: 0,
214
+ textures: 0,
215
+ renderPasses: null,
216
+ };
192
217
  frameStart = now();
193
218
  },
194
219
  beginPhase() {
195
220
  if (!enabled) return;
196
- phaseStart = now();
221
+ phaseStack.push(now());
197
222
  },
198
223
  endPhase(name: string) {
199
224
  if (!enabled) return;
225
+ // See `phaseStack`: pop restores the ENCLOSING phase's own start, so a
226
+ // nested bracket measures itself without truncating its parent.
227
+ const phaseStart = phaseStack.pop() ?? frameStart;
200
228
  const elapsed = now() - phaseStart;
201
229
  const existing = currentPhases.get(name);
202
230
  // Accumulate ms across re-entries of the same phase, but keep the FIRST
@@ -247,6 +275,9 @@ export function createPerformanceProfiler(initiallyEnabled = false) {
247
275
  triangles: number;
248
276
  geometries: number;
249
277
  textures: number;
278
+ /** Omit when this reporter does not count passes — see
279
+ * {@link PerformanceRenderStats.renderPasses}. */
280
+ renderPasses?: number;
250
281
  }) {
251
282
  if (!enabled) return;
252
283
  render = {
@@ -255,6 +286,10 @@ export function createPerformanceProfiler(initiallyEnabled = false) {
255
286
  triangles: render.triangles + stats.triangles,
256
287
  geometries: render.geometries + stats.geometries,
257
288
  textures: render.textures + stats.textures,
289
+ renderPasses:
290
+ stats.renderPasses === undefined
291
+ ? render.renderPasses
292
+ : (render.renderPasses ?? 0) + stats.renderPasses,
258
293
  };
259
294
  },
260
295
  endFrame() {