@babylonjs-toolkit/agent 1.1.66 → 1.1.69
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.
- package/README.md +3 -2
- package/package.json +1 -1
- package/skills/bt-design/SKILL.md +7 -0
- package/skills/bt-design/templates/3d-hero-scroll/hero-scroll.js +27 -9
- package/skills/bt-execute/SKILL.md +4 -4
- package/skills/bt-execute/templates/dashboard/dashboard.html +96 -21
- package/skills/bt-execute/templates/dashboard/data-schema.md +4 -3
- package/skills/bt-gauntlet/references/critic-rubrics.md +1 -0
- package/skills/bt-plan/SKILL.md +1 -1
- package/skills/bt-profile/SKILL.md +318 -0
- package/skills/bt-profile/scripts/analyze.mjs +735 -0
- package/skills/bt-profile/scripts/compare.mjs +87 -0
- package/skills/bt-profile/scripts/lib/chrome.mjs +22 -0
- package/skills/bt-profile/scripts/lib/probe.mjs +340 -0
- package/skills/bt-profile/scripts/lib/progress-panel.mjs +371 -0
- package/skills/bt-profile/scripts/lib/symbolize.mjs +356 -0
- package/skills/bt-profile/scripts/package.json +10 -0
- package/skills/bt-profile/scripts/profile.mjs +566 -0
- package/skills/bt-profile/scripts/progress.mjs +516 -0
- package/skills/bt-profile/scripts/report.mjs +803 -0
- package/skills/bt-profile/templates/census.template.mjs +76 -0
- package/skills/bt-profile/templates/scenario.template.mjs +78 -0
- package/skills/bt-prototype/SKILL.md +1 -1
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* bt-profile compare: prints before → after for two analyses of the same scenario — per phase (FPS, CPU ms/frame,
|
|
3
|
+
* busy, draws), per owner (ms/frame) and the functions whose time changed most — so a fix is kept or reverted on
|
|
4
|
+
* numbers, not impressions.
|
|
5
|
+
*
|
|
6
|
+
* Usage:
|
|
7
|
+
* node compare.mjs --before runs/baseline/cold/analysis.json --after runs/fix-1/cold/analysis.json [--focus "Name.fn,Other.fn"]
|
|
8
|
+
*/
|
|
9
|
+
import fs from "node:fs";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Reads `--name value` pairs from the command line.
|
|
14
|
+
* @param {string[]} argv - process.argv.slice(2)
|
|
15
|
+
* @returns {Record<string, string>} the parsed flags
|
|
16
|
+
*/
|
|
17
|
+
function parseArguments(argv) {
|
|
18
|
+
const flags = {};
|
|
19
|
+
for (let i = 0; i < argv.length; i += 2) flags[argv[i].replace(/^--/, "")] = argv[i + 1];
|
|
20
|
+
return flags;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Formats a signed change. */
|
|
24
|
+
const signed = (value, digits = 1) => (value == null || Number.isNaN(value) ? " –" : `${value > 0 ? "+" : ""}${value.toFixed(digits)}`);
|
|
25
|
+
|
|
26
|
+
/** Total ms per frame of a function (inclusive) in a phase list, by display name. */
|
|
27
|
+
function inclusiveByName(lists) {
|
|
28
|
+
const map = new Map();
|
|
29
|
+
for (const entry of lists.inclusiveTop) map.set(entry.name, (map.get(entry.name) || 0) + (entry.msPerFrame || 0));
|
|
30
|
+
return map;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Entry point. */
|
|
34
|
+
function main() {
|
|
35
|
+
const flags = parseArguments(process.argv.slice(2));
|
|
36
|
+
const before = JSON.parse(fs.readFileSync(path.resolve(flags.before), "utf8"));
|
|
37
|
+
const after = JSON.parse(fs.readFileSync(path.resolve(flags.after), "utf8"));
|
|
38
|
+
const out = [];
|
|
39
|
+
const line = (text = "") => out.push(text);
|
|
40
|
+
line(`before: ${path.dirname(path.resolve(flags.before))} (${before.capture.capturedAt})`);
|
|
41
|
+
line(`after: ${path.dirname(path.resolve(flags.after))} (${after.capture.capturedAt})`);
|
|
42
|
+
line();
|
|
43
|
+
line("PHASE fps before → after CPU ms/frame before → after busy% draws");
|
|
44
|
+
for (const phase of after.phases) {
|
|
45
|
+
const previous = before.phases.find((candidate) => candidate.name === phase.name);
|
|
46
|
+
if (!previous) { line(` ${phase.name.padEnd(14)} (new phase)`); continue; }
|
|
47
|
+
const fps = `${String(previous.frames.fps).padStart(5)} → ${String(phase.frames.fps).padStart(5)} (${signed(phase.frames.fps - previous.frames.fps)})`;
|
|
48
|
+
const cpu = `${String(previous.frames.cpuMeanMs).padStart(6)} → ${String(phase.frames.cpuMeanMs).padStart(6)} (${signed(phase.frames.cpuMeanMs - previous.frames.cpuMeanMs, 2)})`;
|
|
49
|
+
line(` ${phase.name.padEnd(14)} ${fps.padEnd(26)} ${cpu.padEnd(31)} ${String(previous.busyPct).padStart(3)}→${String(phase.busyPct).padEnd(3)} ${previous.frames.draws}→${phase.frames.draws}`);
|
|
50
|
+
}
|
|
51
|
+
line();
|
|
52
|
+
line("OWNER ms/frame (whole run)");
|
|
53
|
+
const ownersBefore = new Map(before.overall.lists.owners.map((entry) => [entry.owner, entry.msPerFrame]));
|
|
54
|
+
for (const entry of after.overall.lists.owners) {
|
|
55
|
+
const previous = ownersBefore.get(entry.owner);
|
|
56
|
+
line(` ${entry.owner.padEnd(10)} ${String(previous ?? "–").padStart(8)} → ${String(entry.msPerFrame).padStart(8)} (${signed(previous != null ? entry.msPerFrame - previous : null, 3)})`);
|
|
57
|
+
}
|
|
58
|
+
line();
|
|
59
|
+
line("FUNCTIONS whose inclusive ms/frame changed most (whole run)");
|
|
60
|
+
const inclusiveBefore = inclusiveByName(before.overall.lists);
|
|
61
|
+
const inclusiveAfter = inclusiveByName(after.overall.lists);
|
|
62
|
+
const names = new Set([...inclusiveBefore.keys(), ...inclusiveAfter.keys()]);
|
|
63
|
+
const changes = [...names].map((name) => ({ name, before: inclusiveBefore.get(name) ?? 0, after: inclusiveAfter.get(name) ?? 0 }))
|
|
64
|
+
.map((entry) => ({ ...entry, change: entry.after - entry.before }))
|
|
65
|
+
.sort((a, b) => Math.abs(b.change) - Math.abs(a.change)).slice(0, 15);
|
|
66
|
+
for (const entry of changes) line(` ${signed(entry.change, 3).padStart(9)} ms/f ${entry.before.toFixed(3)} → ${entry.after.toFixed(3)} ${entry.name}`);
|
|
67
|
+
if (flags.focus) {
|
|
68
|
+
line();
|
|
69
|
+
line("FOCUS");
|
|
70
|
+
for (const name of flags.focus.split(",")) {
|
|
71
|
+
for (const phase of after.phases) {
|
|
72
|
+
const previous = before.phases.find((candidate) => candidate.name === phase.name);
|
|
73
|
+
const now = inclusiveByName(phase.lists).get(name);
|
|
74
|
+
const was = previous ? inclusiveByName(previous.lists).get(name) : null;
|
|
75
|
+
if (now == null && was == null) continue;
|
|
76
|
+
line(` ${name} [${phase.name}] ${was?.toFixed(3) ?? "–"} → ${now?.toFixed(3) ?? "–"} ms/frame`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
if (before.heap && after.heap) {
|
|
81
|
+
line();
|
|
82
|
+
line(`ALLOCATION ${before.heap.mbPerSecond} → ${after.heap.mbPerSecond} MB/s`);
|
|
83
|
+
}
|
|
84
|
+
process.stdout.write(out.join("\n") + "\n");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
main();
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Finds the Chrome (or Chromium) executable that bt-profile drives: the capture (profile.mjs) and the report's PDF
|
|
3
|
+
* (report.mjs). CHROME_PATH wins; otherwise the usual install locations on macOS, Linux and Windows.
|
|
4
|
+
*/
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
|
|
7
|
+
/** @returns {string} the path of a Chrome or Chromium executable */
|
|
8
|
+
export function findChrome() {
|
|
9
|
+
const candidates = [
|
|
10
|
+
process.env.CHROME_PATH,
|
|
11
|
+
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
12
|
+
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
|
13
|
+
"/usr/bin/google-chrome",
|
|
14
|
+
"/usr/bin/chromium",
|
|
15
|
+
"/usr/bin/chromium-browser",
|
|
16
|
+
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
|
|
17
|
+
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
|
|
18
|
+
].filter(Boolean);
|
|
19
|
+
const found = candidates.find((candidate) => fs.existsSync(candidate));
|
|
20
|
+
if (found) return found;
|
|
21
|
+
throw new Error("No Chrome found. Set CHROME_PATH to a Chrome or Chromium executable.");
|
|
22
|
+
}
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The in-page half of the bt-profile capture. `installProbe` is serialised into every document the profiled page
|
|
3
|
+
* opens (puppeteer `evaluateOnNewDocument`), so it must stay self-contained: no imports, no outer variables.
|
|
4
|
+
*
|
|
5
|
+
* It records, on `window.__btProfile`:
|
|
6
|
+
* - one entry per rendered Babylon frame: begin time, CPU work (begin → end of the engine frame), draw calls, active
|
|
7
|
+
* meshes and particles, and the SceneInstrumentation timers the engine exposes — or, on a page with no Babylon engine,
|
|
8
|
+
* one entry per browser frame (requestAnimationFrame: time only, `frameSource: "raf"`);
|
|
9
|
+
* - counters sampled every half second: meshes, materials, textures, particle systems, compiled effects (shader
|
|
10
|
+
* programs / pipelines), JS heap;
|
|
11
|
+
* - long animation frames (LoAF) with their script attribution, when the browser supports them;
|
|
12
|
+
* - every shader module / pipeline (WebGPU) and program (WebGL) the page creates, with its time (`gpuCompiles`);
|
|
13
|
+
* - phase marks set by the scenario (`__btProfile.mark("countdown")`).
|
|
14
|
+
*
|
|
15
|
+
* Every time is an epoch time in milliseconds (`performance.timeOrigin + performance.now()`), so frames, marks and
|
|
16
|
+
* the CPU profile line up across page navigations.
|
|
17
|
+
*/
|
|
18
|
+
export function installProbe() {
|
|
19
|
+
/** How often the scene counters are sampled, in milliseconds. */
|
|
20
|
+
const COUNTER_INTERVAL_MS = 500;
|
|
21
|
+
/** How often the probe looks for a new engine or scene, in milliseconds. */
|
|
22
|
+
const ATTACH_POLL_MS = 50;
|
|
23
|
+
/** Frames longer than this (ms) keep their full instrumentation breakdown in the spike list. */
|
|
24
|
+
const LONG_FRAME_MS = 50;
|
|
25
|
+
/** Most shader / pipeline creations kept (a run creates tens to a few thousand). */
|
|
26
|
+
const MAX_GPU_COMPILES = 20000;
|
|
27
|
+
|
|
28
|
+
const epochNow = () => performance.timeOrigin + performance.now();
|
|
29
|
+
const state = {
|
|
30
|
+
frames: [],
|
|
31
|
+
counters: [],
|
|
32
|
+
marks: [],
|
|
33
|
+
longFrames: [],
|
|
34
|
+
loafs: [],
|
|
35
|
+
engineAttachedAt: null,
|
|
36
|
+
scenesSeen: 0,
|
|
37
|
+
rafFrames: [],
|
|
38
|
+
};
|
|
39
|
+
window.__btProfile = state;
|
|
40
|
+
|
|
41
|
+
/** Records a named phase boundary (the scenario calls it: "intro", "countdown", "takeoff" …). */
|
|
42
|
+
state.mark = (name) => {
|
|
43
|
+
state.marks.push({ name, at: epochNow() });
|
|
44
|
+
return name;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
const babylon = () => window.BABYLON || null;
|
|
48
|
+
const currentEngine = () => {
|
|
49
|
+
const library = babylon();
|
|
50
|
+
if (!library || !library.EngineStore) return null;
|
|
51
|
+
return library.EngineStore.LastCreatedEngine || null;
|
|
52
|
+
};
|
|
53
|
+
const currentScene = () => {
|
|
54
|
+
const library = babylon();
|
|
55
|
+
if (!library || !library.EngineStore) return null;
|
|
56
|
+
return library.EngineStore.LastCreatedScene || null;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
let hookedEngine = null;
|
|
60
|
+
let hookedScene = null;
|
|
61
|
+
let instrumentation = null;
|
|
62
|
+
let frameBegin = 0;
|
|
63
|
+
|
|
64
|
+
/** Turns on every SceneInstrumentation timer this Babylon version has, for the scene now rendering. */
|
|
65
|
+
const instrumentScene = (scene) => {
|
|
66
|
+
const library = babylon();
|
|
67
|
+
if (!library.SceneInstrumentation) return;
|
|
68
|
+
if (instrumentation) {
|
|
69
|
+
try { instrumentation.dispose(); } catch { /* the old scene is already gone */ }
|
|
70
|
+
}
|
|
71
|
+
instrumentation = new library.SceneInstrumentation(scene);
|
|
72
|
+
for (const flag of ["captureFrameTime", "captureRenderTime", "captureRenderTargetsRenderTime", "captureActiveMeshesEvaluationTime",
|
|
73
|
+
"captureAnimationsTime", "capturePhysicsTime", "captureParticlesRenderTime", "captureCameraRenderTime", "captureInterFrameTime"]) {
|
|
74
|
+
try { instrumentation[flag] = true; } catch { /* timer not supported by this engine */ }
|
|
75
|
+
}
|
|
76
|
+
hookedScene = scene;
|
|
77
|
+
state.scenesSeen++;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const timer = (name) => {
|
|
81
|
+
const counter = instrumentation && instrumentation[name];
|
|
82
|
+
return counter && typeof counter.current === "number" ? counter.current : null;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const activeParticles = (scene) => {
|
|
86
|
+
let total = 0;
|
|
87
|
+
for (const system of scene.particleSystems || []) {
|
|
88
|
+
try { total += system.getActiveCount ? system.getActiveCount() : 0; } catch { /* a GPU system mid-dispose */ }
|
|
89
|
+
}
|
|
90
|
+
return total;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const onBeginFrame = () => { frameBegin = performance.now(); };
|
|
94
|
+
const onEndFrame = () => {
|
|
95
|
+
const end = performance.now();
|
|
96
|
+
const scene = hookedScene;
|
|
97
|
+
const engine = hookedEngine;
|
|
98
|
+
const drawCounter = engine && engine._drawCalls;
|
|
99
|
+
const frame = {
|
|
100
|
+
at: performance.timeOrigin + frameBegin,
|
|
101
|
+
cpuMs: +(end - frameBegin).toFixed(3),
|
|
102
|
+
draws: drawCounter && typeof drawCounter.current === "number" ? drawCounter.current : null,
|
|
103
|
+
activeMeshes: scene && scene.getActiveMeshes ? scene.getActiveMeshes().length : null,
|
|
104
|
+
particles: scene ? activeParticles(scene) : null,
|
|
105
|
+
renderMs: timer("renderTimeCounter"),
|
|
106
|
+
targetsMs: timer("renderTargetsRenderTimeCounter"),
|
|
107
|
+
evaluateMs: timer("activeMeshesEvaluationTimeCounter"),
|
|
108
|
+
animationsMs: timer("animationsTimeCounter"),
|
|
109
|
+
physicsMs: timer("physicsTimeCounter"),
|
|
110
|
+
particlesMs: timer("particlesRenderTimeCounter"),
|
|
111
|
+
};
|
|
112
|
+
state.frames.push(frame);
|
|
113
|
+
if (frame.cpuMs >= LONG_FRAME_MS) state.longFrames.push(frame);
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
/** Hooks the engine's frame observables once, and re-instruments whenever a new scene starts rendering. */
|
|
117
|
+
const attach = () => {
|
|
118
|
+
const engine = currentEngine();
|
|
119
|
+
if (engine && engine !== hookedEngine && engine.onBeginFrameObservable && engine.onEndFrameObservable) {
|
|
120
|
+
hookedEngine = engine;
|
|
121
|
+
engine.onBeginFrameObservable.add(onBeginFrame);
|
|
122
|
+
engine.onEndFrameObservable.add(onEndFrame);
|
|
123
|
+
state.engineAttachedAt = epochNow();
|
|
124
|
+
state.engine = engine.isWebGPU ? "WebGPU" : "WebGL" + (engine.webGLVersion || "");
|
|
125
|
+
}
|
|
126
|
+
const scene = currentScene();
|
|
127
|
+
if (scene && scene !== hookedScene && !scene.isDisposed) instrumentScene(scene);
|
|
128
|
+
};
|
|
129
|
+
setInterval(attach, ATTACH_POLL_MS);
|
|
130
|
+
|
|
131
|
+
// Any web app: until a Babylon engine is found, the browser's own frames (requestAnimationFrame) are timed, so a page
|
|
132
|
+
// with no Babylon at all still gets FPS, frame gaps and the timeline. They are used only when no engine ever attaches.
|
|
133
|
+
let rafPrevious = null;
|
|
134
|
+
const onAnimationFrame = (now) => {
|
|
135
|
+
if (hookedEngine != null) return;
|
|
136
|
+
if (rafPrevious != null) state.rafFrames.push({ at: performance.timeOrigin + now, cpuMs: null });
|
|
137
|
+
rafPrevious = now;
|
|
138
|
+
requestAnimationFrame(onAnimationFrame);
|
|
139
|
+
};
|
|
140
|
+
requestAnimationFrame(onAnimationFrame);
|
|
141
|
+
|
|
142
|
+
/** Counts what the scene holds and how many shader programs / pipelines the engine has compiled so far. */
|
|
143
|
+
const sampleCounters = () => {
|
|
144
|
+
const engine = hookedEngine;
|
|
145
|
+
const scene = hookedScene;
|
|
146
|
+
const memory = performance.memory;
|
|
147
|
+
const entry = { at: epochNow(), heapMb: memory ? +(memory.usedJSHeapSize / 1048576).toFixed(1) : null };
|
|
148
|
+
if (engine) {
|
|
149
|
+
const compiled = engine._compiledEffects;
|
|
150
|
+
entry.compiledEffects = compiled ? Object.keys(compiled).length : null;
|
|
151
|
+
entry.textureCache = engine.getLoadedTexturesCache ? engine.getLoadedTexturesCache().length : null;
|
|
152
|
+
}
|
|
153
|
+
if (scene && !scene.isDisposed) {
|
|
154
|
+
entry.meshes = scene.meshes.length;
|
|
155
|
+
entry.materials = scene.materials.length;
|
|
156
|
+
entry.textures = scene.textures.length;
|
|
157
|
+
entry.particleSystems = (scene.particleSystems || []).length;
|
|
158
|
+
entry.animationGroups = (scene.animationGroups || []).length;
|
|
159
|
+
entry.skeletons = (scene.skeletons || []).length;
|
|
160
|
+
}
|
|
161
|
+
state.counters.push(entry);
|
|
162
|
+
};
|
|
163
|
+
setInterval(sampleCounters, COUNTER_INTERVAL_MS);
|
|
164
|
+
|
|
165
|
+
// GPU work the main thread does not see: every shader module, render / compute pipeline (WebGPU) and linked program
|
|
166
|
+
// (WebGL) the page creates, with its time. A frame gap with little script in it right after a burst of these is the GPU
|
|
167
|
+
// process compiling pipelines — the classic first-visit stutter (the browser's shader caches hide it on later visits).
|
|
168
|
+
state.gpuCompiles = [];
|
|
169
|
+
const recordCompile = (kind) => { if (state.gpuCompiles.length < MAX_GPU_COMPILES) state.gpuCompiles.push({ at: epochNow(), kind }); };
|
|
170
|
+
const wrapCompile = (prototype, method, kind) => {
|
|
171
|
+
if (!prototype || typeof prototype[method] !== "function") return;
|
|
172
|
+
const original = prototype[method];
|
|
173
|
+
prototype[method] = function (...args) { recordCompile(kind); return original.apply(this, args); };
|
|
174
|
+
};
|
|
175
|
+
if (typeof GPUDevice !== "undefined") {
|
|
176
|
+
wrapCompile(GPUDevice.prototype, "createShaderModule", "shaderModule");
|
|
177
|
+
wrapCompile(GPUDevice.prototype, "createRenderPipeline", "renderPipeline");
|
|
178
|
+
wrapCompile(GPUDevice.prototype, "createRenderPipelineAsync", "renderPipeline");
|
|
179
|
+
wrapCompile(GPUDevice.prototype, "createComputePipeline", "computePipeline");
|
|
180
|
+
wrapCompile(GPUDevice.prototype, "createComputePipelineAsync", "computePipeline");
|
|
181
|
+
}
|
|
182
|
+
for (const name of ["WebGLRenderingContext", "WebGL2RenderingContext"]) {
|
|
183
|
+
if (typeof window[name] !== "undefined") wrapCompile(window[name].prototype, "linkProgram", "program");
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Long Animation Frames name the script, function and invoker behind every frame over 50 ms.
|
|
187
|
+
try {
|
|
188
|
+
const observer = new PerformanceObserver((list) => {
|
|
189
|
+
for (const entry of list.getEntries()) {
|
|
190
|
+
state.loafs.push({
|
|
191
|
+
at: performance.timeOrigin + entry.startTime,
|
|
192
|
+
durationMs: +entry.duration.toFixed(1),
|
|
193
|
+
blockingMs: +(entry.blockingDuration || 0).toFixed(1),
|
|
194
|
+
renderMs: entry.renderStart ? +(entry.startTime + entry.duration - entry.renderStart).toFixed(1) : null,
|
|
195
|
+
scripts: (entry.scripts || []).slice(0, 6).map((script) => ({
|
|
196
|
+
invoker: script.invoker,
|
|
197
|
+
invokerType: script.invokerType,
|
|
198
|
+
sourceUrl: script.sourceURL,
|
|
199
|
+
sourceFunction: script.sourceFunctionName,
|
|
200
|
+
sourceChar: script.sourceCharPosition,
|
|
201
|
+
durationMs: +script.duration.toFixed(1),
|
|
202
|
+
forcedLayoutMs: +(script.forcedStyleAndLayoutDuration || 0).toFixed(1),
|
|
203
|
+
})),
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
observer.observe({ type: "long-animation-frame", buffered: true });
|
|
208
|
+
} catch {
|
|
209
|
+
// Long Animation Frames are Chrome 123+; the CPU profile still attributes the time without them.
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Static census of the scene now rendering: what the GPU is asked to do each frame and what may be expensive.
|
|
214
|
+
* @returns {object|null} null before a scene exists
|
|
215
|
+
*/
|
|
216
|
+
state.census = () => {
|
|
217
|
+
const scene = currentScene();
|
|
218
|
+
const engine = currentEngine();
|
|
219
|
+
if (!scene || !engine) return null;
|
|
220
|
+
const particleSystems = (scene.particleSystems || []).map((system) => ({
|
|
221
|
+
name: system.name,
|
|
222
|
+
className: system.getClassName ? system.getClassName() : "",
|
|
223
|
+
capacity: system.getCapacity ? system.getCapacity() : null,
|
|
224
|
+
emitRate: system.emitRate,
|
|
225
|
+
active: system.isStarted ? system.isStarted() : null,
|
|
226
|
+
activeCount: system.getActiveCount ? system.getActiveCount() : null,
|
|
227
|
+
emitter: system.emitter && system.emitter.name ? system.emitter.name : null,
|
|
228
|
+
}));
|
|
229
|
+
let adapter = "";
|
|
230
|
+
try { adapter = engine.getGlInfo ? JSON.stringify(engine.getGlInfo()) : ""; } catch { adapter = ""; }
|
|
231
|
+
return {
|
|
232
|
+
engine: engine.isWebGPU ? "WebGPU" : "WebGL" + (engine.webGLVersion || ""),
|
|
233
|
+
adapter,
|
|
234
|
+
hardwareScaling: engine.getHardwareScalingLevel(),
|
|
235
|
+
renderSize: [engine.getRenderWidth(), engine.getRenderHeight()],
|
|
236
|
+
devicePixelRatio: window.devicePixelRatio,
|
|
237
|
+
meshes: scene.meshes.length,
|
|
238
|
+
materials: scene.materials.length,
|
|
239
|
+
textures: scene.textures.length,
|
|
240
|
+
lights: scene.lights.length,
|
|
241
|
+
shadowGenerators: scene.lights.filter((light) => light.getShadowGenerator && light.getShadowGenerator()).length,
|
|
242
|
+
skeletons: (scene.skeletons || []).length,
|
|
243
|
+
animationGroups: (scene.animationGroups || []).length,
|
|
244
|
+
compiledEffects: engine._compiledEffects ? Object.keys(engine._compiledEffects).length : null,
|
|
245
|
+
particleSystems,
|
|
246
|
+
postProcesses: scene.activeCamera && scene.activeCamera._postProcesses ? scene.activeCamera._postProcesses.filter(Boolean).map((post) => post.name) : [],
|
|
247
|
+
physics: !!(scene.getPhysicsEngine && scene.getPhysicsEngine()),
|
|
248
|
+
};
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
/** Everything the probe recorded, for the capture script to save. */
|
|
252
|
+
state.dump = () => ({
|
|
253
|
+
engine: state.engine || null,
|
|
254
|
+
engineAttachedAt: state.engineAttachedAt,
|
|
255
|
+
scenesSeen: state.scenesSeen,
|
|
256
|
+
frameSource: state.engine ? "babylon" : "raf",
|
|
257
|
+
frames: state.engine ? state.frames : state.rafFrames,
|
|
258
|
+
counters: state.counters,
|
|
259
|
+
marks: state.marks,
|
|
260
|
+
loafs: state.loafs,
|
|
261
|
+
gpuCompiles: state.gpuCompiles,
|
|
262
|
+
gpuCold: window.__btGpuCold || null,
|
|
263
|
+
location: location.href,
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* `--gpu-cold true`: makes every fragment shader unique to this page load, so the GPU process cannot reuse a pipeline
|
|
269
|
+
* compiled on an earlier visit. A fresh Chrome profile only makes the browser cold — on macOS the compiled Metal pipelines
|
|
270
|
+
* live in a system cache outside it, so without this only the first capture after a shader change is a true first visit.
|
|
271
|
+
* Each fragment shader gets a branch that is never taken but cannot be folded away (it compares the pixel position with a
|
|
272
|
+
* random bound), so it renders exactly the same. Nothing on disk is touched. Serialised into every document like
|
|
273
|
+
* `installProbe`, so it must stay self-contained.
|
|
274
|
+
*/
|
|
275
|
+
export function installGpuCold() {
|
|
276
|
+
const bound = (1000000 + Math.floor(Math.random() * 1000000)) + 0.123;
|
|
277
|
+
const stats = { bound, tagged: 0, untagged: 0 };
|
|
278
|
+
window.__btGpuCold = stats;
|
|
279
|
+
|
|
280
|
+
/** WGSL: finds the @fragment entry point and the name of its pixel position, and opens its body with the branch. */
|
|
281
|
+
const tagWgsl = (code) => {
|
|
282
|
+
const head = /@fragment\s+fn\s+\w+\s*\(/.exec(code);
|
|
283
|
+
if (!head) return null;
|
|
284
|
+
// The parameter list holds attributes with their own parentheses (@location(0)): find its matching ")".
|
|
285
|
+
const open = head.index + head[0].length;
|
|
286
|
+
let depth = 1;
|
|
287
|
+
let close = open;
|
|
288
|
+
for (; close < code.length && depth > 0; close++) {
|
|
289
|
+
if (code[close] === "(") depth++;
|
|
290
|
+
else if (code[close] === ")") depth--;
|
|
291
|
+
}
|
|
292
|
+
close--; // the matching ")"
|
|
293
|
+
const body = code.indexOf("{", close);
|
|
294
|
+
if (depth !== 0 || body < 0) return null;
|
|
295
|
+
const parameters = code.slice(open, close);
|
|
296
|
+
const at = body + 1;
|
|
297
|
+
let position = null;
|
|
298
|
+
const direct = /@builtin\s*\(\s*position\s*\)\s*(\w+)\s*:/.exec(parameters);
|
|
299
|
+
if (direct) position = direct[1];
|
|
300
|
+
else {
|
|
301
|
+
for (const typed of parameters.matchAll(/(?:^|,)\s*(\w+)\s*:\s*(\w+)\s*(?=,|$)/g)) {
|
|
302
|
+
const struct = new RegExp(`struct\\s+${typed[2]}\\s*\\{([^}]*)\\}`).exec(code);
|
|
303
|
+
const field = struct && /@builtin\s*\(\s*position\s*\)\s*(\w+)\s*:/.exec(struct[1]);
|
|
304
|
+
if (field) { position = `${typed[1]}.${field[1]}`; break; }
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
if (position) return `${code.slice(0, at)}\n if (${position}.x < -${bound}) { discard; }${code.slice(at)}`;
|
|
308
|
+
// No pixel position among the inputs (a blit, a mip-map pass): add one — a builtin input never shifts the vertex
|
|
309
|
+
// stage's @location interface.
|
|
310
|
+
const kept = parameters.replace(/,\s*$/, "");
|
|
311
|
+
const signature = `${kept}${kept.trim() ? ", " : ""}@builtin(position) btGpuColdPosition : vec4<f32>`;
|
|
312
|
+
return `${code.slice(0, open)}${signature}${code.slice(close, at)}\n if (btGpuColdPosition.x < -${bound}) { discard; }${code.slice(at)}`;
|
|
313
|
+
};
|
|
314
|
+
if (typeof GPUDevice !== "undefined") {
|
|
315
|
+
const createShaderModule = GPUDevice.prototype.createShaderModule;
|
|
316
|
+
GPUDevice.prototype.createShaderModule = function (descriptor) {
|
|
317
|
+
const code = descriptor && typeof descriptor.code === "string" ? descriptor.code : null;
|
|
318
|
+
if (code == null || !code.includes("@fragment")) return createShaderModule.call(this, descriptor);
|
|
319
|
+
const tagged = tagWgsl(code);
|
|
320
|
+
if (tagged == null) { stats.untagged++; return createShaderModule.call(this, descriptor); }
|
|
321
|
+
stats.tagged++;
|
|
322
|
+
return createShaderModule.call(this, { ...descriptor, code: tagged });
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
// GLSL (WebGL): a fragment shader's main() opens with the same never-taken branch on gl_FragCoord.
|
|
326
|
+
for (const name of ["WebGLRenderingContext", "WebGL2RenderingContext"]) {
|
|
327
|
+
if (typeof window[name] === "undefined") continue;
|
|
328
|
+
const shaderSource = window[name].prototype.shaderSource;
|
|
329
|
+
window[name].prototype.shaderSource = function (shader, source) {
|
|
330
|
+
let fragment = false;
|
|
331
|
+
try { fragment = this.getShaderParameter(shader, this.SHADER_TYPE) === this.FRAGMENT_SHADER; } catch { /* not a shader */ }
|
|
332
|
+
const main = fragment && typeof source === "string" ? /void\s+main\s*\(\s*(void)?\s*\)\s*\{/.exec(source) : null;
|
|
333
|
+
if (!fragment) return shaderSource.call(this, shader, source);
|
|
334
|
+
if (!main) { stats.untagged++; return shaderSource.call(this, shader, source); }
|
|
335
|
+
stats.tagged++;
|
|
336
|
+
const at = main.index + main[0].length;
|
|
337
|
+
return shaderSource.call(this, shader, `${source.slice(0, at)}\n if (gl_FragCoord.x < -${bound}) discard;${source.slice(at)}`);
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
}
|