Add 27-model production-line Web FreeCAD course tooling and pages

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
2026-11-13 04:16:04 +08:00
parent 789e18ca3e
commit 4eff6110e7
447 changed files with 29820 additions and 71 deletions

View File

@@ -0,0 +1,57 @@
// Assembly helpers shared by the line-course E17 episode.
export async function executeCommand(page, command, payload, timeout = 300000) {
const before = await page.evaluate(() => window.__freecadWorkbenchState?.response?.requestId ?? null);
await page.locator(`button[data-help-page="${command}"]`).first().click();
await page.locator("#payload-editor").fill(JSON.stringify(payload));
await page.getByRole("button", { name: "执行选中命令" }).click();
await page.waitForFunction(id => {
const response = window.__freecadWorkbenchState?.response;
return Boolean(response) && response.requestId !== id;
}, before, { timeout });
const response = await page.evaluate(() => window.__freecadWorkbenchState?.response);
if (response?.kind !== "result") throw new Error(`${command}: ${response?.error?.code} ${response?.error?.message}`);
return response.result?.records?.find(record => record.status === "exposed")?.result ?? response.result;
}
export async function createAssembly(page, { document = "LineAssembly", label = "生产线总装" } = {}) {
const create = page.getByRole("region", { name: "Create assembly" });
await create.waitFor({ state: "visible", timeout: 60000 });
await page.locator('input[aria-label="Assembly document name"]').fill(document);
await page.locator('input[aria-label="Assembly label"]').fill(label);
await create.getByRole("button", { name: "Create", exact: true }).click();
const linksTask = page.getByRole("region", { name: "Insert assembly link" });
await linksTask.waitFor({ state: "visible", timeout: 120000 });
return linksTask;
}
export async function insertLinks(page, linksTask, source = "line-course-E16.FCStd", expectedLinks = 27) {
await page.locator('select[aria-label="Insert link source file"]').selectOption(source);
await linksTask.getByRole("button", { name: "Load source", exact: true }).click();
await page.waitForFunction(() => {
const select = document.querySelector('select[aria-label="Insert link source object"]');
return select && select.options.length > 1;
}, null, { timeout: 180000 });
const options = (await page.locator('select[aria-label="Insert link source object"] option').allTextContents())
.filter(option => option && !option.startsWith("Choose"));
const select = page.locator('select[aria-label="Insert link source object"]');
const list = linksTask.locator('ul[aria-label="Inserted links"] li');
for (const option of options) {
await select.selectOption({ label: option });
await page.waitForTimeout(350);
await linksTask.getByRole("button", { name: "Insert", exact: true }).click();
await page.waitForTimeout(600);
}
await page.waitForTimeout(1200);
await linksTask.getByRole("button", { name: "Accept", exact: true }).click();
await page.waitForTimeout(1500);
const items = await list.allTextContents();
const linkNames = items.map(text => /→\s+([^(]+?)\s+\(/.exec(text)?.[1]?.trim()).filter(Boolean);
if (items.length !== expectedLinks) throw new Error(`expected ${expectedLinks} links, got ${items.length}`);
return { linkNames, items };
}
export async function buildAssembly(page, options = {}) {
const linksTask = await createAssembly(page, options);
const result = await insertLinks(page, linksTask, options.source, options.expectedLinks ?? 27);
return { document: options.document ?? "LineAssembly", ...result };
}

View File

@@ -0,0 +1,159 @@
// Shared UI building blocks for the production-line course drivers.
import { closeTask, openGroup, openPartMenu, removeObject, renameSelected,
selectTreeLabel, simpleCopy, treeLabels } from "../../carrier-course/lib/ui-actions.mjs";
export const hex = color => `#${color.map(value =>
Math.round(Math.min(1, Math.max(0, value)) * 255).toString(16).padStart(2, "0")).join("")}`;
export function createBuilder({ page, rec, logStep }) {
const labels = () => treeLabels(page);
const pause = ms => page.waitForTimeout(ms);
const applyLabel = async (from, to) => {
await selectTreeLabel(page, from);
const input = page.locator('input[aria-label="Object Label"]').first();
await input.fill(to);
await input.press("Enter");
await pause(700);
};
const place = async (label, part) => {
await selectTreeLabel(page, label);
await rec.clickSelector(page, 'button:has-text("Position")');
await page.locator('input[aria-label="Position X"]').first().fill(String(part.position[0]));
await page.locator('input[aria-label="Position Y"]').first().fill(String(part.position[1]));
await page.locator('input[aria-label="Position Z"]').first().fill(String(part.position[2]));
const [ax, ay, az] = part.rotation.axis;
await page.locator('input[aria-label="Rotation axis X"]').first().fill(String(ax));
await page.locator('input[aria-label="Rotation axis Y"]').first().fill(String(ay));
await page.locator('input[aria-label="Rotation axis Z"]').first().fill(String(az));
await page.locator('input[aria-label="Rotation angle"]').first().fill(String(part.rotation.angleDeg));
await rec.clickSelector(page, 'button[aria-label="应用位置与旋转"]');
await pause(1600);
await closeTask(page);
};
const setColor = async (label, color) => {
await selectTreeLabel(page, label);
const input = page.locator('input[aria-label="Object Color"]').first();
if (await input.count()) {
await input.fill(hex(color));
await input.dispatchEvent("change");
await pause(500);
}
};
const createBox = async (label, dims, localPosition, rotation) => {
const before = await labels();
await openPartMenu(page, rec);
await openGroup(page, "Primitives");
await rec.clickSelector(page, 'button[data-command="Part_Box"]');
await pause(800);
let created = null;
for (let attempt = 0; attempt < 20 && !created; attempt++) {
await pause(300);
created = (await labels()).find(item => !before.includes(item)) ?? null;
}
if (!created) throw new Error(`box ${label} not created`);
await selectTreeLabel(page, created);
await pause(300);
await page.locator('input[aria-label="Length"]').first().fill(String(dims[0]));
await page.locator('input[aria-label="Width"]').first().fill(String(dims[1]));
await page.locator('input[aria-label="Height"]').first().fill(String(dims[2]));
await rec.clickSelector(page, 'button:has-text("应用尺寸并重算")');
await pause(1400);
await closeTask(page);
await applyLabel(created, label);
if (localPosition) {
await selectTreeLabel(page, label);
await rec.clickSelector(page, 'button:has-text("Position")');
await page.locator('input[aria-label="Position X"]').first().fill(String(localPosition[0]));
await page.locator('input[aria-label="Position Y"]').first().fill(String(localPosition[1]));
await page.locator('input[aria-label="Position Z"]').first().fill(String(localPosition[2]));
if (rotation) {
await page.locator('input[aria-label="Rotation axis X"]').first().fill(String(rotation.axis[0]));
await page.locator('input[aria-label="Rotation axis Y"]').first().fill(String(rotation.axis[1]));
await page.locator('input[aria-label="Rotation axis Z"]').first().fill(String(rotation.axis[2]));
await page.locator('input[aria-label="Rotation angle"]').first().fill(String(rotation.angleDeg));
}
await rec.clickSelector(page, 'button[aria-label="应用位置与旋转"]');
await pause(900);
await closeTask(page);
}
logStep?.({ step: "box", label, dims, localPosition });
return label;
};
const createCylinder = async (label, radius, height, localPosition, rotation) => {
const before = await labels();
await openPartMenu(page, rec);
await openGroup(page, "Primitives");
await rec.clickSelector(page, 'button[data-command="Part_Cylinder"]');
await pause(800);
let created = null;
for (let attempt = 0; attempt < 20 && !created; attempt++) {
await pause(300);
created = (await labels()).find(item => !before.includes(item)) ?? null;
}
if (!created) throw new Error(`cylinder ${label} not created`);
await selectTreeLabel(page, created);
await applyLabel(created, label);
await selectTreeLabel(page, label);
for (const [name, value] of [["Property Radius", radius], ["Property Height", height]]) {
const input = page.locator(`input[aria-label="${name}"]`).first();
if (await input.count()) { await input.fill(String(value)); await input.press("Tab"); await pause(600); }
}
await closeTask(page);
if (localPosition) {
await selectTreeLabel(page, label);
await rec.clickSelector(page, 'button:has-text("Position")');
await page.locator('input[aria-label="Position X"]').first().fill(String(localPosition[0]));
await page.locator('input[aria-label="Position Y"]').first().fill(String(localPosition[1]));
await page.locator('input[aria-label="Position Z"]').first().fill(String(localPosition[2]));
if (rotation) {
await page.locator('input[aria-label="Rotation axis X"]').first().fill(String(rotation.axis[0]));
await page.locator('input[aria-label="Rotation axis Y"]').first().fill(String(rotation.axis[1]));
await page.locator('input[aria-label="Rotation axis Z"]').first().fill(String(rotation.axis[2]));
await page.locator('input[aria-label="Rotation angle"]').first().fill(String(rotation.angleDeg));
}
await rec.clickSelector(page, 'button[aria-label="应用位置与旋转"]');
await pause(900);
await closeTask(page);
}
logStep?.({ step: "cylinder", label, radius, height, localPosition });
return label;
};
const compoundCopy = async (sources, name, baseLabels) => {
await openPartMenu(page, rec);
const group = page.locator("details.part-submenu").filter({ has: page.locator("summary", { hasText: /^Compound$/ }) }).first();
if (!(await group.evaluate(element => element.open))) { await group.locator(":scope > summary").click(); await pause(300); }
await rec.clickSelector(page, '.part-command-menu button[data-command="Part_Compound"]');
const task = page.getByRole("region", { name: "Compound tools" });
await task.waitFor({ state: "visible", timeout: 30000 });
for (const source of sources) {
const box = task.locator("label").filter({ hasText: source }).first().locator('input[type="checkbox"]').first();
if (!(await box.isChecked())) await box.click();
await pause(250);
}
await task.getByRole("button", { name: "Create compound feature", exact: true }).click();
await pause(1400);
await closeTask(page);
const after = await labels();
const compound = after.find(label => !baseLabels.includes(label) && !sources.includes(label)) ?? null;
if (!compound) throw new Error(`compound not created: ${JSON.stringify(after)}`);
await selectTreeLabel(page, compound);
await simpleCopy({ page, rec, source: compound });
const copied = await labels();
const copy = copied.find(label => label !== compound && label.startsWith(compound)) ?? null;
if (!copy) throw new Error(`compound copy not found: ${JSON.stringify(copied)}`);
await selectTreeLabel(page, copy);
await renameSelected(page, name);
await removeObject(page, rec, compound);
for (const source of sources) await removeObject(page, rec, source);
logStep?.({ step: "compound", compound, copy, name, labels: await labels() });
return name;
};
return { labels, pause, place, setColor, createBox, createCylinder, compoundCopy, applyLabel };
}

View File

@@ -0,0 +1,109 @@
// Compares a built line-course checkpoint with line-spec.json.
// Geometry/centre come from the Node WASM probe (inspectFcstd); colours come
// from Document.xml's WebDisplayColor property, which the Web save persists.
import fs from "node:fs";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { inspectFcstd } from "../../carrier-course/lib/inspect.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const spec = JSON.parse(fs.readFileSync(path.join(here, "..", "line-spec.json"), "utf8"));
const partByName = new Map(spec.models.flatMap(model =>
model.parts.map(part => [part.partName, { ...part, model: model.name }])));
const modelByName = new Map(spec.models.map(model => [model.name, model]));
const nearArray = (actual, expected, tolerance, label, issues) => {
if (!Array.isArray(actual) || actual.length !== expected.length) {
issues.push({ name: label, detail: { actual, expected } });
return;
}
const worst = Math.max(...actual.map((value, index) => Math.abs(Number(value) - Number(expected[index]))));
if (!Number.isFinite(worst) || worst > tolerance)
issues.push({ name: label, detail: { actual, expected, worst, tolerance } });
};
const parseHex = hex => {
const match = /^#?([0-9a-f]{6})$/i.exec(String(hex ?? "").trim());
if (!match) return null;
const value = parseInt(match[1], 16);
return [(value >> 16) & 255, (value >> 8) & 255, value & 255].map(channel => channel / 255);
};
const readDocumentColors = filePath => {
const xml = execFileSync("/usr/bin/unzip", ["-p", filePath, "Document.xml"],
{ encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
const colors = new Map();
const objects = xml.split("<Object ").slice(1);
for (const block of objects) {
const name = /\bname="([^"]*)"/.exec(block)?.[1];
const label = /<Property name="Label"[^>]*>\s*<String value="([^"]*)"/s.exec(block)?.[1] ?? name;
const color = /<Property name="WebDisplayColor"[^>]*>\s*<String value="([^"]*)"/s.exec(block)?.[1];
if (label) colors.set(label, color ?? null);
if (name && name !== label) colors.set(name, color ?? null);
}
return colors;
};
export function compareLinePart(expected, actual, color) {
const issues = [];
nearArray(actual.bbox, expected.worldBBox, 1.5, "bbox", issues);
nearArray(actual.center, expected.center, 3, "center", issues);
if (actual.valid !== true) issues.push({ name: "valid", detail: actual.valid });
const actualColor = parseHex(color);
const expectedColor = expected.color;
if (!actualColor) {
issues.push({ name: "color", detail: { actual: color, expected: expectedColor } });
} else {
const worst = Math.max(...actualColor.map((value, index) => Math.abs(value - expectedColor[index])));
if (worst > 0.02) issues.push({ name: "color", detail: { actual: actualColor, expected: expectedColor, worst } });
}
return { name: expected.partName, label: expected.label, model: expected.model,
tolerance: 1.5, ok: issues.length === 0, issues };
}
export async function checkLineCheckpoint(filePath, expectedNames) {
const { objects } = await inspectFcstd(filePath);
const byLabel = new Map(objects.map(object => [object.label, object]));
const colors = readDocumentColors(filePath);
const results = [];
for (const name of expectedNames) {
const expected = partByName.get(name);
if (!expected) throw new Error(`line-spec has no part ${name}`);
const actual = byLabel.get(name) ?? objects.find(object => object.name === name);
if (!actual) {
results.push({ name, ok: false, issues: [{ name: "missing", detail: expected.label }] });
continue;
}
results.push(compareLinePart(expected, actual, colors.get(actual.label) ?? colors.get(actual.name)));
}
const extra = objects.filter(object => !expectedNames.includes(object.label)).map(object => object.label);
const built = objects.filter(object => expectedNames.includes(object.label));
const models = [];
for (const model of spec.models) {
const names = model.parts.map(part => part.partName).filter(partName => expectedNames.includes(partName));
if (!names.length) continue;
const builtParts = built.filter(object => names.includes(object.label));
const issues = [];
nearArray(
builtParts.length ? [0, 1, 2].map(axis => Math.min(...builtParts.map(object => object.bbox[axis])))
.concat([0, 1, 2].map(axis => Math.max(...builtParts.map(object => object.bbox[axis + 3])))) : [],
[model.overallBBox[0], model.overallBBox[1], model.overallBBox[2],
model.overallBBox[3], model.overallBBox[4], model.overallBBox[5]],
model.parts.length <= 2 ? 2 : 5, "model-bbox", issues);
models.push({ name: model.name, label: model.label, parts: names.length, ok: issues.length === 0, issues });
}
return {
schema: "freecad-web-line-course/precision/v1",
objectCount: objects.length,
extra,
results,
models,
ok: results.every(result => result.ok) && extra.length === 0 && models.every(model => model.ok),
};
}
export function loadLineSpec() { return spec; }
export function lineModel(name) { return modelByName.get(name); }

