#!/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 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)); }