#!/usr/bin/env node /** * Capture the real Web Blender UI for the beginner render tutorial. * * DISPLAY=:1 node tools/web/capture-render-basics.mjs --port 5184 --gpu hardware * * Produces, under web/app/public/tutorial/render-basics/: * steps/ numbered 1600x900 screenshots of the actual interface * evidence/ finished frames (png) downloaded through the product's own links * and tests/golden/RENDER-BASICS-001/capture-report.json. * * The server-native path needs the dev server started with BLENDER_BIN; when it * is missing every engine attempt is recorded as FAIL and the run continues, * because the tutorial must state what actually happened, not what was expected. */ import fs from "node:fs"; import path from "node:path"; import { REPO, parseArgs, waitForServer, launchBrowser, newPage, openFile, waitScene, sha256File, } from "./course/lib/lesson-recorder.mjs"; import { imageStats } from "./lib/image-stats.mjs"; const args = parseArgs(); const BASE = args.baseUrl || `http://127.0.0.1:${args.port}`; const OUT = path.join(REPO, "tests/golden/RENDER-BASICS-001"); const GUIDE = path.join(REPO, "web/app/public/tutorial/render-basics"); const STEPS = path.join(GUIDE, "steps"); const EVIDENCE = path.join(GUIDE, "evidence"); const SCENE = path.join(REPO, "web/app/public/tutorial/rendering/render-studio.blend"); for (const directory of [OUT, STEPS, EVIDENCE]) fs.mkdirSync(directory, { recursive: true }); const now = () => new Date().toISOString(); const report = { startedAt: now(), base: BASE, gpu: args.gpu, scene: SCENE, sceneSha256: sha256File(SCENE), steps: [], engines: [], embeddedEngines: [], status: "FAIL" }; async function step(page, name, run) { const started = Date.now(); const entry = { name, startedAt: now() }; try { await run(); const file = path.join(STEPS, `${name}.jpg`); await page.screenshot({ path: file, type: "jpeg", quality: 82 }); entry.shot = { path: file, bytes: fs.statSync(file).size, sha256: sha256File(file) }; entry.status = "PASS"; } catch (error) { entry.error = String(error?.message ?? error).split("\n")[0]; entry.status = "FAIL"; } entry.ms = Date.now() - started; report.steps.push(entry); console.log(`${entry.status} ${name} ${entry.ms} ms${entry.error ? ` — ${entry.error}` : ""}`); return entry; } const saveDownload = async (page, selector, file) => { if (!(await page.locator(selector).count())) return null; const [download] = await Promise.all([ page.waitForEvent("download", { timeout: 120_000 }), page.locator(selector).first().click({ force: true }), ]); await download.saveAs(file); return { path: file, bytes: fs.statSync(file).size, sha256: sha256File(file), name: download.suggestedFilename() }; }; const saveImageArtifact = async (page, file) => { const links = page.locator(".native-render-panel .native-workflow-artifacts a[download]"); for (let index = 0; index < await links.count(); index += 1) { const name = (await links.nth(index).getAttribute("download")) ?? ""; if (!/\.png$/i.test(name)) continue; const [download] = await Promise.all([ page.waitForEvent("download", { timeout: 120_000 }), links.nth(index).click({ force: true }), ]); await download.saveAs(file); return { path: file, bytes: fs.statSync(file).size, sha256: sha256File(file), name }; } return null; }; // A frame whose pixels are all transparent is not a photograph of a scene. The // embedded EEVEE path returns exactly that while reporting SUCCEEDED, so the // report records pixel statistics instead of trusting the file size. // The decoder lives in lib/image-stats.mjs and is shared with // tools/web/inspect-image.mjs and the gate. const opaqueStats = (file) => { try { const stats = imageStats(file); return {width: stats.width, height: stats.height, maxAlpha: stats.maxAlpha, opaqueRatio: stats.opaqueRatio, maxRgb: stats.maxRgb, verdict: stats.verdict}; } catch { return null; } }; const openNativePanel = async (page) => { // The React workspace (and therefore the panel) only mounts once the native // desktop canvas is left through the product's own toggle. const webTools = page.getByTestId("native-web-tools-toggle"); if (await webTools.count() && await webTools.first().isVisible().catch(() => false)) { await webTools.first().click({ force: true }); await page.waitForTimeout(1500); } const details = page.locator("details.native-render-fallback").first(); await details.waitFor({ timeout: 120_000 }); if (!(await details.evaluate((element) => element.open))) { await details.locator("summary").first().click({ force: true }); } await page.locator(".native-render-panel").first().waitFor({ timeout: 60_000 }); }; const openRendering = async (page) => { await page.waitForFunction( () => [...document.querySelectorAll(".workspace-tab")].some((tab) => tab.getAttribute("aria-current") !== null), null, { timeout: 90_000 }); await page.evaluate(() => { const tab = [...document.querySelectorAll(".workspace-tab")].find((item) => item.textContent === "Rendering"); if (tab instanceof HTMLElement) tab.click(); }); await page.waitForFunction(() => [...document.querySelectorAll(".workspace-tab")] .some((tab) => tab.getAttribute("aria-current") !== null && tab.textContent === "Rendering"), null, { timeout: 30_000 }); await page.waitForTimeout(900); }; let browser; let context; try { await waitForServer(`${BASE}/?ui=web`); browser = await launchBrowser(args.gpu); ({ context } = await newPage(browser, { baseUrl: `${BASE}/?ui=web` })); const page = context.pages()[0] ?? await context.newPage(); await page.locator("main.blender-app").waitFor({ timeout: 120_000 }); report.gpuRenderer = await page.evaluate(() => { const canvas = document.createElement("canvas"); const gl = canvas.getContext("webgl2"); const info = gl?.getExtension("WEBGL_debug_renderer_info"); return gl && info ? gl.getParameter(info.UNMASKED_RENDERER_WEBGL) : gl ? gl.getParameter(gl.RENDERER) : null; }).catch(() => null); const shadingMode = () => page.locator('button[aria-label="着色模式"]').first().getAttribute("title"); const cycleTo = async (label, clicks = 4) => { const button = page.locator('button[aria-label="着色模式"]').first(); for (let index = 0; index < clicks; index += 1) { if (new RegExp(label).test((await button.getAttribute("title")) ?? "")) return; await button.click({ force: true }); await page.waitForTimeout(700); } throw new Error(`shading stuck at ${await button.getAttribute("title")}, wanted ${label}`); }; await step(page, "01-open-project", async () => { await openFile(page, SCENE); await waitScene(page, { objects: 7, timeout: 120_000 }); // Start from 实体 so the two shading steps below each change the picture; // whatever the stored preference cycles in with is not a step of this guide. await cycleTo("实体"); await page.waitForTimeout(1200); }); // Viewport shading: click the real 着色模式 button until it reports 材质, then // one more click for 渲染. Reading the button title is what tells the capture // which mode is on screen; the shading itself is a canvas repaint. await step(page, "02-viewport-material", async () => { await cycleTo("材质"); await page.waitForTimeout(1200); }); await step(page, "03-viewport-rendered", async () => { await cycleTo("渲染", 2); await page.waitForTimeout(1500); }); await step(page, "04-rendering-workspace", async () => { await openRendering(page); // The PBR panel is a tall section; scrolling it into view is what the step // shows. Leaving it unscrolled made 04 and 05 byte-identical. await page.locator('section[aria-label="Web PBR 渲染"]').scrollIntoViewIfNeeded(); await page.waitForTimeout(400); }); await step(page, "05-pbr-512-result", async () => { const panel = page.locator('section[aria-label="Web PBR 渲染"]'); await panel.locator('select[aria-label="PBR 渲染分辨率"]').selectOption("512"); const started = Date.now(); await panel.getByRole("button", { name: "渲染 PBR", exact: true }).click({ force: true }); await panel.locator(".pbr-render-result img").waitFor({ timeout: 120_000 }); await page.waitForTimeout(500); report.pbr = { resolution: 512, ms: Date.now() - started, artifact: await saveDownload(page, ".pbr-render-download", path.join(EVIDENCE, "pbr-512.png")) }; }); await step(page, "06-render-result-editor", async () => { // The React RenderResultView fills the editor slot that Blender uses for // Render Result; it must already show the PBR frame just rendered. const view = page.locator('[data-testid="render-result-view"]').first(); await view.waitFor({ timeout: 30_000 }); const image = view.locator("img"); await image.waitFor({ timeout: 30_000 }); const size = await image.evaluate((element) => element instanceof HTMLImageElement ? [element.naturalWidth, element.naturalHeight] : [0, 0]); report.renderResultView = { naturalWidth: size[0], naturalHeight: size[1], source: await view.getAttribute("data-source") }; if (size[0] !== 512) throw new Error(`render result shows ${size[0]}x${size[1]}, expected the 512 PBR frame`); // Show the 1:1 view: it is a real control of the new editor and makes this // frame distinct from the PBR panel frame above it. await view.getByRole("button", { name: "1:1", exact: true }).click({ force: true }); await page.waitForTimeout(400); report.renderResultView.actualSize = await view.getByRole("button", { name: "适应窗口", exact: true }).isVisible(); // 1:1 overflows the slot, so the toolbar (name, size, 下载) scrolls away. // The step is about that toolbar, so pin the area's own scroller to the top; // `scrollIntoViewIfNeeded` does nothing for an element taller than its // container. await view.evaluate((element) => { const scroller = element.closest(".area-content"); if (scroller) scroller.scrollTop = 0; }); await page.waitForTimeout(500); }); await step(page, "07-native-panel", async () => { await openNativePanel(page); await page.waitForTimeout(600); }); // One engine attempt = select engine, render a still, wait for a terminal // state, save the PNG if one appeared. A failure is recorded, never thrown. const renderEngine = async (engine, timeout) => { const started = Date.now(); const entry = { engine, startedAt: now() }; try { await openNativePanel(page); const panel = page.locator(".native-render-panel").first(); await panel.locator('select[aria-label="Engine"]').selectOption(engine); await panel.locator('select[aria-label="Format"]').selectOption("PNG"); await panel.getByRole("button", { name: "Render Frame", exact: true }).scrollIntoViewIfNeeded(); // The previous engine's SUCCEEDED text and artifact links stay on screen // until the new result replaces them, so waiting on that text returns // instantly and saves the *previous* frame. Each render mints a fresh // blob URL for its image; that is the identity worth waiting on. const previousSrc = await panel.locator(".native-render-image img").getAttribute("src").catch(() => null); await panel.getByRole("button", { name: "Render Frame", exact: true }).click(); await page.waitForFunction((previous) => { const panel = document.querySelector(".native-render-panel"); if (!panel) return false; const text = panel.querySelector(".native-workflow-output")?.textContent ?? ""; if (/FAILED|CANCELLED/.test(text)) return true; const image = panel.querySelector(".native-render-image img"); return /SUCCEEDED/.test(text) && image !== null && image.getAttribute("src") !== previous && panel.querySelector(".native-workflow-artifacts a[download]") !== null; }, previousSrc, { timeout }); await openNativePanel(page); entry.output = (await page.locator(".native-render-panel .native-workflow-output").first().textContent().catch(() => "")) ?? ""; entry.artifact = await saveImageArtifact(page, path.join(EVIDENCE, `native-${engine.toLowerCase()}.png`)); if (entry.artifact) entry.pixels = opaqueStats(entry.artifact.path); entry.status = entry.artifact ? "PASS" : /SUCCEEDED/.test(entry.output) ? "PARTIAL" : "FAIL"; } catch (error) { entry.status = "FAIL"; entry.error = String(error?.message ?? error).split("\n")[0]; } entry.ms = Date.now() - started; report.engines.push(entry); console.log(`engine ${engine}: ${entry.status} ${entry.ms} ms${entry.error ? ` — ${entry.error}` : ""}`); return entry; }; await step(page, "08-native-eevee", async () => { const entry = await renderEngine("BLENDER_EEVEE", 180_000); if (entry.status !== "PASS") throw new Error(`EEVEE ${entry.status}: ${entry.error ?? entry.output?.slice(0, 120)}`); await page.waitForTimeout(500); }); await step(page, "09-native-workbench", async () => { await renderEngine("BLENDER_WORKBENCH", 180_000); }); await step(page, "10-native-cycles", async () => { await renderEngine("CYCLES", 240_000); }); // Path four: the default URL runs Blender inside the page; F12 is the user // shortcut. A second context keeps the two backends from sharing a WASM heap. const embedded = await browser.newContext({ viewport: { width: 1600, height: 900 }, deviceScaleFactor: 1, acceptDownloads: true }); const embeddedPage = await embedded.newPage(); try { await step(embeddedPage, "11-wasm-f12", async () => { await embeddedPage.goto(`${BASE}/`, { waitUntil: "domcontentloaded" }); await embeddedPage.locator("main.blender-app").waitFor({ timeout: 120_000 }); await openFile(embeddedPage, SCENE); await waitScene(embeddedPage, { objects: 7, timeout: 120_000 }); await openRendering(embeddedPage); await embeddedPage.evaluate(() => { if (document.activeElement instanceof HTMLElement) document.activeElement.blur(); }); const started = Date.now(); await embeddedPage.keyboard.press("F12"); await embeddedPage.waitForFunction(() => document.querySelector(".native-render-panel") !== null, null, { timeout: 120_000 }); await openNativePanel(embeddedPage); await embeddedPage.waitForFunction(() => /SUCCEEDED|FAILED|CANCELLED/.test( document.querySelector(".native-render-panel .native-workflow-output")?.textContent ?? ""), null, { timeout: 120_000 }); report.wasm = { ms: Date.now() - started, output: (await embeddedPage.locator(".native-render-panel .native-workflow-output").first().textContent().catch(() => "")) ?? "", artifact: await saveImageArtifact(embeddedPage, path.join(EVIDENCE, "wasm-f12-scene.png")), }; if (report.wasm.artifact) report.wasm.pixels = opaqueStats(report.wasm.artifact.path); // The panel only exists behind the React tools; the step screenshot has to // show what the user sees, which is the native canvas holding Render Result. await embeddedPage.getByTestId("native-web-tools-toggle").first().click({ force: true }).catch(() => {}); await embeddedPage.waitForTimeout(2000); }); // Which engines actually produce pixels in the page matters more than which // ones accept the command: EEVEE reports SUCCEEDED while writing an // all-transparent frame, so each engine is rendered and measured. for (const engine of ["BLENDER_WORKBENCH", "BLENDER_EEVEE"]) { const started = Date.now(); const entry = { engine, startedAt: now() }; try { const panel = embeddedPage.locator(".native-render-panel").first(); await panel.locator('select[aria-label="Engine"]').selectOption(engine); const previousSrc = await panel.locator(".native-render-image img").getAttribute("src").catch(() => null); await panel.getByRole("button", { name: "Render Frame", exact: true }).click(); await embeddedPage.waitForFunction((previous) => { const element = document.querySelector(".native-render-panel"); if (!element) return false; const text = element.querySelector(".native-workflow-output")?.textContent ?? ""; if (/FAILED|CANCELLED/.test(text)) return true; const image = element.querySelector(".native-render-image img"); return /SUCCEEDED/.test(text) && image !== null && image.getAttribute("src") !== previous; }, previousSrc, { timeout: 240_000 }); entry.output = (await panel.locator(".native-workflow-output").first().textContent().catch(() => "")) ?? ""; entry.artifact = await saveImageArtifact(embeddedPage, path.join(EVIDENCE, `wasm-${engine.toLowerCase()}.png`)); if (entry.artifact) entry.pixels = opaqueStats(entry.artifact.path); entry.status = entry.artifact ? "PASS" : "FAIL"; } catch (error) { entry.status = "FAIL"; entry.error = String(error?.message ?? error).split("\n")[0]; } entry.ms = Date.now() - started; report.embeddedEngines.push(entry); console.log(`embedded ${engine}: ${entry.status} ${entry.ms} ms ${JSON.stringify(entry.pixels ?? null)}`); } } finally { await embedded.close().catch(() => {}); } // Two adjacent screenshots of the same state are useless as instruction, so // the report records the hash and the gate rejects a repeat. const duplicates = []; for (let index = 1; index < report.steps.length; index += 1) { const previous = report.steps[index - 1].shot; const current = report.steps[index].shot; if (previous && current && previous.sha256 === current.sha256) duplicates.push(`${report.steps[index - 1].name} == ${report.steps[index].name}`); } report.duplicateScreenshots = duplicates; const failed = report.steps.filter((entry) => entry.status !== "PASS"); report.status = failed.length === 0 && duplicates.length === 0 ? "PASS" : "PARTIAL"; } catch (error) { report.error = String(error?.message ?? error).split("\n")[0]; } finally { report.finishedAt = now(); fs.writeFileSync(path.join(OUT, "capture-report.json"), `${JSON.stringify(report, null, 2)}\n`); await context?.close().catch(() => {}); await browser?.close().catch(() => {}); console.log(JSON.stringify({ status: report.status, steps: report.steps.map((entry) => `${entry.status} ${entry.name}`), engines: report.engines.map((entry) => `${entry.engine}:${entry.status}`) }, null, 2)); }