dsh-cad-studio 0.23.0 → 0.25.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.
- package/README.md +2 -0
- package/client.js +84 -0
- package/index.js +507 -89
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -18,11 +18,13 @@ 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` 换路径后原地重建;面板「信息」里能直接填新路径 |
|
|
21
22
|
| 外观 | 面板里改的颜色/显隐/透明度/线框按模型保存(`POST /cad-studio/appearance`),刷新和重启后仍在 |
|
|
22
23
|
| 其它 | `cad_studio_open`(STEP/STL/BREP/IGES 进来看)、`cad_studio_export`、`cad_studio_measure`、`cad_studio_env` |
|
|
23
24
|
| 模型清单 | `cad_studio_scene`(`action: list / delete / rename`)——面板里那条列表就是它;探查脚本留下的卡片可以直接删 |
|
|
24
25
|
| 模型改名 / 复制 | `cad_studio_doc {action:"rename", name, to}` 与 `{action:"duplicate", name, to}`:改名会同步列表里的标题与 `docKey`,复制会得到一条独立的新场景(副本不继承运行历史与撤销栈);两者都可 `cad_studio_undo` 回退 |
|
|
25
26
|
| 几何自检 | `cad_studio_check {source}` 在导出/打印前问一次:是否有效实体、外壳是否闭合、每个实体体积多少,返回中文问题清单(零体积 / 外壳未闭合 / 几何无效 / 没有实体) |
|
|
27
|
+
| 展开图 | `cad_studio_unfold {source, target:"…/net.dxf"}` 把板类零件按共享边摊平成下料图(面片等距铺开,面积与模型一致;孔各自成环;圆柱/圆角等曲面报 `curvedSkipped` 而不是瞎编),可写 DXF 或 SVG |
|
|
26
28
|
| 打印网格 | `cad_studio_mesh {source, target:"…/x.stl"}` 三角化 + 去重合并点/面、修形变、统一法向,可选 `fillHoles`、`targetSize`(减面);回报修复前后的 facets/points,避免「导出成功但网格是碎的」 |
|
|
27
29
|
| 旋转体与凹槽 | `revolve` 的 `axis` 取草图平面内的轴(`"Y"` 或 `[0,1,0]`)才是实体;垂直轴(XY 草图的 Z)只会扫出零厚度圆环,插件会直接报错。凹槽=`{kind:"cut", with:{kind:"revolve", …}}`,不需要单独 op |
|
|
28
30
|
| 面板改草图 | 特征抽屉里点「草图 N」展开:数值约束是可编辑输入框(`distance*`/`radius`/`angle` 按度),改完立刻重解并重建;解不出来就回滚并报错 |
|
package/client.js
CHANGED
|
@@ -1571,6 +1571,11 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
|
|
|
1571
1571
|
// 'models' | 'info' | '' (closed). Same icon again closes it.
|
|
1572
1572
|
const [panel, setPanel] = useState('')
|
|
1573
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])
|
|
1574
1579
|
const theme = useTheme()
|
|
1575
1580
|
// Colour overrides picked by hand in the tree. Two levels, because an
|
|
1576
1581
|
// assembly can show one part many times: `inst` is one row, `part` is
|
|
@@ -1711,6 +1716,11 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
|
|
|
1711
1716
|
const [featDraft, setFeatDraft] = useState({})
|
|
1712
1717
|
const [featAdd, setFeatAdd] = useState(false)
|
|
1713
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('')
|
|
1714
1724
|
// Which document sketch is expanded in the 草图 section.
|
|
1715
1725
|
const [openSketch, setOpenSketch] = useState('')
|
|
1716
1726
|
const featTimer = useRef(null)
|
|
@@ -1769,6 +1779,31 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
|
|
|
1769
1779
|
rememberView(tabKey, payloadRef.current)
|
|
1770
1780
|
showScene(scene, { keepView: true, tabKey })
|
|
1771
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
|
+
}
|
|
1772
1807
|
const postMotion = async (path, body) => {
|
|
1773
1808
|
try {
|
|
1774
1809
|
const res = await fetch(`${ROUTE}${path}`, {
|
|
@@ -2441,6 +2476,11 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
|
|
|
2441
2476
|
: []
|
|
2442
2477
|
|
|
2443
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
|
|
2444
2484
|
// --- inspector: the properties of the one selected instance ----------
|
|
2445
2485
|
const pickedInst = payload ? (payload.instances || []).find((i) => i.name === picked) : null
|
|
2446
2486
|
const pickedPart = pickedInst ? (payload.parts || []).find((p) => p.id === pickedInst.part) : null
|
|
@@ -2680,6 +2720,50 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
|
|
|
2680
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)),
|
|
2681
2721
|
])),
|
|
2682
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
|
+
: []),
|
|
2683
2767
|
]
|
|
2684
2768
|
: null
|
|
2685
2769
|
|
package/index.js
CHANGED
|
@@ -652,6 +652,101 @@ function normalizeLook(raw) {
|
|
|
652
652
|
}
|
|
653
653
|
}
|
|
654
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
|
+
|
|
655
750
|
class FreeCadBridge {
|
|
656
751
|
constructor(getConfig, log) {
|
|
657
752
|
this.getConfig = getConfig
|
|
@@ -792,6 +887,7 @@ class FreeCadBridge {
|
|
|
792
887
|
center: a.center,
|
|
793
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 })),
|
|
794
889
|
mates: a.mates ?? [],
|
|
890
|
+
spec: a.spec ?? null,
|
|
795
891
|
explode: a.explode,
|
|
796
892
|
})),
|
|
797
893
|
}
|
|
@@ -1010,7 +1106,7 @@ class FreeCadBridge {
|
|
|
1010
1106
|
}
|
|
1011
1107
|
|
|
1012
1108
|
/** Register the base placements of a published assembly so joints can move it. */
|
|
1013
|
-
registerAssembly({ title, sceneId, scene, joints, id: givenId }) {
|
|
1109
|
+
registerAssembly({ title, sceneId, scene, joints, id: givenId, spec = null }) {
|
|
1014
1110
|
const id = givenId ?? `asm-${++this.assemblySeq}`
|
|
1015
1111
|
const seq = /^asm-(\d+)$/.exec(id)
|
|
1016
1112
|
if (seq) this.assemblySeq = Math.max(this.assemblySeq, Number(seq[1]))
|
|
@@ -1029,6 +1125,9 @@ class FreeCadBridge {
|
|
|
1029
1125
|
center: bboxCenterOfInstances(scene.parts, scene.instances),
|
|
1030
1126
|
joints: joints ?? [],
|
|
1031
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,
|
|
1032
1131
|
explode: 0,
|
|
1033
1132
|
}
|
|
1034
1133
|
this.assemblies.set(id, record)
|
|
@@ -1218,6 +1317,24 @@ class FreeCadBridge {
|
|
|
1218
1317
|
* scene file (geometry never changes when a joint moves, so any scene of
|
|
1219
1318
|
* this assembly carries the right parts).
|
|
1220
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
|
+
|
|
1221
1338
|
async loadAssembly(id) {
|
|
1222
1339
|
if (id && this.assemblies.has(id)) return this.assemblies.get(id)
|
|
1223
1340
|
let pointer
|
|
@@ -1987,7 +2104,7 @@ if _EXPORT:
|
|
|
1987
2104
|
*/
|
|
1988
2105
|
const BRIDGE_API = [
|
|
1989
2106
|
'run', 'publishScene', 'hydrateHistory', 'registerAssembly', 'loadAssembly',
|
|
1990
|
-
'setJoint', 'driveJoint', 'setExplode', 'republishAssembly', 'status', 'refresh',
|
|
2107
|
+
'setJoint', 'driveJoint', 'setExplode', 'republishAssembly', 'hydrateAssemblies', 'status', 'refresh',
|
|
1991
2108
|
]
|
|
1992
2109
|
|
|
1993
2110
|
function sharedState(resolved, logger) {
|
|
@@ -3036,6 +3153,242 @@ __out = {
|
|
|
3036
3153
|
},
|
|
3037
3154
|
})
|
|
3038
3155
|
|
|
3156
|
+
tool({
|
|
3157
|
+
name: 'cad_studio_unfold',
|
|
3158
|
+
description: 'Unfold a solid made of flat faces into a 2D net (板金展开): every planar face is laid flat next to the one it shares an edge with, without stretching — a net you can cut and fold. Curved faces (cylinders, fillets, bends) are reported as skipped, not invented. Writes DXF (polylines, mm) or SVG; areas are reported so a net that came out wrong is visible.',
|
|
3159
|
+
parameters: {
|
|
3160
|
+
type: 'object',
|
|
3161
|
+
properties: {
|
|
3162
|
+
source: { type: 'string', description: 'Existing model file (STEP/IGES/BREP).' },
|
|
3163
|
+
code: { type: 'string', description: 'FreeCAD Python that binds `scene` or `export_shapes`.' },
|
|
3164
|
+
target: { type: 'string', description: 'Absolute path: .dxf (polylines) or .svg (outline).' },
|
|
3165
|
+
deflection: { type: 'number', description: 'Curve sampling for the outline, mm (default 0.25).' },
|
|
3166
|
+
holes: { type: 'boolean', description: 'Include inner wires (holes) as separate closed outlines (default true).' },
|
|
3167
|
+
},
|
|
3168
|
+
additionalProperties: false,
|
|
3169
|
+
},
|
|
3170
|
+
output: {
|
|
3171
|
+
schema: { type: 'object', properties: { ok: { type: 'boolean' }, unfolded: { type: 'number' }, areaModel: { type: 'number' }, areaFlat: { type: 'number' }, curvedSkipped: { type: 'number' }, target: { type: 'string' } } },
|
|
3172
|
+
render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
|
|
3173
|
+
},
|
|
3174
|
+
execute: async ({ source, code, target, deflection = 0.25, holes = true }) => {
|
|
3175
|
+
if (!source && !code) return { ok: false, error: 'pass either source (a model file) or code (FreeCAD Python)' }
|
|
3176
|
+
const absTarget = target ? String(target) : ''
|
|
3177
|
+
if (absTarget && !(absTarget.startsWith('/') || /^[A-Za-z]:[\\/]/.test(absTarget))) return { ok: false, error: 'target must be an absolute path' }
|
|
3178
|
+
const src = shapesFrom({ source, code })
|
|
3179
|
+
const py = `${PRELUDE}
|
|
3180
|
+
${src}
|
|
3181
|
+
_DEFL = float(${Number.isFinite(deflection) ? deflection : 0.25})
|
|
3182
|
+
_HOLES = ${holes === false ? 'False' : 'True'}
|
|
3183
|
+
_TARGET = ${absTarget ? JSON.stringify(absTarget) : 'None'}
|
|
3184
|
+
|
|
3185
|
+
import math
|
|
3186
|
+
from FreeCAD import Vector as _V
|
|
3187
|
+
|
|
3188
|
+
def _k(_p):
|
|
3189
|
+
return (round(_p.x, 4), round(_p.y, 4), round(_p.z, 4))
|
|
3190
|
+
|
|
3191
|
+
def _ordered(_wire):
|
|
3192
|
+
"""Vertices of a wire in traversal order (OuterWire.Vertexes is unordered)."""
|
|
3193
|
+
_edges = _wire.Edges
|
|
3194
|
+
if not _edges:
|
|
3195
|
+
return []
|
|
3196
|
+
_pts = [_edges[0].Vertexes[0].Point, _edges[0].Vertexes[-1].Point]
|
|
3197
|
+
_used = {0}
|
|
3198
|
+
while len(_used) < len(_edges):
|
|
3199
|
+
_tail = _pts[-1]; _found = False
|
|
3200
|
+
for _i, _e in enumerate(_edges):
|
|
3201
|
+
if _i in _used: continue
|
|
3202
|
+
_a, _b = _e.Vertexes[0].Point, _e.Vertexes[-1].Point
|
|
3203
|
+
if _k(_a) == _k(_tail): _pts.append(_b); _used.add(_i); _found = True; break
|
|
3204
|
+
if _k(_b) == _k(_tail): _pts.append(_a); _used.add(_i); _found = True; break
|
|
3205
|
+
if not _found: break
|
|
3206
|
+
if len(_pts) > 1 and _k(_pts[0]) == _k(_pts[-1]): _pts.pop()
|
|
3207
|
+
return _pts
|
|
3208
|
+
|
|
3209
|
+
def _ordered_edges(_wire):
|
|
3210
|
+
"""Edges of a wire in traversal order, each flagged when it runs backwards."""
|
|
3211
|
+
_edges = list(_wire.Edges)
|
|
3212
|
+
if not _edges:
|
|
3213
|
+
return []
|
|
3214
|
+
_out = [(_edges[0], False)]
|
|
3215
|
+
_used = {0}
|
|
3216
|
+
_tail = _edges[0].Vertexes[-1].Point
|
|
3217
|
+
while len(_used) < len(_edges):
|
|
3218
|
+
_found = False
|
|
3219
|
+
for _i, _e in enumerate(_edges):
|
|
3220
|
+
if _i in _used:
|
|
3221
|
+
continue
|
|
3222
|
+
_a, _b = _e.Vertexes[0].Point, _e.Vertexes[-1].Point
|
|
3223
|
+
if _k(_a) == _k(_tail):
|
|
3224
|
+
_out.append((_e, False)); _used.add(_i); _tail = _b; _found = True; break
|
|
3225
|
+
if _k(_b) == _k(_tail):
|
|
3226
|
+
_out.append((_e, True)); _used.add(_i); _tail = _a; _found = True; break
|
|
3227
|
+
if not _found:
|
|
3228
|
+
break
|
|
3229
|
+
return _out
|
|
3230
|
+
|
|
3231
|
+
def _sample(_wire):
|
|
3232
|
+
"""Outline points in traversal order: endpoints for lines, sampled arcs.
|
|
3233
|
+
|
|
3234
|
+
Wire.Edges comes back unordered, so walking them as given would splice the
|
|
3235
|
+
outline out of order and the shoelace area would come out wrong.
|
|
3236
|
+
"""
|
|
3237
|
+
_out = []
|
|
3238
|
+
for _e, _rev in _ordered_edges(_wire):
|
|
3239
|
+
_c = _e.Curve
|
|
3240
|
+
_straight = isinstance(_c, Part.Line) or isinstance(_c, Part.LineSegment)
|
|
3241
|
+
_pts = list(_e.discretize(Deflection=_DEFL)) if not _straight else [_e.Vertexes[0].Point, _e.Vertexes[-1].Point]
|
|
3242
|
+
if _rev:
|
|
3243
|
+
_pts.reverse()
|
|
3244
|
+
for _p in _pts:
|
|
3245
|
+
if not _out or _k(_out[-1]) != _k(_p):
|
|
3246
|
+
_out.append(_p)
|
|
3247
|
+
if len(_out) > 1 and _k(_out[0]) == _k(_out[-1]):
|
|
3248
|
+
_out.pop()
|
|
3249
|
+
return _out
|
|
3250
|
+
|
|
3251
|
+
def _frame(_f):
|
|
3252
|
+
_n = _f.Surface.Axis.normalize()
|
|
3253
|
+
_c = _f.CenterOfMass
|
|
3254
|
+
_pts = _ordered(_f.OuterWire)
|
|
3255
|
+
if not _pts:
|
|
3256
|
+
return None
|
|
3257
|
+
_u = _pts[0] - _c
|
|
3258
|
+
_u = _u - _n * _u.dot(_n)
|
|
3259
|
+
if _u.Length < 1e-9:
|
|
3260
|
+
return None
|
|
3261
|
+
_u.normalize()
|
|
3262
|
+
return _c, _u, _n.cross(_u)
|
|
3263
|
+
|
|
3264
|
+
def _unfold(_shape):
|
|
3265
|
+
_faces = [_f for _f in _shape.Faces if isinstance(_f.Surface, Part.Plane)]
|
|
3266
|
+
_curved = len(_shape.Faces) - len(_faces)
|
|
3267
|
+
if not _faces:
|
|
3268
|
+
return {"ok": False, "error": "这个形状没有平面:展开只适用于板类零件"}
|
|
3269
|
+
_owner = {}
|
|
3270
|
+
for _fi, _f in enumerate(_faces):
|
|
3271
|
+
for _e in _f.Edges:
|
|
3272
|
+
_ka, _kb = _k(_e.Vertexes[0].Point), _k(_e.Vertexes[-1].Point)
|
|
3273
|
+
_owner.setdefault((_ka, _kb) if _ka <= _kb else (_kb, _ka), []).append(_fi)
|
|
3274
|
+
_root = max(range(len(_faces)), key=lambda i: _faces[i].Area)
|
|
3275
|
+
_fr = _frame(_faces[_root])
|
|
3276
|
+
if _fr is None:
|
|
3277
|
+
return {"ok": False, "error": "最大平面没有可用的局部坐标系"}
|
|
3278
|
+
_c, _u, _v = _fr
|
|
3279
|
+
def _to2(_p):
|
|
3280
|
+
_d = _p - _c
|
|
3281
|
+
return (_d.dot(_u), _d.dot(_v))
|
|
3282
|
+
_pos = {}
|
|
3283
|
+
for _p in _ordered(_faces[_root].OuterWire):
|
|
3284
|
+
_pos[_k(_p)] = _to2(_p)
|
|
3285
|
+
_polys = []
|
|
3286
|
+
def _rings(_f, _map3):
|
|
3287
|
+
# Takes a 3D point to the flat layout: the root face projects with its
|
|
3288
|
+
# own frame, every other face composes that with its hinge placement.
|
|
3289
|
+
_rs = []
|
|
3290
|
+
_wires = _f.Wires if _HOLES else [_f.OuterWire]
|
|
3291
|
+
for _w in _wires:
|
|
3292
|
+
_pts = _sample(_w)
|
|
3293
|
+
if len(_pts) >= 3:
|
|
3294
|
+
_rs.append([_map3(_p) for _p in _pts])
|
|
3295
|
+
return _rs
|
|
3296
|
+
_polys.extend(_rings(_faces[_root], _to2))
|
|
3297
|
+
_seen, _queue, _worst = {_root}, [_root], 0.0
|
|
3298
|
+
while _queue:
|
|
3299
|
+
_cur = _queue.pop(0)
|
|
3300
|
+
_cur2 = [_pos[_k(_p)] for _p in _ordered(_faces[_cur].OuterWire) if _k(_p) in _pos]
|
|
3301
|
+
if not _cur2: continue
|
|
3302
|
+
_cxc = sum(q[0] for q in _cur2) / len(_cur2); _cyc = sum(q[1] for q in _cur2) / len(_cur2)
|
|
3303
|
+
for _e in _faces[_cur].Edges:
|
|
3304
|
+
_a, _b = _e.Vertexes[0].Point, _e.Vertexes[-1].Point
|
|
3305
|
+
_ka, _kb = _k(_a), _k(_b)
|
|
3306
|
+
for _nb in _owner.get((_ka, _kb) if _ka <= _kb else (_kb, _ka), []):
|
|
3307
|
+
if _nb in _seen: continue
|
|
3308
|
+
_ag, _bg = _pos.get(_ka), _pos.get(_kb)
|
|
3309
|
+
if _ag is None or _bg is None: continue
|
|
3310
|
+
_fnb = _frame(_faces[_nb])
|
|
3311
|
+
if _fnb is None: continue
|
|
3312
|
+
_cn, _un, _vn = _fnb
|
|
3313
|
+
def _local(_p, _cn=_cn, _un=_un, _vn=_vn):
|
|
3314
|
+
_d = _p - _cn
|
|
3315
|
+
return (_d.dot(_un), _d.dot(_vn))
|
|
3316
|
+
_la, _lb = _local(_a), _local(_b)
|
|
3317
|
+
_th = math.atan2(_bg[1] - _ag[1], _bg[0] - _ag[0]) - math.atan2(_lb[1] - _la[1], _lb[0] - _la[0])
|
|
3318
|
+
_ct, _st = math.cos(_th), math.sin(_th)
|
|
3319
|
+
def _place(q, _ag=_ag, _la=_la, _ct=_ct, _st=_st):
|
|
3320
|
+
_dx, _dy = q[0] - _la[0], q[1] - _la[1]
|
|
3321
|
+
return (_ag[0] + _ct * _dx - _st * _dy, _ag[1] + _st * _dx + _ct * _dy)
|
|
3322
|
+
# A hinge has exactly two ways to fold flat: pick the one that
|
|
3323
|
+
# puts the new face on the other side of the edge from the face
|
|
3324
|
+
# we are folding from (same side = the two would overlap).
|
|
3325
|
+
_out = _ordered(_faces[_nb].OuterWire)
|
|
3326
|
+
_m = [_place(_local(_p)) for _p in _out]
|
|
3327
|
+
_cx = sum(q[0] for q in _m) / len(_m); _cy = sum(q[1] for q in _m) / len(_m)
|
|
3328
|
+
_sd = (_bg[0] - _ag[0]) * (_cy - _ag[1]) - (_bg[1] - _ag[1]) * (_cx - _ag[0])
|
|
3329
|
+
_sc = (_bg[0] - _ag[0]) * (_cyc - _ag[1]) - (_bg[1] - _ag[1]) * (_cxc - _ag[0])
|
|
3330
|
+
if (_sd > 0) == (_sc > 0):
|
|
3331
|
+
_dhx, _dhy = _bg[0] - _ag[0], _bg[1] - _ag[1]
|
|
3332
|
+
_L = math.hypot(_dhx, _dhy)
|
|
3333
|
+
if _L < 1e-9: continue
|
|
3334
|
+
_dhx, _dhy = _dhx / _L, _dhy / _L
|
|
3335
|
+
def _mirror(q, _ag=_ag, _dhx=_dhx, _dhy=_dhy):
|
|
3336
|
+
_vx, _vy = q[0] - _ag[0], q[1] - _ag[1]
|
|
3337
|
+
_dot = _vx * _dhx + _vy * _dhy
|
|
3338
|
+
return (_ag[0] + 2 * _dot * _dhx - _vx, _ag[1] + 2 * _dot * _dhy - _vy)
|
|
3339
|
+
_place_inner = lambda q: _mirror(_place(q))
|
|
3340
|
+
else:
|
|
3341
|
+
_place_inner = _place
|
|
3342
|
+
_polys.extend(_rings(_faces[_nb], lambda _p, _loc=_local, _pl=_place_inner: _pl(_loc(_p))))
|
|
3343
|
+
_seen.add(_nb); _queue.append(_nb)
|
|
3344
|
+
for _p, _q in zip(_out, [_place_inner(_local(_p)) for _p in _out]):
|
|
3345
|
+
if _k(_p) in _pos:
|
|
3346
|
+
_worst = max(_worst, math.hypot(_pos[_k(_p)][0] - _q[0], _pos[_k(_p)][1] - _q[1]))
|
|
3347
|
+
_pos[_k(_p)] = _q
|
|
3348
|
+
def _area2(_m):
|
|
3349
|
+
return abs(sum((_m[_i][0] * _m[(_i + 1) % len(_m)][1] - _m[(_i + 1) % len(_m)][0] * _m[_i][1]) for _i in range(len(_m)))) / 2.0
|
|
3350
|
+
_flat = sum(_area2(_m) for _m in _polys)
|
|
3351
|
+
_xs = [q[0] for _m in _polys for q in _m]
|
|
3352
|
+
_ys = [q[1] for _m in _polys for q in _m]
|
|
3353
|
+
_out = {"ok": True, "faces": len(_faces), "unfolded": len(_seen), "curvedSkipped": _curved,
|
|
3354
|
+
"areaModel": round(_shape.Area, 3), "areaFlat": round(_flat, 3),
|
|
3355
|
+
"bbox": [round(min(_xs), 3), round(min(_ys), 3), round(max(_xs), 3), round(max(_ys), 3)]}
|
|
3356
|
+
if _TARGET:
|
|
3357
|
+
os.makedirs(os.path.dirname(_TARGET) or ".", exist_ok=True)
|
|
3358
|
+
if _TARGET.lower().endswith(".svg"):
|
|
3359
|
+
_minx, _miny, _maxx, _maxy = _out["bbox"]
|
|
3360
|
+
_w = _maxx - _minx + 10; _h = _maxy - _miny + 10
|
|
3361
|
+
_parts = []
|
|
3362
|
+
for _m in _polys:
|
|
3363
|
+
_d = " ".join("%.3f,%.3f" % (q[0] - _minx + 5, _maxy - q[1] + 5) for q in _m)
|
|
3364
|
+
_parts.append('<polygon points="%s" fill="none" stroke="#111" stroke-width="0.3"/>' % _d)
|
|
3365
|
+
open(_TARGET, "w").write('<svg xmlns="http://www.w3.org/2000/svg" width="%.2fmm" height="%.2fmm" viewBox="0 0 %.2f %.2f">%s</svg>' % (_w, _h, _w, _h, "".join(_parts)))
|
|
3366
|
+
else:
|
|
3367
|
+
_wires = []
|
|
3368
|
+
for _m in _polys:
|
|
3369
|
+
_pts = [Vector(q[0], q[1], 0.0) for q in _m]
|
|
3370
|
+
if len(_pts) >= 3:
|
|
3371
|
+
_pts.append(_pts[0])
|
|
3372
|
+
_wires.append(Part.makePolygon(_pts))
|
|
3373
|
+
import importDXF
|
|
3374
|
+
importDXF.export([Part.makeCompound(_wires)], _TARGET)
|
|
3375
|
+
_out["target"] = _TARGET
|
|
3376
|
+
_out["bytes"] = os.path.getsize(_TARGET)
|
|
3377
|
+
return _out
|
|
3378
|
+
|
|
3379
|
+
_out = None
|
|
3380
|
+
for _s in _shapes:
|
|
3381
|
+
_r = _unfold(_s)
|
|
3382
|
+
if _r.get("ok"):
|
|
3383
|
+
_out = _r
|
|
3384
|
+
break
|
|
3385
|
+
_out = _r
|
|
3386
|
+
__out = _out
|
|
3387
|
+
`
|
|
3388
|
+
return bridge.run(py, { title: 'unfold', publishHint: false })
|
|
3389
|
+
},
|
|
3390
|
+
})
|
|
3391
|
+
|
|
3039
3392
|
tool({
|
|
3040
3393
|
name: 'cad_studio_mesh',
|
|
3041
3394
|
description: 'Turn a solid into a printable mesh and clean it up: dedupe coincident points/facets, fix deformations, harmonize normals, optionally fill small holes or decimate to a facet budget, then write an STL. Reports facets/points before and after so you can see what the repair actually changed.',
|
|
@@ -3300,92 +3653,7 @@ else:
|
|
|
3300
3653
|
const missing = [...referenced].filter((name) => !parts.some((p) => p.name === name))
|
|
3301
3654
|
if (missing.length) return { ok: false, error: `instances reference unknown parts: ${missing.slice(0, 5).join(', ')}` }
|
|
3302
3655
|
const used = parts.filter((p) => referenced.has(p.name))
|
|
3303
|
-
const py =
|
|
3304
|
-
import os
|
|
3305
|
-
_PART_FILES = ${JSON.stringify(used.map((p) => (p.color ? { name: p.name, path: p.path, color: p.color } : { name: p.name, path: p.path })))}
|
|
3306
|
-
_INSTS = ${JSON.stringify(instances.map((i) => ({ name: i.name, part: i.part, at: i.at ?? [0, 0, 0], rot: i.rot ?? [0, 0, 0] })))}
|
|
3307
|
-
_TARGET = ${target ? JSON.stringify(target) : 'None'}
|
|
3308
|
-
|
|
3309
|
-
_shapes = {}
|
|
3310
|
-
_parts = []
|
|
3311
|
-
for _p in _PART_FILES:
|
|
3312
|
-
if not os.path.isfile(_p["path"]):
|
|
3313
|
-
raise RuntimeError("part file not found: " + _p["path"])
|
|
3314
|
-
_s = Part.Shape()
|
|
3315
|
-
_s.read(_p["path"])
|
|
3316
|
-
_shapes[_p["name"]] = _s
|
|
3317
|
-
_m = _mesh(_s)
|
|
3318
|
-
_part = {"id": _p["name"], "verts": _m["verts"], "tris": _m["tris"], "volume": round(_s.Volume, 3)}
|
|
3319
|
-
if "color" in _p and _p["color"]:
|
|
3320
|
-
_part["color"] = _p["color"]
|
|
3321
|
-
_parts.append(_part)
|
|
3322
|
-
|
|
3323
|
-
_placed = []
|
|
3324
|
-
_instances = []
|
|
3325
|
-
for _i in _INSTS:
|
|
3326
|
-
if _i["part"] not in _shapes:
|
|
3327
|
-
raise RuntimeError("instance '" + _i["name"] + "' references unknown part '" + _i["part"] + "'")
|
|
3328
|
-
_rx, _ry, _rz = _i["rot"]
|
|
3329
|
-
_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)
|
|
3330
|
-
_ax = _R.multVec(FreeCAD.Vector(1, 0, 0))
|
|
3331
|
-
_ay = _R.multVec(FreeCAD.Vector(0, 1, 0))
|
|
3332
|
-
_az = _R.multVec(FreeCAD.Vector(0, 0, 1))
|
|
3333
|
-
_rot = [_ax.x, _ay.x, _az.x, _ax.y, _ay.y, _az.y, _ax.z, _ay.z, _az.z]
|
|
3334
|
-
_instances.append({"name": _i["name"], "part": _i["part"], "rot": _rot, "translate": [float(c) for c in _i["at"]]})
|
|
3335
|
-
_copy = _shapes[_i["part"]].copy()
|
|
3336
|
-
_copy.Placement = FreeCAD.Placement(FreeCAD.Vector(*_i["at"]), _R)
|
|
3337
|
-
_placed.append(_copy)
|
|
3338
|
-
|
|
3339
|
-
_MEASURE = ${measure ? 'True' : 'False'}
|
|
3340
|
-
_INTERF = ${interference ? 'True' : 'False'}
|
|
3341
|
-
|
|
3342
|
-
__out = {"ok": True, "instances": len(_instances), "parts": len(_parts),
|
|
3343
|
-
"scene": {"parts": _parts, "instances": _instances}}
|
|
3344
|
-
|
|
3345
|
-
if _MEASURE:
|
|
3346
|
-
# Per-instance numbers, so "how big is this part, and does it fit" is one
|
|
3347
|
-
# call instead of an export plus a re-import.
|
|
3348
|
-
_rows = []
|
|
3349
|
-
for _k, _inst in enumerate(_INSTS):
|
|
3350
|
-
_s = _placed[_k]
|
|
3351
|
-
_bb = _s.BoundBox
|
|
3352
|
-
_rows.append({
|
|
3353
|
-
"name": _inst["name"], "part": _inst["part"],
|
|
3354
|
-
"volume": round(float(_s.Volume), 3), "solids": len(_s.Solids),
|
|
3355
|
-
"bounds": {"min": [round(_bb.XMin, 3), round(_bb.YMin, 3), round(_bb.ZMin, 3)],
|
|
3356
|
-
"max": [round(_bb.XMax, 3), round(_bb.YMax, 3), round(_bb.ZMax, 3)]},
|
|
3357
|
-
})
|
|
3358
|
-
_box = Part.makeCompound(_placed).BoundBox
|
|
3359
|
-
__out["measure"] = {
|
|
3360
|
-
"instances": _rows,
|
|
3361
|
-
"totalVolume": round(sum(r["volume"] for r in _rows), 3),
|
|
3362
|
-
"bounds": {"min": [round(_box.XMin, 3), round(_box.YMin, 3), round(_box.ZMin, 3)],
|
|
3363
|
-
"max": [round(_box.XMax, 3), round(_box.YMax, 3), round(_box.ZMax, 3)]},
|
|
3364
|
-
}
|
|
3365
|
-
|
|
3366
|
-
if _INTERF:
|
|
3367
|
-
# Bounding boxes first: a boolean common on every pair of a 30-solid
|
|
3368
|
-
# assembly is minutes of work for answers that are mostly zero.
|
|
3369
|
-
_pairs = []
|
|
3370
|
-
for _i in range(len(_placed)):
|
|
3371
|
-
for _j in range(_i + 1, len(_placed)):
|
|
3372
|
-
_a, _b = _placed[_i], _placed[_j]
|
|
3373
|
-
if not _a.BoundBox.intersect(_b.BoundBox):
|
|
3374
|
-
continue
|
|
3375
|
-
try:
|
|
3376
|
-
_c = _a.common(_b)
|
|
3377
|
-
_v = float(_c.Volume) if (_c is not None and not _c.isNull()) else 0.0
|
|
3378
|
-
except Exception:
|
|
3379
|
-
_v = 0.0
|
|
3380
|
-
if _v > 1e-3:
|
|
3381
|
-
_pairs.append({"a": _INSTS[_i]["name"], "b": _INSTS[_j]["name"], "volume": round(_v, 3)})
|
|
3382
|
-
__out["interference"] = _pairs
|
|
3383
|
-
if _TARGET:
|
|
3384
|
-
os.makedirs(os.path.dirname(_TARGET) or ".", exist_ok=True)
|
|
3385
|
-
Part.makeCompound(_placed).exportStep(_TARGET)
|
|
3386
|
-
__out["exported"] = _TARGET
|
|
3387
|
-
__out["bytes"] = os.path.getsize(_TARGET)
|
|
3388
|
-
`
|
|
3656
|
+
const py = assemblyScript(used, instances, target, measure, interference)
|
|
3389
3657
|
// Allocate the assembly id before publishing: the scene carries `asm:<id>`
|
|
3390
3658
|
// so later joint moves rewrite this same entry instead of adding one.
|
|
3391
3659
|
// Re-running with `assembly` rebuilds THAT assembly in place: same id, so
|
|
@@ -3405,7 +3673,14 @@ if _TARGET:
|
|
|
3405
3673
|
if (!scene) return out
|
|
3406
3674
|
const record = reuse
|
|
3407
3675
|
? bridge.rebaseAssembly(reuse, { title: title || reuse.title, sceneId: out.sceneId, scene })
|
|
3408
|
-
: bridge.registerAssembly({
|
|
3676
|
+
: bridge.registerAssembly({
|
|
3677
|
+
id: asmId,
|
|
3678
|
+
title: assembly || title || 'assembly',
|
|
3679
|
+
sceneId: out.sceneId,
|
|
3680
|
+
scene,
|
|
3681
|
+
joints: [],
|
|
3682
|
+
spec: { parts: used.map((p) => ({ name: p.name, path: p.path, ...(p.color ? { color: p.color } : {}) })), instances },
|
|
3683
|
+
})
|
|
3409
3684
|
for (const spec of joints ?? []) {
|
|
3410
3685
|
try {
|
|
3411
3686
|
bridge.setJoint(record, spec)
|
|
@@ -3445,6 +3720,118 @@ if _TARGET:
|
|
|
3445
3720
|
return all[all.length - 1]
|
|
3446
3721
|
}
|
|
3447
3722
|
|
|
3723
|
+
// ---- Dependencies: which files a model is made of, and relinking them ---
|
|
3724
|
+
// An assembly stores the part files it read. Moving or re-exporting a STEP
|
|
3725
|
+
// breaks the next rebuild, and the failure only surfaces deep in a Python
|
|
3726
|
+
// traceback, so the files are listed with their state and can be repointed.
|
|
3727
|
+
|
|
3728
|
+
const specRows = (record) => (record.spec?.parts ?? []).map((p) => {
|
|
3729
|
+
let exists = false
|
|
3730
|
+
let bytes = 0
|
|
3731
|
+
let modified = ''
|
|
3732
|
+
try {
|
|
3733
|
+
const st = statSync(p.path)
|
|
3734
|
+
exists = st.isFile()
|
|
3735
|
+
bytes = st.size
|
|
3736
|
+
modified = new Date(st.mtimeMs).toISOString()
|
|
3737
|
+
} catch {}
|
|
3738
|
+
return {
|
|
3739
|
+
part: p.name,
|
|
3740
|
+
path: p.path,
|
|
3741
|
+
exists,
|
|
3742
|
+
bytes,
|
|
3743
|
+
modified,
|
|
3744
|
+
color: Array.isArray(p.color) ? p.color : null,
|
|
3745
|
+
instances: (record.spec?.instances ?? []).filter((i) => i.part === p.name).map((i) => i.name),
|
|
3746
|
+
}
|
|
3747
|
+
})
|
|
3748
|
+
|
|
3749
|
+
// relink: swap one part's file, then re-run the same build so the model keeps
|
|
3750
|
+
// its id, joints, mates and saved look. Shared by the tool and the panel route.
|
|
3751
|
+
// relink: swap one part's file, then re-run the same build so the model keeps
|
|
3752
|
+
// its id, joints, mates and saved look. Shared by the tool and the panel route.
|
|
3753
|
+
const relinkPart = async ({ assembly, part, path }) => {
|
|
3754
|
+
let record
|
|
3755
|
+
try { record = findAssembly(assembly) } catch (error) { return { ok: false, error: String(error?.message ?? error) } }
|
|
3756
|
+
if (!record.spec) return { ok: false, error: `${record.id} 没有记录来源文件(不是用 cad_studio_assembly 建的)` }
|
|
3757
|
+
const name = String(part ?? '').trim()
|
|
3758
|
+
const next = String(path ?? '').trim()
|
|
3759
|
+
if (!name) return { ok: false, error: 'relink 需要 part(零件名)' }
|
|
3760
|
+
if (!next) return { ok: false, error: 'relink 需要 path(新的文件路径)' }
|
|
3761
|
+
const idx = record.spec.parts.findIndex((p) => p.name === name)
|
|
3762
|
+
if (idx < 0) return { ok: false, error: `这个装配里没有零件:${name}(有 ${record.spec.parts.map((p) => p.name).join(', ')})` }
|
|
3763
|
+
if (!existsSync(next)) return { ok: false, error: `文件不存在:${next}` }
|
|
3764
|
+
const before = { ...record.spec.parts[idx] }
|
|
3765
|
+
record.spec.parts[idx] = { ...before, path: next }
|
|
3766
|
+
const py = assemblyScript(record.spec.parts, record.spec.instances, '', false, false)
|
|
3767
|
+
const out = await bridge.run(py, { title: record.title, docKey: `asm:${record.id}` })
|
|
3768
|
+
if (!out.ok || !out.sceneId) {
|
|
3769
|
+
record.spec.parts[idx] = before // a bad file must not leave the model pointing at it
|
|
3770
|
+
return { ok: false, error: out.error ?? '重新读取文件失败', stderr: out.stderr ?? '' }
|
|
3771
|
+
}
|
|
3772
|
+
const scene = bridge.scenes.get(out.sceneId)
|
|
3773
|
+
if (!scene) {
|
|
3774
|
+
record.spec.parts[idx] = before
|
|
3775
|
+
return { ok: false, error: '重新读取后没有拿到场景' }
|
|
3776
|
+
}
|
|
3777
|
+
bridge.rebaseAssembly(record, { title: record.title, sceneId: out.sceneId, scene })
|
|
3778
|
+
const published = await bridge.republishAssembly(record)
|
|
3779
|
+
return {
|
|
3780
|
+
ok: true,
|
|
3781
|
+
assembly: record.id,
|
|
3782
|
+
sceneId: published.id,
|
|
3783
|
+
part: name,
|
|
3784
|
+
from: before.path,
|
|
3785
|
+
to: next,
|
|
3786
|
+
instances: record.spec.instances.length,
|
|
3787
|
+
volume: round6(Number(scene.parts.find((p) => p.id === name)?.volume ?? 0)),
|
|
3788
|
+
missingParts: specRows(record).filter((f) => !f.exists).map((f) => f.part),
|
|
3789
|
+
}
|
|
3790
|
+
}
|
|
3791
|
+
|
|
3792
|
+
tool({
|
|
3793
|
+
name: 'cad_studio_deps',
|
|
3794
|
+
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.',
|
|
3795
|
+
parameters: {
|
|
3796
|
+
type: 'object',
|
|
3797
|
+
properties: {
|
|
3798
|
+
action: { type: 'string', enum: ['list', 'relink'], description: 'Default: list.' },
|
|
3799
|
+
assembly: { type: 'string', description: 'Assembly id (asm-1) or unique title. Omitted: every assembly for `list`, newest for `relink`.' },
|
|
3800
|
+
part: { type: 'string', description: 'Part name to repoint (relink).' },
|
|
3801
|
+
path: { type: 'string', description: 'New file path for that part (relink).' },
|
|
3802
|
+
},
|
|
3803
|
+
additionalProperties: false,
|
|
3804
|
+
},
|
|
3805
|
+
output: {
|
|
3806
|
+
schema: { type: 'object', properties: { ok: { type: 'boolean' }, models: { type: 'array' }, missing: { type: 'number' } } },
|
|
3807
|
+
render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
|
|
3808
|
+
},
|
|
3809
|
+
execute: async ({ action, assembly, part, path }) => {
|
|
3810
|
+
const mode = action ?? 'list'
|
|
3811
|
+
if (mode === 'list') {
|
|
3812
|
+
if (!assembly) await bridge.hydrateAssemblies()
|
|
3813
|
+
const records = assembly
|
|
3814
|
+
? [(() => { try { return findAssembly(assembly) } catch { return null } })()].filter(Boolean)
|
|
3815
|
+
: [...bridge.assemblies.values()]
|
|
3816
|
+
if (!records.length) return { ok: false, error: assembly ? `没有这个装配:${assembly}` : '还没有装配' }
|
|
3817
|
+
const models = records.map((r) => {
|
|
3818
|
+
const files = specRows(r)
|
|
3819
|
+
return {
|
|
3820
|
+
assembly: r.id,
|
|
3821
|
+
title: r.title,
|
|
3822
|
+
sceneId: r.sceneId,
|
|
3823
|
+
tracked: Boolean(r.spec),
|
|
3824
|
+
files,
|
|
3825
|
+
missingParts: files.filter((f) => !f.exists).map((f) => f.part),
|
|
3826
|
+
}
|
|
3827
|
+
})
|
|
3828
|
+
const missing = models.reduce((n, m) => n + m.missingParts.length, 0)
|
|
3829
|
+
return { ok: true, models, missing }
|
|
3830
|
+
}
|
|
3831
|
+
return relinkPart({ assembly, part, path })
|
|
3832
|
+
},
|
|
3833
|
+
})
|
|
3834
|
+
|
|
3448
3835
|
tool({
|
|
3449
3836
|
name: 'cad_studio_joint',
|
|
3450
3837
|
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.',
|
|
@@ -4744,6 +5131,37 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
|
|
|
4744
5131
|
return send(200, JSON.stringify({ ok: false, error: String(error?.message ?? error) }))
|
|
4745
5132
|
}
|
|
4746
5133
|
}
|
|
5134
|
+
if (url.pathname === `${ROUTE_PREFIX}/deps`) {
|
|
5135
|
+
// What the panel shows under "来源文件": which STEP each part came from
|
|
5136
|
+
// and whether it is still there.
|
|
5137
|
+
const records = [...(await bridge.hydrateAssemblies()).values()]
|
|
5138
|
+
const models = records.map((r) => {
|
|
5139
|
+
const files = (r.spec?.parts ?? []).map((p) => {
|
|
5140
|
+
let exists = false
|
|
5141
|
+
let bytes = 0
|
|
5142
|
+
let modified = ''
|
|
5143
|
+
try {
|
|
5144
|
+
const st = statSync(p.path)
|
|
5145
|
+
exists = st.isFile()
|
|
5146
|
+
bytes = st.size
|
|
5147
|
+
modified = new Date(st.mtimeMs).toISOString()
|
|
5148
|
+
} catch {}
|
|
5149
|
+
return { part: p.name, path: p.path, exists, bytes, modified }
|
|
5150
|
+
})
|
|
5151
|
+
return { assembly: r.id, title: r.title, tracked: Boolean(r.spec), files, missingParts: files.filter((f) => !f.exists).map((f) => f.part) }
|
|
5152
|
+
})
|
|
5153
|
+
return send(200, JSON.stringify({ ok: true, models }))
|
|
5154
|
+
}
|
|
5155
|
+
if (url.pathname === `${ROUTE_PREFIX}/relink` && req.method === 'POST') {
|
|
5156
|
+
const body = await bodyOf()
|
|
5157
|
+
if (!body || typeof body.part !== 'string' || typeof body.path !== 'string') return send(400, JSON.stringify({ error: 'bad request' }))
|
|
5158
|
+
try {
|
|
5159
|
+
const out = await relinkPart({ assembly: body.assembly, part: body.part, path: body.path })
|
|
5160
|
+
return send(200, JSON.stringify(out))
|
|
5161
|
+
} catch (error) {
|
|
5162
|
+
return send(200, JSON.stringify({ ok: false, error: String(error?.message ?? error) }))
|
|
5163
|
+
}
|
|
5164
|
+
}
|
|
4747
5165
|
if (url.pathname === `${ROUTE_PREFIX}/doctor`) {
|
|
4748
5166
|
bridge.refresh()
|
|
4749
5167
|
return send(200, JSON.stringify(diagnose(bridge, resolved)))
|