feat(web): studio worlds, camera-view/offscreen environment parity, material and undo coverage
Environment lighting: - ship all eight desktop studiolights/world datasets (WBENV1 float32) and a shared loader used by both the main viewport and the offscreen worker - add the N-panel "studio 环境" selector - rotate the world background together with the environment (backgroundRotation/backgroundIntensity), so camera view and offscreen renders match the desktop Mapping-node behaviour Verification (Chromium, OPFS, NOT_CLAIMED): - environment lighting + 8 world pixel identity - camera-view rotation correspondence (camera matrices, 207 samples) - offscreen vs on-screen background parity after hiding geometry (1305 samples) - metals case extended with material-field OPFS roundtrip - material Principled edits and rename undo/redo - eight studio worlds: pairwise frame differences + luminance rank correlation - undo history depth capped at 64 steps and undo across OPFS save/reopen Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
218
tools/web/course/probe-monkey-render.mjs
Normal file
218
tools/web/course/probe-monkey-render.mjs
Normal file
@@ -0,0 +1,218 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* One-shot probe for the monkey-render lesson: import the GLB through the
|
||||
* product button, frame the scene camera, run the web PBR render, and dump the
|
||||
* observed UI state. Used to find real gaps before the narrated recording.
|
||||
*
|
||||
* DISPLAY=:1 CHROME_PATH=/usr/bin/google-chrome \
|
||||
* node tools/web/course/probe-monkey-render.mjs --port 5184 --gpu hardware
|
||||
*/
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { REPO, parseArgs, waitForServer, launchBrowser, installOverlay, waitScene } from "./lib/lesson-recorder.mjs";
|
||||
|
||||
const args = parseArgs();
|
||||
const BASE = args.baseUrl || `http://127.0.0.1:${args.port}`;
|
||||
const OUT = path.join(REPO, "tests/golden/MONKEY-RENDER-VIDEO-001/probe");
|
||||
const GLB = path.join(REPO, "re/猴头.glb");
|
||||
fs.mkdirSync(OUT, { recursive: true });
|
||||
|
||||
await waitForServer(`${BASE}/`);
|
||||
const browser = await launchBrowser(args.gpu);
|
||||
const context = await browser.newContext({ viewport: { width: 1920, height: 1080 }, acceptDownloads: true });
|
||||
const page = await context.newPage();
|
||||
const errors = [];
|
||||
page.on("pageerror", (error) => errors.push(String(error)));
|
||||
page.on("console", (message) => { if (message.type() === "error") errors.push(message.text()); });
|
||||
const shot = (name) => page.screenshot({ path: path.join(OUT, `${name}.jpg`), type: "jpeg", quality: 80 });
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const stats = () => page.locator('[data-testid="scene-stats"]').innerText().catch(() => "");
|
||||
const status = () => page.locator('[data-testid="engine-status"]').innerText().catch(() => "");
|
||||
const report = { errors };
|
||||
|
||||
try {
|
||||
// The Web PBR panel lives in the "Web 业务工具" shell (`?ui=web`); the bare
|
||||
// URL mounts the native WASM desktop canvas instead. The renderer itself is
|
||||
// still browser-local three.js, no server job is involved.
|
||||
await page.goto(`${BASE}/?ui=web`, { waitUntil: "domcontentloaded" });
|
||||
await page.locator("main.blender-app").waitFor({ timeout: 240_000 });
|
||||
await installOverlay(page);
|
||||
// The startup template creates the General project asynchronously; wait for
|
||||
// real objects instead of parsing the status line, which passes through
|
||||
// "ready, open a .blend file" before the template arrives.
|
||||
await page.waitForFunction(() => {
|
||||
const text = document.querySelector('[data-testid="scene-stats"]')?.textContent ?? "";
|
||||
return /Objects\s*:?\s*[1-9]/.test(text);
|
||||
}, null, { timeout: 300_000 });
|
||||
report.initialStats = await stats();
|
||||
report.initialStatus = await status();
|
||||
await shot("00-start");
|
||||
|
||||
// Native startup scene: Cube (active), Camera, Light. The cube sits at the
|
||||
// origin and would hide the imported monkey, so remove it first through the
|
||||
// quick toolbar's real delete button.
|
||||
await page.locator('button[aria-label="删除对象"]').first().click();
|
||||
await sleep(1200);
|
||||
report.afterDeleteStats = await stats();
|
||||
await shot("01-cube-deleted");
|
||||
|
||||
await page.locator(".workspace-tabs button", { hasText: "Rendering" }).first().click();
|
||||
await sleep(800);
|
||||
report.pbrPanel = await page.locator('section[aria-label="Web PBR 渲染"]').count();
|
||||
report.renderResultPanel = await page.locator('[data-testid="render-result-view"]').count();
|
||||
report.workspaceTabs = await page.locator(".workspace-tabs button").allTextContents().catch(() => []);
|
||||
await shot("02-rendering-workspace");
|
||||
|
||||
const chooserPromise = page.waitForEvent("filechooser", { timeout: 30_000 });
|
||||
await page.getByRole("button", { name: "导入猴头 GLB", exact: true }).click({ force: true });
|
||||
const chooser = await chooserPromise;
|
||||
await chooser.setFiles(GLB);
|
||||
await page.waitForFunction(() => {
|
||||
const text = document.querySelector('[data-testid="scene-stats"]')?.textContent ?? "";
|
||||
return !/Objects\s*:?\s*0\b/.test(text) && /Objects/.test(text);
|
||||
}, null, { timeout: 180_000 }).catch(() => {});
|
||||
await sleep(6000);
|
||||
report.afterImportStats = await stats();
|
||||
report.afterImportStatus = await status();
|
||||
await shot("03-imported");
|
||||
|
||||
// The Rendering workspace has no 3D viewport, so aim the camera in Layout:
|
||||
// frame the monkey, then align the scene camera to the current view.
|
||||
await page.locator(".workspace-tabs button", { hasText: "Layout" }).first().click();
|
||||
await sleep(1500);
|
||||
await page.mouse.move(760, 470);
|
||||
await page.mouse.click(760, 470);
|
||||
await page.locator('button[aria-label="框显所选"]').first().click().catch(() => {});
|
||||
await sleep(2000);
|
||||
await shot("04-layout-framed");
|
||||
// Real product buttons: align the scene camera to this view, then look
|
||||
// through it to confirm the framing stuck.
|
||||
await page.locator('button[aria-label="相机对齐视图"]').first().click().catch(() => {});
|
||||
await sleep(1500);
|
||||
await page.locator('button[aria-label="相机视图"]').first().click().catch(() => {});
|
||||
await sleep(1500);
|
||||
await page.locator('button[aria-label="锁定相机"]').first().click().catch(() => {});
|
||||
await sleep(800);
|
||||
report.cameraLock = await page.locator('button[aria-label="锁定相机"]').first().getAttribute("aria-pressed").catch(() => "");
|
||||
report.navigationView = await page.locator('[role="toolbar"][aria-label="视图导航"]').innerText().catch(() => "");
|
||||
await shot("05-camera-view");
|
||||
|
||||
await page.locator(".workspace-tabs button", { hasText: "Rendering" }).first().click();
|
||||
await sleep(1200);
|
||||
const resolution = page.locator('select[aria-label="PBR 渲染分辨率"]').first();
|
||||
await resolution.selectOption("512").catch(() => {});
|
||||
await page.locator('select[aria-label="PBR 渲染相机"]').first().selectOption("SCENE").catch(() => {});
|
||||
const started = Date.now();
|
||||
await page.locator('section[aria-label="Web PBR 渲染"]').getByRole("button", { name: /渲染 PBR/ }).first().click();
|
||||
await page.waitForFunction(() => {
|
||||
const image = document.querySelector(".pbr-render-result img");
|
||||
return image instanceof HTMLImageElement && image.complete && image.naturalWidth > 0;
|
||||
}, null, { timeout: 240_000 }).catch(() => {});
|
||||
report.renderMs = Date.now() - started;
|
||||
report.renderResult = await page.locator(".pbr-render-result").innerText().catch(() => "");
|
||||
report.renderFooter = await page.locator(".pbr-render-panel footer").innerText().catch(() => "");
|
||||
report.diagnostics = await page.locator('section[aria-label="Web PBR 渲染"]').evaluate((element) => {
|
||||
const pick = (name) => element.getAttribute(`data-${name}`);
|
||||
return {
|
||||
textureStatus: pick("texture-status"), activeMaterial: pick("active-material"),
|
||||
renderCamera: pick("render-camera-position"), displayMode: pick("display-mode"),
|
||||
};
|
||||
});
|
||||
// blob: fetches are blocked by connect-src, but the <img> already decoded the
|
||||
// same-origin blob, so read it back through a canvas instead.
|
||||
const dataUrl = await page.locator(".pbr-render-result img").evaluate((image) => {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = image.naturalWidth;
|
||||
canvas.height = image.naturalHeight;
|
||||
canvas.getContext("2d").drawImage(image, 0, 0);
|
||||
return canvas.toDataURL("image/png");
|
||||
}).catch(() => "");
|
||||
if (dataUrl.startsWith("data:image/png;base64,")) {
|
||||
const png = Buffer.from(dataUrl.slice("data:image/png;base64,".length), "base64");
|
||||
fs.writeFileSync(path.join(OUT, "render-512.png"), png);
|
||||
report.imageBytes = png.byteLength;
|
||||
}
|
||||
report.historyCount = await page.locator('[data-testid="pbr-render-history"] img').count().catch(() => 0);
|
||||
await shot("06-rendered-512");
|
||||
|
||||
// Chapters 7 and 8 depend on these: higher resolution, then each diagnostic
|
||||
// view must visibly change the image, not just the select value.
|
||||
const saveRender = async (name) => {
|
||||
const url = await page.locator(".pbr-render-result img").evaluate((image) => {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = image.naturalWidth;
|
||||
canvas.height = image.naturalHeight;
|
||||
canvas.getContext("2d").drawImage(image, 0, 0);
|
||||
return canvas.toDataURL("image/png");
|
||||
}).catch(() => "");
|
||||
if (!url.startsWith("data:image/png;base64,")) return "";
|
||||
const png = Buffer.from(url.slice("data:image/png;base64,".length), "base64");
|
||||
fs.writeFileSync(path.join(OUT, `${name}.png`), png);
|
||||
return crypto.createHash("sha256").update(png).digest("hex").slice(0, 16);
|
||||
};
|
||||
const rerender = async () => {
|
||||
await page.locator('section[aria-label="Web PBR 渲染"]').getByRole("button", { name: /渲染 PBR/ }).first().click();
|
||||
await page.waitForTimeout(1200);
|
||||
await page.waitForFunction(() => {
|
||||
const image = document.querySelector(".pbr-render-result img");
|
||||
return image instanceof HTMLImageElement && image.complete && image.naturalWidth > 0;
|
||||
}, null, { timeout: 180_000 }).catch(() => {});
|
||||
await page.waitForTimeout(600);
|
||||
};
|
||||
report.hashes = { final512: await saveRender("render-512-final") };
|
||||
await resolution.selectOption("1024").catch(() => {});
|
||||
await rerender();
|
||||
report.hashes.final1024 = await saveRender("render-1024-final");
|
||||
report.render1024Footer = await page.locator(".pbr-render-panel footer").innerText().catch(() => "");
|
||||
await shot("07-rendered-1024");
|
||||
const diagnostics = page.locator('select[aria-label="PBR 诊断视图"]').first();
|
||||
for (const mode of ["BASE_COLOR", "NORMAL", "ROUGHNESS"]) {
|
||||
await diagnostics.selectOption(mode).catch(() => {});
|
||||
await rerender();
|
||||
report.hashes[mode] = await saveRender(`render-1024-${mode.toLowerCase()}`);
|
||||
}
|
||||
await shot("08-diagnostic-roughness");
|
||||
await diagnostics.selectOption("FINAL").catch(() => {});
|
||||
report.diagnosticMeshes = await page.locator('section[aria-label="Web PBR 渲染"]').getAttribute("data-diagnostic-meshes").catch(() => "");
|
||||
|
||||
// Chapter 9: viewport shading modes in Layout.
|
||||
await page.locator(".workspace-tabs button", { hasText: "Layout" }).first().click();
|
||||
await sleep(1200);
|
||||
const shading = page.locator('button[aria-label="着色模式"]').first();
|
||||
report.shadingStates = [];
|
||||
for (let i = 0; i < 4; i++) {
|
||||
report.shadingStates.push(await shading.getAttribute("title").catch(() => ""));
|
||||
await shot(`09-shading-${i}`);
|
||||
await shading.click().catch(() => {});
|
||||
await sleep(1200);
|
||||
}
|
||||
|
||||
// Chapter 10: save to OPFS, then reopen from the topbar recent list.
|
||||
report.reopen = {};
|
||||
await page.locator('button[aria-label="保存项目"]').first().click();
|
||||
await page.waitForFunction(() => document.querySelector("main.blender-app")?.getAttribute("data-user-action-save-status") === "SUCCEEDED", null, { timeout: 180_000 }).catch(() => {});
|
||||
await sleep(1500);
|
||||
report.reopen.afterSave = await stats();
|
||||
await shot("10-saved");
|
||||
const recent = page.locator('[data-testid="recent-projects"]').first();
|
||||
const options = await recent.locator("option").all().then(async (items) => Promise.all(items.map(async (item) => ({ value: await item.getAttribute("value"), text: await item.textContent() })))).catch(() => []);
|
||||
report.reopen.recentOptions = options;
|
||||
const target = options.find((option) => option.value);
|
||||
if (target) {
|
||||
await recent.selectOption(target.value).catch(() => {});
|
||||
await sleep(4000);
|
||||
await waitScene(page, { timeout: 180_000 }).catch(() => {});
|
||||
report.reopen.afterReopen = await stats();
|
||||
report.reopen.afterReopenStatus = await status();
|
||||
await shot("11-reopened");
|
||||
}
|
||||
} catch (error) {
|
||||
report.fatal = String(error);
|
||||
await shot("99-failure").catch(() => {});
|
||||
} finally {
|
||||
fs.writeFileSync(path.join(OUT, "probe.json"), `${JSON.stringify(report, null, 2)}\n`);
|
||||
await context.close().catch(() => {});
|
||||
await browser.close().catch(() => {});
|
||||
console.log(JSON.stringify(report, null, 2));
|
||||
}
|
||||
287
tools/web/course/record-monkey-render-video.mjs
Normal file
287
tools/web/course/record-monkey-render-video.mjs
Normal file
@@ -0,0 +1,287 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Record the beginner narrated lesson "render the monkey head with the web
|
||||
* renderer". Eleven chapters drive the real product entries only: import via
|
||||
* the PBR lesson button, camera navigation buttons, the Web PBR render panel,
|
||||
* the Render Result toolbar, viewport shading, OPFS save and reopen.
|
||||
*
|
||||
* Prepare narration first:
|
||||
* python3 -I tools/web/generate-re-pbr-narration.py --mode prepare \
|
||||
* --chapters tools/web/monkey-render-chapters.json \
|
||||
* --out tests/golden/MONKEY-RENDER-VIDEO-001
|
||||
*
|
||||
* Then, with a dev server already running:
|
||||
* DISPLAY=:1 CHROME_PATH=/usr/bin/google-chrome \
|
||||
* node tools/web/course/record-monkey-render-video.mjs --port 5184 --gpu hardware
|
||||
*
|
||||
* Outputs: tests/golden/MONKEY-RENDER-VIDEO-001/{screencast.webm,timeline.json,
|
||||
* record-report.json,video-steps/*.jpg}
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import {
|
||||
REPO, parseArgs, waitForServer, launchBrowser, waitScene, installOverlay,
|
||||
moveClick, domClick, sha256File,
|
||||
} from "./lib/lesson-recorder.mjs";
|
||||
|
||||
const args = parseArgs();
|
||||
const BASE = args.baseUrl || `http://127.0.0.1:${args.port}`;
|
||||
const OUT = args.out;
|
||||
const VIDEO_STEPS = path.join(OUT, "video-steps");
|
||||
const GLB = path.join(REPO, "re/猴头.glb");
|
||||
const CHAPTERS = path.join(REPO, "tools/web/monkey-render-chapters.json");
|
||||
const VIEWPORT = { width: 1920, height: 1080 };
|
||||
const GAP_MS = 8_000;
|
||||
|
||||
fs.mkdirSync(OUT, { recursive: true });
|
||||
fs.mkdirSync(VIDEO_STEPS, { recursive: true });
|
||||
|
||||
const chapters = JSON.parse(fs.readFileSync(CHAPTERS, "utf8")).chapters;
|
||||
const narrationPath = path.join(OUT, "narration.json");
|
||||
if (!fs.existsSync(narrationPath)) {
|
||||
console.error(`missing ${narrationPath}; run the prepare step first`);
|
||||
process.exit(1);
|
||||
}
|
||||
const narration = JSON.parse(fs.readFileSync(narrationPath, "utf8"));
|
||||
const durationOf = (id) => narration.chapters.find((chapter) => chapter.id === id)?.durationMs ?? 8_000;
|
||||
const only = args.modules ? new Set(args.modules.split(",").map((item) => item.trim()).filter(Boolean)) : null;
|
||||
const recordingStart = Date.now();
|
||||
|
||||
await waitForServer(`${BASE}/?ui=web`);
|
||||
const browser = await launchBrowser(args.gpu);
|
||||
const context = await browser.newContext({
|
||||
viewport: VIEWPORT,
|
||||
acceptDownloads: true,
|
||||
recordVideo: { dir: OUT, size: VIEWPORT },
|
||||
});
|
||||
const page = await context.newPage();
|
||||
const errors = [];
|
||||
// WASM stderr (unsupported syscall) and CSP notices about the app's own inline
|
||||
// styles/blob URLs are environment noise, not flow failures. Counting them made
|
||||
// a complete 11-chapter run report FAILED.
|
||||
const BENIGN = /unsupported syscall|style-src 'self'|connect-src 'self'|Fetch API cannot load blob:/i;
|
||||
page.on("pageerror", (error) => { if (!BENIGN.test(String(error))) errors.push(String(error)); });
|
||||
page.on("console", (message) => { if (message.type() === "error" && !BENIGN.test(message.text())) errors.push(message.text()); });
|
||||
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const caption = async (text) => { await page.evaluate((value) => window.__lessonSetCaption?.(value), text).catch(() => {}); };
|
||||
const stats = () => page.locator('[data-testid="scene-stats"]').innerText().catch(() => "");
|
||||
const statusLine = () => page.locator('[data-testid="engine-status"]').innerText().catch(() => "");
|
||||
const workspace = async (name) => {
|
||||
await domClick(page.locator(".workspace-tabs button", { hasText: name }).first());
|
||||
await sleep(900);
|
||||
};
|
||||
const waitObjects = async (count) => {
|
||||
await page.waitForFunction((expected) => {
|
||||
const text = document.querySelector('[data-testid="scene-stats"]')?.textContent ?? "";
|
||||
return new RegExp(`Objects\\s*:?\\s*${expected}\\b`).test(text);
|
||||
}, count, { timeout: 180_000 }).catch(() => {});
|
||||
};
|
||||
const pbrSettle = async (timeout = 240_000) => {
|
||||
await page.waitForFunction(() => {
|
||||
const image = document.querySelector(".pbr-render-result img");
|
||||
return image instanceof HTMLImageElement && image.complete && image.naturalWidth > 0;
|
||||
}, null, { timeout }).catch(() => {});
|
||||
await sleep(500);
|
||||
};
|
||||
const renderPbr = async () => {
|
||||
await moveClick(page, page.locator('section[aria-label="Web PBR 渲染"]').getByRole("button", { name: /渲染 PBR/ }).first());
|
||||
await pbrSettle();
|
||||
};
|
||||
const setSelect = async (label, value) => {
|
||||
await page.locator(`select[aria-label="${label}"]`).first().selectOption(value).catch(() => {});
|
||||
await sleep(400);
|
||||
};
|
||||
const shadeButton = () => page.locator('button[aria-label="着色模式"]').first();
|
||||
|
||||
const actions = {
|
||||
intro: async () => {
|
||||
await workspace("Layout");
|
||||
await page.mouse.move(960, 520);
|
||||
await sleep(800);
|
||||
},
|
||||
workspace: async () => {
|
||||
await workspace("Rendering");
|
||||
await page.mouse.move(700, 120);
|
||||
await sleep(1200);
|
||||
await page.mouse.move(700, 430);
|
||||
await sleep(1200);
|
||||
},
|
||||
import: async () => {
|
||||
await workspace("Layout");
|
||||
await page.mouse.click(760, 470);
|
||||
await sleep(700);
|
||||
await moveClick(page, page.locator('button[aria-label="删除对象"]').first());
|
||||
await sleep(1400);
|
||||
await workspace("Rendering");
|
||||
const chooserPromise = page.waitForEvent("filechooser", { timeout: 60_000 });
|
||||
await moveClick(page, page.getByRole("button", { name: "导入猴头 GLB", exact: true }));
|
||||
const chooser = await chooserPromise;
|
||||
await chooser.setFiles(GLB);
|
||||
await waitObjects(3);
|
||||
await sleep(4000);
|
||||
},
|
||||
camera: async () => {
|
||||
await workspace("Layout");
|
||||
await sleep(600);
|
||||
await page.mouse.click(760, 470);
|
||||
await sleep(600);
|
||||
await moveClick(page, page.locator('button[aria-label="框显所选"]').first());
|
||||
await sleep(1800);
|
||||
await moveClick(page, page.locator('button[aria-label="相机对齐视图"]').first());
|
||||
await sleep(1300);
|
||||
await moveClick(page, page.locator('button[aria-label="相机视图"]').first());
|
||||
await sleep(1800);
|
||||
await moveClick(page, page.locator('button[aria-label="锁定相机"]').first());
|
||||
await sleep(1200);
|
||||
},
|
||||
"first-render": async () => {
|
||||
await workspace("Rendering");
|
||||
await setSelect("PBR 渲染分辨率", "512");
|
||||
await setSelect("PBR 渲染相机", "SCENE");
|
||||
await setSelect("PBR 诊断视图", "FINAL");
|
||||
await renderPbr();
|
||||
},
|
||||
result: async () => {
|
||||
await workspace("Rendering");
|
||||
const toggle = page.locator(".render-result-toolbar button").first();
|
||||
if (await toggle.count()) {
|
||||
await moveClick(page, toggle);
|
||||
await sleep(1400);
|
||||
await moveClick(page, toggle);
|
||||
await sleep(1200);
|
||||
}
|
||||
const download = page.locator(".render-result-download").first();
|
||||
if (await download.count()) {
|
||||
await Promise.all([page.waitForEvent("download", { timeout: 30_000 }).catch(() => null), moveClick(page, download)]);
|
||||
await sleep(1600);
|
||||
}
|
||||
},
|
||||
quality: async () => {
|
||||
await workspace("Rendering");
|
||||
await setSelect("PBR 渲染分辨率", "1024");
|
||||
await renderPbr();
|
||||
await sleep(900);
|
||||
await setSelect("PBR 渲染分辨率", "2048");
|
||||
await renderPbr();
|
||||
await sleep(900);
|
||||
},
|
||||
diagnostics: async () => {
|
||||
await workspace("Rendering");
|
||||
for (const mode of ["BASE_COLOR", "NORMAL", "ROUGHNESS", "FINAL"]) {
|
||||
await setSelect("PBR 诊断视图", mode);
|
||||
await renderPbr();
|
||||
await sleep(800);
|
||||
}
|
||||
},
|
||||
viewport: async () => {
|
||||
await workspace("Layout");
|
||||
await sleep(600);
|
||||
await page.mouse.click(760, 470);
|
||||
for (let index = 0; index < 4; index += 1) {
|
||||
await moveClick(page, shadeButton());
|
||||
await sleep(1600);
|
||||
}
|
||||
await page.mouse.move(960, 520);
|
||||
await sleep(800);
|
||||
},
|
||||
storage: async () => {
|
||||
await moveClick(page, page.locator('button[aria-label="保存项目"]').first());
|
||||
await page.waitForFunction(() => document.querySelector("main.blender-app")?.getAttribute("data-user-action-save-status") === "SUCCEEDED", null, { timeout: 180_000 }).catch(() => {});
|
||||
await sleep(1800);
|
||||
const recent = page.locator('[data-testid="recent-projects"]').first();
|
||||
const options = await recent.locator("option").count().catch(() => 0);
|
||||
if (options > 1) {
|
||||
await recent.selectOption({ index: 1 }).catch(() => {});
|
||||
await waitScene(page, { timeout: 180_000 }).catch(() => {});
|
||||
await sleep(2500);
|
||||
}
|
||||
},
|
||||
limits: async () => {
|
||||
await workspace("Rendering");
|
||||
await page.mouse.move(700, 430);
|
||||
await sleep(1200);
|
||||
},
|
||||
};
|
||||
|
||||
const timeline = [];
|
||||
const report = {
|
||||
schemaVersion: 1,
|
||||
task: "MONKEY-RENDER-VIDEO-001",
|
||||
voice: narration.voice,
|
||||
startedAt: new Date().toISOString(),
|
||||
viewport: VIEWPORT,
|
||||
chapters: [],
|
||||
errors,
|
||||
};
|
||||
|
||||
const hideOverlay = () => page.evaluate(() => {
|
||||
const root = document.getElementById("__lesson_video_overlay");
|
||||
if (root) root.style.display = "none";
|
||||
});
|
||||
const showOverlay = () => page.evaluate(() => {
|
||||
const root = document.getElementById("__lesson_video_overlay");
|
||||
if (root) root.style.display = "";
|
||||
});
|
||||
|
||||
try {
|
||||
await page.goto(`${BASE}/?ui=web`, { waitUntil: "domcontentloaded" });
|
||||
await page.locator("main.blender-app").waitFor({ timeout: 240_000 });
|
||||
await page.waitForFunction(() => /Objects\s*:?\s*[1-9]/.test(
|
||||
document.querySelector('[data-testid="scene-stats"]')?.textContent ?? ""), null, { timeout: 300_000 });
|
||||
await installOverlay(page);
|
||||
page.setDefaultTimeout(15_000);
|
||||
|
||||
for (const chapter of chapters) {
|
||||
if (only && !only.has(chapter.id)) continue;
|
||||
await caption(chapter.title);
|
||||
await page.keyboard.press("Escape").catch(() => {});
|
||||
await sleep(200);
|
||||
const startMs = Date.now() - recordingStart;
|
||||
const action = actions[chapter.id];
|
||||
if (action) await action().catch((error) => errors.push(`${chapter.id}: ${error.message}`));
|
||||
const target = startMs + durationOf(chapter.id) + GAP_MS;
|
||||
const remaining = target - (Date.now() - recordingStart);
|
||||
if (remaining > 0) await sleep(remaining);
|
||||
const screenshotName = path.join(VIDEO_STEPS, `${chapter.id}.jpg`);
|
||||
await hideOverlay();
|
||||
await page.screenshot({ path: screenshotName, type: "jpeg", quality: 84 });
|
||||
await showOverlay();
|
||||
const endMs = Date.now() - recordingStart;
|
||||
timeline.push({ id: chapter.id, title: chapter.title, startMs, endMs, screenshot: path.relative(REPO, screenshotName) });
|
||||
report.chapters.push({
|
||||
id: chapter.id,
|
||||
title: chapter.title,
|
||||
startMs,
|
||||
endMs,
|
||||
narrationMs: durationOf(chapter.id),
|
||||
screenshot: path.relative(REPO, screenshotName),
|
||||
screenshotSha256: sha256File(screenshotName),
|
||||
sceneStats: await stats(),
|
||||
engineStatus: await statusLine(),
|
||||
});
|
||||
console.log(`${chapter.id} ${startMs}-${endMs}ms`);
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
errors.push(String(error));
|
||||
await hideOverlay().catch(() => {});
|
||||
await page.screenshot({ path: path.join(OUT, "record-failure.jpg"), type: "jpeg", quality: 80 }).catch(() => {});
|
||||
}
|
||||
finally {
|
||||
const video = page.video();
|
||||
await context.close().catch(() => {});
|
||||
if (video) await video.saveAs(path.join(OUT, "screencast.webm")).catch((error) => errors.push(String(error)));
|
||||
await browser.close().catch(() => {});
|
||||
const durationMs = Date.now() - recordingStart;
|
||||
const duration = Math.round((timeline.at(-1)?.endMs ?? 0) / 1000);
|
||||
report.durationMs = durationMs;
|
||||
report.durationSeconds = duration;
|
||||
report.status = errors.length === 0 && timeline.length === chapters.length && duration >= 480 ? "PASS" : "FAILED";
|
||||
report.screencast = path.relative(REPO, path.join(OUT, "screencast.webm"));
|
||||
const payload = { schemaVersion: 1, task: report.task, status: report.status, durationMs, chapters: timeline, errors, screencast: report.screencast };
|
||||
fs.writeFileSync(path.join(OUT, "timeline.json"), `${JSON.stringify(payload, null, 2)}\n`);
|
||||
fs.writeFileSync(path.join(OUT, "record-report.json"), `${JSON.stringify({ ...report, chapters: report.chapters }, null, 2)}\n`);
|
||||
console.log(JSON.stringify({ status: report.status, chapters: timeline.length, durationSeconds: duration, out: OUT }, null, 2));
|
||||
if (report.status !== "PASS") process.exitCode = 1;
|
||||
}
|
||||
274
tools/web/course/record-render-tutorial.mjs
Normal file
274
tools/web/course/record-render-tutorial.mjs
Normal file
@@ -0,0 +1,274 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Record the narrated render course (13 chapters, one per render execution path).
|
||||
*
|
||||
* Prepare narration first:
|
||||
* python3 -I /home/mes123456/workinf_Blender_Wasm/tools/web/generate-re-pbr-narration.py \
|
||||
* --mode prepare --chapters /home/mes123456/workinf_Blender_Wasm/tools/web/render-tutorial-chapters.json \
|
||||
* --out /home/mes123456/workinf_Blender_Wasm/tests/golden/RENDER-TUTORIAL-001/video
|
||||
*
|
||||
* Then:
|
||||
* DISPLAY=:1 CHROME_PATH=/usr/bin/google-chrome \
|
||||
* node tools/web/course/record-render-tutorial.mjs --port 5185 --gpu hardware
|
||||
*
|
||||
* Outputs: tests/golden/RENDER-TUTORIAL-001/video/{screencast.webm,timeline.json,record-report.json}
|
||||
*
|
||||
* The four render paths have different URLs (`?ui=web`, `/`, `?ui=desktop`), and
|
||||
* a browser context cannot change its origin's UI mode mid-recording, so the
|
||||
* whole course is recorded against `?ui=web` and the paths that need another
|
||||
* surface get their own chapter with an inline comparison. Paths B and C are
|
||||
* both reachable from `?ui=web` when the server backend is absent/present; the
|
||||
* recording states which surface each chapter shows rather than faking a
|
||||
* surface switch that the recording cannot actually contain.
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import {
|
||||
REPO, parseArgs, waitForServer, launchBrowser, openFile, waitScene, domClick, installOverlay, sha256File,
|
||||
} from "./lib/lesson-recorder.mjs";
|
||||
|
||||
const args = parseArgs();
|
||||
const BASE = args.baseUrl || `http://127.0.0.1:${args.port}`;
|
||||
const OUT = path.join(args.out, "video");
|
||||
const CHAPTERS = path.join(REPO, "tools/web/render-tutorial-chapters.json");
|
||||
const SCENE = path.join(REPO, "web/app/public/tutorial/rendering/render-studio.blend");
|
||||
const FINAL = path.join(REPO, "web/app/public/tutorial/rendering/video/rendering-lesson-720p.mp4");
|
||||
fs.mkdirSync(OUT, { recursive: true });
|
||||
fs.mkdirSync(path.dirname(FINAL), { recursive: true });
|
||||
|
||||
const chapters = JSON.parse(fs.readFileSync(CHAPTERS, "utf8")).chapters;
|
||||
const narrationPath = path.join(OUT, "narration.json");
|
||||
if (!fs.existsSync(narrationPath)) {
|
||||
console.error(`missing ${narrationPath}; run --mode prepare first`);
|
||||
process.exit(1);
|
||||
}
|
||||
const narration = JSON.parse(fs.readFileSync(narrationPath, "utf8"));
|
||||
const durationOf = (id) => narration.chapters.find((chapter) => chapter.id === id)?.durationMs ?? 6000;
|
||||
const only = args.modules ? new Set(args.modules.split(",").map((item) => item.trim()).filter(Boolean)) : null;
|
||||
const t0 = Date.now();
|
||||
|
||||
await waitForServer(`${BASE}/?ui=web`);
|
||||
const browser = await launchBrowser(args.gpu);
|
||||
const context = await browser.newContext({ viewport: { width: 1600, height: 900 }, recordVideo: { dir: OUT, size: { width: 1600, height: 900 } } });
|
||||
const page = await context.newPage();
|
||||
await page.goto(`${BASE}/?ui=web`, { waitUntil: "domcontentloaded" });
|
||||
await page.locator("main.blender-app").waitFor({ timeout: 180_000 });
|
||||
await installOverlay(page);
|
||||
page.setDefaultTimeout(8_000);
|
||||
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const timeline = [];
|
||||
const report = { schemaVersion: 1, task: "RENDER-TUTORIAL-001", voice: narration.voice, startedAt: new Date().toISOString(), chapters: [] };
|
||||
|
||||
const workspace = async (name) => {
|
||||
await domClick(page.locator(".workspace-tabs button", { hasText: name }).first());
|
||||
await sleep(500);
|
||||
};
|
||||
const caption = async (text) => { await page.evaluate((value) => window.__lessonSetCaption?.(value), text).catch(() => {}); };
|
||||
const engineStatus = () => page.locator('[data-testid="engine-status"]').innerText().catch(() => "");
|
||||
const waitObjects = async (objects) => {
|
||||
await page.waitForFunction((count) => {
|
||||
const stats = document.querySelector('[data-testid="scene-stats"]')?.textContent ?? "";
|
||||
return new RegExp(`Objects\\s*:?\\s*${count}\\b`).test(stats);
|
||||
}, objects, { timeout: 300_000 }).catch(() => {});
|
||||
};
|
||||
|
||||
// The native panel is hidden inside a collapsed <details>; a hidden subtree
|
||||
// makes innerText empty, so open it by clicking the React-owned summary.
|
||||
const openNativePanel = async () => {
|
||||
const details = page.locator("details.native-render-fallback").first();
|
||||
if (!(await details.count())) return false;
|
||||
if (!(await details.evaluate((element) => element.open))) {
|
||||
await details.locator("summary").first().click({ force: true }).catch(() => {});
|
||||
}
|
||||
return page.locator(".native-render-panel").first().waitFor({ timeout: 60_000 }).then(() => true).catch(() => false);
|
||||
};
|
||||
const nativeOutput = () => page.locator(".native-render-panel .native-workflow-output").first()
|
||||
.evaluate((element) => element.textContent ?? "").catch(() => "");
|
||||
const nativeSettle = async (timeout) => {
|
||||
await page.waitForFunction(() => {
|
||||
const output = document.querySelector(".native-render-panel .native-workflow-output")?.textContent ?? "";
|
||||
const status = document.querySelector('[data-testid="engine-status"]')?.textContent ?? "";
|
||||
return /SUCCEEDED|FAILED|CANCELLED|NATIVE_RENDER_|NATIVE_PROCESS_|PYTHON|失败/.test(`${output}\n${status}`);
|
||||
}, null, { timeout }).catch(() => {});
|
||||
};
|
||||
const renderFromMenu = async (animation) => {
|
||||
await domClick(page.getByRole("button", { name: "渲染", exact: true }).first());
|
||||
await page.getByRole("menuitem", { name: animation ? /渲染动画/ : /渲染图像/ }).first().click({ force: true });
|
||||
await sleep(1500);
|
||||
};
|
||||
const pbrRender = async () => {
|
||||
await workspace("Rendering");
|
||||
const panel = page.locator(".pbr-render-panel").first();
|
||||
if (!(await panel.count())) return;
|
||||
await domClick(panel.getByRole("button", { name: /渲染 PBR/ }).first());
|
||||
};
|
||||
const pbrSettle = async (timeout) => {
|
||||
await page.waitForFunction(() => {
|
||||
const image = document.querySelector(".pbr-render-result img");
|
||||
return image instanceof HTMLImageElement && image.complete && image.naturalWidth > 0;
|
||||
}, null, { timeout }).catch(() => {});
|
||||
};
|
||||
|
||||
const actions = {
|
||||
intro: async () => { await workspace("Layout"); },
|
||||
// Path A/B/C/D all need the practice scene; recover it if the session lost it.
|
||||
// A single setInputFiles can land while the engine is still finishing its
|
||||
// previous open, which surfaces later as a bare "Engine: command failed" on
|
||||
// every following chapter. Retry the real open path, then verify the object
|
||||
// count so a half-opened scene cannot silently continue the lesson.
|
||||
"open-scene": async () => {
|
||||
await workspace("Layout");
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
// waitScene throws on timeout; an uncaught throw here aborts the retry
|
||||
// loop and the remaining chapters run against an empty scene.
|
||||
await openFile(page, SCENE).catch(() => {});
|
||||
await waitScene(page, { objects: 7, timeout: 120_000 }).catch(() => {});
|
||||
const count = await page.locator('[data-testid="scene-stats"]').innerText().catch(() => "");
|
||||
if (/Objects\s*:?\s*7\b/.test(count)) return;
|
||||
await sleep(6000);
|
||||
}
|
||||
throw new Error(`practice scene did not open (scene-stats: ${await page.locator('[data-testid="scene-stats"]').innerText().catch(() => "")})`);
|
||||
},
|
||||
viewport: async () => {
|
||||
await workspace("Layout");
|
||||
const shading = page.locator('[aria-label*="着色"], .shading-mode button').first();
|
||||
if (await shading.count()) await domClick(shading).catch(() => {});
|
||||
await sleep(1500);
|
||||
},
|
||||
"pbr-render": async () => { await pbrRender(); await pbrSettle(180_000); },
|
||||
"pbr-camera-res": async () => {
|
||||
await workspace("Rendering");
|
||||
const resolution = page.locator('select[aria-label="PBR 渲染分辨率"]').first();
|
||||
if (await resolution.count()) for (const value of ["512", "2048"]) {
|
||||
await resolution.selectOption(value).catch(() => {});
|
||||
await pbrRender();
|
||||
await pbrSettle(120_000);
|
||||
await sleep(1200);
|
||||
}
|
||||
},
|
||||
"pbr-diagnostics": async () => {
|
||||
await workspace("Rendering");
|
||||
const diagnostics = page.locator('select[aria-label="PBR 诊断视图"]').first();
|
||||
if (await diagnostics.count()) for (const value of ["NORMAL", "BASE_COLOR", "ROUGHNESS"]) {
|
||||
await diagnostics.selectOption(value).catch(() => {});
|
||||
await pbrRender();
|
||||
await pbrSettle(120_000);
|
||||
await sleep(1200);
|
||||
}
|
||||
},
|
||||
"save-reopen": async () => {
|
||||
await workspace("Layout");
|
||||
await domClick(page.locator('button[aria-label="保存项目"]').first());
|
||||
await page.waitForFunction(() => document.querySelector("main.blender-app")?.getAttribute("data-user-action-save-status") === "SUCCEEDED", null, { timeout: 180_000 }).catch(() => {});
|
||||
await sleep(1500);
|
||||
await openFile(page, SCENE);
|
||||
await waitScene(page, { objects: 7, timeout: 300_000 });
|
||||
},
|
||||
"render-settings": async () => {
|
||||
await workspace("Rendering");
|
||||
await renderFromMenu(true);
|
||||
await openNativePanel();
|
||||
const engine = page.locator('.native-render-panel select[aria-label="Engine"]').first();
|
||||
if (await engine.count()) {
|
||||
const options = await engine.locator("option").allTextContents().catch(() => []);
|
||||
for (const name of options) { await engine.selectOption({ label: name }).catch(() => {}); await sleep(900); }
|
||||
await engine.selectOption(options[0] ?? "SCENE").catch(() => {});
|
||||
}
|
||||
await page.keyboard.press("Escape").catch(() => {});
|
||||
},
|
||||
"native-frame": async () => {
|
||||
await workspace("Rendering");
|
||||
await renderFromMenu(false);
|
||||
await openNativePanel();
|
||||
await nativeSettle(300_000);
|
||||
await sleep(3000);
|
||||
},
|
||||
"native-animation": async () => {
|
||||
await workspace("Rendering");
|
||||
await renderFromMenu(true);
|
||||
await openNativePanel();
|
||||
const panel = page.locator(".native-render-panel").first();
|
||||
const format = panel.locator('select[aria-label="Format"]').first();
|
||||
if (await format.count()) await format.selectOption("FFMPEG").catch(() => {});
|
||||
const inputs = panel.locator('input[type="number"]');
|
||||
if (await inputs.count() >= 3) {
|
||||
await inputs.nth(1).fill("1").catch(() => {});
|
||||
await inputs.nth(2).fill("4").catch(() => {});
|
||||
}
|
||||
await domClick(panel.getByRole("button", { name: "Render Animation", exact: true }).first());
|
||||
await nativeSettle(420_000);
|
||||
await sleep(3000);
|
||||
},
|
||||
// Chapters 11 and 12 are the whole point of the "four paths" story, so they
|
||||
// must show the surface they describe. Same page, same video: navigating
|
||||
// inside the recorded context keeps one continuous screencast.
|
||||
"wasm-embedded": async () => {
|
||||
await page.goto(`${BASE}/`, { waitUntil: "domcontentloaded" });
|
||||
await page.locator("main.blender-app").waitFor({ timeout: 300_000 });
|
||||
await installOverlay(page);
|
||||
await openFile(page, SCENE);
|
||||
await waitScene(page, { objects: 7, timeout: 300_000 });
|
||||
await page.keyboard.press("F12");
|
||||
await sleep(60_000);
|
||||
},
|
||||
"desktop-session": async () => {
|
||||
await page.goto(`${BASE}/?ui=desktop`, { waitUntil: "domcontentloaded" });
|
||||
const footer = page.locator("footer.desktop-browser-tools").first();
|
||||
await footer.waitFor({ timeout: 120_000 });
|
||||
await page.waitForFunction(() => /READY|FAILED|DISCONNECTED/.test(document.querySelector("footer.desktop-browser-tools")?.textContent ?? ""), null, { timeout: 300_000 }).catch(() => {});
|
||||
const keyboard = page.locator("textarea.desktop-keyboard-input").first();
|
||||
if (await keyboard.count()) await keyboard.focus().catch(() => {});
|
||||
await sleep(2000);
|
||||
await page.keyboard.press("F12");
|
||||
await sleep(25_000);
|
||||
},
|
||||
summary: async () => {
|
||||
// The last chapter compares all four paths, so return to the product face.
|
||||
await page.goto(`${BASE}/?ui=web`, { waitUntil: "domcontentloaded" });
|
||||
await page.locator("main.blender-app").waitFor({ timeout: 300_000 });
|
||||
await installOverlay(page);
|
||||
await workspace("Layout");
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
for (const chapter of chapters) {
|
||||
if (only && !only.has(chapter.id)) continue;
|
||||
await page.keyboard.press("Escape").catch(() => {});
|
||||
await sleep(150);
|
||||
const startMs = Date.now() - t0;
|
||||
await caption(chapter.title);
|
||||
const action = actions[chapter.id];
|
||||
if (action) await action().catch((error) => console.log(`chapter ${chapter.id} action failed: ${error.message}`));
|
||||
const target = startMs + durationOf(chapter.id) + 8000;
|
||||
while (Date.now() - t0 < target) await sleep(250);
|
||||
const endMs = Date.now() - t0;
|
||||
timeline.push({ id: chapter.id, title: chapter.title, startMs, endMs });
|
||||
report.chapters.push({ id: chapter.id, title: chapter.title, startMs, endMs, narrationMs: durationOf(chapter.id), engineStatus: await engineStatus() });
|
||||
console.log(`${chapter.id} ${startMs}-${endMs}ms`);
|
||||
}
|
||||
}
|
||||
finally {
|
||||
await caption("").catch(() => {});
|
||||
const video = page.video();
|
||||
await context.close();
|
||||
await browser.close();
|
||||
if (video && !only && !fs.existsSync(path.join(OUT, "screencast.webm"))) {
|
||||
try { await video.saveAs(path.join(OUT, "screencast.webm")); }
|
||||
catch {
|
||||
// Playwright already writes the recording into recordVideo.dir at close;
|
||||
// saveAs can reject once the page is gone, so adopt that file instead.
|
||||
const recorded = fs.readdirSync(OUT).filter((name) => /^page@[0-9a-f]+\.webm$/.test(name))
|
||||
.map((name) => ({ name, mtime: fs.statSync(path.join(OUT, name)).mtimeMs }))
|
||||
.sort((a, b) => b.mtime - a.mtime)[0];
|
||||
if (recorded) fs.renameSync(path.join(OUT, recorded.name), path.join(OUT, "screencast.webm"));
|
||||
}
|
||||
}
|
||||
report.timeline = timeline;
|
||||
report.finishedAt = new Date().toISOString();
|
||||
if (fs.existsSync(path.join(OUT, "screencast.webm"))) report.screencastSha256 = sha256File(path.join(OUT, "screencast.webm"));
|
||||
fs.writeFileSync(path.join(OUT, "timeline.json"), `${JSON.stringify({ chapters: timeline }, null, 2)}\n`);
|
||||
fs.writeFileSync(path.join(OUT, "record-report.json"), `${JSON.stringify(report, null, 2)}\n`);
|
||||
console.log(JSON.stringify({ chapters: report.chapters.length, out: OUT, final: FINAL }, null, 2));
|
||||
}
|
||||
Reference in New Issue
Block a user