@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,181 @@
1
+ /**
2
+ * LIVE RENDER VITALS — the frame explaining its own cost, derived ENTIRELY
3
+ * from `PerformanceProfiler` frames (`dev/performance-profiler.ts`).
4
+ *
5
+ * Nothing in a viewport tells you why it is slow, and a frame-time number on
6
+ * its own tells you only THAT it is. These readings answer the next question:
7
+ * where did the milliseconds go, and which subtree owns them
8
+ * (`dev/render-census.ts` is the address book half).
9
+ *
10
+ * ── THE MEASUREMENT SOURCE, STATED ONCE ─────────────────────────────────────
11
+ * There is no side ledger here. Every number below is folded out of profiler
12
+ * frames — the timing from phase spans, the counters from `reportRender`. The
13
+ * CPU submission cost is the profiler phase {@link RENDER_SUBMIT_PHASE}, which
14
+ * the three adapter brackets around its actual draw; the profiler's phase
15
+ * bookkeeping is a stack precisely so that bracket can sit INSIDE the frame's
16
+ * enclosing `render` phase without truncating it.
17
+ *
18
+ * ── TWO FRAME FLAVOURS, ONE FOLD ────────────────────────────────────────────
19
+ * The real runtime runs sim and presentation on different callbacks
20
+ * (`create-runtime.ts`: `update` → `runFrame({skipRenderPhases})` per fixed
21
+ * substep, `render` → `runRenderFrame` once per display frame), so a profiler
22
+ * "frame" is EITHER a sim substep OR a presentation pass. A capture/offline
23
+ * host drives one `runFrame` that is both. {@link foldProfilerFrame} handles
24
+ * all three the same way, and never has to know which host it is under:
25
+ *
26
+ * - a frame carrying a {@link RENDER_SUBMIT_PHASE} span IS a presentation —
27
+ * that phase only exists when a draw actually happened;
28
+ * - sim CPU accumulates across every frame since the last presentation, so
29
+ * the substeps a display frame consumed are attributed to it;
30
+ * - renderer COUNTERS ride whichever frame `reportRender` landed on (the
31
+ * adapter reports from its `endFrame` hook, which the substep pass drives),
32
+ * so the latest report wins and the counters describe the last completed
33
+ * draw. That is the same one-frame-warm reading `renderer.info` gives any
34
+ * caller — three resets it when the next draw starts.
35
+ *
36
+ * ── WHY THE WORST FRAME IS NOT AN EMA ───────────────────────────────────────
37
+ * A decaying average keeps a restart spike on the readout for ~30 s, long
38
+ * after it stopped being true. The rolling two-window max
39
+ * ({@link WORST_WINDOW_FRAMES}) holds a hitch for one to two windows and then
40
+ * genuinely forgets it, so the number always describes recent history.
41
+ *
42
+ * ── RESOURCE OWNERSHIP ──────────────────────────────────────────────────────
43
+ * OWNER: the caller of {@link createRenderVitals}, which allocates one state
44
+ * object and one `profiler.subscribe` registration. SHARER: none — the state
45
+ * is private to that call. TEARDOWN: the returned `dispose()`, the ONE path
46
+ * that ends the subscription (`setup-three-root-adapter.ts` calls it from
47
+ * `disposeGame`).
48
+ */
49
+ import type { PerformanceFrame, PerformanceProfiler } from './performance-profiler';
50
+ /**
51
+ * The profiler phase name the three adapter brackets its CPU render
52
+ * submission with — spelled HERE and nowhere else, so the producer
53
+ * (`setup-three-root-adapter.ts`) and the consumer ({@link foldProfilerFrame})
54
+ * cannot drift apart. Dotted, so it reads as a decomposition of the enclosing
55
+ * `render` phase rather than a ninth peer of `SystemPhase`.
56
+ */
57
+ export declare const RENDER_SUBMIT_PHASE = "render.submit";
58
+ /**
59
+ * The phases whose cost is SIMULATION. Deliberately not "everything that is
60
+ * not render": `preRender` (LOD selection, particle stepping, culling prep) is
61
+ * neither the simulation nor the submission, so it lands in the hitch's
62
+ * `other` bucket where an investigation can see it. `render` itself is
63
+ * excluded because {@link RENDER_SUBMIT_PHASE} nests inside it — summing both
64
+ * would double-count the draw.
65
+ */
66
+ export declare const SIM_PHASES: readonly string[];
67
+ /** Display frames per worst-frame window — ~5 s at 60 Hz, so the reported
68
+ * worst (the max of the current and previous window) survives 5–10 s. */
69
+ export declare const WORST_WINDOW_FRAMES = 300;
70
+ /** A display frame at or above this is worth decomposing. ~3 dropped frames at
71
+ * 60 Hz: below it, ordinary jitter would rewrite the reading constantly. */
72
+ export declare const HITCH_THRESHOLD_MS = 50;
73
+ /** Smoothing for the frame-time reading — a readable number, not a blur. */
74
+ export declare const FRAME_TIME_EMA_ALPHA = 0.05;
75
+ /** Smoothing for the render-CPU reading. Faster than frame time: submission
76
+ * cost is what a draw-call diet moves, and it should visibly move. */
77
+ export declare const RENDER_CPU_EMA_ALPHA = 0.1;
78
+ /**
79
+ * A hitch, split into the three buckets that route an investigation. `other`
80
+ * is the diagnostic payload, not a rounding remainder: when it dominates, the
81
+ * thief is neither the renderer nor the simulation — it is GC, asset decode,
82
+ * a layout-thrashing DOM overlay, or the browser itself — and every minute
83
+ * spent on draw calls would have been wasted.
84
+ */
85
+ export interface HitchDecomposition {
86
+ /** The display frame's wall-clock cost. */
87
+ readonly totalMs: number;
88
+ /** CPU spent submitting draws ({@link RENDER_SUBMIT_PHASE}). */
89
+ readonly renderMs: number;
90
+ /** CPU spent in {@link SIM_PHASES}, summed over the substeps this frame
91
+ * consumed. */
92
+ readonly simMs: number;
93
+ /** Everything else in the wall clock — see this interface's own note. May be
94
+ * negative if a measurement straddles the frame boundary; reported as
95
+ * measured rather than clamped to a tidier lie. */
96
+ readonly otherMs: number;
97
+ /** The one-line reading: `"NNms = render X + sim Y + other Z"`. */
98
+ readonly text: string;
99
+ }
100
+ /** Split one display frame's wall clock into render / sim / other. Pure. */
101
+ export declare function decomposeHitch(totalMs: number, renderMs: number, simMs: number): HitchDecomposition;
102
+ /** What `render.vitals` reads. Every field is `null` until the fold has
103
+ * actually measured it — a stopped, headless or never-drawn game reports
104
+ * emptiness rather than a fabricated `0 ms / 0 draws`. */
105
+ export interface RenderVitalsReading {
106
+ /** Smoothed wall-clock ms per display frame. */
107
+ readonly frameTimeMs: number | null;
108
+ /** Frames per second implied by {@link frameTimeMs}. */
109
+ readonly fps: number | null;
110
+ /** Draw calls in the last reported draw. */
111
+ readonly drawCalls: number | null;
112
+ /** Triangles in the last reported draw. */
113
+ readonly triangles: number | null;
114
+ /** Smoothed CPU ms spent submitting draws — invisible in frame time once
115
+ * vsync caps the loop, and exactly what fewer draw calls would improve. */
116
+ readonly renderCpuMs: number | null;
117
+ /** Top-level `renderer.render()` submissions the last presentation took. */
118
+ readonly renderPasses: number | null;
119
+ /** Worst display frame in the last one-to-two windows. */
120
+ readonly worstFrameMs: number | null;
121
+ /** The most recent frame over {@link HITCH_THRESHOLD_MS}, decomposed. */
122
+ readonly lastHitch: HitchDecomposition | null;
123
+ /** How many display frames the fold has seen. `0` reads as "nothing has
124
+ * presented yet", which is why every reading above is `null`. */
125
+ readonly presentedFrames: number;
126
+ }
127
+ /** The fold's accumulator. Mutable by design (one allocation for the life of a
128
+ * mount, written once per profiler frame); read through
129
+ * {@link readRenderVitals}. */
130
+ export interface RenderVitalsState {
131
+ /** Highest profiler frame id already folded — the dedupe that makes the fold
132
+ * safe to drive from `profiler.subscribe`, which also fires for
133
+ * enabled/recording changes that publish no new frame. */
134
+ lastFrameId: number;
135
+ /** `timestamp` of the last presentation, or `null` before the first (there
136
+ * is no interval to measure from one sample). */
137
+ lastPresentAt: number | null;
138
+ /** Sim CPU accumulated since the last presentation. */
139
+ pendingSimMs: number;
140
+ frameTimeMs: number | null;
141
+ renderCpuMs: number | null;
142
+ drawCalls: number | null;
143
+ triangles: number | null;
144
+ renderPasses: number | null;
145
+ /** Running max of the CURRENT worst-frame window. */
146
+ worstCurrentMs: number;
147
+ /** The PREVIOUS window's max, kept so the reading does not drop to zero the
148
+ * instant a window rolls over. */
149
+ worstPreviousMs: number;
150
+ /** Display frames counted into the current window. */
151
+ worstWindowFrames: number;
152
+ lastHitch: HitchDecomposition | null;
153
+ presentedFrames: number;
154
+ }
155
+ export declare function createRenderVitalsState(): RenderVitalsState;
156
+ /**
157
+ * Fold ONE profiler frame into the accumulator. Pure with respect to time and
158
+ * randomness — every input is on the frame — which is what makes the whole
159
+ * derivation testable from synthetic frames with no renderer, no clock and no
160
+ * game.
161
+ *
162
+ * Returns `true` when the frame was a presentation (the readings moved).
163
+ */
164
+ export declare function foldProfilerFrame(state: RenderVitalsState, frame: PerformanceFrame): boolean;
165
+ /** The provider body — pure over the accumulator. */
166
+ export declare function readRenderVitals(state: RenderVitalsState): RenderVitalsReading;
167
+ /** What {@link createRenderVitals} hands back. */
168
+ export interface RenderVitals {
169
+ /** The `render.vitals` provider body. */
170
+ read(): RenderVitalsReading;
171
+ /** See the module's ownership note — the ONE path that ends the
172
+ * subscription. Idempotent. */
173
+ dispose(): void;
174
+ }
175
+ /**
176
+ * Attach a fold to a live profiler. `subscribe` fires once per published
177
+ * frame (and on enabled/recording changes, which the id dedupe absorbs), so
178
+ * nothing here polls and nothing here owns a timer.
179
+ */
180
+ export declare function createRenderVitals(profiler: PerformanceProfiler): RenderVitals;
181
+ //# sourceMappingURL=render-vitals.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render-vitals.d.ts","sourceRoot":"","sources":["../../src/dev/render-vitals.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAEpF;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB,kBAAkB,CAAC;AAEnD;;;;;;;GAOG;AACH,eAAO,MAAM,UAAU,EAAE,SAAS,MAAM,EAOvC,CAAC;AAEF;0EAC0E;AAC1E,eAAO,MAAM,mBAAmB,MAAM,CAAC;AAEvC;6EAC6E;AAC7E,eAAO,MAAM,kBAAkB,KAAK,CAAC;AAErC,4EAA4E;AAC5E,eAAO,MAAM,oBAAoB,OAAO,CAAC;AAEzC;uEACuE;AACvE,eAAO,MAAM,oBAAoB,MA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AAM,CAAC;IACpB;sDACkD;IAClD,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,uDAAuD;IACvD,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,qDAAqD;IACrD,cAAc,EAAE,MAAM,CAAC;IACvB;uCACmC;IACnC,eAAe,EAAE,MAAM,CAAC;IACxB,sDAAsD;IACtD,iBAAiB,EAAE,MAAM,CAAC;IAC1B,SAAS,EAAE,kBAAkB,GAAG,IAAI,CAAC;IACrC,eAAe,EAAE,MAAM,CAAC;CACzB;AAED,wBAAgB,uBAAuB,IAAI,iBAAiB,CAgB3D;AAoBD;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,iBAAiB,EAAE,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAmD5F;AAQD,qDAAqD;AACrD,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,iBAAiB,GAAG,mBAAmB,CAc9E;AAED,kDAAkD;AAClD,MAAM,WAAW,YAAY;IAC3B,yCAAyC;IACzC,IAAI,IAAI,mBAAmB,CAAC;IAC5B;oCACgC;IAChC,OAAO,IAAI,IAAI,CAAC;CACjB;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,mBAAmB,GAAG,YAAY,CAe9E"}
@@ -0,0 +1,232 @@
1
+ /**
2
+ * LIVE RENDER VITALS — the frame explaining its own cost, derived ENTIRELY
3
+ * from `PerformanceProfiler` frames (`dev/performance-profiler.ts`).
4
+ *
5
+ * Nothing in a viewport tells you why it is slow, and a frame-time number on
6
+ * its own tells you only THAT it is. These readings answer the next question:
7
+ * where did the milliseconds go, and which subtree owns them
8
+ * (`dev/render-census.ts` is the address book half).
9
+ *
10
+ * ── THE MEASUREMENT SOURCE, STATED ONCE ─────────────────────────────────────
11
+ * There is no side ledger here. Every number below is folded out of profiler
12
+ * frames — the timing from phase spans, the counters from `reportRender`. The
13
+ * CPU submission cost is the profiler phase {@link RENDER_SUBMIT_PHASE}, which
14
+ * the three adapter brackets around its actual draw; the profiler's phase
15
+ * bookkeeping is a stack precisely so that bracket can sit INSIDE the frame's
16
+ * enclosing `render` phase without truncating it.
17
+ *
18
+ * ── TWO FRAME FLAVOURS, ONE FOLD ────────────────────────────────────────────
19
+ * The real runtime runs sim and presentation on different callbacks
20
+ * (`create-runtime.ts`: `update` → `runFrame({skipRenderPhases})` per fixed
21
+ * substep, `render` → `runRenderFrame` once per display frame), so a profiler
22
+ * "frame" is EITHER a sim substep OR a presentation pass. A capture/offline
23
+ * host drives one `runFrame` that is both. {@link foldProfilerFrame} handles
24
+ * all three the same way, and never has to know which host it is under:
25
+ *
26
+ * - a frame carrying a {@link RENDER_SUBMIT_PHASE} span IS a presentation —
27
+ * that phase only exists when a draw actually happened;
28
+ * - sim CPU accumulates across every frame since the last presentation, so
29
+ * the substeps a display frame consumed are attributed to it;
30
+ * - renderer COUNTERS ride whichever frame `reportRender` landed on (the
31
+ * adapter reports from its `endFrame` hook, which the substep pass drives),
32
+ * so the latest report wins and the counters describe the last completed
33
+ * draw. That is the same one-frame-warm reading `renderer.info` gives any
34
+ * caller — three resets it when the next draw starts.
35
+ *
36
+ * ── WHY THE WORST FRAME IS NOT AN EMA ───────────────────────────────────────
37
+ * A decaying average keeps a restart spike on the readout for ~30 s, long
38
+ * after it stopped being true. The rolling two-window max
39
+ * ({@link WORST_WINDOW_FRAMES}) holds a hitch for one to two windows and then
40
+ * genuinely forgets it, so the number always describes recent history.
41
+ *
42
+ * ── RESOURCE OWNERSHIP ──────────────────────────────────────────────────────
43
+ * OWNER: the caller of {@link createRenderVitals}, which allocates one state
44
+ * object and one `profiler.subscribe` registration. SHARER: none — the state
45
+ * is private to that call. TEARDOWN: the returned `dispose()`, the ONE path
46
+ * that ends the subscription (`setup-three-root-adapter.ts` calls it from
47
+ * `disposeGame`).
48
+ */
49
+ /**
50
+ * The profiler phase name the three adapter brackets its CPU render
51
+ * submission with — spelled HERE and nowhere else, so the producer
52
+ * (`setup-three-root-adapter.ts`) and the consumer ({@link foldProfilerFrame})
53
+ * cannot drift apart. Dotted, so it reads as a decomposition of the enclosing
54
+ * `render` phase rather than a ninth peer of `SystemPhase`.
55
+ */
56
+ export const RENDER_SUBMIT_PHASE = 'render.submit';
57
+ /**
58
+ * The phases whose cost is SIMULATION. Deliberately not "everything that is
59
+ * not render": `preRender` (LOD selection, particle stepping, culling prep) is
60
+ * neither the simulation nor the submission, so it lands in the hitch's
61
+ * `other` bucket where an investigation can see it. `render` itself is
62
+ * excluded because {@link RENDER_SUBMIT_PHASE} nests inside it — summing both
63
+ * would double-count the draw.
64
+ */
65
+ export const SIM_PHASES = [
66
+ 'input',
67
+ 'prePhysics',
68
+ 'physics',
69
+ 'postPhysics',
70
+ 'gameLogic',
71
+ 'animation',
72
+ ];
73
+ /** Display frames per worst-frame window — ~5 s at 60 Hz, so the reported
74
+ * worst (the max of the current and previous window) survives 5–10 s. */
75
+ export const WORST_WINDOW_FRAMES = 300;
76
+ /** A display frame at or above this is worth decomposing. ~3 dropped frames at
77
+ * 60 Hz: below it, ordinary jitter would rewrite the reading constantly. */
78
+ export const HITCH_THRESHOLD_MS = 50;
79
+ /** Smoothing for the frame-time reading — a readable number, not a blur. */
80
+ export const FRAME_TIME_EMA_ALPHA = 0.05;
81
+ /** Smoothing for the render-CPU reading. Faster than frame time: submission
82
+ * cost is what a draw-call diet moves, and it should visibly move. */
83
+ export const RENDER_CPU_EMA_ALPHA = 0.1;
84
+ /** Split one display frame's wall clock into render / sim / other. Pure. */
85
+ export function decomposeHitch(totalMs, renderMs, simMs) {
86
+ const otherMs = totalMs - renderMs - simMs;
87
+ return {
88
+ totalMs,
89
+ renderMs,
90
+ simMs,
91
+ otherMs,
92
+ text: `${totalMs.toFixed(0)}ms = render ${renderMs.toFixed(0)} + ` +
93
+ `sim ${simMs.toFixed(0)} + other ${otherMs.toFixed(0)}`,
94
+ };
95
+ }
96
+ export function createRenderVitalsState() {
97
+ return {
98
+ lastFrameId: 0,
99
+ lastPresentAt: null,
100
+ pendingSimMs: 0,
101
+ frameTimeMs: null,
102
+ renderCpuMs: null,
103
+ drawCalls: null,
104
+ triangles: null,
105
+ renderPasses: null,
106
+ worstCurrentMs: 0,
107
+ worstPreviousMs: 0,
108
+ worstWindowFrames: 0,
109
+ lastHitch: null,
110
+ presentedFrames: 0,
111
+ };
112
+ }
113
+ /** Sum of one frame's phase timings whose names are in `names`. */
114
+ function sumPhases(frame, names) {
115
+ let total = 0;
116
+ for (const timing of frame.phases)
117
+ if (names.includes(timing.name))
118
+ total += timing.ms;
119
+ return total;
120
+ }
121
+ /** This frame's CPU render submission, or `null` when it was not a
122
+ * presentation (no draw happened, so no bracket was recorded). */
123
+ function submissionMs(frame) {
124
+ for (const timing of frame.phases)
125
+ if (timing.name === RENDER_SUBMIT_PHASE)
126
+ return timing.ms;
127
+ return null;
128
+ }
129
+ function ema(previous, sample, alpha) {
130
+ return previous === null ? sample : previous * (1 - alpha) + sample * alpha;
131
+ }
132
+ /**
133
+ * Fold ONE profiler frame into the accumulator. Pure with respect to time and
134
+ * randomness — every input is on the frame — which is what makes the whole
135
+ * derivation testable from synthetic frames with no renderer, no clock and no
136
+ * game.
137
+ *
138
+ * Returns `true` when the frame was a presentation (the readings moved).
139
+ */
140
+ export function foldProfilerFrame(state, frame) {
141
+ // Re-publishes and the ring's own re-reads must not double-count. Frame ids
142
+ // are monotonic for the profiler's whole life, including across `clear()`.
143
+ if (frame.id <= state.lastFrameId)
144
+ return false;
145
+ state.lastFrameId = frame.id;
146
+ // Counters ride whichever frame `reportRender` landed on — see the module
147
+ // note. `renderPasses !== null` is the marker that a reporter spoke at all;
148
+ // a frame nobody reported on leaves the previous reading standing rather
149
+ // than blanking it to a zero that would read as "nothing is drawn".
150
+ if (frame.render.renderPasses !== null) {
151
+ state.drawCalls = frame.render.drawCalls;
152
+ state.triangles = frame.render.triangles;
153
+ state.renderPasses = frame.render.renderPasses;
154
+ }
155
+ state.pendingSimMs += sumPhases(frame, SIM_PHASES);
156
+ const renderMs = submissionMs(frame);
157
+ if (renderMs === null)
158
+ return false; // a sim substep: its cost is now pending
159
+ const simMs = state.pendingSimMs;
160
+ state.pendingSimMs = 0;
161
+ state.presentedFrames += 1;
162
+ state.renderCpuMs = ema(state.renderCpuMs, renderMs, RENDER_CPU_EMA_ALPHA);
163
+ const previousAt = state.lastPresentAt;
164
+ state.lastPresentAt = frame.timestamp;
165
+ // The FIRST presentation has no interval behind it. Everything that needs a
166
+ // dt (frame time, worst frame, the hitch) waits for the second one; the
167
+ // alternative is to invent an interval from the profiler's own start, which
168
+ // would report the mount cost as a frame time forever.
169
+ if (previousAt === null)
170
+ return true;
171
+ const dt = frame.timestamp - previousAt;
172
+ state.frameTimeMs = ema(state.frameTimeMs, dt, FRAME_TIME_EMA_ALPHA);
173
+ if (dt > state.worstCurrentMs)
174
+ state.worstCurrentMs = dt;
175
+ state.worstWindowFrames += 1;
176
+ if (state.worstWindowFrames >= WORST_WINDOW_FRAMES) {
177
+ state.worstPreviousMs = state.worstCurrentMs;
178
+ state.worstCurrentMs = 0;
179
+ state.worstWindowFrames = 0;
180
+ }
181
+ // Blame the hitch with THIS frame's own measurements: `dt` spans the work
182
+ // between the two presentations, which is exactly the submission just
183
+ // measured plus the substeps that ran in between.
184
+ if (dt >= HITCH_THRESHOLD_MS)
185
+ state.lastHitch = decomposeHitch(dt, renderMs, simMs);
186
+ return true;
187
+ }
188
+ function round(value, places) {
189
+ if (value === null)
190
+ return null;
191
+ const factor = 10 ** places;
192
+ return Math.round(value * factor) / factor;
193
+ }
194
+ /** The provider body — pure over the accumulator. */
195
+ export function readRenderVitals(state) {
196
+ const frameTimeMs = round(state.frameTimeMs, 2);
197
+ const worst = Math.max(state.worstCurrentMs, state.worstPreviousMs);
198
+ return {
199
+ frameTimeMs,
200
+ fps: frameTimeMs !== null && frameTimeMs > 0 ? round(1000 / frameTimeMs, 1) : null,
201
+ drawCalls: state.drawCalls,
202
+ triangles: state.triangles,
203
+ renderCpuMs: round(state.renderCpuMs, 2),
204
+ renderPasses: state.renderPasses,
205
+ worstFrameMs: state.frameTimeMs === null ? null : round(worst, 2),
206
+ lastHitch: state.lastHitch,
207
+ presentedFrames: state.presentedFrames,
208
+ };
209
+ }
210
+ /**
211
+ * Attach a fold to a live profiler. `subscribe` fires once per published
212
+ * frame (and on enabled/recording changes, which the id dedupe absorbs), so
213
+ * nothing here polls and nothing here owns a timer.
214
+ */
215
+ export function createRenderVitals(profiler) {
216
+ const state = createRenderVitalsState();
217
+ const unsubscribe = profiler.subscribe(() => {
218
+ const frame = profiler.getSnapshot().frames.at(-1);
219
+ if (frame)
220
+ foldProfilerFrame(state, frame);
221
+ });
222
+ let disposed = false;
223
+ return {
224
+ read: () => readRenderVitals(state),
225
+ dispose() {
226
+ if (disposed)
227
+ return;
228
+ disposed = true;
229
+ unsubscribe();
230
+ },
231
+ };
232
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * THE ROUTING from a draw-call reading to the one-line fix.
3
+ *
4
+ * `dev/render-vitals.ts` can already tell a game it is submitting 4,000 draws
5
+ * and `dev/render-census.ts` can already say which subtree they are in. Both
6
+ * require someone to ASK, and both require that someone to already know that
7
+ * static batching exists, is possible here, and is spelled `<Frozen>`. An
8
+ * agent building a game does not know any of that, so the measurement has to
9
+ * do the routing itself — the same idiom as the dev-menu's unconfigured-section
10
+ * warning: the reading names the exact edit.
11
+ *
12
+ * ── THE DECISION IS PURE, THE SCHEDULE IS NOT ───────────────────────────────
13
+ * {@link decideStaticBatchAdvisory} takes a draw-call count and two scan
14
+ * reports and answers with an advisory or `null`. It reads no clock, no
15
+ * scene, no console. `dev/register-render-vitals.ts` owns the impure half —
16
+ * when to scan, and warning once — because that is where the profiler
17
+ * subscription already lives.
18
+ *
19
+ * ── COST ────────────────────────────────────────────────────────────────────
20
+ * The scan is TWO walks of the scene graph, once, after the frame rate has
21
+ * settled ({@link ADVISOR_SETTLE_FRAMES}). Never per frame: a walk of 4,000
22
+ * nodes every frame is itself the kind of cost this advisory exists to
23
+ * remove, and the answer does not change from one frame to the next in a world
24
+ * whose scenery is mount-static — which is the only world the advice applies
25
+ * to anyway.
26
+ *
27
+ * ── WHY IT ASKS INSTEAD OF ACTING ───────────────────────────────────────────
28
+ * "These 2,600 meshes are the same draw" is measurable. "These 2,600 meshes
29
+ * never move" is NOT — nothing in a scene graph distinguishes scenery from a
30
+ * thing that will move on the next input. Inferring it and batching anyway is
31
+ * how a batcher freezes a door half-open. So the advisory names the subtree
32
+ * and the wrapper, and the author (who knows) places it.
33
+ */
34
+ import type { CensusReport, StructuralBatchReport } from './render-census';
35
+ /**
36
+ * Draw calls below which no advisory fires, however batchable the scene.
37
+ *
38
+ * The field measurement this capability came out of: ~4,000 draws cost ~11 ms
39
+ * of CPU submission per frame — about 2.75 µs each on a desktop browser. At
40
+ * 500 draws that is ~1.4 ms, roughly 8% of a 60 Hz frame: the first point
41
+ * where halving it is a visible win rather than noise a profiler cannot
42
+ * separate from jitter. Below it, an advisory would be a nag pointing at
43
+ * something that is not costing anything, and a nag that is usually wrong is
44
+ * one nobody reads when it is right.
45
+ */
46
+ export declare const ADVISOR_DRAW_CALL_THRESHOLD = 500;
47
+ /**
48
+ * The share of the draw calls that must be collapsible before the advice is
49
+ * worth an edit. Half: below that, the wrapper leaves most of the cost exactly
50
+ * where it was, and "you could remove a third of a third" is not a payoff
51
+ * anyone should restructure a scene for.
52
+ */
53
+ export declare const ADVISOR_COLLAPSIBLE_SHARE = 0.5;
54
+ /**
55
+ * A subtree must hold at least this share of the collapsible meshes to be
56
+ * named as THE address. Under it the advisory says "across the scene" — an
57
+ * invented address is worse than none, because the reader wraps the wrong
58
+ * group and measures no change.
59
+ */
60
+ export declare const ADVISOR_SUBTREE_SHARE = 0.4;
61
+ /**
62
+ * Presented frames to wait before scanning — ~2 s at 60 Hz. Long enough for
63
+ * asset loads and the first setup pass to finish populating the graph (a scan
64
+ * at frame one measures an empty world and stays silent forever), short enough
65
+ * that the line lands while the author is still looking at the boot.
66
+ */
67
+ export declare const ADVISOR_SETTLE_FRAMES = 120;
68
+ /** The finding, as a caller can present it however it likes. */
69
+ export interface StaticBatchAdvisory {
70
+ /** The reading that triggered it. */
71
+ readonly drawCalls: number;
72
+ /** Meshes sitting in a structural family of two or more. */
73
+ readonly collapsible: number;
74
+ /** The subtree holding most of them, or `null` when they are spread out. */
75
+ readonly subtree: string | null;
76
+ /** The exact edit, ready to paste — `<Frozen name="Terminal">`. */
77
+ readonly fix: string;
78
+ /** The one-line console message: payoff, address, edit, install. */
79
+ readonly message: string;
80
+ }
81
+ export interface StaticBatchAdvisoryInput {
82
+ /** `render.vitals`' own reading. `null` before the first presented frame. */
83
+ readonly drawCalls: number | null;
84
+ /** The one-level census, used only to sanity-check the address against a
85
+ * subtree that genuinely exists in the graph. */
86
+ readonly census: CensusReport;
87
+ /** The STRUCTURAL scan — see `render-census.ts` for why the identity scan
88
+ * cannot answer this. */
89
+ readonly structural: StructuralBatchReport;
90
+ }
91
+ /**
92
+ * Decide whether this frame's cost is worth an advisory, and what it should
93
+ * say. Pure — every input is an argument, and the same arguments always
94
+ * produce the same message.
95
+ */
96
+ export declare function decideStaticBatchAdvisory(input: StaticBatchAdvisoryInput): StaticBatchAdvisory | null;
97
+ /**
98
+ * Emit `advisory` on the console, at most once per page. Answers whether it
99
+ * warned, so a caller can stop scanning.
100
+ */
101
+ export declare function warnStaticBatchAdvisory(advisory: StaticBatchAdvisory,
102
+ /** Injectable so the decision is testable without a console. */
103
+ warn?: (message: string) => void): boolean;
104
+ /** Test-only: forget that the advisory was ever emitted. */
105
+ export declare function __resetStaticBatchAdvisoryForTest(): void;
106
+ //# source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