Ver código fonte

3D 实验室升级为可编辑工程台

- 新增 core/geometry/parts.js:结构件数据模型(创建/复制/环形阵列/贴内壁/五套工艺规则校验)
- lab.js 重写(204→约900行):三档吸附坞、结构件列表、14 类形体选择器、单件编辑态
- viewer3d.js 扩充(320→约550行):点选/拖动/高亮/相机聚焦/STL 导出/截图
- 导出:整件STL、分件STL、截图PNG、生产需求单md、BOM CSV、工程JSON
- 修复:3D 视口随坞高度收缩(--dock-h)、参数区底部可滚动
- 撤销/重做 40 步栈
liuyuyang 5 dias atrás
pai
commit
0396867894

+ 455 - 0
site/core/geometry/parts.js

@@ -0,0 +1,455 @@
+/**
+ * core/geometry/parts.js —— 实验室「结构件」数据模型(纯函数,零 DOM / 零 Babylon,Node 可测)。
+ *
+ * 一个结构件实例 = 类型 + 参数 + 落位。类型取自 solid.js 的 PRIMS(14 类形体);
+ * 坐标是「壳体局部坐标」:X 向右、Y 向上、Z 向前,壳体外底面中心为原点,单位 mm。
+ *
+ * 导出:
+ *   createPart(type, at)                 新建(按类型给默认参数,可带落位)
+ *   clonePart(part, offsetX = 8)         复制(新 uid,按 offsetX 平移)
+ *   arrayRing(part, count, radius)       环形阵列 → N 个新件
+ *   snapToInnerWall(part, shellDim, gap) 贴内壁 → 修正后的 at(+ 实际落位方向)
+ *   validate(parts, shellDim, proc)      五套工艺规则校验 → [{level, partUid, msg, paramKey}]
+ * 另附:paramSchema(type)(UI 自动生成数值面板)、dimText(part)、PROC_RULES、resolveProc。
+ */
+import { PRIMS, PRIM_KEYS, STD_PILOT } from './solid.js';
+
+const RAD = Math.PI / 180;
+const r3 = (v) => Math.round(v * 1000) / 1000;
+const r2 = (v) => Math.round(v * 100) / 100;
+const num = (v, d = 0) => (Number.isFinite(+v) ? +v : d);
+
+/** 14 类形体的中文名(UI 直接取) */
+export const PART_TYPES = PRIM_KEYS;
+export const PART_LABEL = Object.fromEntries(PRIM_KEYS.map((k) => [k, PRIMS[k].n]));
+export const PART_GROUP = Object.fromEntries(PRIM_KEYS.map((k) => [k, PRIMS[k].short]));
+
+/**
+ * 每种类型的「动画参数」:默认值(在 solid.js 形体默认值上就地命名)与 UI 数值面板 schema。
+ * key 与 solid.js 的类型开关一一对应(圆柱类 dia/dd,方件类 w/dd)。
+ * 螺柱类用 od/holeD 作别名(= solid.js 的 dia/dd),对外统一口径。
+ */
+const SCHEMA = {
+  box: [
+    { key: 'w', label: '宽', def: 8, min: 1, max: 60, step: 0.5 },
+    { key: 'dd', label: '深', def: 8, min: 1, max: 60, step: 0.5 },
+    { key: 'h', label: '高', def: 6, min: 0.5, max: 40, step: 0.5 },
+  ],
+  cyl: [
+    { key: 'dia', label: '直径', def: 10, min: 0.5, max: 60, step: 0.5 },
+    { key: 'h', label: '高', def: 8, min: 0.5, max: 40, step: 0.5 },
+  ],
+  rib: [
+    { key: 'w', label: '长', def: 14, min: 2, max: 80, step: 0.5 },
+    { key: 'dd', label: '厚', def: 1.2, min: 0.3, max: 6, step: 0.1 },
+    { key: 'h', label: '高', def: 5, min: 0.5, max: 40, step: 0.5 },
+    { key: 'draft', label: '拔模', def: 1, min: 0, max: 5, step: 0.1, unit: '°', draft: true },
+  ],
+  pocket: [
+    { key: 'w', label: '长', def: 10, min: 1, max: 80, step: 0.5 },
+    { key: 'dd', label: '宽', def: 10, min: 1, max: 80, step: 0.5 },
+    { key: 'h', label: '深', def: 2, min: 0.3, max: 20, step: 0.1 },
+  ],
+  hole: [
+    { key: 'dia', label: '孔径', def: 3, min: 0.5, max: 30, step: 0.1 },
+    { key: 'h', label: '深', def: 4, min: 0.3, max: 30, step: 0.5 },
+  ],
+  boss2: [
+    { key: 'od', label: '外径', def: 4.0, min: 1.5, max: 12, step: 0.1, alias: 'dia' },
+    { key: 'holeD', label: '预钻孔', def: 1.6, min: 0.5, max: 8, step: 0.1, alias: 'dd', pilot: 'boss2' },
+    { key: 'h', label: '高', def: 7, min: 1, max: 30, step: 0.5 },
+    { key: 'draft', label: '拔模', def: 1, min: 0, max: 5, step: 0.1, unit: '°', draft: true },
+  ],
+  boss25: [
+    { key: 'od', label: '外径', def: 4.8, min: 2, max: 12, step: 0.1, alias: 'dia' },
+    { key: 'holeD', label: '预钻孔', def: 2.1, min: 0.5, max: 8, step: 0.1, alias: 'dd', pilot: 'boss25' },
+    { key: 'h', label: '高', def: 8, min: 1, max: 30, step: 0.5 },
+    { key: 'draft', label: '拔模', def: 1, min: 0, max: 5, step: 0.1, unit: '°', draft: true },
+  ],
+  boss3: [
+    { key: 'od', label: '外径', def: 5.6, min: 2.5, max: 14, step: 0.1, alias: 'dia' },
+    { key: 'holeD', label: '预钻孔', def: 2.6, min: 0.5, max: 10, step: 0.1, alias: 'dd', pilot: 'boss3' },
+    { key: 'h', label: '高', def: 9, min: 1, max: 30, step: 0.5 },
+    { key: 'draft', label: '拔模', def: 1, min: 0, max: 5, step: 0.1, unit: '°', draft: true },
+  ],
+  thru25: [
+    { key: 'dia', label: '孔径', def: 2.7, min: 0.8, max: 10, step: 0.1 },
+    { key: 'h', label: '高', def: 4, min: 0.5, max: 20, step: 0.5 },
+  ],
+  pin3: [
+    { key: 'dia', label: '直径', def: 3, min: 0.5, max: 12, step: 0.1 },
+    { key: 'h', label: '高', def: 4, min: 0.5, max: 20, step: 0.5 },
+  ],
+  pad4: [
+    { key: 'w', label: '间距 X', def: 30, min: 4, max: 120, step: 0.5 },
+    { key: 'dd', label: '间距 Z', def: 30, min: 4, max: 120, step: 0.5 },
+    { key: 'dia', label: '柱外径', def: 4.8, min: 2, max: 12, step: 0.1 },
+    { key: 'hd', label: '预钻孔', def: 2.1, min: 0.5, max: 8, step: 0.1, pilot: 'boss25' },
+    { key: 'h', label: '高', def: 7, min: 1, max: 30, step: 0.5 },
+  ],
+  wall: [
+    { key: 'w', label: '长', def: 20, min: 2, max: 120, step: 0.5 },
+    { key: 'dd', label: '厚', def: 0.8, min: 0.3, max: 6, step: 0.1 },
+    { key: 'h', label: '高', def: 6, min: 0.5, max: 40, step: 0.5 },
+    { key: 'draft', label: '拔模', def: 1, min: 0, max: 5, step: 0.1, unit: '°', draft: true },
+  ],
+  tray: [
+    { key: 'w', label: '长', def: 22, min: 2, max: 120, step: 0.5 },
+    { key: 'dd', label: '宽', def: 18, min: 2, max: 120, step: 0.5 },
+    { key: 'h', label: '高', def: 6, min: 1, max: 30, step: 0.5 },
+  ],
+  clip: [
+    { key: 'w', label: '宽', def: 5, min: 1, max: 30, step: 0.1 },
+    { key: 'dd', label: '厚', def: 1.2, min: 0.3, max: 6, step: 0.1 },
+    { key: 'h', label: '高', def: 4, min: 0.5, max: 20, step: 0.5 },
+  ],
+};
+export const COVER_TYPES = new Set(PART_TYPES);
+
+/** UI 数值面板 schema(副本,调用方可安全改) */
+export function paramSchema(type) {
+  return (SCHEMA[type] || SCHEMA.box).map((f) => ({ ...f }));
+}
+
+/* =========================================================
+   1. 新建 / 复制 / 阵列 / 镜像
+   ========================================================= */
+let uidSeq = 0;
+export const newUid = () => `p${++uidSeq}`;
+
+/** 保证后续 newUid 不与已有 uid 撞号 */
+export function reserveUids(parts = []) {
+  for (const p of parts) {
+    const m = /^p(\d+)$/.exec(p?.uid || '');
+    if (m) uidSeq = Math.max(uidSeq, +m[1]);
+  }
+  return uidSeq;
+}
+
+const at3 = (at) => ({ x: r3(num(at?.x)), y: r3(num(at?.y)), z: r3(num(at?.z)) });
+
+/**
+ * 新建结构件。at 缺省时落在壳底中心(y 由 solid.js 的形体默认高向上抬半高,实际落底由 UI 调)。
+ * 第三个参数 patch 可覆盖 params / label / uid(测试与导入用)。
+ */
+export function createPart(type, at = { x: 0, y: 0, z: 0 }, patch = {}) {
+  const t = PRIMS[type] ? type : 'box';
+  const params = {};
+  for (const f of SCHEMA[t]) params[f.key] = f.def;
+  const part = {
+    uid: patch.uid || newUid(),
+    type: t,
+    label: patch.label || PRIMS[t].n,
+    params: { ...params, ...(patch.params || {}) },
+    at: at3(at),
+    rotY: r3(num(patch.rotY)),
+    mirror: !!patch.mirror,
+    visible: patch.visible !== false,
+  };
+  return part;
+}
+
+/** 复制:新 uid,沿 X 平移 offsetX(默认 8mm,即一个典型柱距);保留参数与朝向 */
+export function clonePart(part, offsetX = 8) {
+  const c = createPart(part.type, { x: num(part.at?.x) + num(offsetX), y: num(part.at?.y), z: num(part.at?.z) }, {
+    label: part.label,
+    params: { ...part.params },
+    rotY: part.rotY,
+    mirror: part.mirror,
+    visible: part.visible,
+  });
+  return c;
+}
+
+/**
+ * 环形阵列:绕壳体中轴(原点,Y 轴)均分 count 份。
+ * 结果包含原件的第 0 份位置(rotY 同步 + 角度),样式统一从 rotY = 起始角 开始。
+ * 每个新件的 rotY 在原件基础上加上扇区角度(朝外时设个件 rotY 为 0 即可)。
+ */
+export function arrayRing(part, count, radius) {
+  const n = Math.max(2, Math.min(24, Math.round(num(count, 4))));
+  const R = Math.max(0, num(radius, Math.hypot(num(part.at?.x), num(part.at?.z))));
+  const y = num(part.at?.y);
+  const out = [];
+  for (let i = 0; i < n; i++) {
+    const a = (i / n) * Math.PI * 2;
+    const at = { x: r3(R * Math.cos(a)), y, z: r3(-R * Math.sin(a)) };
+    out.push(createPart(part.type, at, {
+      label: part.label,
+      params: { ...part.params },
+      rotY: r3(num(part.rotY) + (i / n) * 360),
+      mirror: part.mirror,
+      visible: part.visible,
+    }));
+  }
+  // 参照前件:若原件的 rotY 明显等于弧角(阵列过一次),保持原样只追加序号标签
+  return out;
+}
+
+/** 镜像:跨 X=0 平面(X 取反,绕 Y 转 180°),新 uid */
+export function mirrorPart(part) {
+  return createPart(part.type, { x: -num(part.at?.x), y: num(part.at?.y), z: num(part.at?.z) }, {
+    label: part.label,
+    params: { ...part.params },
+    rotY: r3(num(part.rotY) + 180),
+    mirror: !part.mirror,
+    visible: part.visible,
+  });
+}
+
+/* =========================================================
+   2. 贴内壁
+   ========================================================= */
+/** 结构件在「落位平面」上的外接半径(圆柱取直径 / 方件取对角线 / pad4 取整组) */
+export function footprint(part) {
+  const p = part.params || {};
+  if (part.type === 'pad4') return Math.max(num(p.w), num(p.dd)) / 2;
+  if (p.dia !== undefined && p.od === undefined) return num(p.dia) / 2;
+  if (part.type === 'box' || part.type === 'pocket' || part.type === 'rib' || part.type === 'wall' || part.type === 'clip' || part.type === 'tray') {
+    return Math.hypot(num(p.w, 8), num(p.dd, 8)) / 2;
+  }
+  return num(p.od ?? p.dia, 4.8) / 2;
+}
+
+/** shellDim → 落位包络:{kind:'cyl', r} 或 {kind:'rect', w, d, cornerR?};也接受 number(=圆半径) */
+function envOf(shellDim) {
+  if (typeof shellDim === 'number') return { kind: 'cyl', r: shellDim };
+  if (!shellDim) return { kind: 'rect', w: 100, d: 60 };
+  if (shellDim.kind === 'cyl' || shellDim.r !== undefined) return { kind: 'cyl', r: num(shellDim.r, 20) };
+  if (shellDim.kind === 'rect' || shellDim.w !== undefined || shellDim.d !== undefined) {
+    return { kind: 'rect', w: num(shellDim.w, 90), d: num(shellDim.d, 60), cornerR: num(shellDim.cornerR) };
+  }
+  // 外形尺寸 {length, dTop} → 内腔(扣除壁厚)
+  if (shellDim.length !== undefined || shellDim.dTop !== undefined) {
+    const wall = num(shellDim.wall, 1.5);
+    return { kind: 'rect', w: Math.max(4, num(shellDim.length, 60) - 2 * wall), d: Math.max(4, num(shellDim.dTop, 40) - 2 * wall) };
+  }
+  return { kind: 'rect', w: 90, d: 60 };
+}
+
+/**
+ * 贴内壁:沿 XZ 把件推到离内壁 gap(默认 0.5mm)处。
+ * 方向:圆柱壳取「件当前所在径向」(原点处朝 +Z);方壳取「已在原点的那条轴」方向,
+ * 两轴都不在原点时贴余量更小的那条边,另一轴夹进可用范围。Y 不动。
+ * 返回 {x, y, z, dir:{x,z}, snapped:true}(新对象,不改原 part)。
+ */
+export function snapToInnerWall(part, shellDim, gap = 0.5) {
+  const env = envOf(shellDim);
+  const g = Math.max(0, num(gap, 0.5));
+  const fp = footprint(part);
+  const x0 = num(part.at?.x), z0 = num(part.at?.z), y = num(part.at?.y);
+  if (env.kind === 'cyl') {
+    const r = Math.hypot(x0, z0);
+    const lim = Math.max(0, env.r - fp - g);
+    const ux = r > 1e-6 ? x0 / r : 0, uz = r > 1e-6 ? z0 / r : 1;
+    return { x: r3(ux * lim), y, z: r3(uz * lim), dir: { x: r3(ux), z: r3(uz) }, snapped: true };
+  }
+  const lx = Math.max(0, env.w / 2 - fp - g), lz = Math.max(0, env.d / 2 - fp - g);
+  let x = x0, z = z0, dir;
+  const onX = Math.abs(x0) > 1e-6, onZ = Math.abs(z0) > 1e-6;
+  if (onX && onZ) {
+    const slackX = lx - Math.abs(x0), slackZ = lz - Math.abs(z0);
+    if (slackX <= slackZ) { x = Math.sign(x0) * lx; z = Math.max(-lz, Math.min(lz, z0)); dir = { x: Math.sign(x0), z: 0 }; }
+    else { z = Math.sign(z0) * lz; x = Math.max(-lx, Math.min(lx, x0)); dir = { x: 0, z: Math.sign(z0) }; }
+  } else if (onX) {
+    x = Math.sign(x0) * lx; dir = { x: Math.sign(x0), z: 0 };
+  } else if (onZ) {
+    z = Math.sign(z0) * lz; dir = { x: 0, z: Math.sign(z0) };
+  } else {
+    x = 0; z = lz; dir = { x: 0, z: 1 };
+  }
+  return { x: r3(x), y, z: r3(z), dir, snapped: true };
+}
+
+/** 件在落位包络里余量最小的那条边(mm,负 = 越界) */
+export function clearance(part, shellDim) {
+  const env = envOf(shellDim);
+  const fp = footprint(part);
+  const x = num(part.at?.x), z = num(part.at?.z);
+  if (env.kind === 'cyl') return r2(env.r - Math.hypot(x, z) - fp);
+  return r2(Math.min(env.w / 2 - Math.abs(x) - fp, env.d / 2 - Math.abs(z) - fp));
+}
+
+/* =========================================================
+   3. 五套工艺规则
+   ========================================================= */
+/**
+ * 阈值照 ref-v2 的 RULES(并按本任务书收紧 / 补齐):
+ * 注塑:壁厚 ≥1.0、筋厚 ≥0.6、拔模 ≥1°、柱壁 ≥0.8、深宽比 ≤5
+ * 硅胶:壁厚 ≥1.2、圆角 ≥0.5、无尖角
+ * CNC:壁厚 ≥1.5、内角 R ≥1.0
+ * 复模:壁厚 ≥1.0
+ * 压铸:壁厚 ≥1.2、拔模 ≥1.5°
+ */
+export const PROC_RULES = {
+  injection: { name: '注塑', minWall: 1.0, minRib: 0.6, minDraft: 1, minWallCol: 0.8, maxSlender: 5, minCorner: 0.5 },
+  silicone: { name: '硅胶', minWall: 1.2, minRib: 0.8, minDraft: 3, minWallCol: 0.8, maxSlender: 6, minCorner: 0.5, noSharp: true },
+  cnc: { name: 'CNC', minWall: 1.5, minRib: 0.8, minDraft: 0, minWallCol: 0.9, maxSlender: 6, minCorner: 1.0 },
+  vac: { name: '复模', minWall: 1.0, minRib: 0.6, minDraft: 1, minWallCol: 0.8, maxSlender: 5, minCorner: 0.5 },
+  die: { name: '压铸', minWall: 1.2, minRib: 0.9, minDraft: 1.5, minWallCol: 0.9, maxSlender: 5, minCorner: 0.6 },
+};
+export const PROC_KEYS = Object.keys(PROC_RULES);
+
+/** 工艺 id / 名称 → 规则键(兼容产品里的 inject / diecast / vacuum / vulcanize …) */
+export function resolveProc(proc) {
+  if (proc && PROC_RULES[proc]) return proc;
+  const s = String(proc || '').toLowerCase();
+  if (/sil|硅胶|vulc|bond|rubber/.test(s)) return 'silicone';
+  if (/die|压铸/.test(s)) return 'die';
+  if (/vac|复模|sla|真空/.test(s)) return 'vac';
+  if (/cnc|车|铣|阳极|钛|polish|sandblast|machin/.test(s)) return 'cnc';
+  return 'injection';
+}
+
+const CUT_TYPES = new Set(['pocket', 'hole', 'thru25']);
+const RIBBED = new Set(['rib', 'wall', 'box', 'clip']);
+const BOSSES = new Set(['boss2', 'boss25', 'boss3']);
+const SLENDER = new Set(['rib', 'wall', 'clip', 'pin3']);
+
+/** 参数键的中文提示(校验消息用) */
+function labelOfParam(type, key) {
+  const f = (SCHEMA[type] || []).find((x) => x.key === key);
+  return f ? f.label : key;
+}
+
+/**
+ * 工艺规则校验。
+ * @param {Array} parts 结构件
+ * @param {object|number} shellDim 落位包络 {w,d} / {r} / 外形 {length,dTop,wall};也兼容 {w,d,h}
+ * @param {string} proc 工艺键或工艺 id(resolveProc 归一)
+ * @returns {Array<{level:'error'|'warn', partUid, msg, paramKey}>}
+ */
+export function validate(parts, shellDim, proc = 'injection') {
+  const pk = resolveProc(proc);
+  const rule = PROC_RULES[pk];
+  const out = [];
+  const ids = new Set();
+  for (const part of parts || []) {
+    const t = part.type;
+    const p = part.params || {};
+    const nm = part.label || PART_LABEL[t] || t;
+    const push = (level, msg, paramKey, partUid = part.uid) => out.push({ level, partUid, msg, paramKey });
+
+    // ① 主体壁厚(外壳参数 slab)
+    if (shellDim && (shellDim.wall !== undefined || shellDim.t !== undefined)) {
+      const wall = num(shellDim.wall ?? shellDim.t, 1.5);
+      if (wall + 1e-6 < rule.minWall) push('error', `主壁厚 ${r2(wall)} mm < ${rule.name}下限 ${rule.minWall} mm`, 'wall', null);
+    }
+    // ② uid 唯一
+    if (ids.has(part.uid)) push('error', `${nm} uid ${part.uid} 重复`, 'uid');
+    ids.add(part.uid);
+
+    // ③ 尺寸基本量
+    const w = p.dia !== undefined && p.w === undefined ? num(p.dia) : num(p.w);
+    const d = p.dd !== undefined ? num(p.dd) : num(p.dia);
+    const h = num(p.h, 1);
+    const thin = Math.min(w || d, d || w);
+    if (!(h > 0)) push('error', `${nm} 高度必须 > 0`, 'h');
+
+    // ④ 筋 / 墙 / 方块厚度
+    if (RIBBED.has(t)) {
+      if (t !== 'box' && t !== 'clip' && d + 1e-6 < rule.minRib) push('error', `${nm} ${labelOfParam(t, 'dd')} ${r2(d)} mm < ${rule.name}筋厚下限 ${rule.minRib} mm`, 'dd');
+      if (t === 'clip' && d + 1e-6 < rule.minRib) push('warn', `${nm} 卡扣根厚 ${r2(d)} mm 偏薄(< ${rule.minRib}),易断`, 'dd');
+    }
+    // ⑤ 拔模
+    const needsDraft = t === 'rib' || t === 'wall' || BOSSES.has(t);
+    if (needsDraft && rule.minDraft > 0) {
+      const dr = num(p.draft);
+      if (dr + 1e-6 < rule.minDraft) push('error', `${nm} 拔模 ${r2(dr)}° < ${rule.name}下限 ${rule.minDraft}°`, 'draft');
+    }
+    // ⑥ 螺柱柱壁 / 预钻孔标准 / 自攻深度
+    if (BOSSES.has(t)) {
+      const od = num(p.od ?? p.dia, 4.8), hole = num(p.holeD ?? p.dd, 2.1);
+      const cw = (od - hole) / 2;
+      const minCw = Math.max(rule.minWallCol, (rule.minWall + 0.2) / 2);
+      const cwLv = pk === 'cnc' ? 'error' : 'warn';
+      if (cw + 1e-6 < minCw) push(cwLv, `${nm} 柱壁 ${r2(cw)} mm < ${rule.name}下限 ${r2(minCw)} mm(自攻会胀裂)`, 'od');
+      const std = STD_PILOT[t];
+      if (std && Math.abs(hole - std) > 0.15) push('warn', `${nm} 预钻孔 Ø${r2(hole)} 非${t.replace('boss', 'M')}标准 Ø${std}`, 'holeD');
+      const deep = h / Math.max(1e-6, hole);
+      if (deep > 2.5) push('warn', `${nm} 预钻深径比 ${r2(deep)}:1 > 2.5:1,自攻丝锥易断`, 'h');
+    }
+    if (t === 'pad4') {
+      const cw = (num(p.dia, 4.8) - num(p.hd, 2.1)) / 2;
+      if (cw + 1e-6 < rule.minWallCol) push('warn', `${nm} 四角柱壁 ${r2(cw)} mm < ${r2(rule.minWallCol)} mm`, 'dia');
+      if (num(p.w) <= num(p.dia) || num(p.dd) <= num(p.dia)) push('error', `${nm} 角柱间距必须大于柱外径`, 'w');
+    }
+    // ⑦ 深宽比(加强筋 / 分隔墙 / 凹槽 / 钻孔 / 卡扣)
+    const slenderBy = t === 'hole' || t === 'thru25' ? d : (t === 'pocket' ? Math.min(w, d) : d);
+    const sl = h / Math.max(0.1, slenderBy);
+    if (SLENDER.has(t) || CUT_TYPES.has(t)) {
+      if (sl > rule.maxSlender) push('warn', `${nm} 深宽比 ${r2(sl)}:1 > ${rule.maxSlender}:1`, 'h');
+      else if ((t === 'pocket' || t === 'hole') && sl > Math.max(2, rule.maxSlender - 2)) push('warn', `${nm} 深宽比 ${r2(sl)}:1 > ${Math.max(2, rule.maxSlender - 2)}:1,需分层铣 / 镶件`, 'h');
+    }
+    // ⑧ CNC 内角 R
+    if (pk === 'cnc' && t === 'pocket') push('warn', `${nm} 凹槽内角需 R ≥ ${rule.minCorner}(Ø2 刀具)`, 'w');
+    // ⑨ 硅胶:禁止尖角(0 圆角 / 薄于工艺角的最小件)
+    if (rule.noSharp && (CUT_TYPES.has(t) || thin < rule.minCorner * 2)) {
+      push('warn', `${nm} 尖角风险:薄边 ${r2(thin)} mm,硅胶需 R ≥ ${rule.minCorner} 圆角`, 'dd');
+    }
+    // ⑩ 几何:越界 / 压底 / 顶出壳
+    if (shellDim) {
+      const clr = clearance(part, shellDim);
+      if (clr < 0) push('error', `${nm} 超出内腔 ${r2(-clr)} mm`, 'x');
+      else if (clr < 1.0) push('warn', `${nm} 距内壁 ${r2(clr)} mm < 1 mm(脱模 / 装配余量不足)`, 'x');
+      const hh = shellDim.h ?? shellDim.height;
+      if (hh !== undefined) {
+        const y0 = num(part.at?.y), y1 = y0 + h;
+        if (y0 < -1e-6) push('error', `${nm} 底面低于壳底 ${r2(y0)} mm`, 'y');
+        else if (y1 > num(hh) + 1e-6) push('error', `${nm} 顶面 ${r2(y1)} mm 高过壳顶 ${r2(hh)} mm`, 'h');
+      }
+    }
+  }
+  return out;
+}
+
+/* =========================================================
+   4. 显示文本 / 快照
+   ========================================================= */
+const f1 = (v) => (Math.round(num(v) * 10) / 10).toFixed(1);
+const f2 = (v) => (Math.round(num(v) * 100) / 100).toFixed(2);
+
+/** 一行尺寸文本:圆柱类 Ø×H,方件类 长×深×H */
+export function dimText(part) {
+  const p = part.params || {};
+  const t = part.type;
+  if (RIBBED.has(t) || t === 'pocket' || t === 'tray') return `${f2(p.w)}×${f2(p.dd)}×H${f2(p.h)}`;
+  if (t === 'pad4') return `${f1(p.w)}×${f1(p.dd)} · Ø${f2(p.dia)}/Ø${f2(p.hd)}`;
+  if (BOSSES.has(t)) return `Ø${f2(p.od ?? p.dia)}/Ø${f2(p.holeD ?? p.dd)}×H${f2(p.h)}`;
+  return `Ø${f2(p.dia)}×H${f2(p.h)}`;
+}
+
+/** 一键应用产品 features(契约 §3:{id,type,params:{od,holeD,thickness,height…},at:{x,y}}) */
+export function fromFeatures(features = []) {
+  const map = {
+    'screw-pillar': 'boss25', boss: 'boss25', standoff: 'boss2', rib: 'rib', snap: 'clip',
+    pocket: 'pocket', hole: 'hole', 'through-hole': 'thru25', pin: 'pin3', wall: 'wall',
+    tray: 'tray', block: 'box', cylinder: 'cyl', 'corner-posts': 'pad4',
+  };
+  const out = [];
+  for (const f of features) {
+    const type = PRIMS[f.type] ? f.type : map[f.type];
+    if (!type) continue;
+    const src = f.params || {};
+    const pr = {};
+    if (src.od !== undefined) pr.od = src.od;
+    if (src.holeD !== undefined) pr.holeD = src.holeD;
+    if (src.dia !== undefined) pr.dia = src.dia;
+    if (src.height !== undefined) pr.h = src.height;
+    if (src.h !== undefined) pr.h = src.h;
+    if (src.thickness !== undefined) pr.dd = src.thickness;
+    if (src.w !== undefined) pr.w = src.w;
+    if (src.l !== undefined) pr.w = src.l;
+    if (src.dd !== undefined) pr.dd = src.dd;
+    if (src.width !== undefined) pr.w = src.w ?? src.width;
+    const phi = num(f.at?.phi, 90) * RAD;
+    const r = num(f.at?.r, 0);
+    const at = {
+      x: f.at?.x !== undefined ? num(f.at.x) : r3(r * Math.cos(phi)),
+      y: 0,
+      z: f.at?.y !== undefined ? num(f.at.y) : r3(-r * Math.sin(phi)),
+    };
+    out.push(createPart(type, at, { label: PART_LABEL[type], params: pr }));
+  }
+  return out;
+}

