dsh-cad-studio 0.17.0 → 0.19.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 CHANGED
@@ -23,6 +23,8 @@ 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
+ | 面板改草图 | 特征抽屉里点「草图 N」展开:数值约束是可编辑输入框(`distance*`/`radius`/`angle` 按度),改完立刻重解并重建;解不出来就回滚并报错 |
27
+ | 草图约束 | `equal`(等长)、`symmetric`(三点对称,需 `c` 点)、`angle`(**单位是度**,内部转弧度并在求解后重测);`distance` 是两点距离、`distance_x/y` 是该点的绝对坐标 |
26
28
  | 草图 + 放样/扫掠 | 草图存在文档里(`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) |
27
29
  | 特征 → STEP | `cad_studio_export {model:"名字", target:"…/x.step"}` 或 `cad_studio_doc {action:"show", name, export:"…/x.step"}`;特征列表是源,STEP 是产物,不用自己复刻发射器 |
28
30
  | 旧 dsh-cad 文档 | `cad_studio_legacy`(`action: list / show`)只读列出 `/app/.dsh-cad` 的文档、op 数与体数 |
package/client.js CHANGED
@@ -1677,6 +1677,8 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
1677
1677
  const [featDraft, setFeatDraft] = useState({})
1678
1678
  const [featAdd, setFeatAdd] = useState(false)
1679
1679
  const [featError, setFeatError] = useState('')
1680
+ // Which document sketch is expanded in the 草图 section.
1681
+ const [openSketch, setOpenSketch] = useState('')
1680
1682
  const featTimer = useRef(null)
1681
1683
  const dragRef = useRef({ timer: 0, pending: null })
1682
1684
  const viewportRef = useRef(null)
@@ -2019,10 +2021,64 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
2019
2021
  }, [featureModel])
2020
2022
  const graphNodes = (payload && payload.graph && payload.graph.nodes) || []
2021
2023
  const graphTip = (payload && payload.graph && payload.graph.tip) || null
2024
+ // Sketches are document data, so the panel edits the same thing the
2025
+ // agent writes: change a dimension, the sketch is re-solved, re-measured
2026
+ // and the whole feature chain rebuilds. Non-numeric constraints are shown
2027
+ // read-only — they are geometry relations, not numbers.
2028
+ const sketchDocs = (payload && payload.sketches) || {}
2029
+ const sketchNames = Object.keys(sketchDocs || {})
2030
+ const sketchSection = sketchNames.length
2031
+ ? [
2032
+ h('div', { key: 'sk-h', style: { ...styles.treeHint, display: 'flex', gap: 6, alignItems: 'center', marginTop: 2 }, 'data-cad-sketch-head': '1' }, `草图 ${sketchNames.length}`),
2033
+ ...sketchNames.map((name) => {
2034
+ const sk = sketchDocs[name] || {}
2035
+ const geos = Array.isArray(sk.geometry) ? sk.geometry : []
2036
+ const cons = Array.isArray(sk.constraints) ? sk.constraints : []
2037
+ const open = openSketch === name
2038
+ const setValue = (cid, raw) => {
2039
+ const value = Number(raw)
2040
+ if (!Number.isFinite(value)) return
2041
+ const next = JSON.parse(JSON.stringify(sk))
2042
+ const hit = (next.constraints || []).find((c) => String(c.id) === String(cid))
2043
+ if (!hit) return
2044
+ hit.value = value
2045
+ postFeature({ action: 'sketch', sketch: { name, def: next } })
2046
+ }
2047
+ return h('div', { key: `sk-${name}`, style: styles.featBlock, 'data-cad-sketch': name }, [
2048
+ h('div', {
2049
+ key: 'r',
2050
+ style: { ...styles.featHead, cursor: 'pointer' },
2051
+ 'data-cad-sketch-toggle': name,
2052
+ onClick: (event) => { event.stopPropagation(); setOpenSketch(open ? '' : name) },
2053
+ }, [
2054
+ h('span', { key: 'n', style: { ...styles.featLabel, minWidth: 0, flex: '1 1 auto', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, title: `${name}:${geos.length} 条线 · ${cons.length} 个约束` }, `${name} · ${geos.length} 线 ${cons.length} 约束`),
2055
+ ]),
2056
+ open
2057
+ ? h('div', { key: 'b', style: { paddingLeft: 8, paddingBottom: 4 } }, [
2058
+ ...cons.filter((c) => typeof c.value === 'number').map((c) => h('div', { key: `d-${c.id}`, style: { display: 'flex', gap: 6, alignItems: 'center', margin: '2px 0' } }, [
2059
+ h('span', { key: 'l', style: { fontSize: 11, opacity: 0.72, flex: '1 1 auto', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, title: `${c.type} ${c.a || ''} ${c.b || ''}` }, `${c.type}${c.a ? ` ${c.a}` : ''}`),
2060
+ h('input', {
2061
+ key: 'i',
2062
+ type: 'number',
2063
+ style: { ...styles.jointNum, width: 62, fontSize: 11, flex: '0 0 auto', boxSizing: 'border-box' },
2064
+ 'data-cad-sk-value': `${name}:${c.id}`,
2065
+ value: String(c.value),
2066
+ onChange: (event) => setValue(c.id, event.currentTarget.value),
2067
+ }),
2068
+ ])),
2069
+ ...cons.filter((c) => typeof c.value !== 'number').map((c) => h('div', { key: `g-${c.id}`, style: { fontSize: 11, opacity: 0.62, margin: '1px 0' }, 'data-cad-sk-geo': `${name}:${c.id}` }, `${c.type} ${c.a || ''}${c.b ? ` · ${c.b}` : ''}`)),
2070
+ h('div', { key: 'geo', style: { fontSize: 10.5, opacity: 0.5, marginTop: 2, whiteSpace: 'normal' } }, geos.map((g) => g.id).join(' · ')),
2071
+ ])
2072
+ : null,
2073
+ ])
2074
+ }),
2075
+ ]
2076
+ : []
2022
2077
  const featureBody = paramsSection.length
2023
2078
  ? [...paramsSection, ...(!featureList.length
2024
2079
  ? [h('div', { key: 'script-hint', style: { ...styles.treeHint, whiteSpace: 'nowrap' }, title: '脚本模型:改参数会重跑脚本;逐条特征只适用于声明式模型' }, '脚本模型 · 改参数即重跑脚本')]
2025
2080
  : [h('div', { key: 'feat-h', style: { ...styles.treeHint, marginTop: 2 } }, `${featureList.length} 特征`)])]
2081
+ .concat(sketchSection)
2026
2082
  : !featureModel || !featureList.length
2027
2083
  ? [h('div', { key: 'none', style: styles.propEmpty },
2028
2084
  featureModel
@@ -2054,6 +2110,7 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
2054
2110
  }, kind)))
2055
2111
  : null,
2056
2112
  featError ? h('div', { key: 'e', style: styles.featError, 'data-cad-feat-error': '1' }, featError) : null,
2113
+ ...sketchSection,
2057
2114
  ...featureList.map((feature, index) => {
2058
2115
  const off = feature.enabled === false
2059
2116
  const node = graphNodes.find((n) => n.id === feature.id)
package/index.js CHANGED
@@ -1248,6 +1248,7 @@ _SK_CONSTRAINT = {
1248
1248
  "tangent": ("Tangent", "pair"), "distance_x": ("DistanceX", "size"),
1249
1249
  "distance_y": ("DistanceY", "size"), "radius": ("Radius", "size_one"),
1250
1250
  "angle": ("Angle", "size_pair"), "distance": ("Distance", "ab2v"),
1251
+ "equal": ("Equal", "pair"), "symmetric": ("Symmetric", "sym3"),
1251
1252
  }
1252
1253
 
1253
1254
  def _sketch(name):
@@ -1297,8 +1298,13 @@ def _sketch(name):
1297
1298
  elif form == "ab2v":
1298
1299
  sk.addConstraint(Sketcher.Constraint(fc, gi(c["a"]), int(c.get("pa", 1)), gi(c["b"]), int(c.get("pb", 2)), float(v)))
1299
1300
  dims.append((c, fc, (gi(c["a"]), int(c.get("pa", 1))), (gi(c["b"]), int(c.get("pb", 2))), float(v)))
1301
+ elif form == "sym3":
1302
+ sk.addConstraint(Sketcher.Constraint(fc, gi(c["a"]), int(c.get("pa", 1)), gi(c["b"]), int(c.get("pb", 1)), gi(c.get("c")), int(c.get("pc", 1))))
1300
1303
  else:
1301
- sk.addConstraint(Sketcher.Constraint(fc, gi(c["a"]), gi(c["b"]), float(v)))
1304
+ # Angle is documented in degrees because that is what a human types;
1305
+ # the solver wants radians.
1306
+ _sent = math.radians(float(v)) if fc == "Angle" else float(v)
1307
+ sk.addConstraint(Sketcher.Constraint(fc, gi(c["a"]), gi(c["b"]), _sent))
1302
1308
  dims.append((c, fc, (gi(c["a"]), None), (gi(c["b"]), None), float(v)))
1303
1309
  rc = sk.solve()
1304
1310
  if rc < 0:
@@ -1315,6 +1321,16 @@ def _sketch(name):
1315
1321
  elif fc in ("DistanceX", "DistanceY"):
1316
1322
  p = _pt(ref1)
1317
1323
  got = p.x if fc == "DistanceX" else p.y
1324
+ elif fc == "Equal":
1325
+ got = 1.0 if abs(sk.Geometry[ref1[0]].length() - sk.Geometry[ref2[0]].length()) <= 1e-6 else 0.0
1326
+ want = 1.0
1327
+ elif fc == "Angle":
1328
+ _a = sk.Geometry[ref1[0]]
1329
+ _b = sk.Geometry[ref2[0]]
1330
+ _va = _a.EndPoint - _a.StartPoint
1331
+ _vb = _b.EndPoint - _b.StartPoint
1332
+ _cos = max(-1.0, min(1.0, _va.dot(_vb) / (_va.Length * _vb.Length)))
1333
+ got = math.degrees(math.acos(_cos))
1318
1334
  else:
1319
1335
  continue
1320
1336
  if abs(got - want) > 1e-6:
@@ -3343,7 +3359,7 @@ if _TARGET:
3343
3359
  const code = isFeatures
3344
3360
  ? featuresScript(featureOps(doc), null, { cache, resume, sketches: doc.sketches })
3345
3361
  : `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}`
3346
- const meta = isFeatures ? { model: doc.name, features: publicFeatures(doc), tip: doc.tip ?? null } : { model: doc.name, params: doc.params ?? {} }
3362
+ const meta = isFeatures ? { model: doc.name, features: publicFeatures(doc), sketches: doc.sketches ?? {}, tip: doc.tip ?? null } : { model: doc.name, params: doc.params ?? {} }
3347
3363
  doc.run = (doc.run ?? 0) + 1
3348
3364
  doc.updatedAt = new Date().toISOString()
3349
3365
  // One row per model: a rebuild rewrites the model's existing scene.
@@ -3489,8 +3505,55 @@ if _TARGET:
3489
3505
  throw new Error(`${doc.name} 是脚本模型,没有特征列表(用 cad_studio_doc update 改 params,或新建 kind="features" 的模型)`)
3490
3506
  }
3491
3507
  if (action === 'list') {
3492
- return { ok: true, model: doc.name, kind: doc.kind, features: publicFeatures(doc), graph: graphView(doc, { errors: [], executed: null }), stats: doc.stats ?? null }
3508
+ return { ok: true, model: doc.name, kind: doc.kind, features: publicFeatures(doc), sketches: doc.sketches ?? {}, graph: graphView(doc, { errors: [], executed: null }), stats: doc.stats ?? null }
3493
3509
  }
3510
+ if (action === 'sketch') {
3511
+ // Sketches are document data (geometry + constraints), so editing one is
3512
+ // a document edit: same rollback rule as a feature edit, and the sketch
3513
+ // rides into the BREP cache hash so geometry actually changes.
3514
+ const raw = args.sketch && typeof args.sketch === 'object' ? args.sketch : {}
3515
+ const name = String(raw.name ?? '')
3516
+ if (!name) throw new Error('sketch 需要 name(要改的草图名)')
3517
+ const beforeSketches = JSON.parse(JSON.stringify(doc.sketches ?? {}))
3518
+ const beforeStats = doc.stats ? JSON.parse(JSON.stringify(doc.stats)) : null
3519
+ doc.sketches = normalizeSketches({ [name]: raw.remove ? null : (raw.def ?? raw) }, doc.sketches ?? {})
3520
+ let result
3521
+ try {
3522
+ result = await rebuild(doc, dir, { note: `sketch ${name} ${raw.remove ? 'remove' : 'edit'}` })
3523
+ } catch (error) {
3524
+ doc.sketches = beforeSketches
3525
+ doc.stats = beforeStats
3526
+ await writeModel(doc, dir)
3527
+ return { ok: false, evaluated: false, model: doc.name, action, error: String(error?.message ?? error), sketches: doc.sketches }
3528
+ }
3529
+ doc.history = Array.isArray(doc.history) ? doc.history : []
3530
+ doc.history.push({ at: new Date().toISOString(), note: `sketch ${name}`, params: null, run: result.ok !== false })
3531
+ doc.history = doc.history.slice(-20)
3532
+ await writeModel(doc, dir)
3533
+ return {
3534
+ ok: true,
3535
+ evaluated: result.ok !== false && (result.errors ?? []).length === 0,
3536
+ model: doc.name,
3537
+ kind: doc.kind,
3538
+ action,
3539
+ // A whole-emitter failure has no per-node error, only this message.
3540
+ error: result.ok === false ? String(result.error ?? 'rebuild failed') : '',
3541
+ features: publicFeatures(doc),
3542
+ sketches: doc.sketches ?? {},
3543
+ graph: result.graph,
3544
+ errors: result.errors ?? [],
3545
+ undo: doc.undo.length,
3546
+ redo: doc.redo.length,
3547
+ volume: doc.stats?.volume ?? null,
3548
+ triangles: doc.stats?.triangles ?? null,
3549
+ sceneId: doc.stats?.sceneId ?? '',
3550
+ run: doc.run,
3551
+ cached: result.cached ?? 0,
3552
+ computed: result.computed ?? null,
3553
+ revalidated: result.revalidated === true,
3554
+ }
3555
+ }
3556
+
3494
3557
  const snapshot = () => JSON.parse(JSON.stringify({ features: doc.features, tip: doc.tip ?? null }))
3495
3558
  const restore = (snap) => {
3496
3559
  doc.features = JSON.parse(JSON.stringify(snap.features))
@@ -3591,6 +3654,7 @@ if _TARGET:
3591
3654
  kind: doc.kind,
3592
3655
  action,
3593
3656
  features: publicFeatures(doc),
3657
+ sketches: doc.sketches ?? {},
3594
3658
  graph: result.graph,
3595
3659
  errors: result.errors ?? [],
3596
3660
  undo: doc.undo.length,
@@ -3608,12 +3672,18 @@ if _TARGET:
3608
3672
 
3609
3673
  tool({
3610
3674
  name: 'cad_studio_features',
3611
- description: `Edit a feature-list model one feature at a time (the "边画边改" path): change one feature's parameters and the whole list is re-derived in ~0.2–0.6 s. Actions: list / add / update / remove / move / toggle (alias suppress) / tip / undo / redo. Feature kinds: ${FEATURE_KINDS.join(', ')}. A feature is {kind, label?, params} — params hold that kind's fields (box: size:[dx,dy,dz], at?; cylinder: r,h,at?,axis?; cut/fuse/common: with:<primitive>; fillet: r; chamfer: d; shell: t,open?; pattern_linear: delta,count; rotate: axis?,at?,deg; mirror: normal?,at?). Flat form ({kind:'box', size:[…]}) is accepted too.`,
3675
+ description: `Edit a feature-list model one feature at a time (the "边画边改" path): change one feature's parameters and the whole list is re-derived in ~0.2–0.6 s. Actions: list / add / update / remove / move / toggle (alias suppress) / tip / undo / redo / sketch (edit one document sketch and rebuild). Feature kinds: ${FEATURE_KINDS.join(', ')}. A feature is {kind, label?, params} — params hold that kind's fields (box: size:[dx,dy,dz], at?; cylinder: r,h,at?,axis?; cut/fuse/common: with:<primitive>; fillet: r; chamfer: d; shell: t,open?; pattern_linear: delta,count; rotate: axis?,at?,deg; mirror: normal?,at?). Flat form ({kind:'box', size:[…]}) is accepted too.`,
3612
3676
  parameters: {
3613
3677
  type: 'object',
3614
3678
  properties: {
3615
3679
  model: { type: 'string', description: 'Feature-list model name (created with cad_studio_doc kind="features").' },
3616
- action: { type: 'string', enum: ['list', 'add', 'update', 'remove', 'move', 'toggle', 'suppress', 'tip', 'undo', 'redo'] },
3680
+ action: { type: 'string', enum: ['list', 'add', 'update', 'remove', 'move', 'toggle', 'suppress', 'tip', 'undo', 'redo', 'sketch'] },
3681
+ sketch: {
3682
+ type: 'object',
3683
+ description: 'With action:"sketch": {name, def:{geometry:[…],constraints:[…]}} replaces one sketch, {name, remove:true} deletes it. The document is rebuilt immediately; a constraint the solver cannot meet rolls the sketch back.',
3684
+ properties: { name: { type: 'string' }, remove: { type: 'boolean' }, def: { type: 'object' } },
3685
+ required: ['name'],
3686
+ },
3617
3687
  feature: { type: 'object', description: 'add: the feature to append. update/toggle: {id, ...fields to change}. remove/move: {id}.' },
3618
3688
  id: { type: 'string', description: 'Feature id (f1, f2 …); alternative to feature.id.' },
3619
3689
  to: { type: 'integer', description: 'move: target index (0-based). Default: to the end.' },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cad-studio",
3
- "version": "0.17.0",
3
+ "version": "0.19.0",
4
4
  "type": "module",
5
5
  "description": "CAD Studio — FreeCAD 桥(给 AI 的 14 个工具)+ Web 右栏 3D 面板:建模/装配/关节运动/出图/多页签查看",
6
6
  "exports": {