@babylonjs-toolkit/agent 1.1.52 → 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.
@@ -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
+ });
@@ -4,16 +4,16 @@ description: "The Babylon Toolkit Plan Skill creates the detailed technical plan
4
4
  allowed-tools: Read, Grep, Glob, Write, WebFetch(domain:raw.githubusercontent.com), Agent, Task
5
5
  ---
6
6
 
7
- Turn a feature spec into `_specs/<feature-name>_plan.md`: an ordered checklist of tasks that `bt-execute` runs. Follow the project's agent instructions (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md). The user's message after the skill name is the `arguments`.
7
+ Turn a feature spec into `.agents/specs/<feature-name>_plan.md`: an ordered checklist of tasks that `bt-execute` runs. Follow the project's agent instructions (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md). The user's message after the skill name is the `arguments`.
8
8
 
9
9
  ```
10
10
  /bt-plan [--heavy] [--parity] [--no-time-limit] <feature-spec> <optional-brief>
11
11
 
12
- /bt-plan @_specs/mute-game-audio_spec.md
12
+ /bt-plan @.agents/specs/mute-game-audio_spec.md
13
13
  /bt-plan "add a settings toggle to mute all game audio" # no spec file → Quick Plan: short interview, then plan
14
- /bt-plan --heavy @_specs/feature_spec.md # decision-complete plan for a long or cheaper-model run
15
- /bt-plan --heavy --parity @_specs/feature_spec.md # numeric parity gates against the reference (slow)
16
- /bt-plan --no-time-limit @_specs/feature_spec.md # turn off the default TIME MATTERS mode
14
+ /bt-plan --heavy @.agents/specs/feature_spec.md # decision-complete plan for a long or cheaper-model run
15
+ /bt-plan --heavy --parity @.agents/specs/feature_spec.md # numeric parity gates against the reference (slow)
16
+ /bt-plan --no-time-limit @.agents/specs/feature_spec.md # turn off the default TIME MATTERS mode
17
17
  ```
18
18
 
19
19
  - `--heavy` — Heavy Plan mode (below). `--parity` — plan numeric parity proof; also on when the spec says `proof: parity`. `--no-time-limit` — turn off TIME MATTERS mode (Ground rules). Strip flags, and any literal `TIME MATTERS`, first; they are never part of the brief.
@@ -30,7 +30,7 @@ Turn a feature spec into `_specs/<feature-name>_plan.md`: an ordered checklist o
30
30
  ## Step 1. Analyze (required before writing)
31
31
 
32
32
  1. Read the feature spec in full, and `SPEC.md`'s headings, Architecture, Conventions and the systems the feature touches. The plan must conform to SPEC.md — **if it would conflict, stop and tell the user.** Verification procedures described in SPEC.md are tooling you may reuse, not a bar the plan must meet. Note the spec's `spec_impact`, `size` and `proof`.
33
- 2. **Start from the spec's `## Research Notes`, and any bt-recon doc (`_specs/*_recon.md`) it cites or whose scope covers the systems the feature touches** — its Extension Points and End-to-End Flows usually name the integration points directly. Spot-check that the paths exist, then research only what a plan needs beyond them: how the app is built and tested, the real conventions and the closest feature to mirror, the concrete files and integration points, available dependencies, constraints from the agent instructions.
33
+ 2. **Start from the spec's `## Research Notes`, and any bt-recon doc (`.agents/recon/*_recon.md`) it cites or whose scope covers the systems the feature touches** — its Extension Points and End-to-End Flows usually name the integration points directly. Spot-check that the paths exist, then research only what a plan needs beyond them: how the app is built and tested, the real conventions and the closest feature to mirror, the concrete files and integration points, available dependencies, constraints from the agent instructions.
34
34
  3. Size the research: `small` → inline; `medium` / `large` (or no Research Notes) → up to 3 **read-only** subagents returning findings and paths, not file dumps. Tell each one verbatim: *"Read-only: you may read, search and report. Do not edit or create files, and do not run builds, tests or any command that writes — not even into a build folder. If a fact needs a build or a test run to establish, report it as unknown and say which command would settle it."*