View File

@@ -0,0 +1,92 @@
// Shared "build models -> save checkpoint -> precision" flow for line episodes.
// Scene ids: S00 title (driver), S01 document/checkpoint, S02.. build chunks of
// two parts, then S<last> save. Episode scripts use the same ids.
import fs from "node:fs";
import path from "node:path";
import { saveCheckpoint } from "../../carrier-course/lib/ui-actions.mjs";
import { createBuilder } from "./build.mjs";
import { newDocument, spec } from "./ui.mjs";
import { checkLineCheckpoint } from "./line-precision.mjs";
export async function buildEpisodeModels({
page, rec, webRoot, rawDir, stillsDir, scene, shot, logStep, log = [],
episodeId, modelNames, freshDocument = false,
}) {
const course = JSON.parse(fs.readFileSync(path.join(webRoot, "tools", "line-course", "course.json"), "utf8"));
const episode = course.episodes.find(item => item.id === episodeId);
if (!episode) throw new Error(`course.json has no episode ${episodeId}`);
const parts = modelNames.flatMap(name => {
const model = spec().models.find(item => item.name === name);
if (!model) throw new Error(`line-spec has no model ${name}`);
return model.parts;
});
const expectedNames = episode.checkpointObjects;
const builder = createBuilder({ page, rec, logStep });
await scene("S01", async () => {
if (freshDocument) {
await newDocument(page);
} else {
// Checkpoint loading is asynchronous; wait for the expected number of
// previous objects before creating anything, otherwise the new Box can
// be confused with an existing object (seen with COURSE_FAST=1).
const priorCount = expectedNames.length - parts.length;
for (let attempt = 0; attempt < 120; attempt++) {
const labels = await builder.labels();
if (labels.filter(label => expectedNames.includes(label)).length >= priorCount) break;
await page.waitForTimeout(500);
}
}
logStep({ step: "start", episode: episodeId, labels: await builder.labels(), freshDocument });
await shot("S01-start");
});
const buildPart = async part => {
const dims = part.fcLocalDims;
if (part.primitive === "cylinder") {
// Use the average radius so slightly elliptical references stay inside
// the 1.5 mm bbox tolerance on both axes (ABB_P03: 219.36 x 214.92).
const radius = Math.max(0.1, (dims[0] + dims[1]) / 4);
const position = [part.center[0], part.center[1], part.position[2]];
await builder.createCylinder(part.partName, radius, dims[2], position);
} else {
await builder.createBox(part.partName, dims, part.position);
}
await builder.setColor(part.partName, part.color);
logStep({ step: "part", name: part.partName, dims, position: part.position,
primitive: part.primitive, color: part.color });
};
const sceneIds = [];
for (let index = 0; index < parts.length; index += 2) {
const id = `S${String(2 + index / 2).padStart(2, "0")}`;
sceneIds.push(id);
const slice = parts.slice(index, index + 2);
await scene(id, async () => {
for (const part of slice) await buildPart(part);
await shot(`${id}-parts`);
});
}
const saveId = `S${String(2 + sceneIds.length).padStart(2, "0")}`;
await scene(saveId, async () => {
const saved = await saveCheckpoint({ page, rec, webRoot, episode: episodeId, rawDir,
checkpointDir: path.join(webRoot, "tools", "line-course", "checkpoints"),
expectedLabels: expectedNames });
logStep({ step: "checkpoint", ...saved });
const checkpoint = path.join(webRoot, "tools", "line-course", "checkpoints", `${episodeId}.FCStd`);
const precision = await checkLineCheckpoint(checkpoint, expectedNames);
fs.writeFileSync(path.join(rawDir, `${episodeId}-precision.json`), `${JSON.stringify(precision, null, 2)}\n`);
if (!precision.ok) throw new Error(`precision failed: ${JSON.stringify({ extra: precision.extra,
models: precision.models.filter(item => !item.ok),
failures: precision.results.filter(item => !item.ok) })}`);
fs.writeFileSync(path.join(rawDir, `${episodeId}-state.json`), `${JSON.stringify({
schema: `freecad-web-line-course/${episodeId}/state/v1`,
generatedAt: new Date().toISOString(), models: modelNames, parts: parts.map(part => part.partName),
precision, log,
}, null, 2)}\n`);
await shot(`${saveId}-recap`);
});
return { parts, expectedNames, sceneIds, saveId };
}