+ 728 - 35
site/page/lab.js

@@ -1,6 +1,9 @@
 /**
- * page/lab.js —— 实验室:单屏不滚。
- * 左(手机为上)Babylon 画布 + 底部可收起坞(形体参数 / BOM / 导出)。
+ * page/lab.js —— 实验室 · 可编辑工程台(单屏不滚)。
+ * 3D 视口占满屏幕,底部浮起三档伸缩坞(peek 20% / half 46% / full 72%):
+ *   形体参数 / 结构件 / BOM / 导出。
+ * 结构件:14 类形体库实例化 → 列表增删 → 单件编辑(高亮 + 相机聚焦 + 数值面板 + 吸附 + 阵列 / 贴壁)。
+ * 视口:点选 / 拖动落位(拖动锁相机,靠内壁 1.5mm 自动贴边)/ 双击复位;撤销重做 40 步。
  * Babylon 只在本页初始化;离开页面(自定义元素 disconnected)时 dispose 引擎与监听。
  */
 import { html } from 'lit';
@@ -11,6 +14,14 @@ import { KEY_LABEL, rangeFor, stepFor } from '../utils/format.js';
 import { linkHref, currentPath } from '../utils/router.js';
 import { labStyle } from './styles/lab-style.js';
 import { applyCss } from '../lib/css.js';
