@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.
@@ -0,0 +1,76 @@
1
+ /**
2
+ * bt-profile census template — when the profile says a cheap function runs far too often, count who calls it.
3
+ * Copy to the scratchpad (not the project), adapt `reachTheMoment`, and run it through profile.mjs with --heap false:
4
+ *
5
+ * CENSUS_OUT=/abs/census.json node "$TOOLS/profile.mjs" --url "$URL" --scenario /abs/census.mjs --out /abs/census-run --heap false \
6
+ * --args method=TransformNode.prototype.computeWorldMatrix,seconds=1
7
+ *
8
+ * It wraps the method for `seconds` of play and records, per object (`this.name`, plus "[arg0]" when the first
9
+ * argument is truthy — e.g. a forced recompute), calls per frame and one sample call stack.
10
+ */
11
+
12
+ /** Shown in the report. */
13
+ export const meta = { name: "census", description: "Calls per frame of one prototype method, per object, with a sample stack." };
14
+
15
+ /**
16
+ * Installs the counting wrapper in the page.
17
+ * @param {string} methodPath - "Class.prototype.method" under window.BABYLON (or a full "TOOLKIT.Class.prototype.method")
18
+ */
19
+ function startCensus(methodPath) {
20
+ const parts = methodPath.split(".");
21
+ const root = parts[0] === "TOOLKIT" || parts[0] === "PROJECT" ? window[parts.shift()] : window.BABYLON;
22
+ const methodName = parts.pop();
23
+ const owner = parts.reduce((object, key) => object[key], root);
24
+ const original = owner[methodName];
25
+ const scene = window.BABYLON.EngineStore.LastCreatedScene;
26
+ const census = window.__btCensus = { calls: new Map(), stacks: new Map(), frames: 0 };
27
+ const frameObserver = scene.onAfterRenderObservable.add(() => { census.frames++; });
28
+ owner[methodName] = function (...args) {
29
+ const key = `${this && this.name !== undefined ? this.name : "(no name)"}${args[0] ? " [arg0]" : ""}`;
30
+ census.calls.set(key, (census.calls.get(key) || 0) + 1);
31
+ if (!census.stacks.has(key) && census.stacks.size < 500) census.stacks.set(key, new Error().stack.split("\n").slice(2, 10).map((line) => line.trim()).join(" | "));
32
+ return original.apply(this, args);
33
+ };
34
+ census.stop = () => { owner[methodName] = original; scene.onAfterRenderObservable.remove(frameObserver); };
35
+ }
36
+
37
+ /** Removes the wrapper and returns the per-object counts, busiest first. */
38
+ function stopCensus() {
39
+ const census = window.__btCensus;
40
+ census.stop();
41
+ const frames = Math.max(1, census.frames);
42
+ const total = [...census.calls.values()].reduce((sum, count) => sum + count, 0);
43
+ return {
44
+ frames: census.frames,
45
+ callsPerFrame: +(total / frames).toFixed(1),
46
+ top: [...census.calls].sort((a, b) => b[1] - a[1]).slice(0, 60).map(([key, count]) => ({ key, perFrame: +(count / frames).toFixed(2), stack: census.stacks.get(key) })),
47
+ };
48
+ }
49
+
50
+ /**
51
+ * Gets the game to the moment worth counting. Adapt: wait on the game's own state, hold keys like a player.
52
+ * @param {object} context - the bt-profile scenario context
53
+ */
54
+ async function reachTheMoment(context) {
55
+ await context.open();
56
+ await context.waitFor(() => {
57
+ const scene = window.BABYLON && window.BABYLON.EngineStore ? window.BABYLON.EngineStore.LastCreatedScene : null;
58
+ return scene != null && scene.isReady() && scene.activeCamera != null;
59
+ });
60
+ await context.waitForFrames(120);
61
+ }
62
+
63
+ /**
64
+ * Runs the census.
65
+ * @param {object} context - the bt-profile scenario context
66
+ */
67
+ export async function run(context) {
68
+ const methodPath = context.options.method || "TransformNode.prototype.computeWorldMatrix";
69
+ await reachTheMoment(context);
70
+ await context.evaluate(startCensus, methodPath);
71
+ await context.sleep(Number(context.options.seconds || 1));
72
+ const result = await context.evaluate(stopCensus);
73
+ const fs = await import("node:fs");
74
+ if (process.env.CENSUS_OUT) fs.writeFileSync(process.env.CENSUS_OUT, JSON.stringify(result, null, 1));
75
+ context.log(`census ${methodPath}: ${result.callsPerFrame} calls per frame over ${result.frames} frames; top: ${result.top.slice(0, 5).map((entry) => `${entry.key} ${entry.perFrame}/f`).join(", ")}`);
76
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * bt-profile scenario template — copy to `<project>/.agents/profile/<slug>/data/scenario.mjs` and make it play the
3
+ * moment the user says is slow (a cold load, a level start, a boss fight, a menu → game transition, a page that janks
4
+ * on scroll, a slow route change). It works on any web page; on a Babylon page it also waits for the scene.
5
+ *
6
+ * The capture script calls `run(context)` with:
7
+ * context.open(urlOrPath?) navigate (default: the --url given to profile.mjs)
8
+ * context.expectNavigation() call before a click that loads a new page (so it is not reported as a reload)
9
+ * context.mark(name) start a named phase (the report splits every number by phase)
10
+ * context.waitFor(fn, { timeout, polling, args }) wait until a page function returns truthy
11
+ * context.waitForFrames(count) wait until the page has rendered `count` frames (Babylon frames, else browser frames)
12
+ * context.evaluate(fn, ...args) run a function in the page (window.BABYLON, window.TOOLKIT, window.PROJECT)
13
+ * context.keyDown(key) / keyUp(key) / press(key) keyboard input ("ArrowUp", "w", "Space", …)
14
+ * context.sleep(seconds)
15
+ * context.shot(name) screenshot — only with --snapshots true, otherwise a no-op
16
+ * context.options --args key=value,… parsed into strings (settle = seconds to record after the moment)
17
+ * context.log(message)
18
+ *
19
+ * Rules that keep captures comparable run to run:
20
+ * - Enter the app the way a player does: open the page they open (usually the home page) and click through what they
21
+ * click (a menu, a level button — context.expectNavigation() first when the click loads a new page). A deep link you
22
+ * build yourself can take a path players never take (another route, a server quirk), and then you measure the wrong thing.
23
+ * - Drive the game the way a player would (keys, the game's own components), never by skipping work.
24
+ * - Wait on game state (a phase, a component flag), not on fixed sleeps, for anything that loads.
25
+ * - Mark every phase the user cares about; keep the names stable between runs (before / after compares by name).
26
+ */
27
+
28
+ /** Shown in the report. */
29
+ export const meta = {
30
+ name: "my-scenario",
31
+ description: "Cold load of the page (and its Babylon scene, if any), then N seconds of use.",
32
+ };
33
+
34
+ /** Seconds recorded after the scene is running, unless --args settle=<seconds> overrides it (SKILL.md passes it). */
35
+ const DEFAULT_SETTLE_SECONDS = 60;
36
+
37
+ /**
38
+ * Plays the scenario.
39
+ * @param {object} context - the bt-profile scenario context
40
+ */
41
+ export async function run(context) {
42
+ const settleSeconds = Number(context.options.settle || context.options.play || DEFAULT_SETTLE_SECONDS);
43
+ await context.open();
44
+ await context.mark("load");
45
+ // Any web app: wait for the page to load and paint. A Babylon page also waits for its scene below.
46
+ await context.waitFor(() => document.readyState === "complete");
47
+ await context.waitForFrames(30);
48
+ const babylonPage = await context.evaluate(() => window.BABYLON != null);
49
+ if (babylonPage) {
50
+ await context.waitFor(() => {
51
+ const scene = window.BABYLON.EngineStore ? window.BABYLON.EngineStore.LastCreatedScene : null;
52
+ return scene != null && scene.isReady() && scene.activeCamera != null;
53
+ });
54
+ // An empty scene is "ready" too (a game that loads its level later): wait until something is drawn.
55
+ try {
56
+ await context.waitFor(() => {
57
+ const scene = window.BABYLON.EngineStore.LastCreatedScene;
58
+ return scene != null && scene.getActiveMeshes().length > 0;
59
+ }, { timeout: 120000 });
60
+ } catch {
61
+ context.log("nothing was drawn within 120 s — check the smoke run's screenshots (a content server down? a menu to click through?)");
62
+ }
63
+ }
64
+ // Hitches behind the loading screen are load time, not stutter the player sees: mark the moment it goes away.
65
+ // (A toolkit splash fades through opacity 0; adapt the check to the game's own loading screen.)
66
+ try {
67
+ await context.waitFor(() => {
68
+ const splash = document.getElementById("xbabylonjsSplashScreen");
69
+ return splash == null || splash.style.opacity === "0" || getComputedStyle(splash).display === "none";
70
+ }, { timeout: 60000 });
71
+ } catch {
72
+ context.log("the loading screen did not go away within 60 s — adapt the reveal check to this game");
73
+ }
74
+ await context.mark("running");
75
+ await context.shot("running");
76
+ await context.sleep(settleSeconds);
77
+ await context.shot("end-of-play");
78
+ }
@@ -133,7 +133,7 @@ Each prototype subagent gets: its **direction**, the **theme**, the **world anch
133
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
- 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.
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. Every HUD follows the Agent Reference's **Game UI Performance — ENFORCED**: per-frame values (speed, timers, bars, needles) reach the screen through refs and one frame loop, never React state or a per-frame EventBus message.
137
137
 
138
138
  ## The 3D-hero-scroll batch rule
139
139