View File

@@ -0,0 +1,81 @@
// Shared project-page actions for the production-line course drivers.
import fs from "node:fs";
import { fileURLToPath } from "node:url";
export const REFERENCE_DIR = "/home/mes123456/FreeCADWasmDev/working/GLTFmodel";
export const footerStatus = page => page.locator('footer [role="status"]').textContent().catch(() => "");
export const treeLabels = page => page.locator(".fc-tree-text").allTextContents();
export async function newDocument(page) {
await page.locator('nav[aria-label="Application menus"] details').filter({ hasText: "File" }).locator("summary").click();
await page.getByRole("button", { name: "新建 Document" }).click();
await page.waitForTimeout(2000);
// The File details menu stays open otherwise and covers the tree/toolbar in
// every subsequent still; close it after creating the document.
await page.evaluate(() => {
for (const details of document.querySelectorAll('nav[aria-label="Application menus"] details[open]')) details.open = false;
});
await page.waitForTimeout(250);
}
export async function openFiles(page) {
await page.evaluate(() => {
const details = document.querySelector(".file-tools");
if (details) details.open = true;
});
await page.waitForTimeout(300);
}
export async function importReference(page, file, timeoutSeconds = 180) {
await openFiles(page);
await page.locator('input[aria-label="Import SCAD, CSG, JT, PLMXML, STEPZ, 3MF or shape files"]').setInputFiles(file);
let status = "";
for (let attempt = 0; attempt < timeoutSeconds; attempt++) {
await page.waitForTimeout(1000);
status = await footerStatus(page);
if (/Imported|failed|error|requires|cancel/i.test(status ?? "")) break;
}
return status;
}
export async function orbit(page, dx, dy) {
const view = page.locator('[aria-label="Imported native 3D view"]').first();
const box = await view.boundingBox();
if (!box) return false;
const x = box.x + box.width / 2; const y = box.y + box.height / 2;
await page.mouse.move(x, y);
await page.mouse.down();
await page.mouse.move(x + dx, y + dy, { steps: 18 });
await page.mouse.up();
await page.waitForTimeout(400);
return true;
}
export const spec = () => JSON.parse(fs.readFileSync(
fileURLToPath(new URL("../line-spec.json", import.meta.url)), "utf8"));
export const modelParts = name => {
const model = spec().models.find(item => item.name === name);
if (!model) throw new Error(`line-spec has no model ${name}`);
return model.parts;
};
export async function openLineReference(page) {
await page.getByRole("button", { name: "Toggle line reference viewer" }).click();
const panel = page.getByRole("complementary", { name: "Line reference viewer" });
await panel.waitFor({ state: "visible", timeout: 30000 });
return panel;
}
export async function selectReferenceModel(panel, page, label, expected = /个网格/) {
const select = panel.locator('select[aria-label="Reference model"]');
await select.selectOption({ label });
let footer = "";
for (let attempt = 0; attempt < 100; attempt++) {
await page.waitForTimeout(500);
footer = await panel.locator("footer").textContent().catch(() => "");
if (expected.test(footer ?? "")) return footer;
}
return footer;
}