Files
FreeCADWasmDev/web/teaching/cases/carrier-partdesign/lib/build.mjs
wangdequan 87b2a6cb8a feat(carrier): 航空母舰 PartDesign 有头创建工具包与初学者教学
- 新数据链 web/teaching/cases/carrier-partdesign:20 件零件(spec.json 唯一来源)、
  内核建造器 parts/*.mjs、traces/FCStd/replay 全量产物;装配 20 插入 + 19 关节。
- 工具包 tools/carrier:catalog / preflight / create-part / create-assembly /
  create-all / list / self-test / README,按零件与装配拆分为独立工具。
- 共享驱动扩展 web/tools/cad-ui-rebuild:Loft/Pipe/Hole/Fillet/Chamfer/Mirrored/
  LinearPattern 交互,Reversed 复选框补齐;装配 saveAssemblyBundle 先 Accept 再保存。
- 教学:lessons.mjs 新增 carrier 组(环境课 + 20 件 + 装配),suite-runner 增加
  carrier-part/carrier-assembly,生成 carrier-toolkit.html 并接入 index 与控制台证据。

验证:20 件 210 步全部有头通过(P05 修复后 39640 m³;P06 回归 8/8);
装配 20/20 插入、19/19 关节、20 组件 0 畸形、0 mismatch;check:carrier、
check:reducer、check-console --live 全绿。

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 18:46:27 +08:00

133 lines
6.0 KiB
JavaScript

// One recorded PartDesign build session for a carrier part.
//
// Every builder call goes through `part.timed()`, which is what makes the build
// replayable: the trace carries the exact kernel action, its arguments and the
// document listing after the call (tools/fcweb/kernel.mjs:188). The replay
// generator then derives one volume/mesh record per step from those listings.
//
// Object names are chosen by the builder (HullSketch1, HullLoft …) so the
// feature tree reads like a drawing, not like Sketch001. The UI renames on
// rebuild; web/tools/cad-ui-rebuild/drive.mjs maps the recorded names onto the
// names the workspace actually created.
import path from "node:path";
import fs from "node:fs";
import { fileURLToPath } from "node:url";
import { openPartDesign } from "../../../../../tools/fcweb/partdesign.mjs";
import { configureOpfs, readExportFile } from "../../../../../tools/fcweb/opfs.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
export const caseDir = path.resolve(here, "..");
export const outDir = path.join(caseDir, "out");
/** Point the shared OPFS mirror at this case's out/, per the OPFS contract. */
export function useCaseOpfs() {
return configureOpfs({ root: path.join(outDir, "opfs", "freecad-exports") });
}
export class Build {
constructor(part, { document, builder }) {
this.part = part;
this.document = document;
this.builder = builder ?? null;
this.counters = new Map();
this.steps = [];
}
/** Next name with an increasing suffix: `name("Sketch")` -> Sketch3. */
name(prefix) {
const next = (this.counters.get(prefix) ?? 0) + 1;
this.counters.set(prefix, next);
return `${prefix}${next}`;
}
record(object, label, action, args) {
const result = this.part.timed(`${this.document} · ${label}`, action, { object, body: "Body", ...args });
this.steps.push({ object, label, action, args });
return result;
}
/** Rectangle / Circle / Wire / Geometry sketch. `args` are setSketch fields. */
sketch(object, { profileType = "Rectangle", parameters, position, placementRotation, points, geometries, constraints }, label) {
this.stepsByName ??= new Map();
const args = { profileType };
if (parameters) args.parameters = parameters;
if (position) args.position = position;
if (placementRotation) args.placementRotation = placementRotation;
if (points) args.points = points;
if (geometries) args.geometries = geometries;
if (constraints) args.constraints = constraints;
return this.record(object, label ?? `草图 ${object}`, "setSketch", args);
}
/** Pad / Pocket / Revolution / Groove / Hole / Loft / Pipe (+ subtractive twins). */
feature(object, { featureType = "Pad", profile, length, angle, axis, depth, depthType, midplane, reversed, sections, ruled, closed, spine, pipeMode, transition }, label) {
const args = { featureType, profile };
for (const [key, value] of Object.entries({ length, angle, axis, depth, depthType, midplane, reversed, sections, ruled, closed, spine, pipeMode, transition })) {
if (value !== undefined) args[key] = value;
}
return this.record(object, label ?? `${featureType} ${object}`, "setFeature", args);
}
transform(object, { transformType, originals, direction, mirrorPlane, rotationAxis, length, angle, occurrences, reversed }, label) {
const args = { transformType, originals };
for (const [key, value] of Object.entries({ direction, mirrorPlane, rotationAxis, length, angle, occurrences, reversed })) {
if (value !== undefined) args[key] = value;
}
return this.record(object, label ?? `${transformType} ${object}`, "setTransform", args);
}
dressUp(object, { dressUpType, base, size, edges, useAllEdges, chamferType, size2, angle, flipDirection }, label) {
const args = { dressUpType, base };
for (const [key, value] of Object.entries({ size, edges, useAllEdges, chamferType, size2, angle, flipDirection })) {
if (value !== undefined) args[key] = value;
}
return this.record(object, label ?? `${dressUpType} ${object}`, "setDressUp", args);
}
primitive(object, { primitiveType, parameters, position }, label) {
return this.record(object, label ?? `${primitiveType} ${object}`, "setPrimitive", { primitiveType, parameters, position });
}
}
/**
* Build one document end to end and persist the three artefacts that the rest
* of the toolkit consumes: FCStd (OPFS mirror + evidence copy), trace JSON and,
* indirectly through the trace, the replay.
*/
export async function buildDocument(module, options = {}) {
const { document, builder, build } = module;
const part = await openPartDesign(document, { builder });
const session = new Build(part, { document, builder });
const started = Date.now();
try {
await build(session);
configureOpfs({ root: path.join(outDir, "opfs", "freecad-exports") });
const saved = part.saveDocument();
const bytes = readExportFile(saved.name);
const fcstdDir = path.join(outDir, "FCStd");
fs.mkdirSync(fcstdDir, { recursive: true });
fs.writeFileSync(path.join(fcstdDir, saved.name), bytes);
const traceDir = path.join(outDir, "traces");
fs.mkdirSync(traceDir, { recursive: true });
const trace = part.trace();
fs.writeFileSync(path.join(traceDir, `${document}.json`), `${JSON.stringify(trace, null, 2)}\n`);
const objects = part.snapshot().objects ?? [];
const body = objects.find(object => object.type === "PartDesign::Body");
// The kernel snapshot exposes volume/faceCount/edgeCount per object but no
// bounding box, so replay checks compare those three numbers (plus the step
// list) rather than a bbox.
const summary = {
document, builder, steps: session.steps.length,
volume: body?.volume ?? null,
faceCount: body?.faceCount ?? null,
edgeCount: body?.edgeCount ?? null,
seconds: Number(((Date.now() - started) / 1000).toFixed(2)),
fcstd: path.relative(caseDir, path.join(fcstdDir, saved.name)),
};
if (options.dry) console.log(JSON.stringify(summary));
return summary;
} finally {
part.dispose?.();
}
}