@babylonjs-toolkit/agent 1.2.9 → 1.2.11
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 +1 -1
- package/package.json +1 -1
- package/skills/bt-optimize/SKILL.md +29 -10
- package/skills/bt-optimize/scripts/BtCombine.cs +25 -1
- package/skills/bt-optimize/scripts/BtOptimize.cs +1102 -8
- package/skills/bt-optimize/scripts/qa/compare-profiles.mjs +95 -0
- package/skills/bt-optimize/scripts/qa/profile-browser.mjs +386 -1
|
@@ -30,6 +30,100 @@ function change(before, after, digits = 0) {
|
|
|
30
30
|
return `${before.toFixed(digits)} → **${after.toFixed(digits)}** (${percent >= 0 ? "+" : ""}${percent}%)`;
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
+
/** How many owners and repeated shapes each pin's accounting tables list. */
|
|
34
|
+
const DRAW_OWNER_ROWS = 12;
|
|
35
|
+
|
|
36
|
+
/** The owner name profile-browser.mjs gives main-pass draws no scene object's render call made. */
|
|
37
|
+
const UNOWNED = "(unowned)";
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Whether a run's accounting measured its draws per render call (profiles from before that have no frameMainDraws
|
|
41
|
+
* and no "(unowned)" entry, so a missing owner there means "not measured", not "no draws").
|
|
42
|
+
* @param {object|null} accounting - one run's drawOwners at a pin
|
|
43
|
+
*/
|
|
44
|
+
function isMeasured(accounting) {
|
|
45
|
+
return accounting != null && accounting.frameMainDraws != null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The owner names one pin's table lists: the top DRAW_OWNER_ROWS of every run, plus "(unowned)" whenever a run
|
|
50
|
+
* measured its draws, so a draw no object owns is never cut off the table (and a measured 0 shows every draw owned).
|
|
51
|
+
* @param {(object|null)[]} accountings - each run's drawOwners at this pin (null when the run has none)
|
|
52
|
+
* @returns {string[]} the owner names, in first-seen order
|
|
53
|
+
*/
|
|
54
|
+
function tableOwnerNames(accountings) {
|
|
55
|
+
const present = accountings.filter(Boolean);
|
|
56
|
+
const topOwners = present.flatMap((accounting) => accounting.owners.slice(0, DRAW_OWNER_ROWS).map((owner) => owner.owner));
|
|
57
|
+
const showUnowned = present.some((accounting) => isMeasured(accounting) || accounting.owners.some((owner) => owner.owner === UNOWNED));
|
|
58
|
+
return [...new Set(showUnowned ? [...topOwners, UNOWNED] : topOwners)];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* One run's draws for one owner: its draws, 0 when the run lists no such owner, "—" when the run has no accounting
|
|
63
|
+
* (or, for "(unowned)", did not measure draws per render call).
|
|
64
|
+
* @param {object|null} accounting - the run's drawOwners at this pin
|
|
65
|
+
* @param {string} ownerName - the owner of this table row
|
|
66
|
+
* @returns {number|string} the cell value
|
|
67
|
+
*/
|
|
68
|
+
function ownerDrawsCell(accounting, ownerName) {
|
|
69
|
+
if (accounting == null) return "—";
|
|
70
|
+
const owner = accounting.owners.find((candidate) => candidate.owner === ownerName);
|
|
71
|
+
if (owner) return owner.draws;
|
|
72
|
+
if (ownerName === UNOWNED && !isMeasured(accounting)) return "—";
|
|
73
|
+
return 0;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The last run's description column for one owner: its skinned / instanced / lightmapped mesh counts, or for
|
|
78
|
+
* "(unowned)" the classes whose render made those draws.
|
|
79
|
+
* @param {object|undefined} latest - the owner's entry in the last run, if it has one
|
|
80
|
+
* @returns {string} the cell text
|
|
81
|
+
*/
|
|
82
|
+
function ownerKinds(latest) {
|
|
83
|
+
if (!latest) return "—";
|
|
84
|
+
if (latest.sources) return `made by ${latest.sources.join(", ")}`;
|
|
85
|
+
return `${latest.skinned} / ${latest.instances} / ${latest.lightmapped}`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Appends, per pinned view, the main-pass draws by owning scene object for every run side by side (with any
|
|
90
|
+
* "(unowned)" draws), the accounted total beside the frame's measured main-pass draws, then the last run's repeated
|
|
91
|
+
* shapes that still cost one draw per copy and why. A pin the last run has no accounting for is skipped, and a run
|
|
92
|
+
* without accounting shows "—"; runs profiled before draws were measured per render call have no frameMainDraws (and
|
|
93
|
+
* no "(unowned)" entry) and show "—" in those rows.
|
|
94
|
+
* @param {string[]} lines - the report lines to append to
|
|
95
|
+
* @param {object[]} runs - the parsed profile runs, in label order
|
|
96
|
+
* @param {(index: number) => string} name - the label of run `index`
|
|
97
|
+
*/
|
|
98
|
+
function appendDrawOwners(lines, runs, name) {
|
|
99
|
+
const last = runs[runs.length - 1];
|
|
100
|
+
for (const pin of last.pins) {
|
|
101
|
+
const accountings = runs.map((run) => (run.pins || []).find((candidate) => candidate.atSeconds === pin.atSeconds)?.drawOwners ?? null);
|
|
102
|
+
const lastAccounting = accountings[accountings.length - 1];
|
|
103
|
+
if (lastAccounting == null) continue;
|
|
104
|
+
lines.push(`**Main-pass draws by owner — ${pin.atSeconds} s view**`);
|
|
105
|
+
lines.push("");
|
|
106
|
+
lines.push(`| Owner | ${runs.map((_, index) => name(index)).join(" | ")} | Skinned / instanced / lightmapped meshes (${name(runs.length - 1)}) | Shadow-map casters (${name(runs.length - 1)}) |`);
|
|
107
|
+
lines.push(`|---|${runs.map(() => "---").join("|")}|---|---|`);
|
|
108
|
+
for (const ownerName of tableOwnerNames(accountings)) {
|
|
109
|
+
const cells = accountings.map((accounting) => ownerDrawsCell(accounting, ownerName));
|
|
110
|
+
const latest = lastAccounting.owners.find((owner) => owner.owner === ownerName);
|
|
111
|
+
lines.push(`| ${ownerName} | ${cells.join(" | ")} | ${ownerKinds(latest)} | ${latest?.shadowCasters ?? "—"} |`);
|
|
112
|
+
}
|
|
113
|
+
lines.push(`| **All main-pass draws** (mainDraws) | ${accountings.map((accounting) => (accounting ? `**${accounting.mainDraws}**` : "—")).join(" | ")} | | |`);
|
|
114
|
+
lines.push(`| Main-pass draws of the same frame (frameMainDraws) | ${accountings.map((accounting) => accounting?.frameMainDraws ?? "—").join(" | ")} | | |`);
|
|
115
|
+
lines.push("");
|
|
116
|
+
const costly = lastAccounting.repeats.filter((repeat) => repeat.blocker != null).slice(0, DRAW_OWNER_ROWS);
|
|
117
|
+
if (costly.length === 0) continue;
|
|
118
|
+
lines.push(`Repeated shapes still drawn once per copy (${name(runs.length - 1)}):`);
|
|
119
|
+
lines.push("");
|
|
120
|
+
lines.push("| Shape | Owner | Copies | Draws | Why the copies do not share one draw |");
|
|
121
|
+
lines.push("|---|---|---|---|---|");
|
|
122
|
+
for (const repeat of costly) lines.push(`| ${repeat.shape} | ${repeat.owner} | ${repeat.copies} | ${repeat.draws} | ${repeat.blocker} |`);
|
|
123
|
+
lines.push("");
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
33
127
|
/** Entry point. */
|
|
34
128
|
function main() {
|
|
35
129
|
const { flags, files } = parseArguments(process.argv.slice(2));
|
|
@@ -59,6 +153,7 @@ function main() {
|
|
|
59
153
|
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
154
|
}
|
|
61
155
|
lines.push("");
|
|
156
|
+
appendDrawOwners(lines, runs, name);
|
|
62
157
|
}
|
|
63
158
|
if (first.samples && last.samples) {
|
|
64
159
|
lines.push(`| Timeline | FPS | p95 frame ms | Worst frame ms | Draws / frame |`);
|
|
@@ -315,6 +315,9 @@ function installProbe() {
|
|
|
315
315
|
/**
|
|
316
316
|
* For every active mesh: the lights Babylon actually binds (mesh.lightSources, capped by the material's
|
|
317
317
|
* maxSimultaneousLights) and how many of those cannot reach the mesh at all (point / spot beyond their range).
|
|
318
|
+
* Babylon's Light.canAffectMesh has no range test, so tighter mesh bounds never lower the bindings. The reach test
|
|
319
|
+
* clamps each light into the mesh's world box, so a mesh with scene-sized bounds (a skinned mesh, a track-wide
|
|
320
|
+
* mesh) always counts as in range: a low share on such a scene understates the waste.
|
|
318
321
|
*/
|
|
319
322
|
state.lightAudit = () => {
|
|
320
323
|
const scene = state.scene();
|
|
@@ -342,6 +345,386 @@ function installProbe() {
|
|
|
342
345
|
shadowedBoundPerMesh: +(shadowed / Math.max(1, meshes)).toFixed(2), mostBound: Object.entries(names).sort((a, b) => b[1] - a[1]).slice(0, 6) };
|
|
343
346
|
};
|
|
344
347
|
|
|
348
|
+
/** Babylon classes whose render call draws for one scene object, mapped to the kind of object each draws for. */
|
|
349
|
+
const DRAW_OWNER_CLASSES = { Mesh: "mesh", ParticleSystem: "particles", GPUParticleSystem: "particles", SpriteManager: "sprites", Layer: "layer" };
|
|
350
|
+
|
|
351
|
+
/** Classes whose render call only hands the frame to other render calls, so they never name an unowned draw. */
|
|
352
|
+
const DISPATCHER_CLASSES = new Set(["Scene", "RenderingManager", "RenderingGroup", "SubMesh"]);
|
|
353
|
+
|
|
354
|
+
/** The owner name that collects main-pass draws no wrapped render call made. */
|
|
355
|
+
const UNOWNED = "(unowned)";
|
|
356
|
+
|
|
357
|
+
/** Position of Mesh.render's effectiveMeshReplacement argument (the instance drawn as a regular mesh, if any). */
|
|
358
|
+
const MESH_RENDER_EFFECTIVE_MESH_ARGUMENT = 2;
|
|
359
|
+
|
|
360
|
+
/** Longest drawOwners waits for the scene to render the frame it records, in milliseconds. */
|
|
361
|
+
const DRAW_OWNER_FRAME_TIMEOUT_MS = 10000;
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* Stack frames of the draw counter's own path (this probe, the engine's draw calls, WebGPU's internal _draw),
|
|
365
|
+
* skipped when naming the code behind an unowned draw.
|
|
366
|
+
*/
|
|
367
|
+
const DRAW_COUNTER_FRAME = /countDraws|chargeDraws|describeDrawCaller|addCount|_reportDrawCall|drawElementsType|drawArraysType|\._draw \(|^Error/;
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* The scene object that owns a node: the child of the scene root it sits under (a root node owns itself).
|
|
371
|
+
* @param {any} node - a mesh, transform node or particle emitter
|
|
372
|
+
* @returns {string} the owner's name
|
|
373
|
+
*/
|
|
374
|
+
state.ownerOf = (node) => {
|
|
375
|
+
let current = node;
|
|
376
|
+
while (current.parent && current.parent.parent) current = current.parent;
|
|
377
|
+
return current.parent ? current.name : node.name;
|
|
378
|
+
};
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Names the code that drew outside every wrapped render call: the first stack frame past the draw counter's path.
|
|
382
|
+
* @returns {string} "(no render call) <function and script position>"
|
|
383
|
+
*/
|
|
384
|
+
const describeDrawCaller = () => {
|
|
385
|
+
const stackLines = (new Error().stack || "").split("\n").map((line) => line.trim().replace(/^at /, ""));
|
|
386
|
+
const caller = stackLines.find((line) => line.length > 0 && !DRAW_COUNTER_FRAME.test(line));
|
|
387
|
+
return caller ? "(no render call) " + caller : "(no render call)";
|
|
388
|
+
};
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Charges draws the engine just counted to the frame being recorded: to the innermost owning render call on the
|
|
392
|
+
* call stack, or else to "(unowned)" under the innermost render call's class (or, with none, the calling code).
|
|
393
|
+
* Draws outside the main draw phase, or while no frame is armed, are not charged.
|
|
394
|
+
* @param {number} added - how much the engine's draw counter just went up
|
|
395
|
+
*/
|
|
396
|
+
const chargeDraws = (added) => {
|
|
397
|
+
const frame = state.drawOwnerFrame;
|
|
398
|
+
if (!frame || !frame.inDrawPhase || added <= 0) return;
|
|
399
|
+
const owningCall = frame.callStack.findLast((call) => call.renderer !== undefined);
|
|
400
|
+
if (owningCall) {
|
|
401
|
+
owningCall.draws += added;
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
const sourceCall = frame.callStack.findLast((call) => call.source !== undefined);
|
|
405
|
+
const source = sourceCall ? sourceCall.source : describeDrawCaller();
|
|
406
|
+
frame.unownedSources.set(source, (frame.unownedSources.get(source) || 0) + added);
|
|
407
|
+
};
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* The node a render call draws for, which decides its owner: a mesh's effective mesh (an instance that acts as a
|
|
411
|
+
* regular mesh, else the mesh), a particle system's emitter when it is a node, nothing for sprites and layers.
|
|
412
|
+
* @param {any} renderer - the object whose render was called
|
|
413
|
+
* @param {string} kind - its DRAW_OWNER_CLASSES kind
|
|
414
|
+
* @param {any[]} renderArguments - the render call's arguments (Mesh.render's third is the effective mesh)
|
|
415
|
+
* @returns {any|null} the node, or null when the renderer is not attached to one
|
|
416
|
+
*/
|
|
417
|
+
const drawnNodeOf = (renderer, kind, renderArguments) => {
|
|
418
|
+
if (kind === "mesh") return renderArguments[MESH_RENDER_EFFECTIVE_MESH_ARGUMENT] || renderer;
|
|
419
|
+
if (kind === "particles" && renderer.emitter instanceof BABYLON.Node) return renderer.emitter;
|
|
420
|
+
return null;
|
|
421
|
+
};
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* The recorded frame's draw record for one renderer, created on its first render call.
|
|
425
|
+
* @returns {{kind: string, renderer: any, drawnNode: any, draws: number, calls: number}} the record
|
|
426
|
+
*/
|
|
427
|
+
const rendererRecord = (frame, renderer, kind, renderArguments) => {
|
|
428
|
+
if (!frame.renderers.has(renderer)) {
|
|
429
|
+
frame.renderers.set(renderer, { kind, renderer, drawnNode: drawnNodeOf(renderer, kind, renderArguments), draws: 0, calls: 0 });
|
|
430
|
+
}
|
|
431
|
+
return frame.renderers.get(renderer);
|
|
432
|
+
};
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Calls a wrapped function with a context on the recorded frame's call stack, so draws it makes are charged to
|
|
436
|
+
* that context (an owning renderer's record, or a named source), and takes the context off again afterwards.
|
|
437
|
+
* @returns {any} what the original function returned
|
|
438
|
+
*/
|
|
439
|
+
const callInContext = (frame, context, original, receiver, callArguments) => {
|
|
440
|
+
frame.callStack.push(context);
|
|
441
|
+
try {
|
|
442
|
+
return original.apply(receiver, callArguments);
|
|
443
|
+
} finally {
|
|
444
|
+
frame.callStack.pop();
|
|
445
|
+
}
|
|
446
|
+
};
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* Wraps an owning class's render so each call inside a recorded draw phase sits on the frame's call stack,
|
|
450
|
+
* collecting the draws it makes.
|
|
451
|
+
* @param {object} prototype - the class prototype (marked __btDrawOwnerWrapped)
|
|
452
|
+
* @param {string} kind - the DRAW_OWNER_CLASSES kind of the objects it draws for
|
|
453
|
+
*/
|
|
454
|
+
const wrapOwnerRender = (prototype, kind) => {
|
|
455
|
+
prototype.__btDrawOwnerWrapped = true;
|
|
456
|
+
const original = prototype.render;
|
|
457
|
+
prototype.render = function (...renderArguments) {
|
|
458
|
+
const frame = state.drawOwnerFrame;
|
|
459
|
+
if (!frame || !frame.inDrawPhase) return original.apply(this, renderArguments);
|
|
460
|
+
const record = rendererRecord(frame, this, kind, renderArguments);
|
|
461
|
+
record.calls++;
|
|
462
|
+
return callInContext(frame, record, original, this, renderArguments);
|
|
463
|
+
};
|
|
464
|
+
};
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* Wraps any other class's render so draws it makes outside an owning call are named by its class name.
|
|
468
|
+
* @param {object} prototype - the class prototype (marked __btDrawOwnerWrapped)
|
|
469
|
+
* @param {string} exportName - the class's BABYLON export name, used when an instance has no getClassName
|
|
470
|
+
*/
|
|
471
|
+
const wrapSourceRender = (prototype, exportName) => {
|
|
472
|
+
prototype.__btDrawOwnerWrapped = true;
|
|
473
|
+
const original = prototype.render;
|
|
474
|
+
prototype.render = function (...renderArguments) {
|
|
475
|
+
const frame = state.drawOwnerFrame;
|
|
476
|
+
if (!frame || !frame.inDrawPhase) return original.apply(this, renderArguments);
|
|
477
|
+
const source = typeof this.getClassName === "function" ? this.getClassName() : exportName;
|
|
478
|
+
return callInContext(frame, { source }, original, this, renderArguments);
|
|
479
|
+
};
|
|
480
|
+
};
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* Whether a BABYLON export is a class with its own render method that may draw for no scene object
|
|
484
|
+
* (a bounding-box, edges, outline or lens-flare renderer, an effect layer…) and is not wrapped yet.
|
|
485
|
+
*/
|
|
486
|
+
const isSourceClass = (exportName, value) => {
|
|
487
|
+
if (typeof value !== "function" || !value.prototype) return false;
|
|
488
|
+
if (DISPATCHER_CLASSES.has(exportName) || exportName.endsWith("Engine")) return false;
|
|
489
|
+
if (Object.hasOwn(value.prototype, "__btDrawOwnerWrapped")) return false;
|
|
490
|
+
const descriptor = Object.getOwnPropertyDescriptor(value.prototype, "render");
|
|
491
|
+
return descriptor !== undefined && typeof descriptor.value === "function" && descriptor.writable === true;
|
|
492
|
+
};
|
|
493
|
+
|
|
494
|
+
/** Wraps the owning classes' render calls, then every other BABYLON class's own render as a named source. */
|
|
495
|
+
const wrapRenderClasses = () => {
|
|
496
|
+
for (const [className, kind] of Object.entries(DRAW_OWNER_CLASSES)) {
|
|
497
|
+
const ownerClass = BABYLON[className];
|
|
498
|
+
if (!ownerClass || typeof ownerClass.prototype.render !== "function") continue;
|
|
499
|
+
if (Object.hasOwn(ownerClass.prototype, "__btDrawOwnerWrapped")) continue;
|
|
500
|
+
wrapOwnerRender(ownerClass.prototype, kind);
|
|
501
|
+
}
|
|
502
|
+
for (const exportName of Object.keys(BABYLON)) {
|
|
503
|
+
const value = BABYLON[exportName];
|
|
504
|
+
if (isSourceClass(exportName, value)) wrapSourceRender(value.prototype, exportName);
|
|
505
|
+
}
|
|
506
|
+
};
|
|
507
|
+
|
|
508
|
+
/**
|
|
509
|
+
* Wraps one scene stage step (a scene component's hook into the frame) as a source named by its component.
|
|
510
|
+
* @param {{component: any, action: Function}} step - the step (marked __btDrawOwnerWrapped)
|
|
511
|
+
*/
|
|
512
|
+
const wrapStageStep = (step) => {
|
|
513
|
+
if (step.__btDrawOwnerWrapped || typeof step.action !== "function") return;
|
|
514
|
+
step.__btDrawOwnerWrapped = true;
|
|
515
|
+
const original = step.action;
|
|
516
|
+
const component = step.component;
|
|
517
|
+
const source = (component && component.name) || "SceneComponent";
|
|
518
|
+
step.action = function (...stepArguments) {
|
|
519
|
+
const frame = state.drawOwnerFrame;
|
|
520
|
+
if (!frame || !frame.inDrawPhase) return original.apply(this, stepArguments);
|
|
521
|
+
return callInContext(frame, { source }, original, this, stepArguments);
|
|
522
|
+
};
|
|
523
|
+
};
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* Wraps every step of the scene's stages (bounding boxes, effect layers, outlines, layers…) not wrapped yet. A
|
|
527
|
+
* scene component registers a bound copy of its method, so a prototype wrapper installed after the scene loaded
|
|
528
|
+
* never sees those calls: without this, a bounding-box draw would be unowned with no class to name it. A Stage is
|
|
529
|
+
* an array-like made by Stage.Create (Array.isArray is false), so stages are found by their registerStep method.
|
|
530
|
+
* @param {any} scene - the scene whose `_…Stage` lists to scan
|
|
531
|
+
*/
|
|
532
|
+
const wrapSceneStages = (scene) => {
|
|
533
|
+
for (const key of Object.keys(scene)) {
|
|
534
|
+
const stage = scene[key];
|
|
535
|
+
if (!key.endsWith("Stage") || !stage || typeof stage.registerStep !== "function") continue;
|
|
536
|
+
for (let i = 0; i < stage.length; i++) wrapStageStep(stage[i]);
|
|
537
|
+
}
|
|
538
|
+
};
|
|
539
|
+
|
|
540
|
+
/**
|
|
541
|
+
* Wraps the engine's draw counter so every increment is charged to the recorded frame as it happens.
|
|
542
|
+
* @param {any} counter - engine._drawCalls (marked __btDrawOwnerWrapped)
|
|
543
|
+
*/
|
|
544
|
+
const wrapDrawCounter = (counter) => {
|
|
545
|
+
counter.__btDrawOwnerWrapped = true;
|
|
546
|
+
const originalAddCount = counter.addCount;
|
|
547
|
+
counter.addCount = function countDraws(count, fetchResult) {
|
|
548
|
+
const before = this._current;
|
|
549
|
+
const result = originalAddCount.call(this, count, fetchResult);
|
|
550
|
+
chargeDraws(this._current - before);
|
|
551
|
+
return result;
|
|
552
|
+
};
|
|
553
|
+
};
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* Drives the armed frame through the scene: it starts at the next main draw phase, counts each phase's draws on
|
|
557
|
+
* the engine's counter (frameMainDraws, as passes.main measures it) and resolves at the end of that frame.
|
|
558
|
+
* @param {any} scene - the scene (marked __btDrawOwnerWrapped)
|
|
559
|
+
* @param {any} counter - engine._drawCalls
|
|
560
|
+
*/
|
|
561
|
+
const watchDrawPhases = (scene, counter) => {
|
|
562
|
+
scene.__btDrawOwnerWrapped = true;
|
|
563
|
+
scene.onBeforeDrawPhaseObservable.add(() => {
|
|
564
|
+
const frame = state.drawOwnerFrame;
|
|
565
|
+
if (!frame) return;
|
|
566
|
+
frame.started = true;
|
|
567
|
+
frame.inDrawPhase = true;
|
|
568
|
+
frame.phaseStart = counter._current;
|
|
569
|
+
});
|
|
570
|
+
scene.onAfterDrawPhaseObservable.add(() => {
|
|
571
|
+
const frame = state.drawOwnerFrame;
|
|
572
|
+
if (!frame || !frame.inDrawPhase) return;
|
|
573
|
+
frame.inDrawPhase = false;
|
|
574
|
+
frame.frameMainDraws += counter._current - frame.phaseStart;
|
|
575
|
+
});
|
|
576
|
+
scene.getEngine().onEndFrameObservable.add(() => {
|
|
577
|
+
const frame = state.drawOwnerFrame;
|
|
578
|
+
if (!frame || !frame.started) return;
|
|
579
|
+
state.drawOwnerFrame = null;
|
|
580
|
+
frame.resolve(frame);
|
|
581
|
+
});
|
|
582
|
+
};
|
|
583
|
+
|
|
584
|
+
/**
|
|
585
|
+
* Installs the draw-ownership wrappers once per page: the render calls, the engine's draw counter and the
|
|
586
|
+
* scene's draw-phase observers. Scene stage steps registered since the last call are wrapped on every call.
|
|
587
|
+
* They record nothing until a frame is armed.
|
|
588
|
+
* @returns {boolean} false when the engine has no draw counter to measure
|
|
589
|
+
*/
|
|
590
|
+
state.installDrawOwnerWrappers = () => {
|
|
591
|
+
const scene = state.scene();
|
|
592
|
+
const counter = scene.getEngine()._drawCalls;
|
|
593
|
+
if (!counter) return false;
|
|
594
|
+
if (!Object.hasOwn(BABYLON.Mesh.prototype, "__btDrawOwnerWrapped")) wrapRenderClasses();
|
|
595
|
+
if (!counter.__btDrawOwnerWrapped) wrapDrawCounter(counter);
|
|
596
|
+
if (!scene.__btDrawOwnerWrapped) watchDrawPhases(scene, counter);
|
|
597
|
+
wrapSceneStages(scene);
|
|
598
|
+
return true;
|
|
599
|
+
};
|
|
600
|
+
|
|
601
|
+
/**
|
|
602
|
+
* Arms state.drawOwnerFrame and resolves with it once the next frame's main draw phase has rendered.
|
|
603
|
+
* @returns {Promise<{frameMainDraws: number, renderers: Map<any, object>, unownedSources: Map<string, number>}>}
|
|
604
|
+
*/
|
|
605
|
+
state.recordDrawOwnerFrame = () => new Promise((resolve, reject) => {
|
|
606
|
+
const frame = { started: false, inDrawPhase: false, phaseStart: 0, frameMainDraws: 0, renderers: new Map(), unownedSources: new Map(), callStack: [], resolve };
|
|
607
|
+
state.drawOwnerFrame = frame;
|
|
608
|
+
setTimeout(() => {
|
|
609
|
+
if (state.drawOwnerFrame !== frame) return;
|
|
610
|
+
state.drawOwnerFrame = null;
|
|
611
|
+
reject(new Error(`drawOwners: no frame rendered within ${DRAW_OWNER_FRAME_TIMEOUT_MS} ms`));
|
|
612
|
+
}, DRAW_OWNER_FRAME_TIMEOUT_MS);
|
|
613
|
+
});
|
|
614
|
+
|
|
615
|
+
/**
|
|
616
|
+
* The owner a renderer's measured draws go to. A mesh's go to the owner of the first active mesh drawn through it
|
|
617
|
+
* (the source itself or its first visible instance, the rule the active-mesh census uses); otherwise to the
|
|
618
|
+
* owner of the node it draws for, or to its own name.
|
|
619
|
+
*/
|
|
620
|
+
const ownerOfRenderer = (record, firstOwnerBySource) => {
|
|
621
|
+
if (record.kind === "mesh" && firstOwnerBySource.has(record.renderer)) return firstOwnerBySource.get(record.renderer);
|
|
622
|
+
if (record.drawnNode) return state.ownerOf(record.drawnNode);
|
|
623
|
+
return record.renderer.name || record.renderer.getClassName();
|
|
624
|
+
};
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* Explains a mesh that made more draws than it has sub-meshes, or null when it made no more.
|
|
628
|
+
* @returns {string|null} e.g. "Tree_Mesh0: 2 draws from 1 sub-mesh in 2 render calls (a split instance batch)"
|
|
629
|
+
*/
|
|
630
|
+
const extraDrawsNote = (record, subMeshCount) => {
|
|
631
|
+
if (record.kind !== "mesh" || record.draws <= subMeshCount) return null;
|
|
632
|
+
const instanced = record.renderer.instances && record.renderer.instances.length > 0;
|
|
633
|
+
const counts = `${record.renderer.name}: ${record.draws} draws from ${subMeshCount} sub-mesh(es) in ${record.calls} render calls`;
|
|
634
|
+
if (record.calls > subMeshCount) return counts + (instanced ? " (a split instance batch)" : " (rendered more than once)");
|
|
635
|
+
return counts + " (more than one draw per render call: outline, edges or a multi-pass material)";
|
|
636
|
+
};
|
|
637
|
+
|
|
638
|
+
/**
|
|
639
|
+
* Accounts for every main-pass draw by measuring it: during the next rendered frame each draw the engine counts in
|
|
640
|
+
* the main draw phase is charged to the render call that made it — a mesh, particle system, sprite manager or
|
|
641
|
+
* layer — and from there to the scene object that owns it (the child of the scene root it sits under). Draws no
|
|
642
|
+
* such call made go to "(unowned)", named by the class (or code) that made them. The active meshes give each
|
|
643
|
+
* owner's mesh census and every shape drawn more than once, with what stops its copies from sharing one instanced
|
|
644
|
+
* draw (inferred, as the repeats always were). Also counts each owner's meshes in the shadow maps' caster lists.
|
|
645
|
+
* Per-pass totals say where the frame goes; this says which objects to fix, so no group of draws is skipped
|
|
646
|
+
* unexamined.
|
|
647
|
+
* @returns {Promise<{owners: object[], repeats: object[], mainDraws: number, frameMainDraws: number}|null>} the draw
|
|
648
|
+
* accounting at the current view, or null when the engine has no draw counter. `mainDraws` is the sum of every
|
|
649
|
+
* owner's measured `draws` (including "(unowned)"); `frameMainDraws` is the same frame's main-phase draw counter
|
|
650
|
+
* (what passes.main measures), so the two are equal when every draw is accounted for. Each owner is
|
|
651
|
+
* {owner, meshes, draws, skinned, instances, lightmapped, uniqueShapes, shadowCasters, examples}, where
|
|
652
|
+
* `examples` also notes any mesh that made more draws than its sub-meshes; the unowned entry is
|
|
653
|
+
* {owner: "(unowned)", draws, sources: [class or calling-code names, most draws first]}.
|
|
654
|
+
*/
|
|
655
|
+
state.drawOwners = async () => {
|
|
656
|
+
if (!state.installDrawOwnerWrappers()) return null;
|
|
657
|
+
const frame = await state.recordDrawOwnerFrame();
|
|
658
|
+
const scene = state.scene();
|
|
659
|
+
const activeMeshes = scene.getActiveMeshes().data.slice(0, scene.getActiveMeshes().length);
|
|
660
|
+
const subMeshDraws = (mesh) => (mesh.subMeshes ? mesh.subMeshes.length : 1);
|
|
661
|
+
const owners = new Map();
|
|
662
|
+
const ownerEntry = (ownerName) => {
|
|
663
|
+
if (!owners.has(ownerName)) owners.set(ownerName, { owner: ownerName, meshes: 0, draws: 0, skinned: 0, instances: 0, lightmapped: 0, geometries: new Set(), examples: [] });
|
|
664
|
+
return owners.get(ownerName);
|
|
665
|
+
};
|
|
666
|
+
const repeats = new Map();
|
|
667
|
+
const drawnSources = new Set();
|
|
668
|
+
const firstOwnerBySource = new Map();
|
|
669
|
+
for (const mesh of activeMeshes) {
|
|
670
|
+
const source = mesh.isAnInstance ? mesh.sourceMesh : mesh;
|
|
671
|
+
// Instances draw in their source's single instanced call: the inferred repeat count takes that call once.
|
|
672
|
+
const inferredDraws = mesh.isAnInstance ? (drawnSources.has(source) ? 0 : subMeshDraws(source)) : subMeshDraws(mesh);
|
|
673
|
+
drawnSources.add(source);
|
|
674
|
+
const ownerName = state.ownerOf(mesh);
|
|
675
|
+
if (!firstOwnerBySource.has(source)) firstOwnerBySource.set(source, ownerName);
|
|
676
|
+
const owner = ownerEntry(ownerName);
|
|
677
|
+
owner.meshes++;
|
|
678
|
+
if (source.skeleton) owner.skinned++;
|
|
679
|
+
if (mesh.isAnInstance) owner.instances++;
|
|
680
|
+
if (mesh.material && mesh.material.lightmapTexture) owner.lightmapped++;
|
|
681
|
+
if (source.geometry) owner.geometries.add(source.geometry.uniqueId);
|
|
682
|
+
if (owner.examples.length < 3) owner.examples.push(mesh.name);
|
|
683
|
+
if (!source.geometry) continue;
|
|
684
|
+
const repeatKey = source.geometry.uniqueId + "|" + (mesh.material ? mesh.material.uniqueId : "none");
|
|
685
|
+
if (!repeats.has(repeatKey)) repeats.set(repeatKey, { shape: source.name, owner: ownerName, copies: 0, draws: 0, skinned: 0, instances: 0, lightmapped: 0 });
|
|
686
|
+
const repeat = repeats.get(repeatKey);
|
|
687
|
+
repeat.copies++;
|
|
688
|
+
repeat.draws += inferredDraws;
|
|
689
|
+
if (source.skeleton) repeat.skinned++;
|
|
690
|
+
if (mesh.isAnInstance) repeat.instances++;
|
|
691
|
+
if (mesh.material && mesh.material.lightmapTexture) repeat.lightmapped++;
|
|
692
|
+
}
|
|
693
|
+
for (const record of frame.renderers.values()) {
|
|
694
|
+
if (record.draws === 0) continue;
|
|
695
|
+
const owner = ownerEntry(ownerOfRenderer(record, firstOwnerBySource));
|
|
696
|
+
owner.draws += record.draws;
|
|
697
|
+
const note = extraDrawsNote(record, subMeshDraws(record.renderer));
|
|
698
|
+
if (note) owner.examples.push(note);
|
|
699
|
+
}
|
|
700
|
+
const shadowCasters = new Map();
|
|
701
|
+
for (const light of scene.lights) {
|
|
702
|
+
const generator = light.getShadowGenerator && light.getShadowGenerator();
|
|
703
|
+
const renderList = generator && generator.getShadowMap() ? generator.getShadowMap().renderList || [] : [];
|
|
704
|
+
for (const caster of renderList) shadowCasters.set(state.ownerOf(caster), (shadowCasters.get(state.ownerOf(caster)) || 0) + 1);
|
|
705
|
+
}
|
|
706
|
+
const blockerOf = (repeat) => {
|
|
707
|
+
if (repeat.skinned > 0) return "skinned: every copy is its own draw (Babylon cannot instance separately animated skinned meshes)";
|
|
708
|
+
if (repeat.lightmapped > 0) return "lightmapped: the exporter gives every lightmapped copy its own mesh";
|
|
709
|
+
if (repeat.instances < repeat.copies - 1) return "separate meshes of one shape: not exported as instances (material split by reflection probe or lightmap index?)";
|
|
710
|
+
return null;
|
|
711
|
+
};
|
|
712
|
+
const ownerRows = [...owners.values()].map((owner) => ({
|
|
713
|
+
owner: owner.owner, meshes: owner.meshes, draws: owner.draws, skinned: owner.skinned, instances: owner.instances, lightmapped: owner.lightmapped,
|
|
714
|
+
uniqueShapes: owner.geometries.size, shadowCasters: shadowCasters.get(owner.owner) || 0, examples: owner.examples,
|
|
715
|
+
}));
|
|
716
|
+
const unownedSources = [...frame.unownedSources.entries()].map(([source, draws]) => ({ source, draws })).sort((first, second) => second.draws - first.draws);
|
|
717
|
+
const unownedDraws = unownedSources.reduce((sum, entry) => sum + entry.draws, 0);
|
|
718
|
+
if (unownedDraws > 0) ownerRows.push({ owner: UNOWNED, draws: unownedDraws, sources: unownedSources.map((entry) => entry.source) });
|
|
719
|
+
return {
|
|
720
|
+
mainDraws: ownerRows.reduce((sum, owner) => sum + owner.draws, 0),
|
|
721
|
+
frameMainDraws: frame.frameMainDraws,
|
|
722
|
+
owners: ownerRows.sort((first, second) => second.draws - first.draws),
|
|
723
|
+
repeats: [...repeats.values()].filter((repeat) => repeat.copies > 1).sort((first, second) => second.draws - first.draws).slice(0, 25)
|
|
724
|
+
.map((repeat) => ({ ...repeat, blocker: blockerOf(repeat) })),
|
|
725
|
+
};
|
|
726
|
+
};
|
|
727
|
+
|
|
345
728
|
/**
|
|
346
729
|
* Switches one runtime cost off (on = false) or back on (on = true).
|
|
347
730
|
* Keys: dpr, taa, motionblur, bloom, post (every camera post-process), shadows, lights (every point / spot light).
|
|
@@ -518,6 +901,8 @@ async function main() {
|
|
|
518
901
|
process.stderr.write(`WARNING pin ${seconds}s drifted: target ${JSON.stringify(pinned)} actual ${JSON.stringify(poseBefore)} -> ${JSON.stringify(poseAfter)}\n`);
|
|
519
902
|
const cpu = flags.cpuprofile === "true" ? await cpuProfile(page, windowSeconds) : null;
|
|
520
903
|
const lightAudit = await page.evaluate(() => window.__btProfile.lightAudit());
|
|
904
|
+
// drawOwners is async: it measures the next rendered frame, and page.evaluate waits for that promise.
|
|
905
|
+
const drawOwners = await page.evaluate(() => window.__btProfile.drawOwners());
|
|
521
906
|
const steps = [];
|
|
522
907
|
for (const key of toggles) {
|
|
523
908
|
const change = await page.evaluate((k) => window.__btProfile.toggle(k, false), key);
|
|
@@ -528,7 +913,7 @@ async function main() {
|
|
|
528
913
|
steps.push({ off: key, change, fps: off.fps, p50Ms: off.p50Ms, drawCalls: off.drawCalls, passes: off.passes, cpuRenderMs: off.cpuRenderMs, cpuFrameMs: off.cpuFrameMs });
|
|
529
914
|
}
|
|
530
915
|
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 } });
|
|
916
|
+
report.pins.push({ atSeconds: seconds, readyMs, pinned, actual: { before: poseBefore, after: poseAfter }, baseline, lightAudit, drawOwners, cpu, steps, baselineAgain: { fps: after.fps, p50Ms: after.p50Ms } });
|
|
532
917
|
await page.close();
|
|
533
918
|
}
|
|
534
919
|
}
|