dsh-cad-studio 0.16.0 → 0.17.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 (3) hide show
  1. package/README.md +1 -0
  2. package/index.js +95 -12
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -23,6 +23,7 @@ DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**
23
23
  | 几何自检 | `cad_studio_check {source}` 在导出/打印前问一次:是否有效实体、外壳是否闭合、每个实体体积多少,返回中文问题清单(零体积 / 外壳未闭合 / 几何无效 / 没有实体) |
24
24
  | 打印网格 | `cad_studio_mesh {source, target:"…/x.stl"}` 三角化 + 去重合并点/面、修形变、统一法向,可选 `fillHoles`、`targetSize`(减面);回报修复前后的 facets/points,避免「导出成功但网格是碎的」 |
25
25
  | 旋转体与凹槽 | `revolve` 的 `axis` 取草图平面内的轴(`"Y"` 或 `[0,1,0]`)才是实体;垂直轴(XY 草图的 Z)只会扫出零厚度圆环,插件会直接报错。凹槽=`{kind:"cut", with:{kind:"revolve", …}}`,不需要单独 op |
26
+ | 草图 + 放样/扫掠 | 草图存在文档里(`cad_studio_doc {action:"create", kind:"features", sketches:{S1:{geometry:[…],constraints:[…]}}, features:[{kind:"extrude",sketch:"S1",h:10}]}`);`loft` 用 `sections:[{sketch:"S1"},{sketch:"S2",at:[0,0,40]}]`,`sweep` 用 `path:[[x,y,z],…]`。改草图会重建(草图进了缓存哈希,不会命中旧 BREP) |
26
27
  | 特征 → STEP | `cad_studio_export {model:"名字", target:"…/x.step"}` 或 `cad_studio_doc {action:"show", name, export:"…/x.step"}`;特征列表是源,STEP 是产物,不用自己复刻发射器 |
27
28
  | 旧 dsh-cad 文档 | `cad_studio_legacy`(`action: list / show`)只读列出 `/app/.dsh-cad` 的文档、op 数与体数 |
28
29
  | 自检/安装 | `cad_studio_setup`:报告 freecadcmd 是否可用、版本、包管理器与可执行命令;`action=install` 直接装 |
package/index.js CHANGED
@@ -1163,9 +1163,12 @@ const EMITTER_VERSION = 'e1'
1163
1163
  /** One hash per prefix: hashes[i] = ops[0..i] applied. Skip markers reuse the
1164
1164
  * previous hash, so toggling a suppressed feature does not invalidate
1165
1165
  * anything upstream of it. */