+import { lsGet, lsSet } from '../utils/storage.js';
+import {
+  PRIMS, PRIM_KEYS, cavity, primRequirement, primDimText, ruleKey, procOptions, derived,
+} from '../core/geometry/solid.js';
+import {
+  createPart, clonePart, arrayRing, mirrorPart, snapToInnerWall, validate, paramSchema, dimText,
+  PROC_RULES, PROC_KEYS, resolveProc, reserveUids, footprint, fromFeatures,
+} from '../core/geometry/parts.js';
 
 let babylonPromise = null;
 function ensureBabylon() {
@@ -28,6 +39,32 @@ function ensureBabylon() {
 }
 
 const HIDE_KEYS = new Set(['dBottom']); // 底部外径由壁厚/拔模推导,面板不单独暴露
+const DOCK = { peek: 0.2, half: 0.46, full: 0.72 };
+const SNAP_STEPS = [0.5, 1, 5];
+const UNDO_MAX = 40;
+const buzz = (ms = 8) => { try { navigator.vibrate?.(ms); } catch { /* 不支持则忽略 */ } };
+const fmt = (v, d = 1) => (Math.round((Number(v) || 0) * 10 ** d) / 10 ** d).toFixed(d);
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+
+/** 14 类形体的简图(24×24 viewBox 的 SVG 片段,只用当前文字色描边) */
+export function primIcon(type) {
+  const S = 'fill="none" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"';
+  switch (type) {
+    case 'box': return `<rect x="4" y="7" width="13" height="10" ${S}/><path d="M4 7l4-3h13v10l-4 3M17 7l4-3M17 17l4-3" ${S}/>`;
+    case 'cyl': return `<ellipse cx="12" cy="6" rx="6" ry="2.6" ${S}/><path d="M6 6v11c0 1.4 2.7 2.6 6 2.6s6-1.2 6-2.6V6" ${S}/>`;
+    case 'rib': return `<path d="M5 19V8h3v11M11 19V8h3v11M17 19V8h2" ${S}/>`;
+    case 'pocket': return `<rect x="3" y="4" width="18" height="16" rx="2" ${S}/><rect x="7" y="8" width="10" height="8" rx="1" ${S} stroke-dasharray="2 1.5"/>`;
+    case 'hole': return `<circle cx="12" cy="12" r="7" ${S} stroke-dasharray="2.5 1.8"/><circle cx="12" cy="12" r="3" ${S}/>`;
+    case 'boss2': case 'boss25': case 'boss3': return `<ellipse cx="12" cy="5" rx="5" ry="2" ${S}/><path d="M7 5v13c0 1.1 2.2 2 5 2s5-.9 5-2V5" ${S}/><ellipse cx="12" cy="5" rx="2" ry="1" ${S}/><path d="M10 9v11M14 9v11" ${S} stroke-dasharray="1.5 1.5"/>`;
+    case 'thru25': return `<rect x="3" y="3" width="18" height="18" rx="2" ${S}/><circle cx="12" cy="12" r="3.2" ${S}/><path d="M12 4v4M12 16v4M4 12h4M16 12h4" ${S}/>`;
+    case 'pin3': return `<path d="M12 2v3" ${S}/><ellipse cx="12" cy="7" rx="3" ry="1.4" ${S}/><path d="M9 7v11c0 .9 1.3 1.6 3 1.6s3-.7 3-1.6V7" ${S}/>`;
+    case 'pad4': return `<rect x="4" y="5" width="16" height="14" rx="2" ${S}/>${[[7, 8], [17, 8], [7, 16], [17, 16]].map(([x, y]) => `<circle cx="${x}" cy="${y}" r="1.9" ${S}/>`).join('')}`;
+    case 'wall': return `<rect x="3" y="5" width="18" height="14" rx="2" ${S}/><path d="M12 5v14M3 12h6M15 12h6" ${S}/>`;
+    case 'tray': return `<rect x="4" y="4" width="16" height="16" rx="2" ${S}/><rect x="7" y="7" width="10" height="10" rx="1" ${S}/><path d="M12 7v-3M9 4h6" ${S}/>`;
+    case 'clip': return `<path d="M6 20V8c0-2 .8-3 2-3s2 1 2 3v8" ${S}/><path d="M10 10h5V5" ${S}/>`;
+    default: return `<rect x="5" y="5" width="14" height="14" rx="3" ${S}/>`;
+  }
+}
 
 class PhLab extends PhPage {
   constructor() {
@@ -36,11 +73,17 @@ class PhLab extends PhPage {
     this.p = null;
     this.error = null;
     this.tab = 'shape';
-    this.dockOpen = true;
+    this.dock = 'half';
     this.params = {};
-    this.touched = {};
+    this.parts = [];
+    this.selUid = null;
+    this.picker = false;
+    this.snapStep = 1;
+    this.undoStack = [];
+    this.redoStack = [];
     this.viewer = null;
     this.status = '';
+    this.rk = 'injection';
     this.title = '实验室 · Pocket Hardware Lab · FmodeCode';
   }
 
@@ -58,14 +101,25 @@ class PhLab extends PhPage {
 
   async _load() {
     this.p = await loadProduct(this.id);
-    this.params = { ...(this.p.shape?.defaults || {}) };
+    const base = this.p.shape?.defaults || {};
+    const saved = lsGet('lab:' + this.p.id);
+    this.params = saved?.params ? { ...base, ...saved.params } : { ...base };
+    this.parts = (saved?.parts || []).filter((x) => x && PRIMS[x.type]);
+    this.rk = saved?.rk || this._defaultRk();
+    this.dock = saved?.dock || 'half';
+    reserveUids(this.parts);
     this.title = `${this.p.name} · 实验室 · Pocket Hardware Lab`;
+    this._bindKeys();
     this.requestUpdate();
     await this.updateComplete;
     if (!this.isConnected) return;
     await this._mount3d();
   }
 
+  _defaultRk() {
+    return resolveProc((this.p.processes || [])[0]?.id || 'injection');
+  }
+
   async _mount3d() {
     const canvas = this.querySelector('canvas');
     if (!canvas) return;
@@ -75,15 +129,131 @@ class PhLab extends PhPage {
       if (!this.isConnected) return;
       const { ShellViewer } = await import('../services/viewer3d.js');
       this.viewer = new ShellViewer(canvas, this.p);
+      this.viewer._snapStep = this.snapStep;
       this.viewer.setParams(this.params);
+      this.viewer.setParts(this.parts);
+      this._wireViewer();
       this.viewer._onChange = () => this.requestUpdate();
+      this.viewer.bgPointer = () => { if (this.selUid) this._select(null); };
       this._statsLoop();
+      this._setDockPx(this.dock, 0);
+      this._watchViewport();
     } catch (e) {
       console.warn(e);
       this.error = e;
     }
   }
 
+  _wireViewer() {
+    const v = this.viewer;
+    v.onSelect = (uid, mesh) => {
+      if (uid && uid !== this.selUid) {
+        this._select(uid);
+      } else if (uid === null && this.selUid) {
+        this.selUid = null;
+        this.requestUpdate();
+      }
+      void mesh;
+    };
+    v.onDragEnd = (uid, at) => {
+      const part = this.parts.find((x) => x.uid === uid);
+      if (!part) return;
+      this._pushUndo();
+      part.at = { ...part.at, x: at.x, z: at.z };
+      v.syncPart(part);
+      this._afterChange(0);
+      buzz(8);
+    };
+  }
+
+  /* ---------------- 状态:撤销 / 重做 / 持久化 ---------------- */
+  _snapshot() {
+    return JSON.stringify({ params: this.params, parts: this.parts, selUid: this.selUid });
+  }
+
+  _pushUndo() {
+    const snap = this._snapshot();
+    if (this.undoStack[this.undoStack.length - 1] === snap) return;
+    this.undoStack.push(snap);
+    if (this.undoStack.length > UNDO_MAX) this.undoStack.shift();
+    this.redoStack = [];
+    this._syncHistoryBtns();
+  }
+
+  _restore(snap) {
+    const s = JSON.parse(snap);
+    this.params = s.params;
+    this.parts = s.parts;
+    this.selUid = s.selUid && this.parts.some((p) => p.uid === s.selUid) ? s.selUid : null;
+    this.viewer?.setParams(this.params);
+    this.viewer?.setParts(this.parts);
+    if (this.selUid) this._enterEdit(this.selUid, false);
+    this.requestUpdate();
+  }
+
+  undo() {
+    const snap = this.undoStack.pop();
+    if (!snap) return;
+    this.redoStack.push(this._snapshot());
+    this._restore(snap);
+    this._syncHistoryBtns();
+    buzz(8);
+  }
+
+  redo() {
+    const snap = this.redoStack.pop();
+    if (!snap) return;
+    this.undoStack.push(this._snapshot());
+    this._restore(snap);
+    this._syncHistoryBtns();
+    buzz(8);
+  }
+
+  _syncHistoryBtns() {
+    const u = this.querySelector('.hist .undo'), r = this.querySelector('.hist .redo');
+    if (u) u.disabled = !this.undoStack.length;
+    if (r) r.disabled = !this.redoStack.length;
+  }
+
+  _saveSoon() {
+    clearTimeout(this._saveT);
+    this._saveT = setTimeout(() => {
+      lsSet('lab:' + this.p.id, { params: this.params, parts: this.parts, rk: this.rk, dock: this.dock, v: 3 });
+    }, 260);
+  }
+
+  _bindKeys() {
+    if (this._keysBound) return;
+    this._keysBound = true;
+    this._onKey = (e) => {
+      if (!this.isConnected) return;
+      const tag = (e.target?.tagName || '').toLowerCase();
+      const typing = tag === 'input' || tag === 'textarea';
+      if ((e.ctrlKey || e.metaKey) && (e.key === 'z' || e.key === 'Z')) {
+        if (typing) return;
+        e.preventDefault();
+        if (e.shiftKey) this.redo(); else this.undo();
+      } else if ((e.ctrlKey || e.metaKey) && (e.key === 'y' || e.key === 'Y')) {
+        e.preventDefault();
+        this.redo();
+      } else if (e.key === 'Escape' && this.selUid && !this.picker) {
+        this._select(null);
+      }
+    };
+    addEventListener('keydown', this._onKey);
+  }
+
+  disconnectedCallback() {
+    super.disconnectedCallback();
+    if (this._statRaf) cancelAnimationFrame(this._statRaf);
+    if (this._keysBound) removeEventListener('keydown', this._onKey);
+    this._keysBound = false;
+    this._unwatchViewport?.();
+    clearTimeout(this._saveT);
+    this.viewer?.dispose();
+    this.viewer = null;
+  }
+
   _statsLoop() {
     const tick = () => {
       if (!this.isConnected || !this.viewer) return;
@@ -91,86 +261,483 @@ class PhLab extends PhPage {
       if (s) {
         this.stats = s;
         const el = this.querySelector('.live');
-        if (el) el.textContent = `${s.positions} 顶点 · ${s.indices} 三角面`;
+        if (el) el.textContent = `${s.positions + (s.partVertices || 0)} 顶点 · ${s.parts} 结构件`;
       }
       this._statRaf = requestAnimationFrame(tick);
     };
     this._statRaf = requestAnimationFrame(tick);
   }
 
-  disconnectedCallback() {
-    super.disconnectedCallback();
-    if (this._statRaf) cancelAnimationFrame(this._statRaf);
-    this.viewer?.dispose();
-    this.viewer = null;
-  }
-
-  _set(key, value) {
+  /* ---------------- 形体参数 ---------------- */
+  _set(key, value, push = true) {
     const v = Number(value);
     if (!Number.isFinite(v)) return;
+    if (push && v !== this.params[key]) this._pushUndo();
     this.params = { ...this.params, [key]: v };
     this.viewer?.setParams({ [key]: v });
     this.requestUpdate();
+    this._saveSoon();
   }
 
   _resetAll() {
+    this._pushUndo();
     this.params = { ...(this.p.shape?.defaults || {}) };
     this.viewer?.setParams(this.params);
     this.requestUpdate();
+    this._saveSoon();
+  }
+
+  /* ---------------- 结构件:选中 / 编辑 ---------------- */
+  get sel() { return this.parts.find((p) => p.uid === this.selUid) || null; }
+
+  get checks() { return validate(this.parts, this._shellDim(), this.rk); }
+
+  /** 落位包络:内腔 XZ + 壳高(工艺校验与贴壁共用) */
+  _shellDim() {
+    const c = cavity(this.p.shape?.type, this.params);
+    const h = Number(this.params.height) || 8;
+    if (c.kind === 'cyl') return { kind: 'cyl', r: c.r, h, wall: Number(this.params.wall) };
+    return { kind: 'rect', w: c.halfX * 2, d: c.halfZ * 2, h, wall: Number(this.params.wall) };
+  }
+
+  /** 新建件的落位:内腔底部、离壁 6mm 处,按已有件数错开 */
+  _spawnAt() {
+    const sd = this._shellDim();
+    const n = this.parts.length;
+    if (sd.kind === 'cyl') {
+      const r = Math.max(0, sd.r * 0.55);
+      const a = n * 0.7;
+      return { x: Math.round(r * Math.cos(a) * 2) / 2, y: 0, z: Math.round(-r * Math.sin(a) * 2) / 2 };
+    }
+    return { x: 0, y: 0, z: Math.max(0, Math.round((sd.d / 2 - 8) * 2) / 2) };
+  }
+
+  /** 选中 / 取消选中;列表里点的是「进入编辑」,回到列表走 exitEdit() */
+  _select(uid) {
+    if (uid === this.selUid) return;
+    this.selUid = uid;
+    if (uid) this._enterEdit(uid, true);
+    else { this.viewer?.applySelection(null); this.viewer?.homeView(false); }
+    this.requestUpdate();
+  }
+
+  /** 单件编辑 → 结构件列表(退出选中态、恢复全局视图) */
+  exitEdit() {
+    this._select(null);
+    if (this.tab === 'parts') this.requestUpdate();
+  }
+
+  _enterEdit(uid, focus = true) {
+    const part = this.parts.find((p) => p.uid === uid);
+    if (!part) return;
+    this.viewer?.applySelection(uid);
+    if (focus) this.viewer?.focusPart(part);
+  }
+
+  _addPart(type) {
+    if (!PRIMS[type]) return;
+    this._pushUndo();
+    const part = createPart(type, this._spawnAt());
+    this.parts = [...this.parts, part];
+    this.picker = false;
+    this.tab = 'parts';
+    this.dock = this.dock === 'peek' ? 'half' : this.dock;
+    this.viewer?.setParts(this.parts);
+    this._setDockPx(this.dock, 0);
+    this.selUid = part.uid;
+    this._enterEdit(part.uid);
+    this.requestUpdate();
+    buzz(8);
+  }
+
+  _applyFeatures() {
+    const feats = this.p.features || [];
+    if (!feats.length) return;
+    this._pushUndo();
+    const fresh = fromFeatures(feats);
+    reserveUids(fresh);
+    this.parts = [...this.parts, ...fresh];
+    for (const part of this.parts) {
+      if (['boss2', 'boss25', 'boss3', 'rib', 'wall', 'clip'].includes(part.type)) {
+        if (Math.abs(Number(part.at?.y) || 0) < 1e-6) part.at = { ...part.at, y: 0 };
+      }
+    }
+    this.viewer?.setParts(this.parts);
+    this.requestUpdate();
+    this._saveSoon();
+    this.status = `已应用 ${fresh.length} 个推荐结构件`;
+  }
+
+  _updatePart(uid, fn) {
+    const i = this.parts.findIndex((p) => p.uid === uid);
+    if (i < 0) return;
+    const next = fn({ ...this.parts[i], params: { ...this.parts[i].params }, at: { ...this.parts[i].at } });
+    if (!next) return;
+    this.parts = this.parts.map((p, k) => (k === i ? next : p));
+    this.viewer?.updatePart(next);
+    this.requestUpdate();
+    this._saveSoon();
+  }
+
+  _setPartParam(uid, key, value, push = true) {
+    const v = Number(value);
+    if (!Number.isFinite(v)) return;
+    const cur = this.parts.find((p) => p.uid === uid);
+    if (!cur || cur.params[key] === v) return;
+    if (push) this._pushUndo();
+    this._updatePart(uid, (p) => { p.params[key] = v; return p; });
+  }
+
+  _setPartAt(uid, axis, value, push = true) {
+    const v = Number(value);
+    if (!Number.isFinite(v)) return;
+    const cur = this.parts.find((p) => p.uid === uid);
+    if (!cur || cur.at[axis] === v) return;
+    if (push) this._pushUndo();
+    this._updatePart(uid, (p) => { p.at[axis] = v; return p; });
+  }
+
+  _setRot(uid, deg) {
+    const v = Number(deg);
+    if (!Number.isFinite(v)) return;
+    this._pushUndo();
+    this._updatePart(uid, (p) => { p.rotY = Math.round(v * 10) / 10; return p; });
+  }
+
+  _toggleVisible(uid) {
+    this._pushUndo();
+    this._updatePart(uid, (p) => { p.visible = !p.visible; return p; });
+    buzz(8);
+  }
+
+  _deletePart(uid) {
+    this._pushUndo();
+    this.parts = this.parts.filter((p) => p.uid !== uid);
+    if (this.selUid === uid) { this.selUid = null; this.viewer?.applySelection(null); this.viewer?.homeView(false); }
+    this.viewer?.setParts(this.parts);
+    this.requestUpdate();
+    this._saveSoon();
+    buzz(8);
+  }
+
+  _clone(uid) {
+    const part = this.parts.find((p) => p.uid === uid);
+    if (!part) return;
+    const fp = footprint(part) * 2 + 2;
+    this._pushUndo();
+    const c = clonePart(part, fp);
+    this.parts = [...this.parts, c];
+    this.viewer?.setParts(this.parts);
+    this.selUid = c.uid;
+    this._enterEdit(c.uid, false);
+    this.requestUpdate();
+    buzz(8);
+  }
+
+  _mirror(uid) {
+    const part = this.parts.find((p) => p.uid === uid);
+    if (!part) return;
+    this._pushUndo();
+    const c = mirrorPart(part);
+    this.parts = [...this.parts, c];
+    this.viewer?.setParts(this.parts);
+    this.requestUpdate();
+    buzz(8);
+  }
+
+  _ring(uid, n) {
+    const part = this.parts.find((p) => p.uid === uid);
+    if (!part) return;
+    this._pushUndo();
+    const r = Math.hypot(Number(part.at?.x) || 0, Number(part.at?.z) || 0) || Math.max(8, this._shellDim().r ? this._shellDim().r * 0.55 : 20);
+    const ring = arrayRing(part, n, r);
+    this.parts = [...this.parts, ...ring.slice(1)];
+    this.viewer?.setParts(this.parts);
+    this.requestUpdate();
+    this._saveSoon();
+    buzz(8);
+  }
+
+  _tool(uid, kind) {
+    const part = this.parts.find((p) => p.uid === uid);
+    if (!part) return;
+    const sd = this._shellDim();
+    const h = Number(part.params.h) || 1;
+    if (kind === 'center') {
+      this._pushUndo();
+      this._updatePart(uid, (p) => { p.at.x = 0; p.at.z = 0; return p; });
+    } else if (kind === 'wall') {
+      this._pushUndo();
+      const at = snapToInnerWall(part, sd, 0.5);
+      this._updatePart(uid, (p) => { p.at = { x: at.x, y: p.at.y, z: at.z }; return p; });
+    } else if (kind === 'top') {
+      this._pushUndo();
+      this._updatePart(uid, (p) => { p.at.y = Math.round((sd.h - h) * 10) / 10; return p; });
+    } else if (kind === 'bottom') {
+      this._pushUndo();
+      this._updatePart(uid, (p) => { p.at.y = 0; return p; });
+    }
+  }
+
+  _snapStepChange(v) {
+    this.snapStep = Number(v);
+    if (this.viewer) this.viewer._snapStep = this.snapStep;
+    this.requestUpdate();
   }
 
-  _export() {
-    const payload = { id: this.p.id, name: this.p.name, shapeType: this.p.shape?.type, exportedAt: new Date().toISOString(), params: this.params };
-    const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' });
+  _afterChange() { this.requestUpdate(); }
+
+  /* ---------------- 坞:三档吸附 ---------------- */
+  _setDockPx(name, animateMs = 300) {
+    this.dock = name;
+    const el = this.querySelector('.dock');
+    if (!el) return;
+    const h = Math.round(innerHeight * DOCK[name]);
+    el.style.transitionDuration = `${animateMs}ms`;
+    const px = name === 'peek' ? Math.max(56, h) : h;
+    el.style.height = `${px}px`;
+    // 3D 视口随坞收缩:gl-stage 的 bottom 用这个变量,避免模型被坞压住
+    this.style.setProperty('--dock-h', `${px}px`);
+    if (name === 'peek') el.classList.add('min');
+    else el.classList.remove('min');
+    this._saveSoon();
+  }
+
+  _nearestDock(px) {
+    let best = 'half', bd = Infinity;
+    for (const [k, r] of Object.entries(DOCK)) {
+      const d = Math.abs(px - innerHeight * r);
+      if (d < bd) { bd = d; best = k; }
+    }
+    return best;
+  }
+
+  _bindHead() {
+    const head = this.querySelector('.dock-head');
+    if (!head || head._bound) return;
+    head._bound = true;
+    let dragging = false, startY = 0, h0 = 0, moved = false;
+    head.addEventListener('pointerdown', (e) => {
+      if (e.target.closest('button, input')) return;
+      dragging = true; moved = false;
+      startY = e.clientY;
+      const el = this.querySelector('.dock');
+      h0 = el.getBoundingClientRect().height;
+      el.style.transitionDuration = '0ms';
+      head.setPointerCapture?.(e.pointerId);
+    });
+    head.addEventListener('pointermove', (e) => {
+      if (!dragging) return;
+      const dy = startY - e.clientY;
+      if (Math.abs(dy) > 4) moved = true;
+      const h = Math.max(56, Math.min(innerHeight * 0.86, h0 + dy));
+      this.querySelector('.dock').style.height = `${h}px`;
+      this.style.setProperty('--dock-h', `${Math.round(h)}px`);
+    });
+    const end = () => {
+      if (!dragging) return;
+      dragging = false;
+      const el = this.querySelector('.dock');
+      const h = el.getBoundingClientRect().height;
+      if (!moved) {
+        this._setDockPx(this.dock === 'peek' ? 'half' : 'peek', 300);
+        return;
+      }
+      this._setDockPx(this._nearestDock(h), 300);
+    };
+    head.addEventListener('pointerup', end);
+    head.addEventListener('pointercancel', end);
+  }
+
+  /** 键盘弹出:visualViewport 变矮时把坞顶到键盘上方,并为坞加内边距 */
+  _watchViewport() {
+    const vv = window.visualViewport;
+    if (!vv) return;
+    const onVv = () => {
+      const kb = Math.max(0, innerHeight - vv.height - vv.offsetTop);
+      this.style.setProperty('--kb', `${Math.round(kb)}px`);
+      this.style.setProperty('--dock-max', `${Math.round(vv.height)}px`);
+    };
+    vv.addEventListener('resize', onVv);
+    vv.addEventListener('scroll', onVv);
+    onVv();
+    this._unwatchViewport = () => { vv.removeEventListener('resize', onVv); vv.removeEventListener('scroll', onVv); };
+  }
+
+  /* ---------------- 导出 ---------------- */
+  _download(name, data, type) {
+    const blob = data instanceof Blob ? data : new Blob([data], { type });
+    const url = URL.createObjectURL(blob);
     const a = document.createElement('a');
-    a.href = URL.createObjectURL(blob);
-    a.download = `${this.p.id}-shape.json`;
+    a.href = url;
+    a.download = name;
     document.body.appendChild(a);
     a.click();
     a.remove();
-    setTimeout(() => URL.revokeObjectURL(a.href), 1000);
+    setTimeout(() => URL.revokeObjectURL(url), 1500);
+    this.status = '已导出 ' + name;
+    this.requestUpdate();
+    return url;
+  }
+
+  _exportJson() {
+    const payload = {
+      app: 'Pocket Hardware Lab', version: 'v3', generator: 'FmodeCode', exportedAt: new Date().toISOString(), unit: 'mm',
+      id: this.p.id, name: this.p.name, shapeType: this.p.shape?.type, process: this.rk,
+      params: this.params, parts: this.parts, cav: this._shellDim(),
+    };
+    this._download(`${this.p.id}-engineering.json`, JSON.stringify(payload, null, 2), 'application/json');
+  }
+
+  _exportStl(onlyUid = null) {
+    if (!this.viewer) return;
+    const { buffer, triangles } = this.viewer.exportSTL(onlyUid);
+    if (!triangles) { this.status = '没有可导出的网格'; this.requestUpdate(); return; }
+    const name = onlyUid ? `${this.p.id}-${onlyUid}.stl` : `${this.p.id}-assembly.stl`;
+    this._download(name, buffer, 'model/stl');
+    this.status = `已导出 ${name}(${triangles} 三角面)`;
+    this.requestUpdate();
+  }
+
+  _exportAllStl() {
+    for (const part of this.parts) {
+      if (!part.visible) continue;
+      const { buffer, triangles } = this.viewer.exportSTL(part.uid);
+      if (triangles) this._download(`${this.p.id}-${part.uid}.stl`, buffer, 'model/stl');
+    }
+  }
+
+  _exportBomCsv() {
+    const rows = [['序号', '分组', '名称', '规格', '供应商', '单价', '数量', '小计']];
+    for (const r of this.p.bom?.rows || []) rows.push([r.seq, r.group || '', r.name, r.spec || '', r.supplier || '', r.price, r.qty, r.subtotal]);
+    rows.push(['', '', '合计', '', '', '', '', this.p.bom?.bomTotal ?? '']);
+    const csv = '' + rows.map((r) => r.map((v) => `"${String(v ?? '').replace(/"/g, '""')}"`).join(',')).join('\n');
+    this._download(`${this.p.id}-bom.csv`, csv, 'text/csv;charset=utf-8');
+  }
+
+  async _exportPng() {
+    if (!this.viewer) return;
+    const data = await this.viewer.screenshot(2);
+    if (!data) { this.status = '截图失败(当前渲染后端不支持)'; this.requestUpdate(); return; }
+    const a = document.createElement('a');
+    a.href = data;
+    a.download = `${this.p.id}-${this.selUid || 'view'}.png`;
+    document.body.appendChild(a); a.click(); a.remove();
     this.status = '已导出 ' + a.download;
     this.requestUpdate();
   }
 
+  /** 生产需求单(Markdown):参数快照 + 公差 + 装配 + 结构件坐标 + CNC 弧面 + 报价回填 */
+  specMarkdown() {
+    const p = this.p, params = this.params, rk = this.rk, rule = PROC_RULES[rk];
+    const L = [];
+    const date = new Date().toISOString().slice(0, 10);
+    L.push(`# 生产需求单 · ${p.name}`, '');
+    L.push(`- 型号:${p.latin || p.name}(${p.id})`);
+    L.push(`- 日期:${date};单位 mm / °;工艺:${rule.name}`);
+    L.push('- 本单由 Pocket Hardware Lab 实验室按当前 3D 参数快照自动生成(FmodeCode)', '');
+    L.push('## 1. 参数快照', '', '| 参数 | 键 | 数值 |', '| --- | --- | --- |');
+    for (const [k, v] of Object.entries(params)) if (typeof v === 'number') L.push(`| ${KEY_LABEL[k] || k} | ${k} | ${fmt(v, 2)} |`);
+    L.push('', '派生尺寸:', ...derived(p.shape?.type, params, {}).map(([k, v]) => `- ${k}:${v}`), '');
+    const arcs = ['domeR', 'recessR', 'recessDepth', 'chamferC', 'platform'].filter((k) => params[k] !== undefined);
+    L.push('**CNC 弧面编程参数**:' + arcs.map((k) => `${KEY_LABEL[k] || k} ${fmt(params[k], 2)}`).join(';') + '。');
+    L.push('> 弧面用 R≥1 球头 / 圆鼻刀连续走刀,过渡区禁止接刀台阶;关键尺寸 ±0.05 出首件报告。', '');
+    L.push('## 2. 公差与验收', '', '| 部位 | 公差 |', '| --- | --- |');
+    for (const pt of p.parts || []) if (pt.tolerance) L.push(`| ${pt.name} | ${pt.tolerance} |`);
+    L.push('| 整机外形 | ±0.10 |', '| 孔位 / 柱位 | ±0.05 |', '| 首件 | 三坐标 / 影像仪报告 + 实配照片 |', '| 抽检 | AQL 1.0 外观 / 0.65 关键尺寸 |', '');
+    L.push('## 3. 装配顺序', '');
+    (p.processes || []).forEach((pr, i) => L.push(`${i + 1}. **${pr.name}**:${pr.desc || pr.equipment || '—'}${pr.bulkDays ? `(批量 ${pr.bulkDays})` : ''}`));
+    L.push('', '## 4. 结构件坐标表(壳底中心为原点;X 右 / Y 上 / Z 前)', '');
+    if (!this.parts.length) L.push('- 暂无自定义结构件(按主体参数推定)。');
+    else {
+      L.push('| uid | 类型 | X | Y | Z | 绕 Y | 尺寸 | 工艺要求 |', '| --- | --- | --- | --- | --- | --- | --- | --- |');
+      for (const s of this.parts) {
+        L.push(`| ${s.uid} | ${esc(s.label || PRIMS[s.type]?.n)} | ${fmt(s.at?.x, 2)} | ${fmt(s.at?.y, 2)} | ${fmt(s.at?.z, 2)} | ${fmt(s.rotY, 1)}° | ${primDimText({ ...s.params, type: s.type })} | ${primRequirement({ ...s.params, type: s.type, rot: s.rotY, x: s.at?.x, y: s.at?.y, z: s.at?.z }, rk)} |`);
+      }
+    }
+    L.push('', `## 5. 工艺校验(${rule.name})`, '');
+    const checks = this.checks;
+    if (!checks.length) L.push('- 全部通过。');
+    for (const c of checks) L.push(`- [${c.level === 'error' ? ' ' : 'x'}] ${c.level === 'error' ? '待改' : '提醒'}:${c.msg}`);
+    L.push('', '## 6. 供应商报价回填表', '', '| 项目 | 供应商填写 |', '| --- | --- |');
+    for (const x of ['模具费(含试模 / 改模)', '单品单价(含税 / 不含税)', '最小起订量 MOQ', '打样费及抵扣规则', '交期(打样 / 大货)', '模具归属', '包装方式与费用', '有效期']) L.push(`| ${x} |  |`);
+    L.push('', '---', '生产需求单由 Pocket Hardware Lab · FmodeCode 生成;价格口径见产品页,不构成报价承诺。');
+    return L.join('\n');
+  }
+
+  _exportSpec() {
+    this._download(`${this.p.id}-生产需求单.md`, this.specMarkdown(), 'text/markdown;charset=utf-8');
+  }
 
+  /* ---------------- 渲染 ---------------- */
   render() {
     if (this.error) return html`<ph-error .error=${this.error}></ph-error>`;
     if (!this.p) return html`<div style="padding:96px;text-align:center;color:var(--ink-3)">载入产品…</div>`;
     const p = this.p;
     const keys = Object.keys(p.shape?.defaults || {}).filter((k) => !HIDE_KEYS.has(k));
+    const errs = this.checks.filter((c) => c.level === 'error').length;
+    const warns = this.checks.length - errs;
     return html`
       <div class="lab">
         <div class="bar">
           <span><a data-link href=${linkHref(`/p/${p.id}`)}>← 详情</a></span>
           <span class="t">${p.name} · 实验室</span>
           <span class="live"></span>
+          <button class="reset" @click=${() => this.viewer?.reset()}>复位</button>
         </div>
-        <div class="stage">
-          <canvas aria-label="3D 外壳预览:单指旋转,双指缩放,双击复位"></canvas>
-          <button class="reset" @click=${() => this.viewer?.reset()}>复位视角</button>
-          <div class="hint">单指旋转 · 双指缩放 · 双击复位</div>
+        <div class="stage" style=${`bottom:${this.dock === 'peek' ? 56 : `calc(${DOCK[this.dock] * 100}dvh)`}`}>
+          <canvas aria-label="3D 外壳与结构件:单指旋转,双指缩放,双击复位,点选结构件可拖动"></canvas>
+          <div class="hint">点选结构件拖动 · 单指旋转 · 双指缩放 · 双击复位</div>
+          ${this.sel ? html`<div class="sel-tip">编辑:${this.sel.label} · ${esc(dimText(this.sel))}</div>` : ''}
         </div>
-        <section class="dock ${this.dockOpen ? '' : 'closed'}">
+        <section class="dock ${this.dock}" data-dock=${this.dock}>
+          <div class="dock-head" title="拖动调高度 · 点击档位切换">
+            <div class="grab" aria-hidden="true"></div>
+            <div class="head-row">
+              <button class="tab" @click=${() => this._setDockPx(this.dock === 'peek' ? 'half' : 'peek', 300)} aria-label="切换面板高度">${this.tab === 'shape' ? '形体参数' : this.tab === 'parts' ? '结构件' : this.tab === 'bom' ? 'BOM' : '导出'}</button>
+              <span class="count">${this.parts.length ? `${this.parts.length} 件` : ''}</span>
+              ${errs ? html`<span class="badge err">${errs} 错误</span>` : ''}
+              ${warns ? html`<span class="badge warn">${warns} 提醒</span>` : ''}
+              <span class="grow"></span>
+              <span class="hist">
+                <button class="undo" title="撤销 ⌘Z" ?disabled=${!this.undoStack.length} @click=${() => this.undo()}>↺</button>
+                <button class="redo" title="重做 ⇧⌘Z" ?disabled=${!this.redoStack.length} @click=${() => this.redo()}>↻</button>
+              </span>
+              <button class="fold" aria-label=${this.dock === 'peek' ? '展开面板' : '收起面板'} @click=${() => this._setDockPx(this.dock === 'peek' ? 'half' : 'peek', 300)}>${this.dock === 'peek' ? '⌃' : '⌄'}</button>
+            </div>
+          </div>
           <div class="tabs">
-            ${[['shape', '形体参数'], ['bom', 'BOM'], ['export', '导出']].map(([k, label]) => html`
-              <button class=${this.tab === k ? 'on' : ''} @click=${() => { this.tab = k; this.dockOpen = true; this.requestUpdate(); }}>${label}</button>`)}
-            <span class="grow"></span>
-            <button class="fold" aria-label=${this.dockOpen ? '收起面板' : '展开面板'} @click=${() => { this.dockOpen = !this.dockOpen; this.requestUpdate(); }}>${this.dockOpen ? '⌄' : '⌃'}</button>
+            ${[['shape', '形体'], ['parts', '结构件'], ['bom', 'BOM'], ['export', '导出']].map(([k, label]) => html`
+              <button class=${this.tab === k ? 'on' : ''} @click=${() => { this.tab = k; if (this.dock === 'peek') this._setDockPx('half', 300); this.requestUpdate(); }}>${label}</button>`)}
           </div>
           <div class="body">
             ${this.tab === 'shape' ? this._shapeTab(keys) : ''}
+            ${this.tab === 'parts' ? (this.sel ? this._editTab() : this._partsTab()) : ''}
             ${this.tab === 'bom' ? html`<ph-bom .bom=${p.bom}></ph-bom>` : ''}
             ${this.tab === 'export' ? this._exportTab() : ''}
           </div>
+          ${this.picker ? this._pickerOverlay() : ''}
         </section>
       </div>`;
   }
 
+  updated() {
+    this._bindHead();
+    this._syncHistoryBtns();
+  }
+
   _shapeTab(keys) {
+    const opts = procOptions(this.p);
     return html`
+      <div class="proc-row">
+        <span>工艺规则</span>
+        <select @change=${(e) => { this.rk = resolveProc(e.target.value); this.requestUpdate(); this._saveSoon(); }} aria-label="工艺规则">
+          ${PROC_KEYS.map((k) => html`<option value=${k} ?selected=${this.rk === k}>${PROC_RULES[k].name}</option>`)}
+        </select>
+        <small>${opts.length} 种产品工艺可选</small>
+      </div>
       ${this.viewer?.profile?.warnings?.length ? html`<p class="warn">${this.viewer.profile.warnings.join(';')}</p>` : ''}
-      <p style="margin:0 0 14px;font-size:12px;color:var(--ink-3)">参数按 shape.defaults 自动生成 · 单位 mm / °</p>
+      <p class="muted">参数按 shape.defaults 自动生成 · 单位 mm / ° · 对称结构保证剖面 G1 连续</p>
       <div class="grid">
         ${keys.map((k) => {
           const v = this.params[k];
@@ -179,20 +746,146 @@ class PhLab extends PhPage {
           return html`<div class="ctl">
             <label for="s-${k}"><span>${KEY_LABEL[k] || k}</span><small>${k}</small></label>
             <input type="range" id="s-${k}" min=${lo} max=${hi} step=${step} .value=${String(v)}
-              @input=${(e) => this._set(k, e.target.value)} aria-label=${KEY_LABEL[k] || k} />
+              @input=${(e) => this._set(k, e.target.value, false)} @change=${() => this._pushUndo()}
+              aria-label=${KEY_LABEL[k] || k} />
             <input type="number" min=${lo} max=${hi} step=${step} .value=${String(v)}
               @change=${(e) => this._set(k, e.target.value)} aria-label=${(KEY_LABEL[k] || k) + ' 数值'} />
           </div>`;
         })}
       </div>
-      <div style="margin-top:18px"><button class="btn ghost" style="height:38px;font-size:14px" @click=${() => this._resetAll()}>恢复默认参数</button></div>`;
+      <div style="margin-top:18px"><button class="btn ghost sm" @click=${() => this._resetAll()}>恢复默认参数</button></div>`;
+  }
+
+  _partsTab() {
+    return html`
+      <div class="list">
+        ${this.parts.length ? this.parts.map((s) => html`
+          <div class="row ${s.uid === this.selUid ? 'on' : ''} ${s.visible ? '' : 'hide'}" data-uid=${s.uid}
+            @click=${() => this._select(s.uid)} role="button" tabindex="0"
+            @keydown=${(e) => { if (e.key === 'Enter') this._select(s.uid); }}>
+            <span class="ic" aria-hidden="true" .innerHTML=${primIcon(s.type)}></span>
+            <span class="meta">
+              <b>${s.label}</b>
+              <small>${esc(dimText(s))} · (${fmt(s.at.x, 1)}, ${fmt(s.at.y, 1)}, ${fmt(s.at.z, 1)})</small>
+            </span>
+            <button class="eye" aria-label=${s.visible ? '隐藏' : '显示'} @click=${(e) => { e.stopPropagation(); this._toggleVisible(s.uid); }}>${s.visible ? '◉' : '○'}</button>
+            <button class="del" aria-label="删除" @click=${(e) => { e.stopPropagation(); this._deletePart(s.uid); }}>×</button>
+          </div>`)
+        : html`<div class="empty">还没有结构件 ${this.p.features?.length ? '· 下方可一键应用推荐结构' : ''}</div>`}
+      </div>
+      <div class="add-row">
+        <button class="btn sm" @click=${() => { this.picker = true; this.requestUpdate(); }}>+ 添加结构件</button>
+        ${this.p.features?.length ? html`<button class="btn ghost sm" @click=${() => this._applyFeatures()}>应用推荐结构(${this.p.features.length})</button>` : ''}
+      </div>
+      <p class="muted">点一行进入单件编辑:相机聚焦、其余件半透明;也可直接在视口里点选拖动。</p>`;
+  }
+
+  _editTab() {
+    const s = this.sel;
+    if (!s) return '';
+    const schema = paramSchema(s.type);
+    const issues = this.checks.filter((c) => c.partUid === s.uid);
+    const sd = this._shellDim();
+    const maxY = Math.max(0, sd.h - (Number(s.params.h) || 0));
+    const xzMax = Math.max(10, Math.round((sd.kind === 'cyl' ? sd.r : Math.max(sd.w, sd.d) / 2) + 5));
+    return html`
+      <div class="edit-head">
+        <button class="back" @click=${() => this.exitEdit()}>← 全部</button>
+        <span class="ic" .innerHTML=${primIcon(s.type)}></span>
+        <b>${s.label}</b>
+        <small>${esc(PRIMS[s.type].short)} · ${esc(dimText(s))}</small>
+        <span class="grow"></span>
+        <span class="snap">吸附
+          ${SNAP_STEPS.map((v) => html`<button class=${this.snapStep === v ? 'on' : ''} @click=${() => this._snapStepChange(v)}>${v}</button>`)}
+          <i>mm</i>
+        </span>
+      </div>
+      <div class="grid dense">
+        ${[['x', 'X', -xzMax, xzMax], ['y', 'Y(底面高)', 0, Math.max(0.1, maxY)], ['z', 'Z', -xzMax, xzMax]].map(([k, lb, lo, hi]) => html`
+          <div class="ctl">
+            <label><span>${lb}</span><small>${k}</small></label>
+            <input type="range" min=${lo} max=${hi} step=${this.snapStep} .value=${String(s.at[k])}
+              @input=${(e) => this._setPartAt(s.uid, k, e.target.value, false)} @change=${() => this._pushUndo()} />
+            <input type="number" min=${lo} max=${hi} step=${this.snapStep} .value=${String(s.at[k])}
+              @change=${(e) => { this._setPartAt(s.uid, k, e.target.value, false); this._pushUndo(); }} />
+          </div>`)}
+        ${schema.map((f) => html`
+          <div class="ctl">
+            <label><span>${f.label}${f.unit || ''}</span><small>${f.key}</small></label>
+            <input type="range" min=${f.min} max=${f.max} step=${f.step} .value=${String(s.params[f.key] ?? f.def)}
+              @input=${(e) => this._setPartParam(s.uid, f.key, e.target.value, false)} @change=${() => this._pushUndo()} />
+            <input type="number" min=${f.min} max=${f.max} step=${f.step} .value=${String(s.params[f.key] ?? f.def)}
+              @change=${(e) => { this._setPartParam(s.uid, f.key, e.target.value, false); this._pushUndo(); }} />
+          </div>`)}
+        <div class="ctl">
+          <label><span>绕 Y 旋转</span><small>rotY</small></label>
+          <input type="range" min="0" max="360" step=${this.snapStep === 0.5 ? 1 : this.snapStep} .value=${String(s.rotY)}
+            @input=${(e) => { const cur = this.parts.find((p) => p.uid === s.uid); if (cur) cur.rotY = Number(e.target.value); this.viewer?.updatePart(cur); this.requestUpdate(); }}
+            @change=${(e) => this._setRot(s.uid, e.target.value)} />
+          <input type="number" min="0" max="360" step="1" .value=${String(s.rotY)} @change=${(e) => this._setRot(s.uid, e.target.value)} />
+        </div>
+      </div>
+      <div class="tools">
+        <button @click=${() => this._tool(s.uid, 'center')}>居中</button>
+        <button @click=${() => this._tool(s.uid, 'wall')}>贴内壁</button>
+        <button @click=${() => this._tool(s.uid, 'top')}>贴顶</button>
+        <button @click=${() => this._tool(s.uid, 'bottom')}>贴底</button>
+        <span class="sep"></span>
+        ${[4, 6, 8].map((n) => html`<button @click=${() => this._ring(s.uid, n)}>环形 ×${n}</button>`)}
+        <button @click=${() => this._clone(s.uid)}>复制</button>
+        <button @click=${() => this._mirror(s.uid)}>镜像</button>
+        <button class="danger" @click=${() => this._deletePart(s.uid)}>删除</button>
+      </div>
+      ${issues.length ? html`<ul class="issues">${issues.map((c) => html`<li class=${c.level}>${c.msg}</li>`)}</ul>` : ''}`;
+  }
+
+  _pickerOverlay() {
+    const groups = {};
+    for (const k of PRIM_KEYS) (groups[PRIMS[k].short] = groups[PRIMS[k].short] || []).push(k);
+    return html`
+      <div class="picker" role="dialog" aria-label="选择结构件类型">
+        <div class="picker-head"><b>添加结构件</b><span class="muted">14 类标准形体</span><span class="grow"></span><button class="x" aria-label="关闭" @click=${() => { this.picker = false; this.requestUpdate(); }}>×</button></div>
+        ${Object.entries(groups).map(([g, list]) => html`
+          <div class="pgroup"><div class="glabel">${g}</div>
+            <div class="pgrid">
+              ${list.map((k) => html`<button class="pcell" data-type=${k} @click=${() => this._addPart(k)}>
+                <span class="ic big" .innerHTML=${primIcon(k)}></span><b>${PRIMS[k].n}</b>
+              </button>`)}
+            </div>
+          </div>`)}
+      </div>`;
   }
 
   _exportTab() {
+    const sel = this.sel;
     return html`<div class="export">
-      <p>把当前形体参数导出为 JSON(含产品 id、shape 类型与全部参数),可直接交给结构工程师或复现到 CAD。</p>
-      <pre>${JSON.stringify({ id: this.p.id, shapeType: this.p.shape?.type, params: this.params }, null, 2)}</pre>
-      <button class="btn" @click=${() => this._export()}>下载 JSON</button>
+      <div class="exgrid">
+        <div class="ex">
+          <b>整件 STL</b><small>壳体 + 全部可见结构件,二进制 STL</small>
+          <button class="btn sm" @click=${() => this._exportStl(null)}>下载整件</button>
+        </div>
+        <div class="ex">
+          <b>按零件 STL</b><small>${sel ? `当前编辑:${sel.label}` : '未选中 → 每个结构件一个文件'}</small>
+          <button class="btn ghost sm" @click=${() => (sel ? this._exportStl(sel.uid) : this._exportAllStl())}>${sel ? '下载该件' : '下载全部'}</button>
+        </div>
+        <div class="ex">
+          <b>截图 PNG</b><small>2× 分辨率,当前视角</small>
+          <button class="btn ghost sm" @click=${() => this._exportPng()}>保存截图</button>
+        </div>
+        <div class="ex">
+          <b>生产需求单</b><small>参数 / 公差 / 装配 / 坐标表 / 报价回填</small>
+          <button class="btn ghost sm" @click=${() => this._exportSpec()}>下载 .md</button>
+        </div>
+        <div class="ex">
+          <b>BOM CSV</b><small>物料清单,Excel 可直接打开</small>
+          <button class="btn ghost sm" @click=${() => this._exportBomCsv()}>下载 CSV</button>
+        </div>
+        <div class="ex">
+          <b>工程 JSON</b><small>壳体参数 + 结构件 + 工艺,可复现</small>
+          <button class="btn ghost sm" @click=${() => this._exportJson()}>下载 JSON</button>
+        </div>
+      </div>
+      <p class="muted">文件名前缀 ${this.p.id};STL 单位为 mm,Z 轴向上,壳底中心为原点。</p>
       ${this.status ? html`<span class="status">${this.status}</span>` : ''}
     </div>`;
   }

+ 159 - 35
site/page/styles/lab-style.js

@@ -1,56 +1,180 @@
-/** 静态样式文本(见 lib/css.js 顶部说明) */
+/** 静态样式文本(见 lib/css.js 顶部说明)—— 实验室工程台:视口全屏 + 三档浮起的坞 */
 import { themeCss, sharedHtmlCss } from '../../utils/theme.js';
 
-const own = String.raw`    :host { display: block; height: 100vh; height: 100dvh; overflow: hidden; background: var(--bg); }
-    .lab { display: flex; flex-direction: column; height: 100%; }
+const own = String.raw`    :host {
+      display: block; height: 100vh; height: 100dvh; overflow: hidden; background: var(--bg);
+      --dock-h: 0px;
+    }
+    .lab { position: relative; height: 100%; }
     .bar {
-      flex: none; height: 48px; display: flex; align-items: center; justify-content: space-between; gap: 12px;
-      padding: 0 var(--pad); font-size: 13px; border-bottom: 1px solid var(--line);
+      position: absolute; inset: 0 0 auto 0; z-index: 3; height: 48px; display: flex; align-items: center; gap: 12px;
+      padding: 0 var(--pad); font-size: 13px; pointer-events: none;
     }
+    .bar > * { pointer-events: auto; }
     .bar a { color: var(--ink-2); }
-    .bar .t { font-weight: 600; color: var(--ink); }
-    .bar .live { color: var(--ink-3); font-variant-numeric: tabular-nums; }
-    .stage { position: relative; flex: 1; min-height: 0; }
+    .bar .t { font-weight: 600; color: var(--ink); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+    .bar .live { margin-left: auto; color: var(--ink-3); font-variant-numeric: tabular-nums; }
+    .reset {
+      height: 30px; padding: 0 13px; border-radius: 99px; border: 1px solid var(--line);
+      background: color-mix(in srgb, var(--bg) 82%, transparent); color: var(--ink-2); font-size: 12px; cursor: pointer;
+      backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
+    }
+    .reset:hover { color: var(--ink); }
+
+    /* 视口:铺满,底部让给坞(peek 时让 56px) */
+    .stage {
+      position: absolute; left: 0; right: 0; top: 48px; bottom: var(--dock-h, 0px);
+      transition: bottom 0.3s cubic-bezier(0.22, 1, 0.36, 1);
+    }
     .stage canvas { width: 100%; height: 100%; display: block; touch-action: none; outline: none; }
     .hint {
-      position: absolute; left: 16px; bottom: 12px; font-size: 11px; color: var(--ink-3); letter-spacing: 0.02em; pointer-events: none;
+      position: absolute; left: 16px; bottom: 10px; font-size: 11px; color: var(--ink-3); letter-spacing: 0.02em; pointer-events: none;
     }
-    .reset {
-      position: absolute; right: 16px; top: 12px; height: 32px; padding: 0 14px; border-radius: 99px;
-      border: 1px solid var(--line); background: var(--bg); color: var(--ink-2); font-size: 12px; cursor: pointer;
+    .sel-tip {
+      position: absolute; left: 16px; top: 10px; padding: 5px 11px; border-radius: 99px; font-size: 12px; color: #fff;
+      background: rgba(10, 105, 230, 0.9); pointer-events: none; max-width: calc(100% - 32px); overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
     }
-    .reset:hover { color: var(--ink); }
+
+    /* ---------- 坞:浮起、圆角、三档 ---------- */
     .dock {
-      flex: none; height: 46vh; max-height: 520px; min-height: 180px; display: flex; flex-direction: column;
-      border-top: 1px solid var(--line); background: var(--bg); transition: height 0.3s cubic-bezier(0.22, 1, 0.36, 1); overflow: hidden;
+      position: fixed; left: 0; right: 0; bottom: var(--kb, 0px); z-index: 4;
+      height: calc(46dvh + var(--fx-safe-b, 0px)); display: flex; flex-direction: column; overflow: hidden;
+      border-radius: 20px 20px 0 0; border-top: 1px solid var(--line);
+      background: color-mix(in srgb, var(--bg) 94%, transparent);
+      backdrop-filter: blur(20px) saturate(1.2); -webkit-backdrop-filter: blur(20px) saturate(1.2);
+      box-shadow: 0 -8px 40px rgba(0, 0, 0, 0.08);
+      transition: height 0.3s cubic-bezier(0.22, 1, 0.36, 1);
+      padding-bottom: var(--fx-safe-b, 0px);
     }
-    .dock.closed { height: 52px; min-height: 52px; }
-    .tabs { flex: none; height: 52px; display: flex; align-items: center; gap: 4px; padding: 0 var(--pad); border-bottom: 1px solid var(--line); }
+    .dock-head { flex: none; cursor: grab; user-select: none; touch-action: none; padding: 0 var(--pad); }
+    .dock-head:active { cursor: grabbing; }
+    .grab { width: 40px; height: 5px; border-radius: 99px; background: var(--line); margin: 8px auto 2px; }
+    .head-row { height: 40px; display: flex; align-items: center; gap: 10px; }
+    .head-row .count { font-size: 12px; color: var(--ink-3); font-variant-numeric: tabular-nums; }
+    .head-row .grow { flex: 1; }
+    .head-row .tab {
+      border: 0; background: transparent; color: var(--ink); font: 600 15px/1 var(--font); padding: 0; cursor: pointer;
+    }
+    .badge { font-size: 11px; padding: 2px 8px; border-radius: 99px; font-variant-numeric: tabular-nums; }
+    .badge.err { background: rgba(255, 59, 48, 0.12); color: #ff3b30; }
+    .badge.warn { background: rgba(255, 159, 10, 0.14); color: #c97400; }
+    .hist { display: inline-flex; gap: 2px; }
+    .hist button {
+      width: 30px; height: 30px; border-radius: 8px; border: 1px solid var(--line); background: transparent;
+      color: var(--ink); font-size: 16px; cursor: pointer; line-height: 1;
+    }
+    .hist button:disabled { opacity: 0.3; cursor: default; }
+    .fold { width: 30px; height: 30px; border: 0; background: transparent; color: var(--ink-3); font-size: 16px; cursor: pointer; }
+    .tabs { flex: none; height: 42px; display: flex; align-items: center; gap: 4px; padding: 0 var(--pad); }
     .tabs button {
-      height: 34px; padding: 0 16px; border-radius: 99px; border: 0; background: transparent; color: var(--ink-2);
+      height: 32px; padding: 0 14px; border-radius: 99px; border: 0; background: transparent; color: var(--ink-2);
       font-size: 14px; cursor: pointer;
     }
     .tabs button.on { background: var(--bg-soft); color: var(--ink); font-weight: 600; }
-    .tabs .grow { flex: 1; }
-    .tabs .fold { background: transparent; border: 0; color: var(--ink-3); font-size: 18px; cursor: pointer; width: 34px; }
-    .body { flex: 1; overflow: auto; padding: 20px var(--pad) calc(24px + var(--fx-safe-b, 0px)); -webkit-overflow-scrolling: touch; }
-    .dock.closed .body { display: none; }
-    .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 14px 24px; }
-    .ctl { display: grid; grid-template-columns: 1fr 84px; gap: 6px 12px; align-items: center; }
-    .ctl label { grid-column: 1 / 2; font-size: 13px; color: var(--ink-2); display: flex; justify-content: space-between; }
-    .ctl label small { color: var(--ink-3); font-size: 11px; }
-    .ctl input[type=range] { width: 100%; accent-color: var(--ink); }
+    .body { flex: 1; min-height: 0; overflow-y: auto; overscroll-behavior: contain; padding: 4px var(--pad) calc(56px + var(--fx-safe-b, 0px)); -webkit-overflow-scrolling: touch; }
+    @media (max-width: 640px) {
+      .tabs button { padding: 0 11px; font-size: 13px; }
+      .head-row .count { display: none; }
+    }
+
+    /* 形体页签 */
+    .grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 12px 24px; }
+    .grid.dense { grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px 18px; }
+    .ctl { display: grid; grid-template-columns: 1fr 76px; gap: 4px 10px; align-items: center; }
+    .ctl label { grid-column: 1 / 2; font-size: 12px; color: var(--ink-2); display: flex; justify-content: space-between; }
+    .ctl label small { color: var(--ink-3); font-size: 10px; }
+    .ctl input[type=range] { width: 100%; accent-color: var(--ink); height: 24px; }
     .ctl input[type=number] {
-      width: 100%; height: 30px; border: 1px solid var(--line); border-radius: 8px; background: transparent; color: var(--ink);
-      padding: 0 8px; font-size: 13px; font-variant-numeric: tabular-nums;
+      width: 100%; height: 28px; border: 1px solid var(--line); border-radius: 8px; background: transparent; color: var(--ink);
+      padding: 0 8px; font-size: 13px; font-variant-numeric: tabular-nums; text-align: right;
+    }
+    .proc-row { display: flex; align-items: center; gap: 10px; margin: 6px 0 10px; font-size: 13px; color: var(--ink-2); }
+    .proc-row select {
+      height: 30px; padding: 0 10px; border-radius: 8px; border: 1px solid var(--line); background: var(--bg); color: var(--ink); font-size: 13px;
+    }
+    .proc-row small { color: var(--ink-3); font-size: 11px; }
+    .muted { margin: 4px 0 12px; font-size: 12px; color: var(--ink-3); }
+    .warn { margin: 0 0 12px; font-size: 12px; color: var(--warn, #ff9f0a); }
+    .btn.sm { height: 34px; padding: 0 16px; font-size: 13px; }
+
+    /* 结构件列表 */
+    .list { display: flex; flex-direction: column; gap: 6px; }
+    .row {
+      display: flex; align-items: center; gap: 12px; padding: 8px 10px; border-radius: 12px; cursor: pointer;
+      border: 1px solid transparent; outline: none;
+    }
+    .row:hover, .row:focus-visible { background: var(--bg-soft); }
+    .row.on { border-color: rgba(10, 105, 230, 0.5); background: rgba(10, 105, 230, 0.06); }
+    .row.hide .meta b, .row.hide .ic { opacity: 0.4; }
+    .ic { display: inline-flex; width: 26px; height: 26px; color: var(--ink-2); flex: none; }
+    .ic svg { width: 100%; height: 100%; }
+    .ic.big { width: 34px; height: 34px; }
+    .row .meta { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
+    .row .meta b { font-size: 13px; font-weight: 600; }
+    .row .meta small { font-size: 11px; color: var(--ink-3); font-variant-numeric: tabular-nums; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+    .row .eye, .row .del {
+      width: 30px; height: 30px; border: 0; border-radius: 8px; background: transparent; color: var(--ink-3); font-size: 15px; cursor: pointer;
+    }
+    .row .del:hover { color: #ff3b30; background: rgba(255, 59, 48, 0.08); }
+    .empty { padding: 18px 4px; font-size: 13px; color: var(--ink-3); }
+    .add-row { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 12px; }
+
+    /* 添加结构件:14 类选择器 */
+    .picker {
+      position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: 5; overflow: auto;
+      background: var(--bg); border-radius: 20px 20px 0 0; padding: 4px var(--pad) 24px;
+      animation: picker-in 0.22s cubic-bezier(0.22, 1, 0.36, 1);
+    }
+    @keyframes picker-in { from { transform: translateY(24px); opacity: 0; } to { transform: none; opacity: 1; } }
+    .picker-head { display: flex; align-items: baseline; gap: 10px; padding: 10px 0 6px; }
+    .picker-head .grow { flex: 1; }
+    .picker-head .x { width: 32px; height: 32px; border: 0; border-radius: 99px; background: var(--bg-soft); color: var(--ink); font-size: 18px; cursor: pointer; }
+    .pgroup { margin-top: 8px; }
+    .glabel { font-size: 11px; letter-spacing: 0.08em; color: var(--ink-3); margin: 6px 0; }
+    .pgrid { display: grid; grid-template-columns: repeat(auto-fill, minmax(96px, 1fr)); gap: 8px; }
+    .pcell {
+      display: flex; flex-direction: column; align-items: center; gap: 6px; padding: 12px 6px; border-radius: 14px;
+      border: 1px solid var(--line); background: transparent; color: var(--ink); cursor: pointer; font: 500 12px/1.2 var(--font);
+      transition: transform 0.15s ease, background 0.15s ease;
+    }
+    .pcell:hover { background: var(--bg-soft); }
+    .pcell:active { transform: scale(0.96); }
+
+    /* 单件编辑 */
+    .edit-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin: 4px 0 12px; }
+    .edit-head b { font-size: 14px; }
+    .edit-head small { color: var(--ink-3); font-size: 11px; }
+    .edit-head .grow { flex: 1; }
+    .edit-head .back { height: 28px; padding: 0 10px; border-radius: 8px; border: 1px solid var(--line); background: transparent; color: var(--ink-2); font-size: 12px; cursor: pointer; }
+    .snap { display: inline-flex; align-items: center; gap: 2px; font-size: 12px; color: var(--ink-3); }
+    .snap button {
+      height: 26px; min-width: 32px; padding: 0 8px; border-radius: 7px; border: 1px solid var(--line); background: transparent;
+      color: var(--ink-2); font-size: 12px; cursor: pointer; font-variant-numeric: tabular-nums;
+    }
+    .snap button.on { background: var(--ink); color: var(--bg); border-color: var(--ink); }
+    .snap i { font-style: normal; font-size: 11px; margin-left: 4px; }
+    .tools { display: flex; flex-wrap: wrap; gap: 6px; margin: 16px 0 8px; }
+    .tools button {
+      height: 32px; padding: 0 12px; border-radius: 9px; border: 1px solid var(--line); background: transparent;
+      color: var(--ink); font-size: 12px; cursor: pointer;
     }
-    .warn { margin: 0 0 14px; font-size: 12px; color: var(--warn, #ff9f0a); }
-    .export p { margin: 0 0 18px; color: var(--ink-2); font-size: 14px; line-height: 1.6; }
-    .export pre {
-      margin: 0 0 18px; padding: 14px 16px; border-radius: 12px; background: var(--bg-soft); font: 12px/1.6 var(--fx-mono, monospace);
-      color: var(--ink-2); max-height: 180px; overflow: auto; white-space: pre-wrap;
+    .tools button:hover { background: var(--bg-soft); }
+    .tools button.danger { color: #ff3b30; }
+    .tools .sep { width: 1px; background: var(--line); margin: 4px 2px; }
+    .issues { list-style: none; margin: 8px 0 0; padding: 0; display: flex; flex-direction: column; gap: 4px; }
+    .issues li { font-size: 12px; color: var(--ink-2); padding-left: 14px; position: relative; }
+    .issues li::before { content: '·'; position: absolute; left: 4px; }
+    .issues li.error { color: #ff3b30; }
+
+    /* 导出 */
+    .exgrid { display: grid; grid-template-columns: repeat(auto-fill, minmax(210px, 1fr)); gap: 10px; }
+    .ex {
+      display: flex; flex-direction: column; gap: 4px; padding: 12px 14px; border-radius: 14px; border: 1px solid var(--line);
     }
-    .status { margin-left: 12px; font-size: 12px; color: var(--ink-3); }
+    .ex b { font-size: 13px; }
+    .ex small { font-size: 11px; color: var(--ink-3); line-height: 1.5; min-height: 32px; }
+    .ex button { align-self: flex-start; margin-top: 4px; }
+    .status { display: inline-block; margin-top: 12px; font-size: 12px; color: var(--ink-3); }
   `;
 
 export const labStyle = [themeCss, sharedHtmlCss, own];

+ 413 - 10
site/services/viewer3d.js

@@ -6,8 +6,11 @@
  * - rebuild(params) 合并到 requestAnimationFrame;dispose 释放引擎 / 场景 / 画布监听
  * Babylon 由调用方动态 import(window.BABYLON),见 page/lab.js 的 ensureBabylon()。
  */
-import { roundProfile } from '../core/geometry/profile.js';
-import { radiusAtHeight } from '../core/geometry/profile.js';
+import { roundProfile, radiusAtHeight } from '../core/geometry/profile.js';
+import { primMesh, rotateY, isCutType, cavity, snapDrag, primDims } from '../core/geometry/solid.js';
+import { footprint, snapToInnerWall } from '../core/geometry/parts.js';
+
+const DEG = Math.PI / 180;
 
 /** 整数化顶点,用于 C1(位置重合)去重 */
 const key = (x, y, z) => `${x.toFixed(4)},${y.toFixed(4)},${z.toFixed(4)}`;
@@ -82,6 +85,16 @@ export class ShellViewer {
     this._raf = 0;
     this._disp = null;
     this._onUnload = () => this.dispose();
+    /** 结构件:[{ part(parts.js 实例), mesh, base(顶点缓存), mat }] */
+    this._parts = [];
+    this.selUid = null;
+    this._drv = null;          // 当前拖动会话
+    this._moveRaf = 0;
+    this.bgPointer = null;     // 点空白回调(未拖动时触发)
+    this.onSelect = null;      // 点中件回调 (uid)
+    this.onSelectMesh = null;  // 点中件回调 (uid, mesh)
+    this.onDragEnd = null;     // 拖动松手回调 (uid, {x,z})
+    this.onPartRule = null;    // 拖动结束时规则回调 (uid, at)
 
     const engine = (this.engine = new B.Engine(canvas, true, {
       preserveDrawingBuffer: false, stencil: true, antialias: true,
@@ -113,17 +126,18 @@ export class ShellViewer {
     canvas.addEventListener('pointerdown', this._pd);
     this._dbl = () => this.reset();
     canvas.addEventListener('dblclick', this._dbl);
+    this._bindPicking(canvas);
 
     const hemi = new B.HemisphericLight('hemi', new B.Vector3(0.2, 1, 0.15), scene);
     hemi.intensity = 0.75;
     hemi.groundColor = new B.Color3(0.3, 0.3, 0.33);
-    const key = new B.DirectionalLight('key', new B.Vector3(-0.7, -1, 0.6), scene);
-    key.intensity = 0.85;
+    const keyLight = new B.DirectionalLight('key', new B.Vector3(-0.7, -1, 0.6), scene);
+    keyLight.intensity = 0.85;
     const rim = new B.DirectionalLight('rim', new B.Vector3(0.8, -0.2, -0.8), scene);
     rim.intensity = 0.35;
 
 
-    this.engine.runRenderLoop(() => scene.render());
+    this.engine.runRenderLoop(() => { if (this.scene) this.scene.render(); });
     this._resize = () => engine.resize();
     addEventListener('resize', this._resize);
     addEventListener('pagehide', this._onUnload, { once: true });
@@ -138,7 +152,10 @@ export class ShellViewer {
   /** 当前网格顶点/索引统计(验收用) */
   stats() {
     const m = this.mesh;
-    return m ? { positions: m.getTotalVertices(), indices: m.getTotalIndices(), params: { ...this.params } } : null;
+    if (!m) return null;
+    let pm = 0;
+    for (const e of this._parts || []) if (e.mesh && !e.mesh.isDisposed()) pm += e.mesh.getTotalVertices();
+    return { positions: m.getTotalVertices(), indices: m.getTotalIndices(), parts: this._parts ? this._parts.length : 0, partVertices: pm, params: { ...this.params } };
   }
 
   setParams(patch) {
@@ -173,9 +190,374 @@ export class ShellViewer {
       camSnapshot(this.camera, this._home);
       this._framed = true;
     }
+    if (this._parts.length) this._layoutParts();
+    if (this.selUid) this.applySelection(this.selUid);
     return this.mesh;
   }
 
+  /* =========================================================
+     结构件:渲染 / 选中 / 高亮 / 拖动 / 聚焦
+     ========================================================= */
+
+  /** 壳体落位包络(结构件拖动与贴壁用):圆件 {kind:'cyl',r,floor,top},方件 {kind:'rect',halfX,halfZ,floor,top} */
+  get cav() {
+    const c = cavity(this.product.shape?.type, this.params);
+    this._cavCache = { ...c, h: Number(this.params.height) || 8, w: Number(this.params.dTop) || 40 };
+    return this._cavCache;
+  }
+
+  /** 壳体渲染包围盒(世界坐标) */
+  shellBounds() {
+    const m = this.mesh;
+    if (!m) return { min: new this.B.Vector3(-10, 0, -10), max: new this.B.Vector3(10, 10, 10) };
+    const bb = m.getBoundingInfo().boundingBox;
+    return { min: bb.minimumWorld.clone(), max: bb.maximumWorld.clone(), center: bb.centerWorld.clone() };
+  }
+
+  /** 世界坐标 → 壳体局部坐标(X 右 / Y 上 / Z 前,原点在壳底中心) */
+  _toLocal(v) {
+    const m = this.mesh;
+    if (!m) return { x: v.x, y: v.y, z: v.z };
+    const p = m.position;
+    return { x: v.x - p.x, y: v.y - p.y, z: v.z - p.z };
+  }
+
+  /** 全量重建结构件(增删 / 改参数 / 产品切换时调用;单件量小,直接重建,不节流) */
+  setParts(parts = []) {
+    const B = this.B;
+    for (const e of this._parts) if (e.mesh && !e.mesh.isDisposed()) e.mesh.dispose();
+    this._parts = [];
+    for (const part of parts) {
+      let pm = null;
+      try { pm = primMesh({ ...part.params, type: part.type }).part; } catch (e) { console.warn('[viewer] 结构件网格失败', part.uid, e); continue; }
+      const mesh = new B.Mesh('part:' + part.uid, this.scene);
+      const vd = new B.VertexData();
+      vd.positions = Array.from(pm.positions);
+      vd.indices = Array.from(pm.indices);
+      const nrm = [];
+      B.VertexData.ComputeNormals(vd.positions, vd.indices, nrm);
+      vd.normals = nrm;
+      vd.applyToMesh(mesh, false);
+      const mat = new B.StandardMaterial('pm:' + part.uid, this.scene);
+      const cut = isCutType(part.type);
+      mat.diffuseColor = cut ? new B.Color3(0.98, 0.45, 0.25) : new B.Color3(0.16, 0.46, 0.9);
+      mat.specularColor = new B.Color3(0.3, 0.3, 0.32);
+      mat.emissiveColor = cut ? new B.Color3(0.28, 0.1, 0.04) : new B.Color3(0.04, 0.12, 0.3);
+      if (cut) mat.alpha = 0.55;
+      mat.backFaceCulling = false;
+      mesh.material = mat;
+      mesh.isPickable = true;
+      mesh.metadata = { uid: part.uid, kind: 'part' };
+      this._parts.push({ part, mesh, base: { positions: vd.positions, indices: vd.indices }, mat, cut });
+    }
+    this._layoutParts();
+    this.applySelection(this.selUid);
+    return this._parts;
+  }
+
+  /** 单个件的 params / at / rotY 变了:只重建这一件 */
+  updatePart(part) {
+    const i = this._parts.findIndex((e) => e.part.uid === part.uid);
+    if (i < 0) return this.setParts([...this._parts.map((e) => e.part), part]);
+    const list = this._parts.map((e) => e.part);
+    list[i] = part;
+    this.setParts(list);
+    return this._parts.find((e) => e.part.uid === part.uid);
+  }
+
+  /**
+   * 把件的局部网格(原点在件中心、Y 向上)摆到壳体坐标:
+   *   mirror(X 取反)→ 绕 Y 旋转 → 平移到 at(at.y = 件底面高度)。
+   * 壳体相对网格有偏移 → 再统一加网格位移;结构件尺寸很小,直接烘焙进顶点后 world = identity,
+   * 这样拖动平移、包围盒、拾取都不受父节点影响。
+   */
+  _layoutParts() {
+    const B = this.B;
+    const off = this.mesh ? this.mesh.position : new B.Vector3(0, 0, 0);
+    for (const e of this._parts) {
+      const part = e.part;
+      const p = e.base.positions.slice();
+      if (part.mirror) for (let j = 0; j < p.length; j += 3) p[j] = -p[j];
+      const a = (Number(part.rotY) || 0) * DEG, c = Math.cos(a), s = Math.sin(a);
+      const half = this._partHalfHeight(part);
+      const tx = Number(part.at?.x) || 0, ty = Number(part.at?.y) || 0, tz = Number(part.at?.z) || 0;
+      for (let j = 0; j < p.length; j += 3) {
+        const x = p[j], y = p[j + 1], z = p[j + 2];
+        const X = x * c + z * s, Z = -x * s + z * c;
+        p[j] = X + tx + off.x;
+        p[j + 1] = y + ty + half + off.y;
+        p[j + 2] = Z + tz + off.z;
+      }
+      e.mesh.setVerticesData(this.B.VertexBuffer.PositionKind, p, false);
+      e.mesh.refreshBoundingInfo();
+      e.mesh.isVisible = part.visible !== false;
+    }
+  }
+
+  _partHalfHeight(part) {
+    const p = part.params || {};
+    return Math.max(0.1, Number(p.h) || 1) / 2;
+  }
+
+  /**
+   * 选中高亮:选中件 emissive 亮蓝 + 其余件 alpha 0.25。
+   * uid 为空 → 恢复全部不透明、无选中色。
+   */
+  applySelection(uid) {
+    this.selUid = uid || null;
+    for (const e of this._parts) {
+      if (!e.mesh || e.mesh.isDisposed()) continue;
+      const sel = this.selUid && e.part.uid === this.selUid;
+      if (this.selUid) {
+        e.mesh.visibility = sel ? 1 : 0.25;
+        e.mat.emissiveColor = sel ? new this.B.Color3(0.1, 0.45, 1.0) : (e.cut ? new this.B.Color3(0.28, 0.1, 0.04) : new this.B.Color3(0.02, 0.04, 0.1));
+      } else {
+        e.mesh.visibility = 1;
+        e.mat.emissiveColor = e.cut ? new this.B.Color3(0.28, 0.1, 0.04) : new this.B.Color3(0.04, 0.12, 0.3);
+      }
+    }
+  }
+
+  /** 件中心的壳体局部坐标 */
+  partCenter(part) {
+    return { x: Number(part.at?.x) || 0, y: (Number(part.at?.y) || 0) + this._partHalfHeight(part), z: Number(part.at?.z) || 0 };
+  }
+
+  /** 相机聚焦到某件(壳体局部坐标),半径按件尺寸收紧 */
+  focusPart(part) {
+    const c = this.partCenter(part);
+    const fp = footprint(part) * 2, h = this._partHalfHeight(part) * 2;
+    const r = Math.max(14, Math.max(fp, h) * 3.2);
+    const tgt = this.mesh ? this.mesh.position.clone() : this.B.Vector3.Zero();
+    tgt.addInPlace(new this.B.Vector3(c.x, c.y, c.z));
+    const cam = this.camera;
+    cam.setTarget(tgt);
+    cam.radius = Math.min(cam.upperRadiusLimit, r);
+  }
+
+  /** 回到全局视图(首次自动取景的机位) */
+  homeView(instant = true) {
+    const cam = this.camera;
+    const from = { alpha: cam.alpha, beta: cam.beta, radius: cam.radius, target: cam.target.clone() };
+    const to = this._home;
+    if (instant) {
+      cam.alpha = to.alpha; cam.beta = to.beta; cam.radius = to.radius; cam.target.copyFrom(to.target);
+      return;
+    }
+    const B = this.B, t0 = performance.now(), dur = 320;
+    const step = () => {
+      const k = Math.min(1, (performance.now() - t0) / dur), e = 1 - Math.pow(1 - k, 3);
+      cam.alpha = from.alpha + (to.alpha - from.alpha) * e;
+      cam.beta = from.beta + (to.beta - from.beta) * e;
+      cam.radius = from.radius + (to.radius - from.radius) * e;
+      cam.target.copyFrom(B.Vector3.Lerp(from.target, to.target, e));
+      if (k < 1) requestAnimationFrame(step);
+    };
+    requestAnimationFrame(step);
+  }
+
+  /** 拖动落点:靠内壁 1.5mm 内贴到留 0.5mm 余量;否则按 step 取整 */
+  dragSnap(part, x, z, step = 1) {
+    const cav = this.cav;
+    return snapDrag(cav, { ...part.params, x, z }, x, z, step, 1.5, 0.5);
+  }
+
+  /* ---------- 拾取 / 拖动 ---------- */
+  _pickAt(ev) {
+    const B = this.B, scene = this.scene;
+    if (!scene) return null;
+    const rect = this.canvas.getBoundingClientRect();
+    const x = ev.clientX - rect.left, y = ev.clientY - rect.top;
+    const hit = scene.pick(x, y, (m) => m.isPickable && m.isVisible !== false && m.isEnabled(), false, scene.activeCamera);
+    return hit && hit.hit ? hit : null;
+  }
+
+  _bindPicking(canvas) {
+    const B = this.B;
+    /** 水平面(世界 Y = y),拖动投影用;平面运行中不动,取 p0 预建 */
+    this._planeAt = (y) => B.Plane.FromPositionAndNormal(new B.Vector3(0, y, 0), new B.Vector3(0, 1, 0));
+
+    const down = (ev) => {
+      if (ev.button !== undefined && ev.button > 0) return;          // 只处理主键 / 单指
+      if (this._drv) return;
+      const hit = this._pickAt(ev);
+      const uid = hit?.pickedMesh?.metadata?.uid;
+      if (!uid) return;                                               // 空白处:交给相机旋转,松手再判点空白
+      ev.stopImmediatePropagation();
+      ev.preventDefault();
+      const part = this._parts.find((e) => e.part.uid === uid)?.part;
+      if (!part) return;
+      if (part.visible === false) return;
+      this.camera.detachControl();                                    // 拖动时锁住相机
+      const y = this.mesh.position.y + (Number(part.at?.y) || 0);
+      const pl = this._planeAt(y);
+      const ray = this.scene.createPickingRay(ev.clientX - canvas.getBoundingClientRect().left, ev.clientY - canvas.getBoundingClientRect().top, B.Matrix.Identity(), this.camera);
+      const p0 = ray.intersectsPlane(pl);
+      this._drv = {
+        uid, part, pl, p0, moved: false,
+        start: { x: Number(part.at?.x) || 0, z: Number(part.at?.z) || 0 },
+        sx: ev.clientX, sy: ev.clientY,
+      };
+      this.onSelect?.(uid, this._parts.find((e) => e.part.uid === uid)?.mesh);
+      const move = (e2) => this._onDragMove(e2);
+      const up = () => { this._onDragUp(); };
+      canvas.addEventListener('pointermove', move);
+      canvas.addEventListener('pointerup', up);
+      canvas.addEventListener('pointercancel', up);
+      this._drvCleanup = () => { canvas.removeEventListener('pointermove', move); canvas.removeEventListener('pointerup', up); canvas.removeEventListener('pointercancel', up); };
+    };
+    // 捕获阶段:在 ArcRotateCamera 的 canvas 监听之前截停
+    canvas.addEventListener('pointerdown', down, true);
+
+    // 点空白:pointerup 时若没拖动 → 失焦选中
+    const voidDown = (ev) => {
+      if (ev.button !== undefined && ev.button > 0) return;
+      this._maybeVoid = { x: ev.clientX, y: ev.clientY, t: performance.now() };
+    };
+    const voidUp = (ev) => {
+      const v = this._maybeVoid; this._maybeVoid = null;
+      if (!v || this._drv) return;
+      if (Math.hypot(ev.clientX - v.x, ev.clientY - v.y) > 6 || performance.now() - v.t > 500) return;
+      if (this._pickAt(ev)?.pickedMesh?.metadata?.uid) return;
+      this.bgPointer?.();
+    };
+    canvas.addEventListener('pointerdown', voidDown);
+    canvas.addEventListener('pointerup', voidUp);
+  }
+
+  _onDragMove(ev) {
+    const d = this._drv;
+    if (!d) return;
+    if (!d.moved && Math.hypot(ev.clientX - d.sx, ev.clientY - d.sy) < 4) return;
+    d.moved = true;
+    const rect = this.canvas.getBoundingClientRect();
+    const ray = this.scene.createPickingRay(ev.clientX - rect.left, ev.clientY - rect.top, this.B.Matrix.Identity(), this.camera);
+    const hit = ray.intersectsPlane(d.pl);
+    if (!hit) return;
+    const p = this._toLocal(hit);
+    const s = this._snapStep || 1;
+    const q = this.dragSnap(d.part, p.x, p.z, s);
+    if (!this._moveRaf) {
+      this._moveRaf = requestAnimationFrame(() => {
+        this._moveRaf = 0;
+        if (!this._drv) return;
+        const dr = this._drv;
+        dr.part = { ...dr.part, at: { ...dr.part.at, x: q.x, z: q.z } };
+        const e = this._parts.find((x) => x.part.uid === dr.uid);
+        if (e) { e.part = dr.part; this._layoutParts(); }
+        this.onDragMove?.(dr.uid, { x: q.x, z: q.z });
+      });
+    }
+    d.last = { x: q.x, z: q.z };
+  }
+
+  _onDragUp() {
+    const d = this._drv;
+    this._drvCleanup?.();
+    this._drvCleanup = null;
+    if (this._moveRaf) { cancelAnimationFrame(this._moveRaf); this._moveRaf = 0; }
+    this.camera.attachControl(this.canvas, true);                     // 松手交还相机
+    this._drv = null;
+    if (!d) return;
+    if (d.moved) {
+      const at = d.last ? { x: d.last.x, z: d.last.z } : { x: d.start.x, z: d.start.z };
+      this.onDragEnd?.(d.uid, at);
+    }
+  }
+
+  /** 由页面把「已选中件」的最新实例同步给 viewer(拖动后 page 侧回写) */
+  syncPart(part) {
+    const e = this._parts.find((x) => x.part.uid === part.uid);
+    if (!e) return;
+    e.part = part;
+    this._layoutParts();
+  }
+
+  /* =========================================================
+     导出:STL / 截图
+     ========================================================= */
+
+  /** 收集三角面(世界坐标):壳体 + 可见结构件;onlyUid 时只取该结构件 */
+  collectTriangles(onlyUid = null) {
+    const tris = [];
+    const pushMesh = (mesh, part) => {
+      if (!mesh || mesh.isDisposed()) return;
+      const pos = mesh.getVerticesData(this.B.VertexBuffer.PositionKind);
+      const idx = mesh.getIndices();
+      const wm = mesh.computeWorldMatrix(true);
+      const n = idx ? idx.length : pos.length / 3;
+      for (let i = 0; i < n; i += 3) {
+        const a = new this.B.Vector3(pos[idx[i] * 3], pos[idx[i] * 3 + 1], pos[idx[i] * 3 + 2]);
+        const b = new this.B.Vector3(pos[idx[i + 1] * 3], pos[idx[i + 1] * 3 + 1], pos[idx[i + 1] * 3 + 2]);
+        const c = new this.B.Vector3(pos[idx[i + 2] * 3], pos[idx[i + 2] * 3 + 1], pos[idx[i + 2] * 3 + 2]);
+        this.B.Vector3.TransformCoordinatesToRef(a, wm, a);
+        this.B.Vector3.TransformCoordinatesToRef(b, wm, b);
+        this.B.Vector3.TransformCoordinatesToRef(c, wm, c);
+        const u = b.subtract(a), w = c.subtract(a);
+        const nn = this.B.Vector3.Cross(u, w);
+        tris.push({ a, b, c, n: nn.lengthSquared() > 1e-12 ? nn.normalize() : new this.B.Vector3(0, 1, 0), uid: part?.uid || 'shell' });
+      }
+    };
+    if (onlyUid) {
+      const e = this._parts.find((x) => x.part.uid === onlyUid);
+      if (e) pushMesh(e.mesh, e.part);
+    } else {
+      pushMesh(this.mesh, null);
+      for (const e of this._parts) if (e.mesh.isVisible) pushMesh(e.mesh, e.part);
+    }
+    return tris;
+  }
+
+  /** 二进制 STL(小端 float32);返回 ArrayBuffer */
+  exportSTL(onlyUid = null) {
+    const tris = this.collectTriangles(onlyUid);
+    const buf = new ArrayBuffer(84 + tris.length * 50);
+    const view = new DataView(buf);
+    const header = 'Pocket Hardware Lab · FmodeCode';
+    for (let i = 0; i < Math.min(80, header.length); i++) view.setUint8(i, header.charCodeAt(i));
+    view.setUint32(80, tris.length, true);
+    let o = 84;
+    for (const t of tris) {
+      view.setFloat32(o, t.n.x, true); view.setFloat32(o + 4, t.n.y, true); view.setFloat32(o + 8, t.n.z, true); o += 12;
+      for (const v of [t.a, t.b, t.c]) { view.setFloat32(o, v.x, true); view.setFloat32(o + 4, v.y, true); view.setFloat32(o + 8, v.z, true); o += 12; }
+      view.setUint16(o, 0, true); o += 2;
+    }
+    return { buffer: buf, triangles: tris.length };
+  }
+
+  /**
+   * 截图(scale 倍分辨率):优先 Tools.CreateScreenshot(render target 离屏放大),
+   * GPU / 无头环境下 render-target 路径会抛「ScreenshotTools」,再退到 canvas.toDataURL + 像素放大。
+   * 返回 dataURL(image/png)或 null。
+   */
+  async screenshot(scale = 2) {
+    const B = this.B;
+    const rt = this.canvas.width;
+    let data = await new Promise((resolve) => {
+      let done = false;
+      try {
+        B.Tools.CreateScreenshot(this.engine, this.camera, { precision: scale }, (d) => { done = true; resolve(d); }, 'image/png');
+      } catch (e) {
+        console.warn('[viewer] 截图 render-target 不可用,改用画布像素', e?.message || e);
+        resolve(null);
+      }
+      setTimeout(() => { if (!done) resolve(null); }, 1500);
+    });
+    if (!data) {
+      try {
+        this.scene.render();
+        data = this.canvas.toDataURL('image/png');
+      } catch (e) { console.warn('[viewer] 画布截图失败', e); return null; }
+      if (!data || data.length < 100) return null;
+      if (scale > 1) {
+        const up = await scalePng(data, scale);
+        if (up) data = up;
+      }
+    }
+    void rt;
+    return data;
+  }
+
   _rectMaterial() {
     const B = this.B;
     const m = new B.StandardMaterial('rectMat', this.scene);
@@ -277,10 +659,10 @@ export class ShellViewer {
     return mesh;
   }
 
-  reset() {
-    const c = this.camera;
-    c.alpha = this._home.alpha; c.beta = this._home.beta; c.radius = this._home.radius;
-    c.target.copyFrom(this._home.target);
+  /** 双击复位:退出选中态,相机回到首次取景 */
+  reset(animate = false) {
+    if (this.selUid) { this.applySelection(null); this.onSelect?.(null, null); }
+    this.homeView(!animate);
   }
 
   dispose() {
@@ -291,6 +673,10 @@ export class ShellViewer {
     if (this._ro) { this._ro.disconnect(); this._ro = null; }
     if (this._dbl) this.canvas.removeEventListener('dblclick', this._dbl);
     if (this._pd) this.canvas.removeEventListener('pointerdown', this._pd);
+    this._drvCleanup?.();
+    if (this._moveRaf) cancelAnimationFrame(this._moveRaf);
+    this._parts = [];
+    this.selUid = null;
     try { this.camera?.dispose(); } catch { /* noop */ }
     try { this.scene?.dispose(); } catch { /* noop */ }
     try { this.engine?.stopRenderLoop(); this.engine?.dispose(); } catch { /* noop */ }
@@ -318,3 +704,20 @@ function camSnapshot(cam, into) {
 
 /** 只用于测试半径插值导出的薄封装(避免循环依赖告警) */
 export { radiusAtHeight };
+
+/** 按比例把 canvas 截图 dataURL 缩放成 PNG(无头 / GPU 限制走不通时兜底) */
+export function scalePng(dataUrl, scale = 2) {
+  return new Promise((resolve) => {
+    const img = new Image();
+    img.onload = () => {
+      const c = document.createElement('canvas');
+      c.width = Math.round(img.width * scale); c.height = Math.round(img.height * scale);
+      const ctx = c.getContext('2d');
+      ctx.imageSmoothingQuality = 'high';
+      ctx.drawImage(img, 0, 0, c.width, c.height);
+      resolve(c.toDataURL('image/png'));
+    };
+    img.onerror = () => resolve(null);
+    img.src = dataUrl;
+  });
+}

+ 154 - 0
tasks/E-lab-editor.md

@@ -0,0 +1,154 @@
+# 阶段 E — 3D 实验室补齐到「可编辑工程台」
+
+工作目录:`/opt/data/projects/hardware-lab`
+参考实现:`ref-v2/src/04_geo.js`(几何+爆炸+导出)、`ref-v2/src/05_app.js`(编辑坞+结构件树+工具)
+现状:`site/services/viewer3d.js`(320 行)、`site/core/geometry/solid.js`(927 行,14 类形体已就绪)、`site/page/lab.js`(204 行,只有滑块)
+
+**目标**:把 `page/lab.js` 从「参数面板」升级为「可编辑工程台」。几何内核已具备,重点是**交互层与结构件管理**。
+
+产出方署名 **FmodeCode**,零出现 Claude/Hermes/DeepSeek。
+
+---
+
+## 一、结构件数据模型(先做这个,后面全依赖它)
+
+在 `site/core/geometry/parts.js` 新建,纯函数、Node 可测:
+
+```js
+// 单个结构件实例
+{
+  uid: 'p1',                    // 唯一 id
+  type: 'boss25',               // 对应 solid.js 的 PRIMS 键
+  label: 'M2.5 螺丝柱',
+  params: { od:4.5, holeD:2.7, height:6, draft:1 },  // 类型相关参数
+  at: { x:0, y:0, z:0 },        // 相对壳体局部坐标 (mm)
+  rotY: 0,                      // 绕 Y 旋转(度)
+  mirror: false,                // 是否镜像
+  visible: true,
+}
+```
+
+导出:
+- `createPart(type, at)` — 按类型给默认 params
+- `clonePart(part, offsetX)` — 复制
+- `arrayRing(part, count, radius)` — 环形阵列,返回 N 个新件
+- `snapToInnerWall(part, shellDim, gap=0.5)` — 贴内壁,返回修正后的 at
+- `validate(parts, shellDim, proc)` — 五套工艺规则校验,返回 `[{level:'error'|'warn', partUid, msg, paramKey}]`
+
+工艺规则(阈值照 ref-v2 的 `03_data.js` 里 rules):
+- 注塑:壁厚 ≥1.0,筋厚 ≥0.6,拔模 ≥1°,柱壁 ≥0.8,深宽比 ≤5
+- 硅胶:壁厚 ≥1.2,圆角 ≥0.5,无尖角
+- CNC:壁厚 ≥1.5,内角 R ≥1.0
+- 复模:壁厚 ≥1.0
+- 压铸:壁厚 ≥1.2,拔模 ≥1.5°
+
+### 验收
+```bash
+node --input-type=module -e "
+import('./site/core/geometry/parts.js').then(m=>{
+  console.log(Object.keys(m));
+  const p=m.createPart('boss25',{x:20,y:0,z:0});
+  console.log('create:',p.type, JSON.stringify(p.params));
+  console.log('array:', m.arrayRing(p,6,24).length);
+  console.log('snap:', JSON.stringify(m.snapToInnerWall(p,{w:90,d:62,h:9})));
+  console.log('validate:', m.validate([p],{w:90,d:62,h:9},'injection').length);
+})"
+```
+必须打印出实际数值,不能报错。
+
+---
+
+## 二、编辑坞(单屏工作台)
+
+替换现在的简单面板,照 ref-v2 的交互:
+
+### 布局
+- 3D 视口占满屏幕,坞从底部浮起
+- **三档吸附**:peek 20% / half 46% / full 72%
+- 拖拽坞头手柄,松手吸附最近档
+- 点坞头切换 peek ↔ half
+- 收起时只剩一行标题
+- 键盘弹出用 `visualViewport` 把坞顶到键盘上方
+
+### 坞内四个页签
+1. **形体** — 壳体基础参数(现有 14 个滑块保留、优化)
+2. **结构件** — 新增:结构件列表 + 添加 + 编辑
+3. **BOM** — 现有
+4. **导出** — 扩充
+
+### 结构件列表(核心)
+- 每行:类型图标 + 名称 + 关键尺寸 + 可见性开关 + 删除
+- 底部「+ 添加结构件」→ 弹出 14 类形体选择器(网格布局,每格有名称和简图)
+- 点某一行 → 进入单件编辑态
+
+### 单件编辑态(关键交互)
+- 该件高亮(`emissiveColor` 亮蓝),其余件半透明(`alpha 0.25`)
+- 相机自动聚焦到该件(`target` 移到件中心,半径收紧)
+- 退出编辑态恢复全局视图
+- 数值面板:X/Y/Z、外径、预钻孔、间距、高度、拔模角、绕 Y 旋转
+- **吸附档 0.5 / 1 / 5 mm** 可切换
+- 数值可点数字直接键盘输入,滑块只做粗调
+- 编辑工具按钮:居中 / 贴内壁 / 贴顶 / 贴底 / 环形阵列(×4/×6/×8) / 复制 / 删除
+
+---
+
+## 三、3D 视口交互
+
+现有能力保留(旋转/缩放/双击复位),新增:
+
+- **点选**:点击结构件 → 选中并进编辑态;点空白处取消选中
+- **拖动**:选中件后可沿所在平面拖动,松手落位
+  - 拖动时**锁住相机**(`camera.detachControl()`),松手交还
+  - 拖动靠内壁 1.5mm 内自动贴到留 0.5mm 余量
+- **撤销/重做**:40 步栈,坞头固定撤销/重做按钮,支持 Ctrl+Z / Ctrl+Shift+Z
+- 加件/删件/选件有轻微振动反馈(`navigator.vibrate?.(8)`,不支持则忽略)
+
+---
+
+## 四、导出(扩充)
+
+现在只有「下载 JSON」,补齐:
+
+1. **整件 STL**(二进制 STL,Babylon 的 `STLExport.CreateSTL` 或手写)
+2. **按零件 STL**(编辑态下只导出该件;未选中时导出全部为多个文件)
+3. **截图 PNG**(`Tools.CreateScreenshot`,2x 分辨率)
+4. **生产需求单 .md**:参数快照表 + 公差表 + 装配顺序 + 自定义结构件坐标表(uid/类型/坐标/尺寸)+ CNC 弧面编程参数 + 供应商报价回填表(空白表格)
+5. **BOM CSV**、**工程 JSON**(现有)
+
+---
+
+## 五、性能与状态
+
+- 滑块拖动 `requestAnimationFrame` 合并重建(现有 setParams 已有,保留)
+- 松手后 260ms 才写 localStorage(防抖)
+- 结构件增删改立即重建(不必节流,单件量小)
+- 离开页面 `dispose` 干净(现有 `EngineStore` 从 1→0 的行为保留)
+
+---
+
+## 验收清单(逐条机器验证,我会全跑)
+
+```bash
+# 1. 几何内核可测
+node --input-type=module -e "import('./site/core/geometry/parts.js').then(...)"   # 见上文
+
+# 2. 实验室页有 canvas 且正文含「结构件」字样
+# 3. 浏览器里点「添加结构件」→ 出现 14 类选择器
+# 4. 选中一件 → 其余件 alpha 降低(读 Babylon mesh.visibility)
+# 5. 撤销/重做栈可用(改参数 → 撤销 → 值回退)
+# 6. 导出 STL 能触发下载
+# 7. 控制台 0 错误
+# 8. 零外链、零违禁词
+```
+
+## 交付物
+- `site/core/geometry/parts.js`(新建)
+- `site/page/lab.js` 重写
+- `site/services/viewer3d.js` 扩充(选中/拖动/高亮/截图/STL)
+- `site/page/styles/lab-style.js` 扩充(坞三档、结构件列表、选择器)
+- `docs/BUILD-REPORT.md` 追加本轮记录
+
+## 注意
+- 不要改动 `site/page/product.js`、`gallery.js`、`core/geometry/profile.js`、`solid.js` 的既有导出签名
+- 不要引入新依赖,Babylon 已本地化在 `site/vendor/babylon/babylon.js`
+- 改完必须本地起 `tools/serve.py` 自测 path 路由(`/lab/<id>`)

+ 68 - 0
tools/upload_final.sh

@@ -0,0 +1,68 @@
+#!/bin/bash
+# 上传到项目通道:串行 + STS 自动续期 + 逐文件真实校验
+set -u
+SITE=/opt/data/projects/hardware-lab/site
+LOG=/opt/data/projects/hardware-lab/logs/upload-final.log
+OBS=/opt/data/bin/obsutil
+BUCKET="obs://nova-cloud/dev/GvsWkfZb36"
+: > "$LOG"
+
+refresh_sts() {
+  local ST
+  ST=$(python3 -c "import json;print(json.load(open('/opt/data/.fmode/config.json'))['sessionToken'])")
+  curl -s --max-time 25 -X POST "https://server.fmode.cn/api/apig/deploy/huaweicloud" \
+    -H "Content-Type: application/json" \
+    -d "{\"token\":\"$ST\",\"projectId\":\"GvsWkfZb36\"}" > /tmp/sts.json
+  python3 -c "
+import json
+d=json.load(open('/tmp/sts.json'))['data']
+print(f\"AK='{d['accessKey']}'\nSK='{d['secretKey']}'\nTK='{d['securityToken']}'\")
+" > /tmp/proj_env.sh
+  source /tmp/proj_env.sh
+}
+
+mime() {
+  case "${1##*.}" in
+    html|htm) echo "text/html; charset=utf-8" ;;
+    js|mjs)   echo "application/javascript; charset=utf-8" ;;
+    css)      echo "text/css; charset=utf-8" ;;
+    json)     echo "application/json; charset=utf-8" ;;
+    png)      echo "image/png" ;;
+    jpg|jpeg) echo "image/jpeg" ;;
+    svg)      echo "image/svg+xml" ;;
+    webp)     echo "image/webp" ;;
+    woff2)    echo "font/woff2" ;;
+    *)        echo "application/octet-stream" ;;
+  esac
+}
+
+refresh_sts
+echo "STS 已获取" >> "$LOG"
+
+cd "$SITE" || exit 1
+count=0; failn=0
+while IFS= read -r f; do
+  rel="${f#./}"
+  ct=$(mime "$rel")
+  ok=0
+  for try in 1 2; do
+    if "$OBS" cp "$f" "$BUCKET/$rel" -i="$AK" -k="$SK" -t="$TK" \
+        -e="obs.cn-south-1.myhuaweicloud.com" -acl=public-read -f \
+        -meta="content-type:$ct" >/dev/null 2>&1; then
+      ok=1; break
+    fi
+    refresh_sts; sleep 1
+  done
+  if [ "$ok" = "1" ]; then
+    echo "OK   $rel" >> "$LOG"; count=$((count+1))
+  else
+    echo "FAIL $rel" >> "$LOG"; failn=$((failn+1))
+  fi
+  # 每 40 个续一次 STS(有效期 1 小时,稳妥起见)
+  if [ $((count % 40)) -eq 0 ] && [ "$count" -gt 0 ]; then
+    refresh_sts
+  fi
+done < <(find . -type f ! -name "*.map" ! -path "./node_modules/*" | sort)
+
+echo "成功: $count / 失败: $failn"
+grep '^FAIL' "$LOG" | head -10