dsh-cad-studio 0.22.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +2 -0
  2. package/client.js +124 -6
  3. package/index.js +394 -90
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -18,6 +18,8 @@ DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**
18
18
  | 运动 | `cad_studio_joint`(revolute/linear)+ `cad_studio_drive` + `cad_studio_explode`,面板拖滑杆看运动 |
19
19
  | 出图 | `cad_studio_drawing` HLR → SVG(主/俯/左/等轴);`cad_studio_sheet` 正式图纸(图框 + 标题栏 + 三视图 + 尺寸,A4/A3/A2,可出 DXF) |
20
20
  | 装配 | `cad_studio_assembly` 多零件实例、`cad_studio_joint` 关节、`cad_studio_mate` 约束(同心/贴合/距离)、`cad_studio_drive` 驱动、`cad_studio_explode` 爆炸图 |
21
+ | 依赖 | `cad_studio_deps` 列出模型的来源 STEP(谁在用、还在不在),`relink` 换路径后原地重建;面板「信息」里能直接填新路径 |
22
+ | 外观 | 面板里改的颜色/显隐/透明度/线框按模型保存(`POST /cad-studio/appearance`),刷新和重启后仍在 |
21
23
  | 其它 | `cad_studio_open`(STEP/STL/BREP/IGES 进来看)、`cad_studio_export`、`cad_studio_measure`、`cad_studio_env` |
22
24
  | 模型清单 | `cad_studio_scene`(`action: list / delete / rename`)——面板里那条列表就是它;探查脚本留下的卡片可以直接删 |
23
25
  | 模型改名 / 复制 | `cad_studio_doc {action:"rename", name, to}` 与 `{action:"duplicate", name, to}`:改名会同步列表里的标题与 `docKey`,复制会得到一条独立的新场景(副本不继承运行历史与撤销栈);两者都可 `cad_studio_undo` 回退 |
package/client.js CHANGED
@@ -1309,12 +1309,22 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1309
1309
  pendingCameraRef.current = saved.camera || null
1310
1310
  return
1311
1311
  }
1312
- const nextVisibility = {}
1313
- for (const inst of scene.instances || []) nextVisibility[inst.name] = true
1314
- setVisibility(nextVisibility)
1315
- setOverrides({ inst: {}, part: {} })
1316
- setOpacities({})
1317
- setWireframes({})
1312
+ // No local memory for this tab: start from whatever the model itself
1313
+ // remembers. Colours and hidden parts are the model's, not the tab's.
1314
+ const savedLook = scene.appearance
1315
+ if (savedLook) {
1316
+ setVisibility(savedLook.visibility || {})
1317
+ setOverrides(savedLook.overrides || { inst: {}, part: {} })
1318
+ setOpacities(savedLook.opacities || {})
1319
+ setWireframes(savedLook.wireframes || {})
1320
+ } else {
1321
+ const nextVisibility = {}
1322
+ for (const inst of scene.instances || []) nextVisibility[inst.name] = true
1323
+ setVisibility(nextVisibility)
1324
+ setOverrides({ inst: {}, part: {} })
1325
+ setOpacities({})
1326
+ setWireframes({})
1327
+ }
1318
1328
  pendingCameraRef.current = null
1319
1329
  }
1320
1330
 
@@ -1561,6 +1571,11 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1561
1571
  // 'models' | 'info' | '' (closed). Same icon again closes it.
1562
1572
  const [panel, setPanel] = useState('')
1563
1573
  useEffect(() => { panelRef.current = panel }, [panel])
1574
+ // Dependencies are only interesting while the info drawer is open, and
1575
+ // they change only when a relink happens — so fetch on open, not on poll.
1576
+ useEffect(() => {
1577
+ if (panel === 'info') loadDeps()
1578
+ }, [panel, payload?.docKey])
1564
1579
  const theme = useTheme()
1565
1580
  // Colour overrides picked by hand in the tree. Two levels, because an
1566
1581
  // assembly can show one part many times: `inst` is one row, `part` is
@@ -1640,6 +1655,30 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1640
1655
  setHistTick((t) => t + 1)
1641
1656
  }, [lookSnap, sceneKey])
1642
1657
 
1658
+ // ---- 外观落盘:颜色 / 显隐 / 透明度 / 线框存回模型 --------------------
1659
+ // The look belongs to the model, not to this tab or this browser session:
1660
+ // a reload, a restart, or another tab on the same model all show the same
1661
+ // colours. Debounced because dragging an opacity slider fires per pixel.
1662
+ const lookSaveTimer = useRef(null)
1663
+ const lookSaveRef = useRef('')
1664
+ useEffect(() => {
1665
+ const key = (payload && (payload.docKey || (payload.assembly && payload.assembly.id ? `asm:${payload.assembly.id}` : ''))) || ''
1666
+ if (!key) return
1667
+ const snap = lookSnap
1668
+ if (snap === lookSaveRef.current) return
1669
+ if (lookSaveTimer.current) clearTimeout(lookSaveTimer.current)
1670
+ lookSaveTimer.current = setTimeout(() => {
1671
+ lookSaveRef.current = snap
1672
+ try {
1673
+ fetch('/cad-studio/appearance', {
1674
+ method: 'POST',
1675
+ headers: { 'content-type': 'application/json' },
1676
+ body: JSON.stringify({ docKey: key, look: JSON.parse(snap) }),
1677
+ }).catch(() => {})
1678
+ } catch (err) { /* a failed save must not break the panel */ }
1679
+ }, 700)
1680
+ }, [lookSnap, payload])
1681
+
1643
1682
  useEffect(() => {
1644
1683
  const onKey = (event) => {
1645
1684
  const key = String(event.key || '').toLowerCase()
@@ -1677,6 +1716,11 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1677
1716
  const [featDraft, setFeatDraft] = useState({})
1678
1717
  const [featAdd, setFeatAdd] = useState(false)
1679
1718
  const [featError, setFeatError] = useState('')
1719
+ // Which files the model is made of (assemblies only), fetched when the
1720
+ // info drawer opens: a moved STEP is invisible until a rebuild fails.
1721
+ const [deps, setDeps] = useState(null)
1722
+ const [relinkFor, setRelinkFor] = useState({})
1723
+ const [relinkNote, setRelinkNote] = useState('')
1680
1724
  // Which document sketch is expanded in the 草图 section.
1681
1725
  const [openSketch, setOpenSketch] = useState('')
1682
1726
  const featTimer = useRef(null)
@@ -1735,6 +1779,31 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1735
1779
  rememberView(tabKey, payloadRef.current)
1736
1780
  showScene(scene, { keepView: true, tabKey })
1737
1781
  }
1782
+ const loadDeps = async () => {
1783
+ try {
1784
+ const res = await fetch(`${ROUTE}/deps`, { headers: { accept: 'application/json' } })
1785
+ if (res.ok) setDeps(await res.json())
1786
+ } catch {}
1787
+ }
1788
+ const doRelink = async (assembly, part) => {
1789
+ const path = (relinkFor[part] ?? '').trim()
1790
+ if (!path) return setRelinkNote('先填新的文件路径')
1791
+ setRelinkNote(`重新读取 ${part}…`)
1792
+ try {
1793
+ const res = await fetch(`${ROUTE}/relink`, {
1794
+ method: 'POST',
1795
+ headers: { 'content-type': 'application/json' },
1796
+ body: JSON.stringify({ assembly, part, path }),
1797
+ })
1798
+ const out = await res.json()
1799
+ if (!out || out.ok === false) return setRelinkNote(String((out && out.error) || `HTTP ${res.status}`))
1800
+ setRelinkNote(`${part} 已指向 ${path}`)
1801
+ await loadDeps()
1802
+ if (out.sceneId) await applyScene(out.sceneId, out.at)
1803
+ } catch (error) {
1804
+ setRelinkNote(String(error?.message ?? error))
1805
+ }
1806
+ }
1738
1807
  const postMotion = async (path, body) => {
1739
1808
  try {
1740
1809
  const res = await fetch(`${ROUTE}${path}`, {
@@ -2407,6 +2476,11 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
2407
2476
  : []
2408
2477
 
2409
2478
  const panelTitle = { parts: '零件', features: '特征', props: '选中项', motion: '运动', view: '视图', models: '模型', info: '信息' }[panel] || ''
2479
+ // The scene carries `asm:<id>` for an assembly, which is how the deps list
2480
+ // is matched to what is on screen.
2481
+ const depsModel = deps && payload && typeof payload.docKey === 'string' && payload.docKey.startsWith('asm:')
2482
+ ? (deps.models || []).find((m) => `asm:${m.assembly}` === payload.docKey) || null
2483
+ : null
2410
2484
  // --- inspector: the properties of the one selected instance ----------
2411
2485
  const pickedInst = payload ? (payload.instances || []).find((i) => i.name === picked) : null
2412
2486
  const pickedPart = pickedInst ? (payload.parts || []).find((p) => p.id === pickedInst.part) : null
@@ -2646,6 +2720,50 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
2646
2720
  h('span', { key: 'v', style: { ...styles.infoVal, maxWidth: '52%', whiteSpace: 'normal' }, title: chk.fix || chk.detail }, chk.ok ? chk.detail : (chk.fix || chk.detail)),
2647
2721
  ])),
2648
2722
  ...(installNode ? [installNode] : []),
2723
+ ...(depsModel ? [
2724
+ h('div', { key: 'deps-head', style: { ...styles.infoRow, marginTop: 6 } }, [
2725
+ h('span', { key: 'k', style: styles.infoKey }, '来源文件'),
2726
+ h('span', { key: 'v', style: { ...styles.infoVal, color: depsModel.missingParts?.length ? '#d9534f' : undefined } },
2727
+ depsModel.missingParts?.length ? `缺 ${depsModel.missingParts.length}` : `${depsModel.files.length} 个`),
2728
+ ]),
2729
+ ...depsModel.files.map((f) => h('div', {
2730
+ key: `dep-${f.part}`,
2731
+ style: { display: 'flex', flexDirection: 'column', gap: 3, padding: '4px 0', borderTop: '1px solid rgba(127,127,127,.16)' },
2732
+ 'data-cad-dep': f.part,
2733
+ }, [
2734
+ h('div', { key: 'row', style: { display: 'flex', alignItems: 'center', gap: 6 } }, [
2735
+ h('span', { key: 'dot', style: styles.guideDot(f.exists, true), 'data-cad-dep-state': f.exists ? 'ok' : 'missing' }),
2736
+ h('span', { key: 'n', style: { ...styles.infoKey, flex: '0 0 auto' } }, f.part),
2737
+ h('span', {
2738
+ key: 'p',
2739
+ style: { ...styles.infoVal, flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', opacity: 0.72, fontSize: 10.5 },
2740
+ title: f.path,
2741
+ }, f.path),
2742
+ ]),
2743
+ f.exists ? null : h('div', { key: 'fix', style: { display: 'flex', gap: 4 } }, [
2744
+ h('input', {
2745
+ key: 'in',
2746
+ type: 'text',
2747
+ placeholder: '新的文件路径…',
2748
+ value: relinkFor[f.part] ?? '',
2749
+ 'data-cad-relink-input': f.part,
2750
+ style: { flex: 1, minWidth: 0, fontSize: 11, padding: '3px 5px', borderRadius: 4, border: '1px solid rgba(127,127,127,.35)', background: 'transparent', color: 'inherit' },
2751
+ onChange: (event) => setRelinkFor((prev) => ({ ...prev, [f.part]: event.target.value })),
2752
+ onKeyDown: (event) => { if (event.key === 'Enter') doRelink(depsModel.assembly, f.part) },
2753
+ }),
2754
+ h('button', {
2755
+ key: 'go',
2756
+ type: 'button',
2757
+ 'data-cad-relink': f.part,
2758
+ style: { flex: '0 0 auto', padding: '2px 8px', fontSize: 11, cursor: 'pointer', borderRadius: 4, border: '1px solid rgba(77,107,254,.5)', background: 'rgba(77,107,254,.16)', color: 'inherit' },
2759
+ onClick: () => doRelink(depsModel.assembly, f.part),
2760
+ }, '重定位'),
2761
+ ]),
2762
+ ])),
2763
+ relinkNote ? h('div', { key: 'note', style: { ...styles.treeHint, whiteSpace: 'normal', paddingTop: 4 }, 'data-cad-relink-note': '1' }, relinkNote) : null,
2764
+ ] : payload && payload.docKey && String(payload.docKey).startsWith('model:')
2765
+ ? [h('div', { key: 'deps-na', style: { ...styles.treeHint, whiteSpace: 'normal', paddingTop: 6 } }, '这个模型是特征建的,没有外部文件依赖')]
2766
+ : []),
2649
2767
  ]
2650
2768
  : null
2651
2769
 
package/index.js CHANGED
@@ -616,6 +616,137 @@ function assembleScene(record) {
616
616
  }
617
617
  }
618
618
 
619
+ /**
620
+ * The saved look of one model: which instances are hidden, their hand-picked
621
+ * colours, per-instance opacity and wireframe. Validated here because the panel
622
+ * posts it straight from the browser — anything malformed is dropped, never
623
+ * stored, so a bad value cannot poison every later load.
624
+ */
625
+ const LOOK_HEX = /^#[0-9a-f]{6}$/i
626
+ function normalizeLook(raw) {
627
+ const src = raw && typeof raw === 'object' ? raw : {}
628
+ const pick = (obj, test, fix) => {
629
+ const out = {}
630
+ let n = 0
631
+ for (const [k, v] of Object.entries(obj && typeof obj === 'object' ? obj : {})) {
632
+ if (n >= 400) break
633
+ const key = String(k).slice(0, 120)
634
+ if (!key || !test(v)) continue
635
+ out[key] = fix(v)
636
+ n += 1
637
+ }
638
+ return out
639
+ }
640
+ const isBool = (v) => typeof v === 'boolean'
641
+ const isHex = (v) => typeof v === 'string' && LOOK_HEX.test(v)
642
+ const isNum = (v) => Number.isFinite(Number(v))
643
+ const ov = src.overrides && typeof src.overrides === 'object' ? src.overrides : {}
644
+ return {
645
+ visibility: pick(src.visibility, isBool, (v) => v),
646
+ overrides: {
647
+ inst: pick(ov.inst, isHex, (v) => v.toLowerCase()),
648
+ part: pick(ov.part, isHex, (v) => v.toLowerCase()),
649
+ },
650
+ opacities: pick(src.opacities, isNum, (v) => Math.min(1, Math.max(0, Number(v)))),
651
+ wireframes: pick(src.wireframes, isBool, (v) => v),
652
+ }
653
+ }
654
+
655
+ /**
656
+ * The assembly script: read each part file once, tessellate it, place one copy
657
+ * per instance. Shared by `cad_studio_assembly` and by a relink, which re-runs
658
+ * it against a corrected path so the model keeps its identity.
659
+ */
660
+ function assemblyScript(parts, instances, target, measure, interference) {
661
+ return `${PRELUDE}
662
+ ` + `
663
+ import os
664
+ _PART_FILES = ${JSON.stringify(parts.map((p) => (p.color ? { name: p.name, path: p.path, color: p.color } : { name: p.name, path: p.path })))}
665
+ _INSTS = ${JSON.stringify(instances.map((i) => ({ name: i.name, part: i.part, at: i.at ?? [0, 0, 0], rot: i.rot ?? [0, 0, 0] })))}
666
+ _TARGET = ${target ? JSON.stringify(target) : 'None'}
667
+
668
+ _shapes = {}
669
+ _parts = []
670
+ for _p in _PART_FILES:
671
+ if not os.path.isfile(_p["path"]):
672
+ raise RuntimeError("part file not found: " + _p["path"])
673
+ _s = Part.Shape()
674
+ _s.read(_p["path"])
675
+ _shapes[_p["name"]] = _s
676
+ _m = _mesh(_s)
677
+ _part = {"id": _p["name"], "verts": _m["verts"], "tris": _m["tris"], "volume": round(_s.Volume, 3)}
678
+ if "color" in _p and _p["color"]:
679
+ _part["color"] = _p["color"]
680
+ _parts.append(_part)
681
+
682
+ _placed = []
683
+ _instances = []
684
+ for _i in _INSTS:
685
+ if _i["part"] not in _shapes:
686
+ raise RuntimeError("instance '" + _i["name"] + "' references unknown part '" + _i["part"] + "'")
687
+ _rx, _ry, _rz = _i["rot"]
688
+ _R = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), _rz) * FreeCAD.Rotation(FreeCAD.Vector(0, 1, 0), _ry) * FreeCAD.Rotation(FreeCAD.Vector(1, 0, 0), _rx)
689
+ _ax = _R.multVec(FreeCAD.Vector(1, 0, 0))
690
+ _ay = _R.multVec(FreeCAD.Vector(0, 1, 0))
691
+ _az = _R.multVec(FreeCAD.Vector(0, 0, 1))
692
+ _rot = [_ax.x, _ay.x, _az.x, _ax.y, _ay.y, _az.y, _ax.z, _ay.z, _az.z]
693
+ _instances.append({"name": _i["name"], "part": _i["part"], "rot": _rot, "translate": [float(c) for c in _i["at"]]})
694
+ _copy = _shapes[_i["part"]].copy()
695
+ _copy.Placement = FreeCAD.Placement(FreeCAD.Vector(*_i["at"]), _R)
696
+ _placed.append(_copy)
697
+
698
+ _MEASURE = ${measure ? 'True' : 'False'}
699
+ _INTERF = ${interference ? 'True' : 'False'}
700
+
701
+ __out = {"ok": True, "instances": len(_instances), "parts": len(_parts),
702
+ "scene": {"parts": _parts, "instances": _instances}}
703
+
704
+ if _MEASURE:
705
+ # Per-instance numbers, so "how big is this part, and does it fit" is one
706
+ # call instead of an export plus a re-import.
707
+ _rows = []
708
+ for _k, _inst in enumerate(_INSTS):
709
+ _s = _placed[_k]
710
+ _bb = _s.BoundBox
711
+ _rows.append({
712
+ "name": _inst["name"], "part": _inst["part"],
713
+ "volume": round(float(_s.Volume), 3), "solids": len(_s.Solids),
714
+ "bounds": {"min": [round(_bb.XMin, 3), round(_bb.YMin, 3), round(_bb.ZMin, 3)],
715
+ "max": [round(_bb.XMax, 3), round(_bb.YMax, 3), round(_bb.ZMax, 3)]},
716
+ })
717
+ _box = Part.makeCompound(_placed).BoundBox
718
+ __out["measure"] = {
719
+ "instances": _rows,
720
+ "totalVolume": round(sum(r["volume"] for r in _rows), 3),
721
+ "bounds": {"min": [round(_box.XMin, 3), round(_box.YMin, 3), round(_box.ZMin, 3)],
722
+ "max": [round(_box.XMax, 3), round(_box.YMax, 3), round(_box.ZMax, 3)]},
723
+ }
724
+
725
+ if _INTERF:
726
+ # Bounding boxes first: a boolean common on every pair of a 30-solid
727
+ # assembly is minutes of work for answers that are mostly zero.
728
+ _pairs = []
729
+ for _i in range(len(_placed)):
730
+ for _j in range(_i + 1, len(_placed)):
731
+ _a, _b = _placed[_i], _placed[_j]
732
+ if not _a.BoundBox.intersect(_b.BoundBox):
733
+ continue
734
+ try:
735
+ _c = _a.common(_b)
736
+ _v = float(_c.Volume) if (_c is not None and not _c.isNull()) else 0.0
737
+ except Exception:
738
+ _v = 0.0
739
+ if _v > 1e-3:
740
+ _pairs.append({"a": _INSTS[_i]["name"], "b": _INSTS[_j]["name"], "volume": round(_v, 3)})
741
+ __out["interference"] = _pairs
742
+ if _TARGET:
743
+ os.makedirs(os.path.dirname(_TARGET) or ".", exist_ok=True)
744
+ Part.makeCompound(_placed).exportStep(_TARGET)
745
+ __out["exported"] = _TARGET
746
+ __out["bytes"] = os.path.getsize(_TARGET)
747
+ `
748
+ }
749
+
619
750
  class FreeCadBridge {
620
751
  constructor(getConfig, log) {
621
752
  this.getConfig = getConfig
@@ -641,6 +772,10 @@ class FreeCadBridge {
641
772
  this.modelsDir = ''
642
773
  /** Every models dir a tool has used (panel posts carry no session). */
643
774
  this.modelsSeen = []
775
+ /** Saved look per model key (`asm:asm-3`, `model:名字`): colours,
776
+ * visibility, opacity, wireframe. Keyed by the model, not the scene id,
777
+ * because every republish makes a fresh scene. */
778
+ this.appearances = {}
644
779
  }
645
780
 
646
781
  /** Remember a models dir: newest first, deduped, bounded. */
@@ -696,9 +831,11 @@ class FreeCadBridge {
696
831
  await mkdir(join(dir, 'scenes'), { recursive: true })
697
832
  // Whatever an earlier process registered stays registered.
698
833
  let prevAssemblies = []
834
+ let prevAppearances = {}
699
835
  try {
700
836
  const prev = JSON.parse(await readFile(join(dir, 'state.json'), 'utf8'))
701
837
  prevAssemblies = Array.isArray(prev.assemblies) ? prev.assemblies : []
838
+ if (prev.appearances && typeof prev.appearances === 'object') prevAppearances = prev.appearances
702
839
  } catch {}
703
840
  // Keep new ids clear of the ones already in use.
704
841
  for (const rec of this.assembleRecords(prevAssemblies).values()) {
@@ -731,6 +868,9 @@ class FreeCadBridge {
731
868
  // Base placements ride along so a restarted process can still drive them
732
869
  // (the meshes stay in the scene file; only placements are small).
733
870
  modelsDir: this.modelsDir ?? '',
871
+ // The saved look outlives the process: merged, so a fresh process that
872
+ // only knows about the models it touched does not wipe the others.
873
+ appearances: { ...prevAppearances, ...this.appearances },
734
874
  modelsDirs: this.modelsSeen.slice(0, 12),
735
875
  // Which session last published: the panel only places its tab in the
736
876
  // sidebar for that session (or one that owns older scenes), so unrelated
@@ -747,6 +887,7 @@ class FreeCadBridge {
747
887
  center: a.center,
748
888
  joints: a.joints.map((j) => ({ id: j.id, instance: j.instance, type: j.type, value: j.value, min: j.min, max: j.max, axis: j.axis, origin: j.origin })),
749
889
  mates: a.mates ?? [],
890
+ spec: a.spec ?? null,
750
891
  explode: a.explode,
751
892
  })),
752
893
  }
@@ -767,6 +908,9 @@ class FreeCadBridge {
767
908
  if (!this.modelsDir && typeof pointer.modelsDir === 'string') this.modelsDir = pointer.modelsDir
768
909
  if (Array.isArray(pointer.modelsDirs)) this.modelsSeen = [...new Set([...this.modelsSeen, ...pointer.modelsDirs.filter((d) => typeof d === 'string' && d)])].slice(0, 12)
769
910
  if (!this.lastSession && typeof pointer.lastSession === 'string') this.lastSession = pointer.lastSession
911
+ if (pointer.appearances && typeof pointer.appearances === 'object') {
912
+ this.appearances = { ...pointer.appearances, ...this.appearances }
913
+ }
770
914
  const disk = Array.isArray(pointer.history) ? pointer.history : []
771
915
  const asmTitles = new Map()
772
916
  for (const a of Array.isArray(pointer.assemblies) ? pointer.assemblies : []) {
@@ -820,6 +964,10 @@ class FreeCadBridge {
820
964
  if (!id && typeof opts.id === 'string' && /^scene-\d+$/.test(opts.id)) id = opts.id
821
965
  if (!id) id = `scene-${++this.seq}`
822
966
  else this.seq = Math.max(this.seq, Number(id.slice('scene-'.length)))
967
+ if (docKey) {
968
+ scene.docKey = docKey
969
+ scene.appearance = this.appearances[docKey] ?? null
970
+ }
823
971
  this.scenes.set(id, scene)
824
972
  // Count what the viewport shows: per-instance totals and only the parts an
825
973
  // instance actually references (a scene may carry unreferenced parts).
@@ -928,13 +1076,37 @@ class FreeCadBridge {
928
1076
  return { ok: true, id: key, title: name }
929
1077
  }
930
1078
 
1079
+ /** Save the look of one model and mirror it into that model's scene file. */
1080
+ async setAppearance(docKey, look) {
1081
+ const key = String(docKey ?? '').trim()
1082
+ if (!key) throw new Error('docKey 必填')
1083
+ const clean = normalizeLook(look)
1084
+ this.appearances[key] = clean
1085
+ const dir = FreeCadBridge.dataDir
1086
+ await mkdir(join(dir, 'scenes'), { recursive: true })
1087
+ for (const row of this.history) {
1088
+ if (row.docKey !== key) continue
1089
+ const file = join(dir, 'scenes', `${row.id}.json`)
1090
+ let scene = this.scenes.get(row.id)
1091
+ if (!scene) {
1092
+ try { scene = JSON.parse(await readFile(file, 'utf8')) } catch { continue }
1093
+ this.scenes.set(row.id, scene)
1094
+ }
1095
+ scene.docKey = key
1096
+ scene.appearance = clean
1097
+ try { await writeFile(file, JSON.stringify(scene), 'utf8') } catch {}
1098
+ }
1099
+ await this.persist()
1100
+ return clean
1101
+ }
1102
+
931
1103
  /** Reserve the id before publishing, so the scene can carry `asm:<id>`. */
932
1104
  reserveAssemblyId() {
933
1105
  return `asm-${++this.assemblySeq}`
934
1106
  }
935
1107
 
936
1108
  /** Register the base placements of a published assembly so joints can move it. */
937
- registerAssembly({ title, sceneId, scene, joints, id: givenId }) {
1109
+ registerAssembly({ title, sceneId, scene, joints, id: givenId, spec = null }) {
938
1110
  const id = givenId ?? `asm-${++this.assemblySeq}`
939
1111
  const seq = /^asm-(\d+)$/.exec(id)
940
1112
  if (seq) this.assemblySeq = Math.max(this.assemblySeq, Number(seq[1]))
@@ -953,12 +1125,38 @@ class FreeCadBridge {
953
1125
  center: bboxCenterOfInstances(scene.parts, scene.instances),
954
1126
  joints: joints ?? [],
955
1127
  mates: [],
1128
+ // What was asked for (part files + placements), so a relink can re-run the
1129
+ // same build against a corrected path.
1130
+ spec: spec ?? null,
956
1131
  explode: 0,
957
1132
  }
958
1133
  this.assemblies.set(id, record)
959
1134
  return record
960
1135
  }
961
1136
 
1137
+ /** Replace the parts/placements of an existing assembly, keeping its joints,
1138
+ * mates and saved look. Re-running `cad_studio_assembly` with `assembly` uses
1139
+ * this: the model keeps its identity while its geometry changes. */
1140
+ rebaseAssembly(record, { title, sceneId, scene }) {
1141
+ record.title = title ?? record.title
1142
+ record.sceneId = sceneId
1143
+ record.parts = scene.parts
1144
+ record.base = scene.instances.map((inst) => ({
1145
+ name: inst.name,
1146
+ part: inst.part,
1147
+ rot: inst.rot.slice(),
1148
+ translate: inst.translate.slice(),
1149
+ center: instanceCenter(scene.parts, inst),
1150
+ }))
1151
+ record.center = bboxCenterOfInstances(scene.parts, scene.instances)
1152
+ // A mate or joint naming an instance that no longer exists would silently
1153
+ // do nothing, so drop those rather than keep dead rows in the panel.
1154
+ const names = new Set(record.base.map((b) => b.name))
1155
+ record.joints = (record.joints ?? []).filter((j) => names.has(j.instance))
1156
+ record.mates = (record.mates ?? []).filter((m) => names.has(m.a) && names.has(m.b))
1157
+ return record
1158
+ }
1159
+
962
1160
  setJoint(record, spec) {
963
1161
  const value = normalizeJoint(record, spec)
964
1162
  const existing = record.joints.find((j) => j.id === spec.id)
@@ -1119,6 +1317,24 @@ class FreeCadBridge {
1119
1317
  * scene file (geometry never changes when a joint moves, so any scene of
1120
1318
  * this assembly carries the right parts).
1121
1319
  */
1320
+ /** Load every assembly the pointer knows about. Assembly records are otherwise
1321
+ * lazy (they load when a tool or route names one), so a dependency listing
1322
+ * would show an empty table after a restart without this. */
1323
+ async hydrateAssemblies() {
1324
+ let pointer
1325
+ try {
1326
+ pointer = JSON.parse(await readFile(join(FreeCadBridge.dataDir, 'state.json'), 'utf8'))
1327
+ } catch {
1328
+ return this.assemblies
1329
+ }
1330
+ for (const meta of Array.isArray(pointer.assemblies) ? pointer.assemblies : []) {
1331
+ if (meta?.id && !this.assemblies.has(meta.id)) {
1332
+ try { await this.loadAssembly(meta.id) } catch {}
1333
+ }
1334
+ }
1335
+ return this.assemblies
1336
+ }
1337
+
1122
1338
  async loadAssembly(id) {
1123
1339
  if (id && this.assemblies.has(id)) return this.assemblies.get(id)
1124
1340
  let pointer
@@ -1888,7 +2104,7 @@ if _EXPORT:
1888
2104
  */
1889
2105
  const BRIDGE_API = [
1890
2106
  'run', 'publishScene', 'hydrateHistory', 'registerAssembly', 'loadAssembly',
1891
- 'setJoint', 'driveJoint', 'setExplode', 'republishAssembly', 'status', 'refresh',
2107
+ 'setJoint', 'driveJoint', 'setExplode', 'republishAssembly', 'hydrateAssemblies', 'status', 'refresh',
1892
2108
  ]
1893
2109
 
1894
2110
  function sharedState(resolved, logger) {
@@ -3201,101 +3417,34 @@ else:
3201
3417
  const missing = [...referenced].filter((name) => !parts.some((p) => p.name === name))
3202
3418
  if (missing.length) return { ok: false, error: `instances reference unknown parts: ${missing.slice(0, 5).join(', ')}` }
3203
3419
  const used = parts.filter((p) => referenced.has(p.name))
3204
- const py = `${PRELUDE}
3205
- import os
3206
- _PART_FILES = ${JSON.stringify(used.map((p) => (p.color ? { name: p.name, path: p.path, color: p.color } : { name: p.name, path: p.path })))}
3207
- _INSTS = ${JSON.stringify(instances.map((i) => ({ name: i.name, part: i.part, at: i.at ?? [0, 0, 0], rot: i.rot ?? [0, 0, 0] })))}
3208
- _TARGET = ${target ? JSON.stringify(target) : 'None'}
3209
-
3210
- _shapes = {}
3211
- _parts = []
3212
- for _p in _PART_FILES:
3213
- if not os.path.isfile(_p["path"]):
3214
- raise RuntimeError("part file not found: " + _p["path"])
3215
- _s = Part.Shape()
3216
- _s.read(_p["path"])
3217
- _shapes[_p["name"]] = _s
3218
- _m = _mesh(_s)
3219
- _part = {"id": _p["name"], "verts": _m["verts"], "tris": _m["tris"], "volume": round(_s.Volume, 3)}
3220
- if "color" in _p and _p["color"]:
3221
- _part["color"] = _p["color"]
3222
- _parts.append(_part)
3223
-
3224
- _placed = []
3225
- _instances = []
3226
- for _i in _INSTS:
3227
- if _i["part"] not in _shapes:
3228
- raise RuntimeError("instance '" + _i["name"] + "' references unknown part '" + _i["part"] + "'")
3229
- _rx, _ry, _rz = _i["rot"]
3230
- _R = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), _rz) * FreeCAD.Rotation(FreeCAD.Vector(0, 1, 0), _ry) * FreeCAD.Rotation(FreeCAD.Vector(1, 0, 0), _rx)
3231
- _ax = _R.multVec(FreeCAD.Vector(1, 0, 0))
3232
- _ay = _R.multVec(FreeCAD.Vector(0, 1, 0))
3233
- _az = _R.multVec(FreeCAD.Vector(0, 0, 1))
3234
- _rot = [_ax.x, _ay.x, _az.x, _ax.y, _ay.y, _az.y, _ax.z, _ay.z, _az.z]
3235
- _instances.append({"name": _i["name"], "part": _i["part"], "rot": _rot, "translate": [float(c) for c in _i["at"]]})
3236
- _copy = _shapes[_i["part"]].copy()
3237
- _copy.Placement = FreeCAD.Placement(FreeCAD.Vector(*_i["at"]), _R)
3238
- _placed.append(_copy)
3239
-
3240
- _MEASURE = ${measure ? 'True' : 'False'}
3241
- _INTERF = ${interference ? 'True' : 'False'}
3242
-
3243
- __out = {"ok": True, "instances": len(_instances), "parts": len(_parts),
3244
- "scene": {"parts": _parts, "instances": _instances}}
3245
-
3246
- if _MEASURE:
3247
- # Per-instance numbers, so "how big is this part, and does it fit" is one
3248
- # call instead of an export plus a re-import.
3249
- _rows = []
3250
- for _k, _inst in enumerate(_INSTS):
3251
- _s = _placed[_k]
3252
- _bb = _s.BoundBox
3253
- _rows.append({
3254
- "name": _inst["name"], "part": _inst["part"],
3255
- "volume": round(float(_s.Volume), 3), "solids": len(_s.Solids),
3256
- "bounds": {"min": [round(_bb.XMin, 3), round(_bb.YMin, 3), round(_bb.ZMin, 3)],
3257
- "max": [round(_bb.XMax, 3), round(_bb.YMax, 3), round(_bb.ZMax, 3)]},
3258
- })
3259
- _box = Part.makeCompound(_placed).BoundBox
3260
- __out["measure"] = {
3261
- "instances": _rows,
3262
- "totalVolume": round(sum(r["volume"] for r in _rows), 3),
3263
- "bounds": {"min": [round(_box.XMin, 3), round(_box.YMin, 3), round(_box.ZMin, 3)],
3264
- "max": [round(_box.XMax, 3), round(_box.YMax, 3), round(_box.ZMax, 3)]},
3265
- }
3266
-
3267
- if _INTERF:
3268
- # Bounding boxes first: a boolean common on every pair of a 30-solid
3269
- # assembly is minutes of work for answers that are mostly zero.
3270
- _pairs = []
3271
- for _i in range(len(_placed)):
3272
- for _j in range(_i + 1, len(_placed)):
3273
- _a, _b = _placed[_i], _placed[_j]
3274
- if not _a.BoundBox.intersect(_b.BoundBox):
3275
- continue
3276
- try:
3277
- _c = _a.common(_b)
3278
- _v = float(_c.Volume) if (_c is not None and not _c.isNull()) else 0.0
3279
- except Exception:
3280
- _v = 0.0
3281
- if _v > 1e-3:
3282
- _pairs.append({"a": _INSTS[_i]["name"], "b": _INSTS[_j]["name"], "volume": round(_v, 3)})
3283
- __out["interference"] = _pairs
3284
- if _TARGET:
3285
- os.makedirs(os.path.dirname(_TARGET) or ".", exist_ok=True)
3286
- Part.makeCompound(_placed).exportStep(_TARGET)
3287
- __out["exported"] = _TARGET
3288
- __out["bytes"] = os.path.getsize(_TARGET)
3289
- `
3420
+ const py = assemblyScript(used, instances, target, measure, interference)
3290
3421
  // Allocate the assembly id before publishing: the scene carries `asm:<id>`
3291
3422
  // so later joint moves rewrite this same entry instead of adding one.
3292
- const asmId = bridge.reserveAssemblyId()
3423
+ // Re-running with `assembly` rebuilds THAT assembly in place: same id, so
3424
+ // its joints, mates and saved look survive a change to the parts.
3425
+ // `assembly` is an id when it looks like one (`asm-3`) and a display name
3426
+ // otherwise — older callers passed a title here.
3427
+ let reuse = null
3428
+ if (assembly && /^asm-\d+$/.test(String(assembly))) {
3429
+ try { reuse = await bridge.loadAssembly(String(assembly)) } catch {}
3430
+ if (!reuse) return { ok: false, error: `没有这个装配:${assembly}` }
3431
+ }
3432
+ const asmId = reuse ? reuse.id : bridge.reserveAssemblyId()
3293
3433
  const out = await bridge.run(py, { title: title ?? 'assembly', docKey: `asm:${asmId}` })
3294
3434
  if (!out.ok || !out.sceneId) return out
3295
3435
  // Keep the base placements: without them a joint has nothing to move.
3296
3436
  const scene = bridge.scenes.get(out.sceneId)
3297
3437
  if (!scene) return out
3298
- const record = bridge.registerAssembly({ id: asmId, title: assembly || title || 'assembly', sceneId: out.sceneId, scene, joints: [] })
3438
+ const record = reuse
3439
+ ? bridge.rebaseAssembly(reuse, { title: title || reuse.title, sceneId: out.sceneId, scene })
3440
+ : bridge.registerAssembly({
3441
+ id: asmId,
3442
+ title: assembly || title || 'assembly',
3443
+ sceneId: out.sceneId,
3444
+ scene,
3445
+ joints: [],
3446
+ spec: { parts: used.map((p) => ({ name: p.name, path: p.path, ...(p.color ? { color: p.color } : {}) })), instances },
3447
+ })
3299
3448
  for (const spec of joints ?? []) {
3300
3449
  try {
3301
3450
  bridge.setJoint(record, spec)
@@ -3335,6 +3484,118 @@ if _TARGET:
3335
3484
  return all[all.length - 1]
3336
3485
  }
3337
3486
 
3487
+ // ---- Dependencies: which files a model is made of, and relinking them ---
3488
+ // An assembly stores the part files it read. Moving or re-exporting a STEP
3489
+ // breaks the next rebuild, and the failure only surfaces deep in a Python
3490
+ // traceback, so the files are listed with their state and can be repointed.
3491
+
3492
+ const specRows = (record) => (record.spec?.parts ?? []).map((p) => {
3493
+ let exists = false
3494
+ let bytes = 0
3495
+ let modified = ''
3496
+ try {
3497
+ const st = statSync(p.path)
3498
+ exists = st.isFile()
3499
+ bytes = st.size
3500
+ modified = new Date(st.mtimeMs).toISOString()
3501
+ } catch {}
3502
+ return {
3503
+ part: p.name,
3504
+ path: p.path,
3505
+ exists,
3506
+ bytes,
3507
+ modified,
3508
+ color: Array.isArray(p.color) ? p.color : null,
3509
+ instances: (record.spec?.instances ?? []).filter((i) => i.part === p.name).map((i) => i.name),
3510
+ }
3511
+ })
3512
+
3513
+ // relink: swap one part's file, then re-run the same build so the model keeps
3514
+ // its id, joints, mates and saved look. Shared by the tool and the panel route.
3515
+ // relink: swap one part's file, then re-run the same build so the model keeps
3516
+ // its id, joints, mates and saved look. Shared by the tool and the panel route.
3517
+ const relinkPart = async ({ assembly, part, path }) => {
3518
+ let record
3519
+ try { record = findAssembly(assembly) } catch (error) { return { ok: false, error: String(error?.message ?? error) } }
3520
+ if (!record.spec) return { ok: false, error: `${record.id} 没有记录来源文件(不是用 cad_studio_assembly 建的)` }
3521
+ const name = String(part ?? '').trim()
3522
+ const next = String(path ?? '').trim()
3523
+ if (!name) return { ok: false, error: 'relink 需要 part(零件名)' }
3524
+ if (!next) return { ok: false, error: 'relink 需要 path(新的文件路径)' }
3525
+ const idx = record.spec.parts.findIndex((p) => p.name === name)
3526
+ if (idx < 0) return { ok: false, error: `这个装配里没有零件:${name}(有 ${record.spec.parts.map((p) => p.name).join(', ')})` }
3527
+ if (!existsSync(next)) return { ok: false, error: `文件不存在:${next}` }
3528
+ const before = { ...record.spec.parts[idx] }
3529
+ record.spec.parts[idx] = { ...before, path: next }
3530
+ const py = assemblyScript(record.spec.parts, record.spec.instances, '', false, false)
3531
+ const out = await bridge.run(py, { title: record.title, docKey: `asm:${record.id}` })
3532
+ if (!out.ok || !out.sceneId) {
3533
+ record.spec.parts[idx] = before // a bad file must not leave the model pointing at it
3534
+ return { ok: false, error: out.error ?? '重新读取文件失败', stderr: out.stderr ?? '' }
3535
+ }
3536
+ const scene = bridge.scenes.get(out.sceneId)
3537
+ if (!scene) {
3538
+ record.spec.parts[idx] = before
3539
+ return { ok: false, error: '重新读取后没有拿到场景' }
3540
+ }
3541
+ bridge.rebaseAssembly(record, { title: record.title, sceneId: out.sceneId, scene })
3542
+ const published = await bridge.republishAssembly(record)
3543
+ return {
3544
+ ok: true,
3545
+ assembly: record.id,
3546
+ sceneId: published.id,
3547
+ part: name,
3548
+ from: before.path,
3549
+ to: next,
3550
+ instances: record.spec.instances.length,
3551
+ volume: round6(Number(scene.parts.find((p) => p.id === name)?.volume ?? 0)),
3552
+ missingParts: specRows(record).filter((f) => !f.exists).map((f) => f.part),
3553
+ }
3554
+ }
3555
+
3556
+ tool({
3557
+ name: 'cad_studio_deps',
3558
+ description: 'List the part files a model was built from (existence, size, mtime, which instances use each) or repoint one of them with relink and rebuild the model in place. Only assemblies record their sources; a feature-built part has none.',
3559
+ parameters: {
3560
+ type: 'object',
3561
+ properties: {
3562
+ action: { type: 'string', enum: ['list', 'relink'], description: 'Default: list.' },
3563
+ assembly: { type: 'string', description: 'Assembly id (asm-1) or unique title. Omitted: every assembly for `list`, newest for `relink`.' },
3564
+ part: { type: 'string', description: 'Part name to repoint (relink).' },
3565
+ path: { type: 'string', description: 'New file path for that part (relink).' },
3566
+ },
3567
+ additionalProperties: false,
3568
+ },
3569
+ output: {
3570
+ schema: { type: 'object', properties: { ok: { type: 'boolean' }, models: { type: 'array' }, missing: { type: 'number' } } },
3571
+ render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
3572
+ },
3573
+ execute: async ({ action, assembly, part, path }) => {
3574
+ const mode = action ?? 'list'
3575
+ if (mode === 'list') {
3576
+ if (!assembly) await bridge.hydrateAssemblies()
3577
+ const records = assembly
3578
+ ? [(() => { try { return findAssembly(assembly) } catch { return null } })()].filter(Boolean)
3579
+ : [...bridge.assemblies.values()]
3580
+ if (!records.length) return { ok: false, error: assembly ? `没有这个装配:${assembly}` : '还没有装配' }
3581
+ const models = records.map((r) => {
3582
+ const files = specRows(r)
3583
+ return {
3584
+ assembly: r.id,
3585
+ title: r.title,
3586
+ sceneId: r.sceneId,
3587
+ tracked: Boolean(r.spec),
3588
+ files,
3589
+ missingParts: files.filter((f) => !f.exists).map((f) => f.part),
3590
+ }
3591
+ })
3592
+ const missing = models.reduce((n, m) => n + m.missingParts.length, 0)
3593
+ return { ok: true, models, missing }
3594
+ }
3595
+ return relinkPart({ assembly, part, path })
3596
+ },
3597
+ })
3598
+
3338
3599
  tool({
3339
3600
  name: 'cad_studio_joint',
3340
3601
  description: 'Declare, list or remove joints on a published assembly. A revolute joint rotates its instance about (axis, origin); a linear joint slides it along axis. Driving a joint republishes the scene.',
@@ -4622,6 +4883,49 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
4622
4883
  try { return JSON.parse(raw) } catch { return null }
4623
4884
  }
4624
4885
 
4886
+ if (url.pathname === `${ROUTE_PREFIX}/appearance` && req.method === 'POST') {
4887
+ // Colours / visibility picked by hand in the panel: stored per model so
4888
+ // a reload or a restart shows the same look.
4889
+ const body = await bodyOf()
4890
+ if (!body || typeof body.docKey !== 'string' || !body.docKey) return send(400, JSON.stringify({ error: 'bad request' }))
4891
+ try {
4892
+ const saved = await bridge.setAppearance(body.docKey, body.look ?? body.appearance ?? {})
4893
+ return send(200, JSON.stringify({ ok: true, docKey: body.docKey, appearance: saved }))
4894
+ } catch (error) {
4895
+ return send(200, JSON.stringify({ ok: false, error: String(error?.message ?? error) }))
4896
+ }
4897
+ }
4898
+ if (url.pathname === `${ROUTE_PREFIX}/deps`) {
4899
+ // What the panel shows under "来源文件": which STEP each part came from
4900
+ // and whether it is still there.
4901
+ const records = [...(await bridge.hydrateAssemblies()).values()]
4902
+ const models = records.map((r) => {
4903
+ const files = (r.spec?.parts ?? []).map((p) => {
4904
+ let exists = false
4905
+ let bytes = 0
4906
+ let modified = ''
4907
+ try {
4908
+ const st = statSync(p.path)
4909
+ exists = st.isFile()
4910
+ bytes = st.size
4911
+ modified = new Date(st.mtimeMs).toISOString()
4912
+ } catch {}
4913
+ return { part: p.name, path: p.path, exists, bytes, modified }
4914
+ })
4915
+ return { assembly: r.id, title: r.title, tracked: Boolean(r.spec), files, missingParts: files.filter((f) => !f.exists).map((f) => f.part) }
4916
+ })
4917
+ return send(200, JSON.stringify({ ok: true, models }))
4918
+ }
4919
+ if (url.pathname === `${ROUTE_PREFIX}/relink` && req.method === 'POST') {
4920
+ const body = await bodyOf()
4921
+ if (!body || typeof body.part !== 'string' || typeof body.path !== 'string') return send(400, JSON.stringify({ error: 'bad request' }))
4922
+ try {
4923
+ const out = await relinkPart({ assembly: body.assembly, part: body.part, path: body.path })
4924
+ return send(200, JSON.stringify(out))
4925
+ } catch (error) {
4926
+ return send(200, JSON.stringify({ ok: false, error: String(error?.message ?? error) }))
4927
+ }
4928
+ }
4625
4929
  if (url.pathname === `${ROUTE_PREFIX}/doctor`) {
4626
4930
  bridge.refresh()
4627
4931
  return send(200, JSON.stringify(diagnose(bridge, resolved)))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cad-studio",
3
- "version": "0.22.0",
3
+ "version": "0.24.0",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {