@vgai/engine 0.5.7 → 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 (62) 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/core/game-scoped-slot.d.ts +14 -0
  10. package/dist/core/game-scoped-slot.d.ts.map +1 -0
  11. package/dist/core/game-scoped-slot.js +24 -0
  12. package/dist/core/seeded-random.d.ts.map +1 -1
  13. package/dist/core/seeded-random.js +3 -2
  14. package/dist/core/sim-clock.d.ts.map +1 -1
  15. package/dist/core/sim-clock.js +3 -2
  16. package/dist/dev/performance-profiler.d.ts +13 -7
  17. package/dist/dev/performance-profiler.d.ts.map +1 -1
  18. package/dist/dev/performance-profiler.js +31 -3
  19. package/dist/dev/register-render-vitals.d.ts +95 -0
  20. package/dist/dev/register-render-vitals.d.ts.map +1 -0
  21. package/dist/dev/register-render-vitals.js +182 -0
  22. package/dist/dev/render-census.d.ts +135 -0
  23. package/dist/dev/render-census.d.ts.map +1 -0
  24. package/dist/dev/render-census.js +257 -0
  25. package/dist/dev/render-vitals.d.ts +181 -0
  26. package/dist/dev/render-vitals.d.ts.map +1 -0
  27. package/dist/dev/render-vitals.js +232 -0
  28. package/dist/dev/static-batch-advisor.d.ts +106 -0
  29. package/dist/dev/static-batch-advisor.d.ts.map +1 -0
  30. package/dist/dev/static-batch-advisor.js +141 -0
  31. package/dist/render/render-batch-system.d.ts.map +1 -1
  32. package/dist/render/render-batch-system.js +7 -18
  33. package/dist/render/structural-signature.d.ts +148 -0
  34. package/dist/render/structural-signature.d.ts.map +1 -0
  35. package/dist/render/structural-signature.js +193 -0
  36. package/dist/runtime/debug-registry.d.ts +2 -2
  37. package/dist/runtime/debug-registry.d.ts.map +1 -1
  38. package/dist/runtime/debug-registry.js +4 -3
  39. package/dist/runtime/dev-layers.d.ts.map +1 -1
  40. package/dist/runtime/dev-layers.js +6 -0
  41. package/dist/runtime/game.js +2 -2
  42. package/dist/runtime/gameplay-rng-trap.d.ts.map +1 -1
  43. package/dist/runtime/gameplay-rng-trap.js +2 -1
  44. package/package.json +1 -1
  45. package/schemas/engine-capabilities.json +5 -5
  46. package/src/adapter/ingest/contract-debug-adapter.ts +110 -0
  47. package/src/adapter/ingest/game-contract.ts +63 -1
  48. package/src/adapter/setup-three-root-adapter.ts +94 -2
  49. package/src/core/game-scoped-slot.ts +28 -0
  50. package/src/core/seeded-random.ts +3 -2
  51. package/src/core/sim-clock.ts +3 -2
  52. package/src/dev/performance-profiler.ts +47 -12
  53. package/src/dev/register-render-vitals.ts +249 -0
  54. package/src/dev/render-census.ts +351 -0
  55. package/src/dev/render-vitals.ts +338 -0
  56. package/src/dev/static-batch-advisor.ts +186 -0
  57. package/src/render/render-batch-system.ts +16 -19
  58. package/src/render/structural-signature.ts +231 -0
  59. package/src/runtime/debug-registry.ts +4 -3
  60. package/src/runtime/dev-layers.ts +7 -1
  61. package/src/runtime/game.ts +2 -2
  62. package/src/runtime/gameplay-rng-trap.ts +4 -2
@@ -0,0 +1,257 @@
1
+ /**
2
+ * THE ADDRESS BOOK behind the render vitals (`dev/render-vitals.ts`): which
3
+ * subtree owns the draw calls, and which meshes are identical enough to
4
+ * instance. A draw-call count with no address is a symptom you cannot act on.
5
+ *
6
+ * Pure functions over a live `THREE.Object3D` — no renderer, no profiler, no
7
+ * game. They are what the `render.census` / `render.families` debug commands
8
+ * run; keeping them here (rather than inline in the adapter) is what lets a
9
+ * headless test build a scene by hand and check the arithmetic.
10
+ *
11
+ * ── WHAT "VISIBLE" MEANS HERE, AND WHY IT IS A WALK ─────────────────────────
12
+ * Visibility in three is HIERARCHICAL: a hidden parent hides its whole
13
+ * subtree, and `Object3D.traverse` cannot prune. So these walk manually and
14
+ * stop descending at an invisible node. That is not a detail — `render.toggle`
15
+ * works by hiding a PARENT, and a census that kept counting the children under
16
+ * it would report that nothing changed.
17
+ *
18
+ * ── TWO FAMILY SCANS, AND WHY BOTH ──────────────────────────────────────────
19
+ * {@link meshFamilies} keys on object IDENTITY: meshes sharing one geometry
20
+ * instance and one material instance (`uuid`) — exactly the precondition for
21
+ * collapsing them into a bare `InstancedMesh` as they stand. It deliberately
22
+ * does not compare material PARAMETERS.
23
+ *
24
+ * {@link structuralBatchScan} keys on STRUCTURE (`render/structural-
25
+ * signature.ts`): meshes that are the same DRAW, however many distinct
26
+ * material objects describe it. A project that writes a material per mesh —
27
+ * which is what inline `<meshStandardMaterial>` in a TSX world does, i.e. what
28
+ * every fresh scaffold does — reads as all families-of-one under the first
29
+ * scan and as one big collapsible family under the second. Both readings are
30
+ * true; they answer different questions, and only the second one routes an
31
+ * author to the fix (`dev/static-batch-advisor.ts`).
32
+ *
33
+ * Nothing here assumes a project interns its materials or that its world is
34
+ * static — the STATIC half is a claim only the author can make, which is why
35
+ * the advisory asks rather than acts.
36
+ */
37
+ import { materialMergeSignature, staticBatchSkipReason } from '../render/structural-signature';
38
+ /** How many rows a census/family report carries. A shortlist is actionable;
39
+ * a full dump through a JSON relay is a wall of text nobody reads. */
40
+ export const CENSUS_ROW_LIMIT = 40;
41
+ export const FAMILY_ROW_LIMIT = 30;
42
+ function asMesh(node) {
43
+ const mesh = node;
44
+ return mesh.isMesh || mesh.isSkinnedMesh ? mesh : null;
45
+ }
46
+ /** Triangles one mesh submits: its geometry's own count times its instance
47
+ * count. Non-indexed geometry falls back to the position attribute; a
48
+ * geometry with neither contributes 0 rather than a guess. */
49
+ function triangleCount(mesh) {
50
+ const geometry = mesh.geometry;
51
+ if (!geometry)
52
+ return 0;
53
+ const index = geometry.getIndex?.() ?? null;
54
+ const position = geometry.getAttribute?.('position') ?? null;
55
+ const vertices = index ? index.count : (position?.count ?? 0);
56
+ const instances = mesh.isInstancedMesh ? (mesh.count ?? 1) : 1;
57
+ return Math.round(vertices / 3) * instances;
58
+ }
59
+ /** Walk `node` and its visible descendants, calling `visit` for every visible
60
+ * mesh. Stops at an invisible node — see the module note. */
61
+ function walkVisibleMeshes(node, visit) {
62
+ if (!node.visible)
63
+ return;
64
+ const mesh = asMesh(node);
65
+ if (mesh)
66
+ visit(mesh);
67
+ for (const child of node.children)
68
+ walkVisibleMeshes(child, visit);
69
+ }
70
+ const UNNAMED = '(unnamed)';
71
+ /**
72
+ * Tally visible meshes and triangles per direct child of `root`. Pure.
73
+ *
74
+ * One level, deliberately: the report is a set of addresses to drill into
75
+ * with the same command, and a recursive dump is not something you can act on
76
+ * one step at a time. `root` itself contributes its own meshes under its own
77
+ * name when it has any.
78
+ */
79
+ export function sceneCensus(root, rootLabel = '(scene)') {
80
+ const rows = new Map();
81
+ let totalMeshes = 0;
82
+ let totalTriangles = 0;
83
+ if (!root.visible) {
84
+ return { root: rootLabel, totalMeshes: 0, totalTriangles: 0, subtreeCount: 0, subtrees: [] };
85
+ }
86
+ const tally = (key, node) => {
87
+ walkVisibleMeshes(node, (mesh) => {
88
+ const triangles = triangleCount(mesh);
89
+ const row = rows.get(key) ?? { meshes: 0, triangles: 0 };
90
+ row.meshes += 1;
91
+ row.triangles += triangles;
92
+ rows.set(key, row);
93
+ totalMeshes += 1;
94
+ totalTriangles += triangles;
95
+ });
96
+ };
97
+ // `root`'s own mesh, if it is one, is charged to `root` — not silently
98
+ // dropped because the grouping key is "direct child".
99
+ const selfMesh = asMesh(root);
100
+ if (selfMesh) {
101
+ const triangles = triangleCount(selfMesh);
102
+ rows.set(root.name || rootLabel, { meshes: 1, triangles });
103
+ totalMeshes += 1;
104
+ totalTriangles += triangles;
105
+ }
106
+ for (const child of root.children)
107
+ tally(child.name || UNNAMED, child);
108
+ const sorted = [...rows.entries()]
109
+ .map(([name, row]) => ({ name, meshes: row.meshes, triangles: row.triangles }))
110
+ .sort((a, b) => b.triangles - a.triangles || b.meshes - a.meshes);
111
+ return {
112
+ root: rootLabel,
113
+ totalMeshes,
114
+ totalTriangles,
115
+ subtreeCount: sorted.length,
116
+ subtrees: sorted.slice(0, CENSUS_ROW_LIMIT),
117
+ };
118
+ }
119
+ /** First node named `name` in `root`'s subtree, or `null`. Depth-first, so the
120
+ * shallowest match under an ordinary hierarchy wins. */
121
+ export function findByName(root, name) {
122
+ if (root.name === name)
123
+ return root;
124
+ for (const child of root.children) {
125
+ const hit = findByName(child, name);
126
+ if (hit)
127
+ return hit;
128
+ }
129
+ return null;
130
+ }
131
+ /** Group visible non-instanced meshes by (geometry, material) identity. Pure.
132
+ * See the module note for what identity does and does not assume. */
133
+ export function meshFamilies(root) {
134
+ const families = new Map();
135
+ let plainMeshes = 0;
136
+ walkVisibleMeshes(root, (mesh) => {
137
+ if (mesh.isInstancedMesh)
138
+ return;
139
+ const geometry = mesh.geometry;
140
+ if (!geometry)
141
+ return;
142
+ const material = mesh.material;
143
+ const materialKey = Array.isArray(material)
144
+ ? material.map((entry) => entry.uuid).join('+')
145
+ : (material?.uuid ?? 'none');
146
+ const key = `${geometry.uuid}/${materialKey}`;
147
+ plainMeshes += 1;
148
+ const existing = families.get(key);
149
+ if (existing) {
150
+ existing.meshes += 1;
151
+ return;
152
+ }
153
+ families.set(key, {
154
+ meshes: 1,
155
+ triangles: triangleCount(mesh),
156
+ example: `${mesh.parent?.name || UNNAMED}/${mesh.name || UNNAMED}`,
157
+ });
158
+ });
159
+ const sorted = [...families.values()].sort((a, b) => b.meshes - a.meshes);
160
+ const top = sorted.slice(0, FAMILY_ROW_LIMIT);
161
+ return {
162
+ plainMeshes,
163
+ familyCount: sorted.length,
164
+ top,
165
+ meshesInTop: top.reduce((total, row) => total + row.meshes, 0),
166
+ };
167
+ }
168
+ /**
169
+ * Group visible meshes by STRUCTURAL identity — the same key the batchers use
170
+ * (`render/structural-signature.ts`), so this measures what `<Frozen>` would
171
+ * actually do rather than what a uuid comparison can see.
172
+ *
173
+ * This is the companion to {@link meshFamilies}, not a replacement, and the
174
+ * difference between the two is the finding: `meshFamilies` asks "which meshes
175
+ * SHARE a geometry and material object", which is what a bare `InstancedMesh`
176
+ * needs; this asks "which meshes are the same draw", which is what a merging
177
+ * batcher needs. On a freshly scaffolded world writing inline materials the
178
+ * first reports families of one and the second reports the win — see the uuid
179
+ * trap in `render/structural-signature.ts`.
180
+ *
181
+ * Pure. One walk, plus a tally.
182
+ */
183
+ export function structuralBatchScan(root) {
184
+ const families = new Map();
185
+ const skipped = {};
186
+ // Which subtree each candidate sits under, kept per mesh so attribution can
187
+ // wait until the families are known (a family of one is not collapsible, and
188
+ // charging its member to a subtree would inflate that subtree's row).
189
+ const members = [];
190
+ let plainMeshes = 0;
191
+ /** One node, no recursion. Answers `false` when its subtree must be pruned. */
192
+ const visit = (node, subtree) => {
193
+ if (!node.visible)
194
+ return false;
195
+ const reason = staticBatchSkipReason(node);
196
+ if (reason === 'opted-out') {
197
+ skipped['opted-out'] = (skipped['opted-out'] ?? 0) + 1;
198
+ return false; // an opt-out covers its whole subtree
199
+ }
200
+ if (reason === null) {
201
+ const mesh = node;
202
+ const material = mesh.material;
203
+ const key = `${materialMergeSignature(material)}|${node.castShadow ? 1 : 0}${node.receiveShadow ? 1 : 0}`;
204
+ plainMeshes += 1;
205
+ members.push({ key, subtree });
206
+ const existing = families.get(key);
207
+ if (existing)
208
+ existing.meshes += 1;
209
+ else {
210
+ families.set(key, {
211
+ meshes: 1,
212
+ triangles: triangleCount(mesh),
213
+ example: `${node.parent?.name || UNNAMED}/${node.name || UNNAMED}`,
214
+ });
215
+ }
216
+ }
217
+ else if (reason !== 'not-a-mesh') {
218
+ skipped[reason] = (skipped[reason] ?? 0) + 1;
219
+ }
220
+ return true;
221
+ };
222
+ const scan = (node, subtree) => {
223
+ if (!visit(node, subtree))
224
+ return;
225
+ for (const child of node.children)
226
+ scan(child, subtree);
227
+ };
228
+ // `root`'s own mesh, if it is one, is charged to `root` — the same rule
229
+ // `sceneCensus` uses, so the two reports address the same graph.
230
+ if (visit(root, root.name || UNNAMED)) {
231
+ for (const child of root.children)
232
+ scan(child, child.name || UNNAMED);
233
+ }
234
+ const collapsibleKeys = new Set([...families.entries()].filter(([, family]) => family.meshes >= 2).map(([key]) => key));
235
+ const perSubtree = new Map();
236
+ let collapsible = 0;
237
+ for (const member of members) {
238
+ if (!collapsibleKeys.has(member.key))
239
+ continue;
240
+ collapsible += 1;
241
+ perSubtree.set(member.subtree, (perSubtree.get(member.subtree) ?? 0) + 1);
242
+ }
243
+ const sorted = [...families.values()].sort((a, b) => b.meshes - a.meshes);
244
+ const top = sorted.slice(0, FAMILY_ROW_LIMIT);
245
+ return {
246
+ plainMeshes,
247
+ familyCount: sorted.length,
248
+ top,
249
+ meshesInTop: top.reduce((total, row) => total + row.meshes, 0),
250
+ collapsible,
251
+ skipped,
252
+ bySubtree: [...perSubtree.entries()]
253
+ .map(([name, count]) => ({ name, collapsible: count }))
254
+ .sort((a, b) => b.collapsible - a.collapsible)
255
+ .slice(0, CENSUS_ROW_LIMIT),
256
+ };
257
+ }
@@ -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;;;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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
+ }