1166
- function chainHashes(ops) {
1166
+ function chainHashes(ops, seed = '') {
1167
1167
  const out = []
1168
- let h = crypto.createHash('sha1').update(`cad-studio:${EMITTER_VERSION}`).digest('hex').slice(0, 16)
1168
+ // `seed` carries everything the op list does not spell out — currently the
1169
+ // document's sketches. Without it, editing a sketch leaves the chain hash
1170
+ // unchanged and the BREP cache happily serves the old geometry.
1171
+ let h = crypto.createHash('sha1').update(`cad-studio:${EMITTER_VERSION}`).update(String(seed)).digest('hex').slice(0, 16)
1169
1172
  for (const op of Array.isArray(ops) ? ops : []) {
1170
1173
  if (op && op.kind === '__skip__') { out.push(h); continue }
1171
1174
  const bare = { ...op }
@@ -1397,6 +1400,40 @@ def _prim(op, _cur=None):
1397
1400
  ps = [Vector(float(p[0]), 0.0, float(p[1])) for p in op["points"]]
1398
1401
  ang = float(op.get("angle", 360.0))
1399
1402
  return Part.Face(Part.makePolygon(ps + [ps[0]])).revolve(Vector(0.0, 0.0, 0.0), Vector(0.0, 0.0, 1.0), ang)
1403
+ if k == "loft":
1404
+ # Sections are sketches (or their wires) placed at different heights:
1405
+ # lofting two coplanar wires is degenerate on this kernel (Volume 0),
1406
+ # which is exactly what a mis-specified loft would look like.
1407
+ _sections = op.get("sections")
1408
+ if not isinstance(_sections, list) or len(_sections) < 2:
1409
+ raise RuntimeError("loft 需要至少两个 sections,例如 [{\\\"sketch\\\":\\\"S1\\\"},{\\\"sketch\\\":\\\"S2\\\",\\\"at\\\":[0,0,40]}]")
1410
+ _wires = []
1411
+ for _sec in _sections:
1412
+ _w = _sketch(str(_sec.get("sketch"))) if isinstance(_sec, dict) and _sec.get("sketch") else None
1413
+ if _w is None:
1414
+ raise RuntimeError("loft 的每个 section 都要有 sketch 名字")
1415
+ _at = _v3(_sec.get("at"), (0.0, 0.0, 0.0))
1416
+ if _at.Length > 1e-9:
1417
+ _w = _w.translated(_at)
1418
+ _wires.append(_w)
1419
+ _lofted = Part.makeLoft(_wires, True)
1420
+ if abs(_lofted.Volume) < 1e-9 and len(_wires) > 1:
1421
+ _z = [round(w.BoundBox.ZMin, 3) for w in _wires]
1422
+ raise RuntimeError("loft 得到零体积:所有截面在同一平面上(z=%s)。给 section 加 at:[0,0,z] 把它们分层" % str(_z))
1423
+ return _lofted
1424
+ if k == "sweep":
1425
+ _prof = _sketch(str(op["sketch"])) if op.get("sketch") else None
1426
+ if _prof is None:
1427
+ raise RuntimeError("sweep 需要 sketch(截面轮廓)")
1428
+ _pts = op.get("path")
1429
+ if not isinstance(_pts, list) or len(_pts) < 2:
1430
+ raise RuntimeError("sweep 需要 path:至少两个点 [[x,y,z], ...]")
1431
+ _path = Part.makePolygon([_v3(p) for p in _pts])
1432
+ _tr = int(op.get("transition", 2))
1433
+ _swept = Part.Wire(_path).makePipeShell([Part.Wire(_prof)], True, bool(op.get("frenet", False)), _tr)
1434
+ if abs(_swept.Volume) < 1e-9:
1435
+ raise RuntimeError("sweep 得到零体积:检查 path 是否退化(所有点共线)")
1436
+ return _swept
1400
1437
  raise RuntimeError("未知图元:" + str(k))
1401
1438
 
1402
1439
  # ---- sub-shape selectors -------------------------------------------------
@@ -1538,7 +1575,7 @@ for _idx, _op in enumerate(_OPS):
1538
1575
  continue
1539
1576
  _snap = _shape
1540
1577
  try:
1541
- if _k in ("box", "cylinder", "sphere", "cone", "torus", "extrude", "revolve"):
1578
+ if _k in ("box", "cylinder", "sphere", "cone", "torus", "extrude", "revolve", "loft", "sweep"):
1542
1579
  _s = _prim(_op, _shape)
1543
1580
  _shape = _s if _shape is None else _shape.fuse(_s)
1544
1581
  elif _k in ("fuse", "cut", "common"):
@@ -2625,7 +2662,7 @@ else:
2625
2662
  // A list of ops applied in order. `run` stays the escape hatch; this is the
2626
2663
  // path for "60×40×20 的盒子挖个 φ16 通孔、倒 2mm 圆角".
2627
2664
 
2628
- const FEATURE_KINDS = ['box', 'cylinder', 'sphere', 'cone', 'torus', 'hole', 'extrude', 'revolve', 'fuse', 'cut', 'common', 'fillet', 'chamfer', 'shell', 'pattern_linear', 'pattern_circular', 'translate', 'rotate', 'mirror']
2665
+ const FEATURE_KINDS = ['box', 'cylinder', 'sphere', 'cone', 'torus', 'hole', 'extrude', 'revolve', 'loft', 'sweep', 'fuse', 'cut', 'common', 'fillet', 'chamfer', 'shell', 'pattern_linear', 'pattern_circular', 'translate', 'rotate', 'mirror']
2629
2666
 
2630
2667
  tool({
2631
2668
  name: 'cad_studio_feature',
@@ -3029,6 +3066,7 @@ if _TARGET:
3029
3066
  // Schema 2 keeps the list under `graph.nodes`; `features` stays the in-memory
3030
3067
  // name so every caller keeps working. Reading an old file migrates it.
3031
3068
  if (doc.graph && Array.isArray(doc.graph.nodes)) doc.features = doc.graph.nodes
3069
+ if (!doc.sketches || typeof doc.sketches !== 'object' || Array.isArray(doc.sketches)) doc.sketches = {}
3032
3070
  doc.schema = 2
3033
3071
  // Named dimensions/expressions (schema 2): only finite numbers survive.
3034
3072
  doc.vars = doc.vars && typeof doc.vars === 'object' && !Array.isArray(doc.vars)
@@ -3109,6 +3147,29 @@ if _TARGET:
3109
3147
  * Accept both shapes: `{kind:'box', params:{size:…}}` and the flatter
3110
3148
  * `{kind:'box', size:…}` an agent tends to write.
3111
3149
  */
3150
+ // Sketches live in the same document as the features, so one file is the
3151
+ // whole model: geometry + constraints in, wires out at rebuild time.
3152
+ const normalizeSketches = (raw, base = {}) => {
3153
+ const out = { ...(base && typeof base === 'object' ? base : {}) }
3154
+ if (raw === undefined) return out
3155
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('sketches 必须是 {名字: {geometry:[…], constraints:[…]}}')
3156
+ for (const [name, sk] of Object.entries(raw)) {
3157
+ if (sk === null) { delete out[name]; continue }
3158
+ if (!sk || typeof sk !== 'object') throw new Error(`sketch ${name} 必须是对象`)
3159
+ const geometry = Array.isArray(sk.geometry) ? sk.geometry : []
3160
+ const constraints = Array.isArray(sk.constraints) ? sk.constraints : []
3161
+ if (!geometry.length) throw new Error(`sketch ${name} 的 geometry 不能为空`)
3162
+ for (const g of geometry) {
3163
+ if (!g || typeof g.type !== 'string') throw new Error(`sketch ${name} 的 geometry 每项都要有 type(line/circle/arc)`)
3164
+ }
3165
+ for (const c of constraints) {
3166
+ if (!c || typeof c.type !== 'string') throw new Error(`sketch ${name} 的 constraints 每项都要有 type`)
3167
+ }
3168
+ out[name] = { geometry, constraints }
3169
+ }
3170
+ return out
3171
+ }
3172
+
3112
3173
  const normalizeFeature = (doc, raw) => {
3113
3174
  if (!raw || typeof raw !== 'object') throw new Error('feature 必须是对象(至少给 kind)')
3114
3175
  const kind = String(raw.kind ?? '')
@@ -3149,10 +3210,29 @@ if _TARGET:
3149
3210
  else if (kind === 'cone') need(num(probe.r1) && num(probe.r2) && pos(probe.h), '需要 r1 / r2 / h>0')
3150
3211
  else if (kind === 'torus') need(pos(probe.r1) && pos(probe.r2), '需要 r1>0(主半径)与 r2>0(管半径)')
3151
3212
  else if (kind === 'extrude') {
3152
- const points = Array.isArray(probe.points) ? probe.points : []
3153
- need(points.length >= 3, '需要 points(至少 3 个 [x,y] 或 [x,y,z] 剖面点)')
3154
- need(points.every((q) => Array.isArray(q) && q.length >= 2 && q.slice(0, 3).every(num)), 'points 的每个点都要是数字数组')
3155
- need(pos(probe.h) || triple(probe.dir), '需要 h>0(沿 +Z 挤出)或 dir:[dx,dy,dz](任意方向)')
3213
+ // `return` here would return from normalizeFeature itself and push
3214
+ // `undefined` into doc.features (that cost me a crash on feature.id).
3215
+ const fromSketch = typeof probe.sketch === 'string' && probe.sketch
3216
+ if (fromSketch) {
3217
+ need(pos(probe.h) || triple(probe.dir), `${where} extrude:给 sketch 时仍需要 h>0 或 dir:[dx,dy,dz]`)
3218
+ } else {
3219
+ const points = Array.isArray(probe.points) ? probe.points : []
3220
+ need(points.length >= 3, '需要 points(至少 3 个 [x,y] 或 [x,y,z] 剖面点;或给 sketch:"S1" 用文档里的草图)')
3221
+ need(points.every((q) => Array.isArray(q) && q.length >= 2 && q.slice(0, 3).every(num)), 'points 的每个点都要是数字数组')
3222
+ need(pos(probe.h) || triple(probe.dir), '需要 h>0(沿 +Z 挤出)或 dir:[dx,dy,dz](任意方向)')
3223
+ }
3224
+ } else if (kind === 'loft') {
3225
+ const sections = probe.sections
3226
+ need(Array.isArray(sections) && sections.length >= 2, `${where} loft:需要至少两个 sections,例如 [{sketch:"S1"},{sketch:"S2",at:[0,0,40]}]`)
3227
+ for (const sec of sections) {
3228
+ need(sec && typeof sec === 'object' && typeof sec.sketch === 'string' && sec.sketch, `${where} loft:每个 section 都要有 sketch 名字`)
3229
+ if (sec.at !== undefined) need(Array.isArray(sec.at) && sec.at.length === 3 && sec.at.every((v) => Number.isFinite(v)), `${where} loft:section.at 必须是 [x,y,z]`)
3230
+ }
3231
+ } else if (kind === 'sweep') {
3232
+ need(typeof probe.sketch === 'string' && probe.sketch, `${where} sweep:需要 sketch(截面轮廓)`)
3233
+ const path = probe.path
3234
+ need(Array.isArray(path) && path.length >= 2, `${where} sweep:需要 path,至少两个点 [[x,y,z], …]`)
3235
+ for (const pt of path) need(Array.isArray(pt) && pt.length === 3 && pt.every((v) => Number.isFinite(v)), `${where} sweep:path 的每一项都必须是 [x,y,z]`)
3156
3236
  } else if (kind === 'revolve') {
3157
3237
  const points = Array.isArray(probe.points) ? probe.points : []
3158
3238
  need(points.length >= 2, '需要 points(至少 2 个 [x,z] 剖面点)')
@@ -3239,7 +3319,7 @@ if _TARGET:
3239
3319
  let hashes = []
3240
3320
  if (isFeatures) {
3241
3321
  const ops = featureOps(doc)
3242
- hashes = chainHashes(ops)
3322
+ hashes = chainHashes(ops, JSON.stringify(doc.sketches ?? {}))
3243
3323
  const cacheDir = brepCacheDir()
3244
3324
  try { await mkdir(cacheDir, { recursive: true }) } catch {}
3245
3325
  cache = { dir: cacheDir, hashes }
@@ -3261,7 +3341,7 @@ if _TARGET:
3261
3341
  }
3262
3342
  }
3263
3343
  const code = isFeatures
3264
- ? featuresScript(featureOps(doc), null, { cache, resume })
3344
+ ? featuresScript(featureOps(doc), null, { cache, resume, sketches: doc.sketches })
3265
3345
  : `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}`
3266
3346
  const meta = isFeatures ? { model: doc.name, features: publicFeatures(doc), tip: doc.tip ?? null } : { model: doc.name, params: doc.params ?? {} }
3267
3347
  doc.run = (doc.run ?? 0) + 1
@@ -3336,6 +3416,7 @@ if _TARGET:
3336
3416
  params: { type: 'object', description: 'Parameter dict. On update these are merged into the existing params (set a key to null to delete it).' },
3337
3417
  note: { type: 'string', description: 'What this revision changed (kept in history).' },
3338
3418
  to: { type: 'string', description: 'For action=rename / duplicate: the new model name.' },
3419
+ sketches: { type: 'object', description: 'For kind="features": named sketches stored in the document, e.g. {S1:{geometry:[{id:"g1",type:"line",p1:[0,0,0],p2:[80,0,0]}, …],constraints:[…]}}. A feature extrudes/revolves/lofts one with {kind:"extrude",sketch:"S1"}.' },
3339
3420
  export: { type: 'string', description: 'Also write the model out as STEP at this path (create / update / show). Saves the caller from re-implementing the feature emitter.' },
3340
3421
  },
3341
3422
  required: ['action'],
@@ -3562,7 +3643,7 @@ if _TARGET:
3562
3643
  if (typeof target !== 'string' || !target) throw new Error('export 需要目标路径,例如 /path/model.step')
3563
3644
  await mkdir(dirname(target), { recursive: true })
3564
3645
  const head = doc.kind === 'features'
3565
- ? featuresScript(featureOps(doc), target)
3646
+ ? featuresScript(featureOps(doc), target, { sketches: doc.sketches })
3566
3647
  : `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}\n`
3567
3648
  const code = doc.kind === 'features'
3568
3649
  ? head
@@ -3604,7 +3685,7 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
3604
3685
  kind: doc.kind,
3605
3686
  params: doc.params,
3606
3687
  ...(typeof doc.script === 'string' ? { script: doc.script } : {}),
3607
- ...(doc.kind === 'features' ? { features: publicFeatures(doc), graph: graphView(doc, { errors: [], executed: null }), tip: doc.tip ?? null, vars: doc.vars ?? {} } : {}),
3688
+ ...(doc.kind === 'features' ? { features: publicFeatures(doc), graph: graphView(doc, { errors: [], executed: null }), tip: doc.tip ?? null, vars: doc.vars ?? {}, sketches: doc.sketches } : {}),
3608
3689
  runs: doc.run ?? 0,
3609
3690
  updatedAt: doc.updatedAt ?? '',
3610
3691
  stats: doc.stats ?? null,
@@ -3632,6 +3713,7 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
3632
3713
  // Vars must exist before the first feature is validated: dimensions
3633
3714
  // are allowed to be expressions over them.
3634
3715
  vars: normalizeVars(args.vars),
3716
+ sketches: normalizeSketches(args.sketches),
3635
3717
  params: args.params && typeof args.params === 'object' ? args.params : {},
3636
3718
  run: 0,
3637
3719
  createdAt: new Date().toISOString(),
@@ -3668,6 +3750,7 @@ __out = {"ok": True, "exported": ${JSON.stringify(target)}, "volume": round(scen
3668
3750
  if (action === 'update') {
3669
3751
  const doc = await readModel(args.name, dir)
3670
3752
  if (args.vars !== undefined) doc.vars = normalizeVars(args.vars, doc.vars)
3753
+ if (args.sketches !== undefined) doc.sketches = normalizeSketches(args.sketches, doc.sketches)
3671
3754
  const before = {
3672
3755
  script: doc.script,
3673
3756
  params: JSON.parse(JSON.stringify(doc.params)),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cad-studio",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {