@babylonjs-toolkit/agent 1.1.54 → 1.1.55

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.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * bt-combine browser check: loads each exported scene in the toolkit's player page (headless Chrome), captures the
2
+ * bt-optimize browser check: loads each exported scene in the toolkit's player page (headless Chrome), captures the
3
3
  * same moments after load, and records console errors and load time. Comparing captures of the source scene and the
4
4
  * combined scene at the same moment shows whether a merge changed what the player sees (time-driven flythroughs land
5
5
  * on the same frame within a second or so; capture a burst to line them up).
@@ -0,0 +1,80 @@
1
+ /**
2
+ * bt-optimize report table: compares profile-browser.mjs runs of the same views (pinned with --poses, or timeline
3
+ * runs with the same --times) and prints a Markdown table — FPS, frame times, draws per pass, active meshes.
4
+ *
5
+ * Usage:
6
+ * node compare-profiles.mjs --label Original,Optimized before-pinned.json after-pinned.json [more.json …]
7
+ */
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+
11
+ /**
12
+ * Reads `--name value` pairs and positional file arguments.
13
+ * @param {string[]} argv - process.argv.slice(2)
14
+ * @returns {{flags: Record<string, string>, files: string[]}}
15
+ */
16
+ function parseArguments(argv) {
17
+ const flags = {};
18
+ const files = [];
19
+ for (let i = 0; i < argv.length; i++) {
20
+ if (argv[i].startsWith("--")) flags[argv[i].slice(2)] = argv[++i];
21
+ else files.push(argv[i]);
22
+ }
23
+ return { flags, files };
24
+ }
25
+
26
+ /** Formats a number change as "a → b (±x%)". */
27
+ function change(before, after, digits = 0) {
28
+ if (before == null || after == null) return "—";
29
+ const percent = before !== 0 ? Math.round(((after - before) / before) * 100) : 0;
30
+ return `${before.toFixed(digits)} → **${after.toFixed(digits)}** (${percent >= 0 ? "+" : ""}${percent}%)`;
31
+ }
32
+
33
+ /** Entry point. */
34
+ function main() {
35
+ const { flags, files } = parseArguments(process.argv.slice(2));
36
+ if (files.length < 2) throw new Error("Pass at least two profile JSON files (before, after).");
37
+ const runs = files.map((file) => JSON.parse(fs.readFileSync(path.resolve(file), "utf8")));
38
+ const labels = (flags.label || "").split(",").filter(Boolean);
39
+ const name = (index) => labels[index] || path.basename(files[index], ".json");
40
+ const lines = [];
41
+
42
+ lines.push(`| | ${runs.map((_, i) => name(i)).join(" | ")} |`);
43
+ lines.push(`|---|${runs.map(() => "---").join("|")}|`);
44
+ const census = (key) => runs.map((run) => (run.census ? run.census[key] : "")).join(" | ");
45
+ lines.push(`| Meshes | ${census("meshes")} |`);
46
+ lines.push(`| Materials | ${census("materials")} |`);
47
+ lines.push(`| Lights / shadow generators | ${runs.map((run) => run.census ? `${run.census.lights.length} / ${run.census.shadows.length}` : "").join(" | ")} |`);
48
+ lines.push(`| Post passes | ${census("postProcesses")} |`);
49
+ lines.push("");
50
+
51
+ const first = runs[0], last = runs[runs.length - 1];
52
+ if (first.pins && last.pins) {
53
+ lines.push(`| View | FPS | p50 frame ms | p95 frame ms | Draws / frame | Shadow-map draws | Depth / other target draws | Main-pass draws | Active meshes |`);
54
+ lines.push(`|---|---|---|---|---|---|---|---|---|`);
55
+ for (const pin of first.pins) {
56
+ const other = last.pins.find((candidate) => candidate.atSeconds === pin.atSeconds);
57
+ if (!other) continue;
58
+ const a = pin.baseline, b = other.baseline;
59
+ lines.push(`| ${pin.atSeconds} s @ ${pin.pinned.position ? pin.pinned.position.map((v) => v.toFixed(1)).join(",") : pin.pinned} | ${change(a.fps, b.fps, 1)} | ${change(a.p50Ms, b.p50Ms, 1)} | ${change(a.p95Ms, b.p95Ms, 1)} | ${change(a.drawCalls, b.drawCalls)} | ${change(a.passes.shadowMaps, b.passes.shadowMaps)} | ${change(a.passes.otherTargets, b.passes.otherTargets)} | ${change(a.passes.main, b.passes.main)} | ${change(a.activeMeshes, b.activeMeshes)} |`);
60
+ }
61
+ lines.push("");
62
+ }
63
+ if (first.samples && last.samples) {
64
+ lines.push(`| Timeline | FPS | p95 frame ms | Worst frame ms | Draws / frame |`);
65
+ lines.push(`|---|---|---|---|---|`);
66
+ for (const sample of first.samples) {
67
+ const other = last.samples.find((candidate) => candidate.atSeconds === sample.atSeconds);
68
+ if (!other) continue;
69
+ lines.push(`| ${sample.atSeconds} s | ${change(sample.fps, other.fps, 1)} | ${change(sample.p95Ms, other.p95Ms)} | ${change(sample.worstMs, other.worstMs)} | ${change(sample.drawCalls, other.drawCalls)} |`);
70
+ }
71
+ const mean = (run, key) => run.samples.reduce((sum, s) => sum + s[key], 0) / run.samples.length;
72
+ const worst = (run) => Math.max(...run.samples.map((s) => s.worstMs));
73
+ lines.push(`| **Average / worst** | ${change(mean(first, "fps"), mean(last, "fps"), 1)} | ${change(mean(first, "p95Ms"), mean(last, "p95Ms"))} | ${change(worst(first), worst(last))} | ${change(mean(first, "drawCalls"), mean(last, "drawCalls"))} |`);
74
+ lines.push("");
75
+ lines.push("Timeline rows are moments after load; a lighter scene loads sooner, so its tour can be ahead — compare pinned views for like-for-like numbers.");
76
+ }
77
+ process.stdout.write(lines.join("\n") + "\n");
78
+ }
79
+
80
+ main();
@@ -1,5 +1,5 @@
1
1
  /**
2
- * bt-combine export stats: compares exported .gltf scenes — drawn mesh nodes, meshes, primitives (draw calls before
2
+ * bt-optimize export stats: compares exported .gltf scenes — drawn mesh nodes, meshes, primitives (draw calls before
3
3
  * LOD selection), materials, textures, drawn vertices and the size on disk of the .gltf plus its buffers.
4
4
  *
5
5
  * Usage:
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "bt-optimize-qa",
3
+ "private": true,
4
+ "type": "module",
5
+ "description": "Browser profiling, comparison and glTF checks for the bt-optimize skill. Installed into <project>/.agents/optimize/.qa-tools, never into the Unity project's own package.json.",
6
+ "dependencies": {
7
+ "puppeteer-core": "23.11.1"
8
+ }
9
+ }
@@ -0,0 +1,547 @@
1
+ /**
2
+ * bt-optimize browser profiler: loads one exported scene in the toolkit's player page (engine.html), samples frame rate
3
+ * and render statistics at moments along the scene's own timeline, then turns off one runtime cost at a time (device
4
+ * pixel ratio, shadows, post-processing, realtime reflection probes) and measures again. The deltas say which cost
5
+ * dominates the frame, so the fix goes where the time actually goes rather than where it is guessed to go.
6
+ *
7
+ * Usage:
8
+ * node profile-browser.mjs --base http://localhost:8888 --scene level.gltf --times 15,30,45 --out ./profile.json
9
+ * node profile-browser.mjs --scene level.gltf --pin 20,35 --toggles dpr,taa,motionblur,bloom,post,shadows,lights
10
+ * node profile-browser.mjs --scene optimized.gltf --poses ./before-pinned.json --toggles none (same views as an earlier run)
11
+ * [--headed true] [--dpr 2] [--window 3] [--settle 4] [--shots ./shots] [--cpuprofile true] [--toggles none]
12
+ */
13
+ import fs from "node:fs";
14
+ import os from "node:os";
15
+ import path from "node:path";
16
+ import puppeteer from "puppeteer-core";
17
+
18
+ /** Default sample moments, in seconds after the scene reports it is ready. */
19
+ const DEFAULT_TIMES = "10,20,30,45";
20
+
21
+ /** Seconds of rendering each sample averages over. */
22
+ const DEFAULT_WINDOW_SECONDS = 3;
23
+
24
+ /** How long to wait for the scene to finish loading, in milliseconds. */
25
+ const READY_TIMEOUT_MS = 600000;
26
+
27
+ /**
28
+ * Reads `--name value` pairs from the command line.
29
+ * @param {string[]} argv - process.argv.slice(2)
30
+ * @returns {Record<string, string>} the parsed flags
31
+ */
32
+ function parseArguments(argv) {
33
+ const flags = {};
34
+ for (let i = 0; i < argv.length; i += 2) {
35
+ flags[argv[i].replace(/^--/, "")] = argv[i + 1];
36
+ }
37
+ return flags;
38
+ }
39
+
40
+ /**
41
+ * Finds a Chrome or Chromium executable: CHROME_PATH, the usual install locations, then puppeteer's own cache.
42
+ * @returns {string} absolute path of the browser executable
43
+ * @throws {Error} when no browser can be found
44
+ */
45
+ function findChrome() {
46
+ const candidates = [
47
+ process.env.CHROME_PATH,
48
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
49
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
50
+ "/usr/bin/google-chrome",
51
+ "/usr/bin/chromium",
52
+ "/usr/bin/chromium-browser",
53
+ "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
54
+ "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
55
+ ].filter(Boolean);
56
+ const found = candidates.find((candidate) => fs.existsSync(candidate));
57
+ if (found) return found;
58
+ const cacheRoot = path.join(os.homedir(), ".cache", "puppeteer", "chrome");
59
+ if (fs.existsSync(cacheRoot)) {
60
+ for (const version of fs.readdirSync(cacheRoot)) {
61
+ const cached = [
62
+ path.join(cacheRoot, version, "chrome-mac-arm64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"),
63
+ path.join(cacheRoot, version, "chrome-linux64", "chrome"),
64
+ path.join(cacheRoot, version, "chrome-win64", "chrome.exe"),
65
+ ].find((candidate) => fs.existsSync(candidate));
66
+ if (cached) return cached;
67
+ }
68
+ }
69
+ throw new Error("No Chrome found. Set CHROME_PATH to a Chrome or Chromium executable.");
70
+ }
71
+
72
+ /**
73
+ * Runs inside the page: installs the frame sampler and the static scene census on window.__btProfile.
74
+ * Kept self-contained because puppeteer serialises it into the page.
75
+ */
76
+ function installProbe() {
77
+ const state = { frames: [], recording: false };
78
+ window.__btProfile = state;
79
+
80
+ /** @returns {any} the toolkit's scene, once one exists */
81
+ state.scene = () => (window.BABYLON && BABYLON.EngineStore && BABYLON.EngineStore.LastCreatedScene) || null;
82
+
83
+ /** Starts recording frame timestamps and per-frame counters. */
84
+ state.start = () => {
85
+ const scene = state.scene();
86
+ state.frames = [];
87
+ state.recording = true;
88
+ if (!state.instrumentation) {
89
+ state.instrumentation = new BABYLON.SceneInstrumentation(scene);
90
+ state.instrumentation.captureFrameTime = true;
91
+ state.instrumentation.captureActiveMeshesEvaluationTime = true;
92
+ state.instrumentation.captureRenderTargetsRenderTime = true;
93
+ state.instrumentation.captureRenderTime = true;
94
+ state.observer = scene.onAfterRenderObservable.add(() => {
95
+ if (!state.recording) return;
96
+ const engine = scene.getEngine();
97
+ const instrumentation = state.instrumentation;
98
+ const drawCalls = (engine._drawCalls && engine._drawCalls.current) || (instrumentation.drawCallsCounter && instrumentation.drawCallsCounter.current) || 0;
99
+ state.frames.push({
100
+ t: performance.now(),
101
+ drawCalls,
102
+ activeMeshes: scene.getActiveMeshes().length,
103
+ activeIndices: scene.getActiveIndices(),
104
+ evaluateMs: instrumentation.activeMeshesEvaluationTimeCounter.current,
105
+ targetsMs: instrumentation.renderTargetsRenderTimeCounter.current,
106
+ renderMs: instrumentation.renderTimeCounter.current,
107
+ frameMs: instrumentation.frameTimeCounter.current,
108
+ });
109
+ });
110
+ }
111
+ };
112
+
113
+ /** Stops recording and returns the window's summary. */
114
+ state.stop = () => {
115
+ state.recording = false;
116
+ const frames = state.frames;
117
+ if (frames.length < 2) return { frames: frames.length };
118
+ const intervals = [];
119
+ for (let i = 1; i < frames.length; i++) intervals.push(frames[i].t - frames[i - 1].t);
120
+ intervals.sort((first, second) => first - second);
121
+ const average = (key) => frames.reduce((sum, frame) => sum + frame[key], 0) / frames.length;
122
+ const seconds = (frames[frames.length - 1].t - frames[0].t) / 1000;
123
+ const camera = state.scene().activeCamera;
124
+ const watch = state.targetWatch;
125
+ const perFrame = (key) => (watch && watch.frames ? Math.round(watch[key] / watch.frames) : null);
126
+ const passes = { shadowMaps: perFrame("shadow"), otherTargets: perFrame("targets"), main: perFrame("main"), afterMain: perFrame("after") };
127
+ const byTarget = {};
128
+ if (watch && watch.frames) for (const [key, entry] of Object.entries(watch.byTarget)) byTarget[key] = { drawsPerFrame: Math.round(entry.draws / watch.frames), rendersPerFrame: +(entry.renders / watch.frames).toFixed(2) };
129
+ if (watch) { watch.shadow = watch.targets = watch.main = watch.after = watch.frames = 0; watch.byTarget = {}; }
130
+ return {
131
+ passes,
132
+ byTarget,
133
+ fps: +((frames.length - 1) / seconds).toFixed(1),
134
+ p50Ms: +intervals[Math.floor(intervals.length * 0.5)].toFixed(1),
135
+ p95Ms: +intervals[Math.floor(intervals.length * 0.95)].toFixed(1),
136
+ worstMs: +intervals[intervals.length - 1].toFixed(1),
137
+ drawCalls: Math.round(average("drawCalls")),
138
+ activeMeshes: Math.round(average("activeMeshes")),
139
+ activeTriangles: Math.round(average("activeIndices") / 3),
140
+ cpuEvaluateMs: +average("evaluateMs").toFixed(2),
141
+ cpuRenderTargetsMs: +average("targetsMs").toFixed(2),
142
+ cpuRenderMs: +average("renderMs").toFixed(2),
143
+ cpuFrameMs: +average("frameMs").toFixed(2),
144
+ camera: camera ? [camera.globalPosition.x, camera.globalPosition.y, camera.globalPosition.z].map((v) => +v.toFixed(1)) : null,
145
+ };
146
+ };
147
+
148
+ /** Static census of what the scene asks the GPU to do every frame. */
149
+ state.census = () => {
150
+ const scene = state.scene();
151
+ const engine = scene.getEngine();
152
+ const shadows = [];
153
+ for (const light of scene.lights) {
154
+ const generator = light.getShadowGenerator && light.getShadowGenerator();
155
+ if (!generator) continue;
156
+ const map = generator.getShadowMap();
157
+ shadows.push({
158
+ light: light.name,
159
+ type: light.getClassName(),
160
+ enabled: light.isEnabled(),
161
+ mapSize: map ? map.getSize().width : 0,
162
+ cascades: generator.numCascades || 1,
163
+ casters: map && map.renderList ? map.renderList.length : -1,
164
+ refreshRate: map ? map.refreshRate : -1,
165
+ });
166
+ }
167
+ let textureBytes = 0;
168
+ for (const texture of scene.textures) {
169
+ const size = texture.getSize ? texture.getSize() : { width: 0, height: 0 };
170
+ textureBytes += size.width * size.height * 4 * (texture.isCube ? 6 : 1) * 1.33;
171
+ }
172
+ const meshes = scene.meshes;
173
+ const drawn = meshes.filter((mesh) => mesh.getTotalVertices && mesh.getTotalVertices() > 0);
174
+ const lights = scene.lights.map((light) => ({ name: light.name, type: light.getClassName(), enabled: light.isEnabled(), intensity: +light.intensity.toFixed(2) }));
175
+ const renderTargets = scene.customRenderTargets.map((target) => ({ name: target.name, size: target.getSize().width, list: target.renderList ? target.renderList.length : -1, refreshRate: target.refreshRate }));
176
+ const probes = (scene.reflectionProbes || []).map((probe) => ({ name: probe.name, size: probe.cubeTexture.getSize().width, list: probe.renderList.length, refreshRate: probe.refreshRate }));
177
+ const materialsByClass = {};
178
+ for (const material of scene.materials) materialsByClass[material.getClassName()] = (materialsByClass[material.getClassName()] || 0) + 1;
179
+ return {
180
+ engine: engine.isWebGPU ? "WebGPU" : "WebGL" + engine.webGLVersion,
181
+ adapter: engine.getGlInfo ? engine.getGlInfo().renderer : "",
182
+ hardwareScaling: engine.getHardwareScalingLevel(),
183
+ renderSize: [engine.getRenderWidth(), engine.getRenderHeight()],
184
+ devicePixelRatio: window.devicePixelRatio,
185
+ snapshotRendering: engine.snapshotRendering === true,
186
+ meshes: meshes.length,
187
+ drawnMeshes: drawn.length,
188
+ instancedMeshes: meshes.filter((mesh) => mesh.getClassName() === "InstancedMesh").length,
189
+ thinInstanced: drawn.filter((mesh) => mesh.thinInstanceCount > 0).length,
190
+ frozenWorldMatrices: drawn.filter((mesh) => mesh.isWorldMatrixFrozen).length,
191
+ totalVertices: scene.getTotalVertices(),
192
+ materials: scene.materials.length,
193
+ materialsByClass,
194
+ textures: scene.textures.length,
195
+ textureMegabytesEstimate: Math.round(textureBytes / 1048576),
196
+ lights,
197
+ shadows,
198
+ renderTargets,
199
+ reflectionProbes: probes,
200
+ postProcesses: scene.postProcesses.length + (scene.activeCamera ? scene.activeCamera._postProcesses.filter(Boolean).length : 0),
201
+ postProcessNames: scene.activeCamera ? scene.activeCamera._postProcesses.filter(Boolean).map((p) => p.name) : [],
202
+ skipFrustumClipping: scene.skipFrustumClipping === true,
203
+ prePassRenderer: !!(scene.prePassRenderer && scene.prePassRenderer.enabled),
204
+ geometryBufferRenderer: !!(scene.geometryBufferRenderer && scene.geometryBufferRenderer.enabled !== false),
205
+ renderQuality: (window.TOOLKIT && TOOLKIT.SceneManager && TOOLKIT.SceneManager.GetRenderQuality) ? TOOLKIT.SceneManager.GetRenderQuality() : null,
206
+ activeMeshesFrozen: scene._activeMeshesFrozen === true,
207
+ };
208
+ };
209
+
210
+ /**
211
+ * Pins the active camera at its current world pose: detaches it from its rig so whatever animates the rig
212
+ * (a Timeline, a controller) no longer moves the view, keeping its post-processes attached.
213
+ * @returns {number[]} the pinned position
214
+ */
215
+ state.pin = () => {
216
+ const camera = state.scene().activeCamera;
217
+ const scale = new BABYLON.Vector3(), rotation = new BABYLON.Quaternion(), position = new BABYLON.Vector3();
218
+ camera.computeWorldMatrix(true).decompose(scale, rotation, position);
219
+ camera.parent = null;
220
+ camera.position.copyFrom(position);
221
+ camera.rotationQuaternion = rotation;
222
+ if (camera.inputs) camera.inputs.clear();
223
+ state.lockLens(camera, { fov: camera.fov, fovMode: camera.fovMode, minZ: camera.minZ, maxZ: camera.maxZ });
224
+ // The lens is part of the view: Timeline / Cinemachine tracks animate the field of view too.
225
+ return { position: [position.x, position.y, position.z].map((v) => +v.toFixed(4)), rotation: [rotation.x, rotation.y, rotation.z, rotation.w].map((v) => +v.toFixed(6)),
226
+ fov: +camera.fov.toFixed(6), fovMode: camera.fovMode, minZ: camera.minZ, maxZ: camera.maxZ };
227
+ };
228
+
229
+ /** The active camera's current world pose and lens, to prove a pinned view did not drift. */
230
+ state.actualPose = () => {
231
+ const camera = state.scene().activeCamera;
232
+ const p = camera.globalPosition;
233
+ return { camera: camera.name, position: [p.x, p.y, p.z].map((v) => +v.toFixed(3)), fov: +camera.fov.toFixed(4), parent: camera.parent ? camera.parent.name : null };
234
+ };
235
+
236
+ /** Holds the camera's lens before every render, so an animation track that writes the field of view cannot change the view. */
237
+ state.lockLens = (camera, lens) => {
238
+ state.lens = lens;
239
+ // A Timeline / Cinemachine lens track keeps writing the field of view every frame, and TAA builds its jittered
240
+ // projection from it before any render observer could restore ours — so the lens fields become read-only.
241
+ for (const key of ["fov", "fovMode", "minZ", "maxZ"]) {
242
+ Object.defineProperty(camera, key, { configurable: true, enumerable: true, get: () => state.lens[key], set: () => {} });
243
+ }
244
+ camera.getProjectionMatrix(true);
245
+ };
246
+
247
+ /** Pins the active camera at a pose recorded by an earlier run (same view in a different export). */
248
+ state.pose = (pose) => {
249
+ state.pin();
250
+ const camera = state.scene().activeCamera;
251
+ camera.position.copyFromFloats(pose.position[0], pose.position[1], pose.position[2]);
252
+ camera.rotationQuaternion = new BABYLON.Quaternion(pose.rotation[0], pose.rotation[1], pose.rotation[2], pose.rotation[3]);
253
+ if (pose.fov != null) state.lockLens(camera, { fov: pose.fov, fovMode: pose.fovMode, minZ: pose.minZ, maxZ: pose.maxZ });
254
+ camera.computeWorldMatrix(true);
255
+ return pose;
256
+ };
257
+
258
+ /**
259
+ * Splits each frame's draw calls by pass, read from the engine's running draw counter: shadow maps, other render
260
+ * targets before the main pass (geometry / velocity buffers for motion blur, TAA, SSAO; realtime probes), the main
261
+ * camera pass, and everything after it (post-processes, GUI).
262
+ */
263
+ state.watchTargets = () => {
264
+ const scene = state.scene();
265
+ const engine = scene.getEngine();
266
+ const counter = engine._drawCalls;
267
+ if (!counter || state.targetWatch) return;
268
+ const watch = state.targetWatch = { shadow: 0, targets: 0, main: 0, after: 0, frames: 0 };
269
+ let frameStart = 0, mainStart = 0, mainEnd = 0, shadowFrame = 0;
270
+ const hookShadowMaps = () => {
271
+ for (const light of scene.lights) {
272
+ const generator = light.getShadowGenerator && light.getShadowGenerator();
273
+ const map = generator && generator.getShadowMap();
274
+ if (!map || map.__btHooked) continue;
275
+ map.__btHooked = true;
276
+ let before = 0;
277
+ map.onBeforeRenderObservable.add(() => { before = counter._current; });
278
+ map.onAfterRenderObservable.add(() => { shadowFrame += counter._current - before; });
279
+ }
280
+ };
281
+ hookShadowMaps();
282
+ // Attribute every render-target pass to its target by name (shadow maps, depth / velocity / geometry buffers,
283
+ // realtime probes, mirrors): wraps RenderTargetTexture.render once per page.
284
+ watch.byTarget = {};
285
+ const proto = BABYLON.RenderTargetTexture.prototype;
286
+ if (!proto.__btWrapped) {
287
+ proto.__btWrapped = true;
288
+ const original = proto.render;
289
+ proto.render = function (...args) {
290
+ const before = counter._current;
291
+ const result = original.apply(this, args);
292
+ if (state.recording && state.targetWatch) {
293
+ const key = (this.name || this.getClassName()).replace(/[0-9]+/g, "#");
294
+ const entry = state.targetWatch.byTarget[key] || (state.targetWatch.byTarget[key] = { draws: 0, renders: 0 });
295
+ entry.draws += counter._current - before;
296
+ entry.renders++;
297
+ }
298
+ return result;
299
+ };
300
+ }
301
+ scene.onBeforeRenderObservable.add(() => { frameStart = counter._current; shadowFrame = 0; hookShadowMaps(); });
302
+ scene.onBeforeDrawPhaseObservable.add(() => { mainStart = counter._current; });
303
+ scene.onAfterDrawPhaseObservable.add(() => { mainEnd = counter._current; });
304
+ engine.onEndFrameObservable.add(() => {
305
+ if (!state.recording) return;
306
+ const total = counter._current;
307
+ watch.shadow += shadowFrame;
308
+ watch.targets += Math.max(0, mainStart - frameStart - shadowFrame);
309
+ watch.main += Math.max(0, mainEnd - mainStart);
310
+ watch.after += Math.max(0, total - mainEnd);
311
+ watch.frames++;
312
+ });
313
+ };
314
+
315
+ /**
316
+ * For every active mesh: the lights Babylon actually binds (mesh.lightSources, capped by the material's
317
+ * maxSimultaneousLights) and how many of those cannot reach the mesh at all (point / spot beyond their range).
318
+ */
319
+ state.lightAudit = () => {
320
+ const scene = state.scene();
321
+ let meshes = 0, bound = 0, outOfRange = 0, shadowed = 0;
322
+ const names = {};
323
+ for (const mesh of scene.getActiveMeshes().data.slice(0, scene.getActiveMeshes().length)) {
324
+ const material = mesh.material;
325
+ if (!material) continue;
326
+ const cap = material.maxSimultaneousLights || 4;
327
+ const lights = (mesh.lightSources || []).slice(0, cap);
328
+ meshes++;
329
+ const box = mesh.getBoundingInfo().boundingBox;
330
+ for (const light of lights) {
331
+ bound++;
332
+ if (light.getShadowGenerator && light.getShadowGenerator()) shadowed++;
333
+ names[light.name] = (names[light.name] || 0) + 1;
334
+ if (light.getClassName() === "PointLight" || light.getClassName() === "SpotLight") {
335
+ const p = light.getAbsolutePosition();
336
+ const c = BABYLON.Vector3.Clamp(p, box.minimumWorld, box.maximumWorld);
337
+ if (BABYLON.Vector3.Distance(p, c) > light.range) outOfRange++;
338
+ }
339
+ }
340
+ }
341
+ return { activeMeshes: meshes, lightsBoundPerMesh: +(bound / Math.max(1, meshes)).toFixed(2), boundButOutOfRangePct: +((outOfRange / Math.max(1, bound)) * 100).toFixed(1),
342
+ shadowedBoundPerMesh: +(shadowed / Math.max(1, meshes)).toFixed(2), mostBound: Object.entries(names).sort((a, b) => b[1] - a[1]).slice(0, 6) };
343
+ };
344
+
345
+ /**
346
+ * Switches one runtime cost off (on = false) or back on (on = true).
347
+ * Keys: dpr, taa, motionblur, bloom, post (every camera post-process), shadows, lights (every point / spot light).
348
+ * @returns {string} what changed
349
+ */
350
+ state.toggle = (key, on) => {
351
+ const scene = state.scene();
352
+ const engine = scene.getEngine();
353
+ const camera = scene.activeCamera;
354
+ const patterns = { taa: /^taa/i, motionblur: /motionblur/i, bloom: /bloom/i, post: /./ };
355
+ if (key === "dpr") {
356
+ if (state.savedScaling === undefined) state.savedScaling = engine.getHardwareScalingLevel();
357
+ engine.setHardwareScalingLevel(on ? state.savedScaling : 1);
358
+ engine.resize();
359
+ return "hardware scaling " + engine.getHardwareScalingLevel();
360
+ }
361
+ if (patterns[key]) {
362
+ if (!state.savedPost) state.savedPost = camera._postProcesses.filter(Boolean).slice();
363
+ for (const p of state.savedPost) camera.detachPostProcess(p);
364
+ const keep = on ? state.savedPost : state.savedPost.filter((p) => !patterns[key].test(p.name));
365
+ for (const p of keep) camera.attachPostProcess(p);
366
+ return (on ? "restored " : "removed ") + (state.savedPost.length - keep.length || state.savedPost.length) + " post-process passes (" + key + ")";
367
+ }
368
+ if (key === "shadows") { scene.shadowsEnabled = on; return "scene.shadowsEnabled = " + on; }
369
+ if (key === "lights") {
370
+ let count = 0;
371
+ for (const light of scene.lights) if (light.getClassName() !== "HemisphericLight" && light.getClassName() !== "DirectionalLight") { light.setEnabled(on); count++; }
372
+ return (on ? "enabled " : "disabled ") + count + " point/spot lights";
373
+ }
374
+ return "unknown";
375
+ };
376
+ }
377
+
378
+ /**
379
+ * Waits until the toolkit scene exists, is ready and has rendered for a moment.
380
+ * @param {import("puppeteer-core").Page} page - the player page
381
+ * @returns {Promise<number>} milliseconds from navigation to ready
382
+ */
383
+ async function waitForScene(page, startedAt) {
384
+ await page.waitForFunction(() => {
385
+ const scene = window.__btProfile && window.__btProfile.scene();
386
+ return scene && scene.meshes.length > 0 && scene.isReady() && scene.activeCamera && window.loaded === true;
387
+ }, { timeout: READY_TIMEOUT_MS, polling: 500 });
388
+ return Date.now() - startedAt;
389
+ }
390
+
391
+ /** Pauses for the given number of seconds. */
392
+ const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
393
+
394
+ /**
395
+ * Opens the scene in a fresh page and waits until it is ready.
396
+ * @returns {Promise<{page: import("puppeteer-core").Page, readyMs: number}>}
397
+ */
398
+ async function openScene(browser, baseUrl, scene, deviceScaleFactor, consoleErrors) {
399
+ const page = await browser.newPage();
400
+ await page.setViewport({ width: 1600, height: 900, deviceScaleFactor });
401
+ page.on("console", (message) => { if (message.type() === "error") consoleErrors.push(message.text()); });
402
+ page.on("pageerror", (error) => consoleErrors.push(String(error)));
403
+ await page.evaluateOnNewDocument(installProbe);
404
+ const startedAt = Date.now();
405
+ await page.goto(`${baseUrl}/engine.html?scene=${encodeURIComponent(scene)}`, { waitUntil: "load", timeout: READY_TIMEOUT_MS });
406
+ const readyMs = await waitForScene(page, startedAt);
407
+ await page.evaluate(() => window.__btProfile.watchTargets());
408
+ return { page, readyMs };
409
+ }
410
+
411
+ /**
412
+ * Waits until every material has finished compiling again (a scene-wide toggle recompiles all of them, which can
413
+ * take many seconds on a big scene), then a further quiet period so the frame rate has recovered.
414
+ */
415
+ async function settle(page, quietSeconds) {
416
+ await page.evaluate(() => window.__btProfile.scene().whenReadyAsync());
417
+ await sleep(quietSeconds);
418
+ await page.evaluate(() => window.__btProfile.scene().whenReadyAsync());
419
+ }
420
+
421
+ /**
422
+ * Records a CPU profile of the page for the given seconds and returns the top functions by self time.
423
+ * @returns {Promise<{totalMs: number, top: {fn: string, selfMs: number, pct: number}[]}>}
424
+ */
425
+ async function cpuProfile(page, seconds) {
426
+ const session = await page.createCDPSession();
427
+ await session.send("Profiler.enable");
428
+ await session.send("Profiler.setSamplingInterval", { interval: 500 });
429
+ await session.send("Profiler.start");
430
+ await sleep(seconds);
431
+ const { profile } = await session.send("Profiler.stop");
432
+ await session.detach();
433
+ const byId = new Map(profile.nodes.map((node) => [node.id, node]));
434
+ const self = new Map();
435
+ const deltas = profile.timeDeltas || [];
436
+ for (let i = 0; i < profile.samples.length; i++) {
437
+ const node = byId.get(profile.samples[i]);
438
+ const frame = node.callFrame;
439
+ const file = (frame.url || "").split("/").pop();
440
+ const key = (frame.functionName || "(anonymous)") + " " + file + ":" + frame.lineNumber;
441
+ self.set(key, (self.get(key) || 0) + (deltas[i] || 0) / 1000);
442
+ }
443
+ const totalMs = [...self.values()].reduce((sum, value) => sum + value, 0);
444
+ const top = [...self.entries()].sort((a, b) => b[1] - a[1]).slice(0, 30).map(([fn, ms]) => ({ fn, selfMs: +ms.toFixed(1), pct: +((ms / totalMs) * 100).toFixed(1) }));
445
+ return { totalMs: Math.round(totalMs), top };
446
+ }
447
+
448
+ /** Records one measurement window on the page. */
449
+ async function measure(page, windowSeconds) {
450
+ await page.evaluate(() => window.__btProfile.start());
451
+ await sleep(windowSeconds);
452
+ return page.evaluate(() => window.__btProfile.stop());
453
+ }
454
+
455
+ /**
456
+ * Entry point. Two modes:
457
+ * - timeline (default): samples at --times seconds after ready, as the scene plays.
458
+ * - --pin s1,s2: for each moment, a fresh load pins the camera there and measures every --toggles cost switched off on
459
+ * its own (then back on), each against the same pinned baseline.
460
+ */
461
+ async function main() {
462
+ const flags = parseArguments(process.argv.slice(2));
463
+ const baseUrl = (flags.base || "http://localhost:8888").replace(/\/$/, "");
464
+ const scene = flags.scene;
465
+ if (!scene) throw new Error("Pass --scene <exported scene file>, e.g. --scene level.gltf");
466
+ const times = (flags.times || DEFAULT_TIMES).split(",").map(Number).sort((first, second) => first - second);
467
+ const poses = flags.poses ? JSON.parse(fs.readFileSync(path.resolve(flags.poses), "utf8")).pins.map((pin) => ({ atSeconds: pin.atSeconds, pose: pin.pinned })) : null;
468
+ const pins = poses ? poses.map((entry) => entry.atSeconds) : (flags.pin || "").split(",").filter(Boolean).map(Number);
469
+ const toggles = (flags.toggles || "dpr,taa,motionblur,bloom,post,shadows,lights").split(",").filter((key) => key && key !== "none");
470
+ const windowSeconds = Number(flags.window || DEFAULT_WINDOW_SECONDS);
471
+ const settleSeconds = Number(flags.settle || 4);
472
+ const deviceScaleFactor = Number(flags.dpr || 2);
473
+ const headed = flags.headed === "true";
474
+ const shots = flags.shots ? path.resolve(flags.shots) : null;
475
+ if (shots) fs.mkdirSync(shots, { recursive: true });
476
+ const tag = path.basename(scene, path.extname(scene));
477
+
478
+ const browser = await puppeteer.launch({
479
+ executablePath: findChrome(),
480
+ headless: headed ? false : "new",
481
+ defaultViewport: null,
482
+ args: ["--use-angle=metal", "--enable-gpu", "--ignore-gpu-blocklist", "--enable-unsafe-webgpu", "--disable-frame-rate-limit",
483
+ "--disable-background-timer-throttling", "--disable-renderer-backgrounding", "--window-size=1600,900"],
484
+ });
485
+ const consoleErrors = [];
486
+ const report = { scene, deviceScaleFactor, headed };
487
+ try {
488
+ if (pins.length === 0) {
489
+ const { page, readyMs } = await openScene(browser, baseUrl, scene, deviceScaleFactor, consoleErrors);
490
+ report.readyMs = readyMs;
491
+ report.census = await page.evaluate(() => window.__btProfile.census());
492
+ report.samples = [];
493
+ let elapsed = 0;
494
+ for (const seconds of times) {
495
+ await sleep(Math.max(0, seconds - elapsed));
496
+ const sample = await measure(page, windowSeconds);
497
+ elapsed = seconds + windowSeconds;
498
+ report.samples.push({ atSeconds: seconds, ...sample });
499
+ if (shots) await page.screenshot({ path: path.join(shots, `${tag}_${seconds}s.png`) });
500
+ }
501
+ await page.close();
502
+ } else {
503
+ report.pins = [];
504
+ for (const [index, seconds] of pins.entries()) {
505
+ const { page, readyMs } = await openScene(browser, baseUrl, scene, deviceScaleFactor, consoleErrors);
506
+ if (!report.census) report.census = await page.evaluate(() => window.__btProfile.census());
507
+ await sleep(seconds);
508
+ // With --poses, the camera goes to the exact pose an earlier run pinned, so two exports are measured from one view.
509
+ const pinned = poses ? await page.evaluate((pose) => window.__btProfile.pose(pose), poses[index].pose) : await page.evaluate(() => window.__btProfile.pin());
510
+ await settle(page, settleSeconds);
511
+ if (shots) await page.screenshot({ path: path.join(shots, `${tag}_pin${seconds}s.png`) });
512
+ const poseBefore = await page.evaluate(() => window.__btProfile.actualPose());
513
+ const baseline = await measure(page, windowSeconds);
514
+ const poseAfter = await page.evaluate(() => window.__btProfile.actualPose());
515
+ const target = pinned.position || pinned;
516
+ const drift = Math.max(...[poseBefore, poseAfter].map((actual) => Math.hypot(actual.position[0] - target[0], actual.position[1] - target[1], actual.position[2] - target[2])));
517
+ if (drift > 0.05 || (pinned.fov != null && Math.abs(poseAfter.fov - pinned.fov) > 1e-3) || poseBefore.camera !== poseAfter.camera)
518
+ process.stderr.write(`WARNING pin ${seconds}s drifted: target ${JSON.stringify(pinned)} actual ${JSON.stringify(poseBefore)} -> ${JSON.stringify(poseAfter)}\n`);
519
+ const cpu = flags.cpuprofile === "true" ? await cpuProfile(page, windowSeconds) : null;
520
+ const lightAudit = await page.evaluate(() => window.__btProfile.lightAudit());
521
+ const steps = [];
522
+ for (const key of toggles) {
523
+ const change = await page.evaluate((k) => window.__btProfile.toggle(k, false), key);
524
+ await settle(page, settleSeconds);
525
+ const off = await measure(page, windowSeconds);
526
+ await page.evaluate((k) => window.__btProfile.toggle(k, true), key);
527
+ await settle(page, settleSeconds);
528
+ steps.push({ off: key, change, fps: off.fps, p50Ms: off.p50Ms, drawCalls: off.drawCalls, passes: off.passes, cpuRenderMs: off.cpuRenderMs, cpuFrameMs: off.cpuFrameMs });
529
+ }
530
+ const after = await measure(page, windowSeconds);
531
+ report.pins.push({ atSeconds: seconds, readyMs, pinned, actual: { before: poseBefore, after: poseAfter }, baseline, lightAudit, cpu, steps, baselineAgain: { fps: after.fps, p50Ms: after.p50Ms } });
532
+ await page.close();
533
+ }
534
+ }
535
+ report.consoleErrors = consoleErrors.slice(0, 20);
536
+ const text = JSON.stringify(report, null, 2);
537
+ if (flags.out) fs.writeFileSync(path.resolve(flags.out), text);
538
+ process.stdout.write(text + "\n");
539
+ } finally {
540
+ await browser.close();
541
+ }
542
+ }
543
+
544
+ main().catch((error) => {
545
+ process.stderr.write(String(error && error.stack ? error.stack : error) + "\n");
546
+ process.exit(1);
547
+ });