Files
FreeCADWasmDev/tools/fcweb/part.mjs
wangdequan 300c8efb01 docs(web): full UI surface inventory, illustrated manual, panel screenshots
Interface design document and manual now share one authoritative surface
inventory (333 surfaces across 9 categories, gap 0), and every chapter carries
real Playwright screenshots of the panels it documents.

- tools/fcweb: ui-surface-scan/ui-surface-inventory (deterministic --check),
  build-ui-doc renders panel catalog, workbench matrix and mapping tables;
  blank toolbar crops (<1 KB) are skipped and pruned instead of embedded
- web/tools/manual: generate-panel-index (ch16), audit-ui-gaps,
  generate-final-status, generate-gaps-doc; pager is per-chapter so the manual
  no longer overflows horizontally
- manual: 130 screenshot references / 128 PNGs, panel sections for ch02-ch13
- web/src: utility menus stop click propagation (menu reopened on item click);
  workbench shell gains an OPFS document picker so workbench.html can bind a
  real document instead of the fixed workbench-document id; Sketcher panel
  moves from the command column to the main stage

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 01:30:31 +08:00

288 lines
12 KiB
JavaScript

// Part workbench client: primitives, booleans, placement, import/export.
//
// Serves `cmd: "part.document"` via FreeCADWebDocumentProbe
// (freecad-source/src/WebAssembly/FreeCADCoreProbe/DocumentProbe.cpp:918).
//
// The point of this module is to collapse the four-step "create -> size ->
// position -> label" triad that every teaching case used to hand-write, and to
// stop callers from guessing which object an import produced.
import fs from "node:fs";
import path from "node:path";
import {
STEM_PART, KernelError, openKernel, createSession, writeTrace,
} from "./kernel.mjs";
import { storeBytes } from "./opfs.mjs";
export const PART_SCHEMA = "freecad-web-part/document/v1";
export const PART_MODULE = "Part";
/** Kernel rule (DocumentProbe.cpp setBoolean): names are identifiers. */
const NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
const PRIMITIVES = ["Box", "Cylinder", "Sphere", "Torus", "Cone"];
const BOOLEANS = ["Fuse", "Cut", "Common"];
function assertName(name, what = "object") {
if (typeof name !== "string" || !NAME.test(name)) {
throw new KernelError(`${what} name must match ${NAME} (got ${JSON.stringify(name)})`, { code: "bad_name" });
}
return name;
}
function assertPositive(values, what) {
for (const value of values) {
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
throw new KernelError(`${what} must be positive finite numbers (got ${JSON.stringify(values)})`, { code: "bad_dimension" });
}
}
}
function vector3(value, fallback, what) {
if (value == null) return fallback;
if (!Array.isArray(value) || value.length !== 3 || value.some(item => typeof item !== "number" || !Number.isFinite(item))) {
throw new KernelError(`${what} must be a 3-number array (got ${JSON.stringify(value)})`, { code: "bad_vector" });
}
return value;
}
export class PartDocument {
constructor(session, kernelDir) {
this.session = session;
this.document = session.document;
this.kernel = session.kernel;
this.kernelDir = kernelDir;
}
get call() { return this.session.call; }
get timed() { return this.session.timed; }
get timings() { return this.session.timings; }
get events() { return this.session.events; }
// ---- document lifecycle -------------------------------------------------
create() { return this.call("create"); }
open(file) { return this.call("open", { path: file }); }
close() { return this.call("close"); }
remove(object) { assertName(object); return this.call("remove", { object }); }
label(object, text) { assertName(object); return this.call("setLabel", { object, label: String(text) }); }
// ---- primitives ---------------------------------------------------------
/**
* Part::Box built the way the desktop box command builds it:
* createFixedBox -> setBox(dimensions) -> setPosition -> setLabel.
*/
box(object, { length, width, height, position, label } = {}) {
assertName(object);
assertPositive([length, width, height], "box dimensions");
const at = vector3(position, [0, 0, 0], "box position");
// createFixedBox allocates the object; setBox is what actually sizes it.
let result = this.call("createFixedBox", { boxCommand: "Part_Box", object });
result = this.call("setBox", { object, dimensions: [length, width, height] });
result = this.call("setPosition", { object, position: at });
if (label) result = this.call("setLabel", { object, label: String(label) });
return result;
}
/**
* Any Part primitive. `kind` selects the Part:: type; `parameters` are the
* native property names (Radius/Height/Angle for a cylinder, Length/Width/
* Height for a box, and so on -- the kernel wants the capitalised names).
*/
primitive(object, { kind, parameters = {}, placement, container, label, builderInfo = true } = {}) {
assertName(object);
if (!PRIMITIVES.includes(kind)) {
throw new KernelError(`unknown part primitive ${JSON.stringify(kind)}; expected one of ${PRIMITIVES.join(", ")}`, { code: "bad_primitive" });
}
const args = {
primitive: kind,
object,
primitiveCreate: true,
parameters,
builderInfo,
};
if (container) args.primitiveContainer = container;
if (placement) {
args.primitivePlacement = {
position: vector3(placement.position, [0, 0, 0], "primitive position"),
axis: vector3(placement.axis, [0, 0, 1], "primitive axis"),
angle: typeof placement.angle === "number" ? placement.angle : 0,
};
}
let result = this.call("setPrimitive", args);
if (label) result = this.call("setLabel", { object, label: String(label) });
return result;
}
/** Convenience for the very common "cylinder, rotated about Y" shaft case. */
cylinder(object, { radius, height, position, axis = [0, 1, 0], angle = 90, container, label } = {}) {
assertPositive([radius, height], "cylinder dimensions");
return this.primitive(object, {
kind: "Cylinder",
parameters: { Radius: radius, Height: height, Angle: 360, FirstAngle: 0, SecondAngle: 0 },
placement: { position: position ?? [0, 0, 0], axis, angle },
container,
label,
});
}
// ---- booleans -----------------------------------------------------------
boolean(operation, { object, base, tool } = {}) {
if (!BOOLEANS.includes(operation)) {
throw new KernelError(`unknown boolean ${JSON.stringify(operation)}; expected ${BOOLEANS.join(", ")}`, { code: "bad_boolean" });
}
assertName(object);
assertName(base, "base");
assertName(tool, "tool");
return this.call("setBoolean", { operation, object, base, tool });
}
fuse(args) { return this.boolean("Fuse", args); }
cut(args) { return this.boolean("Cut", args); }
common(args) { return this.boolean("Common", args); }
// ---- placement ----------------------------------------------------------
move(object, position) {
assertName(object);
return this.call("setPosition", { object, position: vector3(position, [0, 0, 0], "position") });
}
place(object, { position, axis = [0, 0, 1], angle = 0 } = {}) {
assertName(object);
return this.call("setPlacement", {
object,
position: vector3(position, [0, 0, 0], "placement position"),
axis: vector3(axis, [0, 0, 1], "placement axis"),
angle: typeof angle === "number" ? angle : 0,
});
}
compound(object, links, { label } = {}) {
assertName(object);
if (!Array.isArray(links) || links.length === 0) {
throw new KernelError("compound requires a non-empty links array", { code: "bad_request" });
}
links.forEach(link => assertName(link, "compound link"));
let result = this.call("createCompound", { object, links });
if (label) result = this.call("setLabel", { object, label: String(label) });
return result;
}
// ---- import / export ----------------------------------------------------
/**
* Import a STEP or BREP file that already sits in the kernel's MEMFS.
*
* Returns `{ object, solid, objects }`: `solid` is the first imported object
* that actually carries volume, which is the "pick the real body out of the
* import result" step every caller used to write by hand.
*/
importPath(file, { object, step = null, command, label } = {}) {
const isStep = step ?? /\.(stp|step)$/i.test(file);
const action = isStep ? "importStep" : "importShape";
const args = { path: file };
if (object) args.object = assertName(object);
if (command) args.desktopImportCommand = command;
else if (!isStep) args.desktopImportCommand = "Import_ReadBREP";
let result = this.call(action, args);
if (label && object) result = this.call("setLabel", { object, label: String(label) });
const objects = result?.objects ?? [];
const solid = objects.find(item => typeof item?.volume === "number" && item.volume > 0) ?? null;
return { object: solid?.name ?? object ?? null, solid, objects };
}
/** Put host bytes into the kernel's virtual file system (never host /tmp). */
stageFile(name, bytes) {
const target = `/tmp/${path.basename(name)}`;
this.kernel.FS.writeFile(target, new Uint8Array(bytes));
return target;
}
/**
* Export one object and store it through the OPFS contract.
* `extension` is the OCCT format: brep, step, stp, iges, stl.
*/
exportObject(object, extension = "brep", { name } = {}) {
assertName(object);
const suffix = String(extension).replace(/^\./, "").toLowerCase();
const staged = `/tmp/${this.document}-${object}.${suffix}`;
const reply = this.call("exportShape", { path: staged, object });
const bytes = this.kernel.FS.readFile(staged);
const stored = storeBytes(name ?? `${this.document}-${object}.${suffix}`, bytes);
return { object, format: suffix, ...stored, nativeSize: reply?.size ?? null };
}
/** Save the whole document as FCStd (Assembly_InsertLink only accepts .FCStd). */
saveDocument({ name } = {}) {
const staged = `/tmp/${this.document}.FCStd`;
this.call("save", { path: staged });
const bytes = this.kernel.FS.readFile(staged);
return { format: "FCStd", ...storeBytes(name ?? `${this.document}.FCStd`, bytes) };
}
// ---- inspection ---------------------------------------------------------
//
// Primitive-editing actions (setBox/setPosition/setLabel) answer with object
// stubs that carry no geometry, so measurement always goes through snapshot.
objects() { return this.snapshot().objects ?? []; }
objectOf(name) { return this.objects().find(item => item.name === name) ?? null; }
volumeOf(name) { return this.objectOf(name)?.volume ?? null; }
snapshot({ mesh = false, objects } = {}) {
const args = { includeMesh: mesh === true, builderInfo: false };
if (mesh && Array.isArray(objects)) args.includeMeshObjects = objects;
return this.call("snapshot", args);
}
/**
* Mesh projection for a viewer: positions/normals rounded to 1e-3 and a
* triangle count, which is what the teaching pages consume.
*
* The kernel nests the geometry under `object.mesh` ({positions, normals,
* triangleCount, bounds, colors, ...}); the object itself only carries the
* B-rep summary.
*/
meshOf(name) {
const result = this.snapshot({ mesh: true, objects: [name] });
const item = (result?.objects ?? []).find(entry => entry.name === name);
if (!item) throw new KernelError(`snapshot returned no object ${name}`, { code: "missing_object" });
const mesh = item.mesh ?? {};
const round = values => (values ?? []).map(value => Math.round(value * 1000) / 1000);
const positions = round(mesh.positions);
return {
name,
label: item.label ?? name,
volume: item.volume ?? null,
bounds: mesh.bounds ?? null,
positions,
normals: round(mesh.normals),
triangleCount: mesh.triangleCount ?? positions.length / 9,
};
}
trace() { return this.session.trace(); }
writeTrace(extra) { return writeTrace(this.session, { extra }); }
}
/**
* Open a Part document. Does not create it -- callers decide whether to
* `create()` or `open(path)`, because both flows are legitimate.
*/
export async function openPart(document, { kernelDirs, print, printErr, builder } = {}) {
if (!document) throw new KernelError("openPart requires a document name", { code: "bad_request" });
const handle = await openKernel({ stem: STEM_PART, dirs: kernelDirs, print, printErr });
const session = createSession({
handle,
cmd: "part.document",
schema: PART_SCHEMA,
module: PART_MODULE,
document,
extra: builder ? { builder } : {},
});
const part = new PartDocument(session, handle.directory);
// `close` here closes the pthread pool; closing the *document* is explicit.
part.dispose = () => handle.close();
return part;
}
/** Read a file from the host and stage it into the kernel FS. */
export function hostBytes(file) {
return fs.readFileSync(file);
}