35
35
  4. Sibling-skill pattern (e.g. bt-design's 3D-Hero-Scroll): read that skill's reference **and templates** *(where skills load through a tool: `load_skill` + `read_skill_resource`, never a guessed path; where they are files: the skills directory this skill was loaded from, e.g. `~/.claude/skills/`, `~/.agents/skills/` or the project's equivalent)*. The plan **copies and configures the template engine — never re-implements it**; each behavioral option the spec records (e.g. `sweep: page`) becomes an Acceptance item stated in observable terms. Prefer copying and wiring the template as the first task, so later tasks only configure it.
36
36
  5. Too ambiguous to plan responsibly → ask the user. **Already built?** If the research shows some or all of the feature already exists, say so first and plan only what is missing (often just tests and the live check).
@@ -54,7 +54,7 @@ Execution time is mostly *how the work is proven*, not the code. Keep proof stro
54
54
 
55
55
  ## Step 3. Write the plan
56
56
 
57
- Print `✍️ [bt-plan] Writing _specs/<feature-name>_plan.md …`. The file has, in order:
57
+ Print `✍️ [bt-plan] Writing .agents/specs/<feature-name>_plan.md …`. The file has, in order:
58
58
 
59
59
  **`## Codebase Analysis`** — what Step 1 found, citing real files; the SPEC.md sections the plan conforms to; `spec_impact`, `size`, `proof` (say which were inferred); Quick Plan assumptions.
60
60
 
@@ -126,8 +126,8 @@ Each task above is a checkbox. To implement:
126
126
  Then **stop**. Final message: a short summary, the estimated time, and:
127
127
 
128
128
  ```
129
- Plan written to _specs/<feature-name>_plan.md — <n> tasks, estimated <total range> of agent time
130
- Run a single task with `bt-execute _specs/<feature-name>_plan.md T1`, or every task with `bt-execute _specs/<feature-name>_plan.md ALL` (add `--strict` for an adversarial verifier on every task).
129
+ Plan written to .agents/specs/<feature-name>_plan.md — <n> tasks, estimated <total range> of agent time
130
+ Run a single task with `bt-execute .agents/specs/<feature-name>_plan.md T1`, or every task with `bt-execute .agents/specs/<feature-name>_plan.md ALL` (add `--strict` for an adversarial verifier on every task).
131
131
  ```
132
132
 
133
133
  ## Heavy Plan mode (`--heavy`)
@@ -88,7 +88,7 @@ Before building anything, decide the **N distinct directions** so the batch does
88
88
 
89
89
  **Full-bleed does not mean a single locked screen — these are landing pages, so scroll stays first-class** (bt-design's *scroll is the transport, not the enemy* rule). Full-viewport views scroll between and through each other, and any **3D-hero-scroll direction plays its cinematic scroll, then settles into the full-bleed console home view at the end** (the sweep-into-console handoff) rather than dead-ending or dropping into a stock template. Compose each view full-bleed; let scroll carry the user between them.
90
90
 
91
- Write the plan to `_prototypes/_directions.md` (id, name, one-line design language, inspiration source + attribution if any, whether it's a 3D-hero-scroll direction). This is the batch's manifest.
91
+ Write the plan to `.agents/prototypes/_directions.md` (id, name, one-line design language, inspiration source + attribution if any, whether it's a 3D-hero-scroll direction). This is the batch's manifest.
92
92
 
93
93
  ## Sourcing directions from awwwards
94
94
 
@@ -128,16 +128,16 @@ Build the N prototypes **in parallel via subagents** — if a subagent-spawning/
128
128
 
129
129
  Each prototype subagent gets: its **direction**, the **theme**, the **world anchor** (screenshots + extracted palette/mood/silhouettes), the **`--type`**, and the **asset workflows** available, plus the full text of the Agent Reference's **Coding Practices — ENFORCED**. It must:
130
130
 
131
- 1. **Own its folder.** Create `_prototypes/<NN-slug>/` and put **everything self-contained inside it** — markup, styles, scripts, and all generated/downloaded assets. No shared globals; a prototype is copy-out-able on its own.
131
+ 1. **Own its folder.** Create `.agents/prototypes/<NN-slug>/` and put **everything self-contained inside it** — markup, styles, scripts, and all generated/downloaded assets. No shared globals; a prototype is copy-out-able on its own.
132
132
  2. **Build to the Fable bar for its lens** — advanced 3D tactics, otherworldly animation, exceptional palette, novel type. Not a template with the colors swapped; a distinct, *mind-blowing* execution of that direction for this game. **Full-bleed console UI by default** (bt-design's *Layout Philosophy*): fill the whole viewport edge-to-edge like a console dashboard / game menu, not a centered fixed-width website — unless this direction is the noted contained exception.
133
- 3. **Produce assets** via any mix of the available workflows: Pinterest pulls for reference, **GPT Image 2** for stills, **KIE MCP servers (default) / the Higgsfield CLI (Kling, Seedance, etc.)** for motion/video, hand-authored WebGL/SVG/CSS. All assets stay faithful to the world anchor and live in the prototype's folder. **On Higgsfield, every generation goes through the reference's `scripts/hf-generate.mjs` wrapper** with `--out _prototypes/<NN-slug>/<file>`: the CLI alone only returns a CDN URL, and a prototype must never hot-link one. Local reference images are passed as file paths (`--image-references`, `--start-image`, `--end-image`) and uploaded automatically.
133
+ 3. **Produce assets** via any mix of the available workflows: Pinterest pulls for reference, **GPT Image 2** for stills, **KIE MCP servers (default) / the Higgsfield CLI (Kling, Seedance, etc.)** for motion/video, hand-authored WebGL/SVG/CSS. All assets stay faithful to the world anchor and live in the prototype's folder. **On Higgsfield, every generation goes through the reference's `scripts/hf-generate.mjs` wrapper** with `--out .agents/prototypes/<NN-slug>/<file>`: the CLI alone only returns a CDN URL, and a prototype must never hot-link one. Local reference images are passed as file paths (`--image-references`, `--start-image`, `--end-image`) and uploaded automatically.
134
134
  4. **3D-hero-scroll directions:** follow *The 3D-hero-scroll batch rule* below.
135
135
  5. Run its own **iteration passes** (Step 4) before returning.
136
136
  6. **Write clean, readable code.** Every file follows the Coding Practices: clean, professional TypeScript or JavaScript in the project's own language; meaningful full-word names, never one- or two-letter names or obfuscation; well-structured, readable, maintainable code for human developers; meaningful JSDoc on every class, function, method and public member (always written, but never a reason to fail a test or verification). The chosen prototype becomes the user's real front end, so its code must be maintainable.
137
137
 
138
138
  ## The 3D-hero-scroll batch rule
139
139
 
140
- When `--3d-hero-scroll` is set (or a direction inherently calls for the cinematic hero), that prototype is built via **bt-hero → bt-design's 3D-Hero-Scroll protocol** — copy the templates, run the footage pipeline, calibrate, verify. **But this is a batch: bt-hero must never prompt.** So all of bt-hero's creative slots must be **pre-resolved before the subagent starts** — the star, look/anchor, journey/beats, HUD, controls, sweep, brand/overlays, and below-the-journey are derived from the theme + world anchor + direction and written into a hero brief (`_prototypes/<NN-slug>/_hero-brief.md`) up front. The subagent runs bt-hero's build against that brief with **zero questions** ("enough to fly," always). If a slot genuinely can't be resolved without the user, resolve it with a sensible default and note it — do **not** pause the batch.
140
+ When `--3d-hero-scroll` is set (or a direction inherently calls for the cinematic hero), that prototype is built via **bt-hero → bt-design's 3D-Hero-Scroll protocol** — copy the templates, run the footage pipeline, calibrate, verify. **But this is a batch: bt-hero must never prompt.** So all of bt-hero's creative slots must be **pre-resolved before the subagent starts** — the star, look/anchor, journey/beats, HUD, controls, sweep, brand/overlays, and below-the-journey are derived from the theme + world anchor + direction and written into a hero brief (`.agents/prototypes/<NN-slug>/_hero-brief.md`) up front. The subagent runs bt-hero's build against that brief with **zero questions** ("enough to fly," always). If a slot genuinely can't be resolved without the user, resolve it with a sensible default and note it — do **not** pause the batch.
141
141
 
142
142
  ## Step 4 — Iteration passes (the quality gate)
143
143