dsh-cad-studio 0.20.0 → 0.22.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 -1
- package/index.js +482 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -16,7 +16,8 @@ DeepSeek Harness 的 CAD 插件:**把 FreeCAD 桥接成给 AI 用的工具**
|
|
|
16
16
|
| 工程文件 | `cad_studio_doc` 存 `script` 或 `features` 两种模型;`cad_studio_features` 改一条特征→整表重算(0.2–0.6 s),失败整表回滚 |
|
|
17
17
|
| 装配 | `cad_studio_assembly` 读 manifest,`App::Link` 语义的实例位姿;零件是 STEP 文件级引用(改零件重开即跟随);`measure:true` 回每实例体积/包围盒,`interference:true` 回真正重叠的实例对 |
|
|
18
18
|
| 运动 | `cad_studio_joint`(revolute/linear)+ `cad_studio_drive` + `cad_studio_explode`,面板拖滑杆看运动 |
|
|
19
|
-
| 出图 | `cad_studio_drawing` HLR → SVG
|
|
19
|
+
| 出图 | `cad_studio_drawing` HLR → SVG(主/俯/左/等轴);`cad_studio_sheet` 正式图纸(图框 + 标题栏 + 三视图 + 尺寸,A4/A3/A2,可出 DXF) |
|
|
20
|
+
| 装配 | `cad_studio_assembly` 多零件实例、`cad_studio_joint` 关节、`cad_studio_mate` 约束(同心/贴合/距离)、`cad_studio_drive` 驱动、`cad_studio_explode` 爆炸图 |
|
|
20
21
|
| 其它 | `cad_studio_open`(STEP/STL/BREP/IGES 进来看)、`cad_studio_export`、`cad_studio_measure`、`cad_studio_env` |
|
|
21
22
|
| 模型清单 | `cad_studio_scene`(`action: list / delete / rename`)——面板里那条列表就是它;探查脚本留下的卡片可以直接删 |
|
|
22
23
|
| 模型改名 / 复制 | `cad_studio_doc {action:"rename", name, to}` 与 `{action:"duplicate", name, to}`:改名会同步列表里的标题与 `docKey`,复制会得到一条独立的新场景(副本不继承运行历史与撤销栈);两者都可 `cad_studio_undo` 回退 |
|
package/index.js
CHANGED
|
@@ -353,6 +353,21 @@ function instanceCenter(parts, inst) {
|
|
|
353
353
|
return scaleVec(addVec(mn, mx), 0.5)
|
|
354
354
|
}
|
|
355
355
|
|
|
356
|
+
/** World AABB of one placement ({rot, translate}) of an instance. */
|
|
357
|
+
function worldBox(parts, placement) {
|
|
358
|
+
if (!placement) return null
|
|
359
|
+
const bx = partLocalBox(parts, placement.part)
|
|
360
|
+
if (!bx) return null
|
|
361
|
+
const mn = [Infinity, Infinity, Infinity]
|
|
362
|
+
const mx = [-Infinity, -Infinity, -Infinity]
|
|
363
|
+
for (let i = 0; i < 8; i += 1) {
|
|
364
|
+
const p = [i & 1 ? bx.mx[0] : bx.mn[0], i & 2 ? bx.mx[1] : bx.mn[1], i & 4 ? bx.mx[2] : bx.mn[2]]
|
|
365
|
+
const w = addVec(mulVec(placement.rot, p), placement.translate)
|
|
366
|
+
for (let k = 0; k < 3; k += 1) { if (w[k] < mn[k]) mn[k] = w[k]; if (w[k] > mx[k]) mx[k] = w[k] }
|
|
367
|
+
}
|
|
368
|
+
return { mn, mx }
|
|
369
|
+
}
|
|
370
|
+
|
|
356
371
|
function bboxCenterOfInstances(parts, instances) {
|
|
357
372
|
const centers = instances.map((inst) => instanceCenter(parts, inst))
|
|
358
373
|
if (!centers.length) return [0, 0, 0]
|
|
@@ -361,6 +376,33 @@ function bboxCenterOfInstances(parts, instances) {
|
|
|
361
376
|
}
|
|
362
377
|
|
|
363
378
|
/** Normalise one joint spec against the assembly it belongs to. */
|
|
379
|
+
/**
|
|
380
|
+
* One mate, normalised. A mate PLACES the moving instance against a fixed one
|
|
381
|
+
* and then stops being dynamic — it is solved once per republish, not stepped
|
|
382
|
+
* like a joint. Three kinds cover the assembly idioms we can verify:
|
|
383
|
+
* concentric two axes become collinear, axial distance = offset
|
|
384
|
+
* flush two faces touch, gap = 0 (offset must be 0)
|
|
385
|
+
* distance two faces stay `offset` apart along the axis
|
|
386
|
+
*/
|
|
387
|
+
function normalizeMate(record, spec) {
|
|
388
|
+
const names = new Set(record.base.map((b) => b.name))
|
|
389
|
+
const a = String(spec.a ?? '')
|
|
390
|
+
const b = String(spec.b ?? '')
|
|
391
|
+
if (!names.has(a)) throw new Error(`装配里没有这个实例(移动件 a):${a}`)
|
|
392
|
+
if (!names.has(b)) throw new Error(`装配里没有这个实例(固定件 b):${b}`)
|
|
393
|
+
if (a === b) throw new Error('a 与 b 不能是同一个实例')
|
|
394
|
+
const TYPES = ['concentric', 'flush', 'distance']
|
|
395
|
+
const type = TYPES.includes(spec.type) ? spec.type : 'concentric'
|
|
396
|
+
const axis = normVec(Array.isArray(spec.axis) && spec.axis.length === 3 ? spec.axis.map(Number) : [0, 0, 1])
|
|
397
|
+
const offset = Number.isFinite(Number(spec.offset)) ? Number(spec.offset) : 0
|
|
398
|
+
if (type === 'flush' && Math.abs(offset) > 1e-9) {
|
|
399
|
+
throw new Error('flush 是「贴住」,offset 必须为 0(要留缝用 distance)')
|
|
400
|
+
}
|
|
401
|
+
const side = Number(spec.side) === -1 ? -1 : 1
|
|
402
|
+
const id = typeof spec.id === 'string' && spec.id.trim() ? spec.id.trim() : `mate-${(record.mates?.length ?? 0) + 1}`
|
|
403
|
+
return { id, type, a, b, axis, offset, side }
|
|
404
|
+
}
|
|
405
|
+
|
|
364
406
|
function normalizeJoint(record, spec) {
|
|
365
407
|
const inst = record.base.find((b) => b.name === spec.instance)
|
|
366
408
|
if (!inst) throw new Error(`装配里没有这个实例:${spec.instance}`)
|
|
@@ -488,12 +530,59 @@ function resolveParams(value, vars, where) {
|
|
|
488
530
|
return value
|
|
489
531
|
}
|
|
490
532
|
|
|
533
|
+
/** Projection range of an AABB along a unit axis (handles negative components). */
|
|
534
|
+
function projRange(box, axis) {
|
|
535
|
+
let lo = 0
|
|
536
|
+
let hi = 0
|
|
537
|
+
for (let k = 0; k < 3; k += 1) {
|
|
538
|
+
const a = axis[k]
|
|
539
|
+
lo += a > 0 ? box.mn[k] * a : box.mx[k] * a
|
|
540
|
+
hi += a > 0 ? box.mx[k] * a : box.mn[k] * a
|
|
541
|
+
}
|
|
542
|
+
return [lo, hi]
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/** Per-instance placements after the mates, before joints and explode. */
|
|
546
|
+
function solveMates(record) {
|
|
547
|
+
const out = new Map()
|
|
548
|
+
for (const base of record.base) out.set(base.name, { name: base.name, part: base.part, rot: base.rot.slice(), translate: base.translate.slice() })
|
|
549
|
+
for (const mate of record.mates ?? []) {
|
|
550
|
+
const moving = out.get(mate.a)
|
|
551
|
+
const fixed = out.get(mate.b)
|
|
552
|
+
if (!moving || !fixed) continue
|
|
553
|
+
const axis = normVec(mate.axis ?? [0, 0, 1])
|
|
554
|
+
const offset = Number.isFinite(Number(mate.offset)) ? Number(mate.offset) : 0
|
|
555
|
+
const boxB = worldBox(record.parts, out.get(mate.b))
|
|
556
|
+
const boxA = worldBox(record.parts, moving)
|
|
557
|
+
if (!boxA || !boxB) continue
|
|
558
|
+
if (mate.type === 'concentric') {
|
|
559
|
+
// Perpendicular drift to zero, axial distance to `offset`: the two axes
|
|
560
|
+
// end up collinear. Keep the moving part's own orientation — a mate moves
|
|
561
|
+
// it, it does not re-aim it.
|
|
562
|
+
const ca = scaleVec(addVec(boxA.mn, boxA.mx), 0.5)
|
|
563
|
+
const cb = scaleVec(addVec(boxB.mn, boxB.mx), 0.5)
|
|
564
|
+
const want = addVec(cb, scaleVec(axis, offset))
|
|
565
|
+
moving.translate = addVec(moving.translate, subVec(want, ca))
|
|
566
|
+
} else {
|
|
567
|
+
// flush / distance: face-to-face gap along the axis equals `offset`.
|
|
568
|
+
const ra = projRange(boxA, axis)
|
|
569
|
+
const rb = projRange(boxB, axis)
|
|
570
|
+
const side = mate.side === -1 ? -1 : 1
|
|
571
|
+
const shift = side > 0 ? (rb[1] + offset) - ra[0] : (rb[0] - offset) - ra[1]
|
|
572
|
+
moving.translate = addVec(moving.translate, scaleVec(axis, shift))
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
return out
|
|
576
|
+
}
|
|
577
|
+
|
|
491
578
|
/** Base placements + joints + explode → a scene payload ready to publish. */
|
|
492
579
|
function assembleScene(record) {
|
|
493
580
|
const explode = record.explode ?? 0
|
|
581
|
+
const placed = solveMates(record)
|
|
494
582
|
const instances = record.base.map((base) => {
|
|
495
|
-
|
|
496
|
-
let
|
|
583
|
+
const start = placed.get(base.name) ?? base
|
|
584
|
+
let rot = start.rot.slice()
|
|
585
|
+
let translate = start.translate.slice()
|
|
497
586
|
for (const joint of record.joints) {
|
|
498
587
|
if (joint.instance !== base.name) continue
|
|
499
588
|
const axis = normVec(joint.axis)
|
|
@@ -657,6 +746,7 @@ class FreeCadBridge {
|
|
|
657
746
|
base: a.base,
|
|
658
747
|
center: a.center,
|
|
659
748
|
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
|
+
mates: a.mates ?? [],
|
|
660
750
|
explode: a.explode,
|
|
661
751
|
})),
|
|
662
752
|
}
|
|
@@ -862,6 +952,7 @@ class FreeCadBridge {
|
|
|
862
952
|
})),
|
|
863
953
|
center: bboxCenterOfInstances(scene.parts, scene.instances),
|
|
864
954
|
joints: joints ?? [],
|
|
955
|
+
mates: [],
|
|
865
956
|
explode: 0,
|
|
866
957
|
}
|
|
867
958
|
this.assemblies.set(id, record)
|
|
@@ -876,6 +967,24 @@ class FreeCadBridge {
|
|
|
876
967
|
return value
|
|
877
968
|
}
|
|
878
969
|
|
|
970
|
+
/** Add or replace one mate; returns the stored spec. */
|
|
971
|
+
setMate(record, spec) {
|
|
972
|
+
const value = normalizeMate(record, spec)
|
|
973
|
+
record.mates = Array.isArray(record.mates) ? record.mates : []
|
|
974
|
+
const existing = record.mates.find((m) => m.id === value.id)
|
|
975
|
+
if (existing) Object.assign(existing, value)
|
|
976
|
+
else record.mates.push(value)
|
|
977
|
+
return value
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
removeMate(record, id) {
|
|
981
|
+
const list = record.mates ?? []
|
|
982
|
+
const at = list.findIndex((m) => m.id === id)
|
|
983
|
+
if (at < 0) return null
|
|
984
|
+
const [gone] = list.splice(at, 1)
|
|
985
|
+
return gone
|
|
986
|
+
}
|
|
987
|
+
|
|
879
988
|
driveJoint(record, jointId, rawValue) {
|
|
880
989
|
const joint = record.joints.find((j) => j.id === jointId)
|
|
881
990
|
if (!joint) return null
|
|
@@ -895,7 +1004,12 @@ class FreeCadBridge {
|
|
|
895
1004
|
|
|
896
1005
|
// ---- 装配层撤销:关节值 / 关节增删 / 爆炸系数 ----
|
|
897
1006
|
snapshotAssembly(record) {
|
|
898
|
-
return {
|
|
1007
|
+
return {
|
|
1008
|
+
id: record.id,
|
|
1009
|
+
joints: JSON.parse(JSON.stringify(record.joints ?? [])),
|
|
1010
|
+
mates: JSON.parse(JSON.stringify(record.mates ?? [])),
|
|
1011
|
+
explode: record.explode ?? 0,
|
|
1012
|
+
}
|
|
899
1013
|
}
|
|
900
1014
|
|
|
901
1015
|
beginAssemblyEdit(record, label) {
|
|
@@ -2414,6 +2528,291 @@ else:
|
|
|
2414
2528
|
},
|
|
2415
2529
|
})
|
|
2416
2530
|
|
|
2531
|
+
tool({
|
|
2532
|
+
name: 'cad_studio_sheet',
|
|
2533
|
+
description: 'Write a drawing sheet you can hand to a shop: sheet frame, title block, arranged HLR views (first- or third-angle), overall dimensions in mm, SVG (and optional DXF). Views are oriented to the usual convention (front = width x height, top = width x depth, right = depth x height) by measuring the projection basis instead of assuming it.',
|
|
2534
|
+
parameters: {
|
|
2535
|
+
type: 'object',
|
|
2536
|
+
properties: {
|
|
2537
|
+
target: { type: 'string', description: 'Absolute .svg output path.' },
|
|
2538
|
+
source: { type: 'string', description: 'Existing BRep model file (STEP/IGES/BREP).' },
|
|
2539
|
+
code: { type: 'string', description: 'FreeCAD Python that binds `scene` or `export_shapes`.' },
|
|
2540
|
+
model: { type: 'string', description: 'Draw a saved model document by name instead of a file or a script.' },
|
|
2541
|
+
size: { type: 'string', description: 'Sheet size: A4, A3 or A2 (landscape). Default A3.' },
|
|
2542
|
+
projection: { type: 'string', description: 'first (GB/ISO, default) or third (ASME).' },
|
|
2543
|
+
views: { type: 'array', items: { type: 'string' }, description: 'Subset of ["front","top","right"]. Default all three.' },
|
|
2544
|
+
scale: { type: 'number', description: 'Drawing scale factor, e.g. 0.5 for 1:2. Omit to fit the sheet.' },
|
|
2545
|
+
title: { type: 'string', description: 'Part name for the title block.' },
|
|
2546
|
+
number: { type: 'string', description: 'Drawing number for the title block.' },
|
|
2547
|
+
material: { type: 'string', description: 'Material text for the title block.' },
|
|
2548
|
+
dims: { type: 'boolean', description: 'Draw overall dimension lines (default true).' },
|
|
2549
|
+
dxf: { type: 'boolean', description: 'Also write a sidecar .dxf next to the SVG.' },
|
|
2550
|
+
},
|
|
2551
|
+
required: ['target'],
|
|
2552
|
+
additionalProperties: false,
|
|
2553
|
+
},
|
|
2554
|
+
output: {
|
|
2555
|
+
schema: { type: 'object', properties: { ok: { type: 'boolean' }, path: { type: 'string' }, scale: { type: 'number' } } },
|
|
2556
|
+
render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
|
|
2557
|
+
},
|
|
2558
|
+
execute: async ({ target, source, code, model, size, projection, views, scale, title, number, material, dims, dxf }) => {
|
|
2559
|
+
if (!target || extOf(target) !== 'svg') return { ok: false, error: 'target must be a .svg path' }
|
|
2560
|
+
let src = ''
|
|
2561
|
+
if (typeof model === 'string' && model) {
|
|
2562
|
+
src = await modelShapes(model)
|
|
2563
|
+
if (!src) return { ok: false, error: `没有这个模型:${model}` }
|
|
2564
|
+
} else {
|
|
2565
|
+
const x = shapesFrom({ source, code })
|
|
2566
|
+
if (!x) return { ok: false, error: 'pass either source (a model file), model (a saved document) or code' }
|
|
2567
|
+
src = x
|
|
2568
|
+
}
|
|
2569
|
+
const wanted = Array.isArray(views) && views.length ? views : ['front', 'top', 'right']
|
|
2570
|
+
const py = `${PRELUDE}
|
|
2571
|
+
${src}
|
|
2572
|
+
import os, re, TechDraw
|
|
2573
|
+
_SIZES = {"A4": (297.0, 210.0), "A3": (420.0, 297.0), "A2": (594.0, 420.0)}
|
|
2574
|
+
# (view direction, horizontal model axis, vertical model axis) — the pair is what
|
|
2575
|
+
# a reader expects: front shows width x height, top shows width x depth.
|
|
2576
|
+
_WANT = {"front": ("X", "Z"), "top": ("X", "Y"), "right": ("Y", "Z")}
|
|
2577
|
+
_CAND = {"front": ((0, -1, 0), (0, 1, 0)), "top": ((0, 0, 1), (0, 0, -1)), "right": ((1, 0, 0), (-1, 0, 0))}
|
|
2578
|
+
_M = 10.0
|
|
2579
|
+
_TBW, _TBH = 180.0, 40.0
|
|
2580
|
+
_GAP = 26.0
|
|
2581
|
+
_PL = 10.0 # probe segment length (mm)
|
|
2582
|
+
|
|
2583
|
+
def _seg(vec):
|
|
2584
|
+
return Part.makeLine(FreeCAD.Vector(0, 0, 0), FreeCAD.Vector(*vec))
|
|
2585
|
+
|
|
2586
|
+
def _nums(d):
|
|
2587
|
+
return [float(x) for x in re.findall(r'-?[0-9]+(?:[.][0-9]+)?(?:[eE]-?[0-9]+)?', d)]
|
|
2588
|
+
|
|
2589
|
+
def _axis_vectors(dv):
|
|
2590
|
+
"""Fragment-space image of each model axis, as a unit vector (+-1, 0).
|
|
2591
|
+
|
|
2592
|
+
One 10 mm edge per axis, projected on its own: an axis pointing along the
|
|
2593
|
+
view direction collapses to nothing, the other two give their direction in
|
|
2594
|
+
the fragment. Probing beats guessing — TechDraw's basis is not the naive
|
|
2595
|
+
"front shows X-Z" one.
|
|
2596
|
+
"""
|
|
2597
|
+
out = {}
|
|
2598
|
+
for name, vec in (("X", (_PL, 0, 0)), ("Y", (0, _PL, 0)), ("Z", (0, 0, _PL))):
|
|
2599
|
+
frag = TechDraw.projectToSVG(_seg(vec), FreeCAD.Vector(*dv))
|
|
2600
|
+
ds = re.findall(r'd="([^"]+)"', frag)
|
|
2601
|
+
if not ds:
|
|
2602
|
+
continue
|
|
2603
|
+
ns = _nums(ds[0])
|
|
2604
|
+
if len(ns) < 4:
|
|
2605
|
+
continue
|
|
2606
|
+
dx, dy = ns[-2] - ns[0], ns[-1] - ns[1]
|
|
2607
|
+
ln = math.hypot(dx, dy)
|
|
2608
|
+
if ln < 1e-6:
|
|
2609
|
+
continue # this axis is the view direction
|
|
2610
|
+
out[name] = (round(dx / ln), round(dy / ln))
|
|
2611
|
+
return out
|
|
2612
|
+
|
|
2613
|
+
def _solve(view):
|
|
2614
|
+
"""Pick a projection direction whose fragment basis is a rotation.
|
|
2615
|
+
|
|
2616
|
+
F maps read-space (u', v') to fragment-space (u, v): its columns are the
|
|
2617
|
+
fragment images of the two read axes. det(F) < 0 means the drawing would be
|
|
2618
|
+
mirrored (a reader would see the part the wrong way round), so the opposite
|
|
2619
|
+
candidate direction wins instead.
|
|
2620
|
+
"""
|
|
2621
|
+
pa, pb = _WANT[view]
|
|
2622
|
+
for dv in _CAND[view]:
|
|
2623
|
+
vec = _axis_vectors(dv)
|
|
2624
|
+
if pa not in vec or pb not in vec:
|
|
2625
|
+
continue
|
|
2626
|
+
fu, fv = vec[pa], vec[pb]
|
|
2627
|
+
det = fu[0] * fv[1] - fu[1] * fv[0]
|
|
2628
|
+
if det <= 0:
|
|
2629
|
+
continue
|
|
2630
|
+
inv = (fv[1] / det, -fv[0] / det, -fu[1] / det, fu[0] / det)
|
|
2631
|
+
return {"dir": dv, "inv": inv}
|
|
2632
|
+
return None
|
|
2633
|
+
|
|
2634
|
+
def _remap(frag, inv):
|
|
2635
|
+
"""Rewrite the fragment paths in read-space, y flipped for SVG."""
|
|
2636
|
+
ia, ib, ic, id_ = inv
|
|
2637
|
+
out = []
|
|
2638
|
+
for d in re.findall(r'd="([^"]+)"', frag):
|
|
2639
|
+
ns = _nums(d)
|
|
2640
|
+
pts = [(ns[i], ns[i + 1]) for i in range(0, len(ns) - 1, 2)]
|
|
2641
|
+
if not pts:
|
|
2642
|
+
continue
|
|
2643
|
+
q = [(ia * x + ib * y, -(ic * x + id_ * y)) for x, y in pts]
|
|
2644
|
+
out.append("M " + " L ".join("%r %r" % p for p in q))
|
|
2645
|
+
return out
|
|
2646
|
+
|
|
2647
|
+
if not _shapes:
|
|
2648
|
+
__out = {"ok": False, "error": "nothing to draw: pass a source path, a model, or bind scene / export_shapes"}
|
|
2649
|
+
else:
|
|
2650
|
+
_shape = _shapes[0] if len(_shapes) == 1 else Part.makeCompound(_shapes)
|
|
2651
|
+
_SW, _SH = _SIZES.get(str(${JSON.stringify(String(size || 'A3').toUpperCase())}).upper(), _SIZES["A3"])
|
|
2652
|
+
_wanted = [v for v in ${JSON.stringify(wanted)} if v in _WANT] or ["front", "top", "right"]
|
|
2653
|
+
_views = {}
|
|
2654
|
+
_missing = []
|
|
2655
|
+
for _v in _wanted:
|
|
2656
|
+
_sol = _solve(_v)
|
|
2657
|
+
if not _sol:
|
|
2658
|
+
_missing.append(_v)
|
|
2659
|
+
continue
|
|
2660
|
+
_paths = _remap(TechDraw.projectToSVG(_shape, FreeCAD.Vector(*_sol["dir"])), _sol["inv"])
|
|
2661
|
+
_pts = []
|
|
2662
|
+
for _d in _paths:
|
|
2663
|
+
_ns = _nums(_d)
|
|
2664
|
+
_pts += [(_ns[i], _ns[i + 1]) for i in range(0, len(_ns) - 1, 2)]
|
|
2665
|
+
if not _pts:
|
|
2666
|
+
_missing.append(_v)
|
|
2667
|
+
continue
|
|
2668
|
+
_xs = [p[0] for p in _pts]; _ys = [p[1] for p in _pts]
|
|
2669
|
+
_views[_v] = {"paths": _paths, "dir": _sol["dir"],
|
|
2670
|
+
"box": (min(_xs), min(_ys), max(_xs), max(_ys))}
|
|
2671
|
+
if _missing:
|
|
2672
|
+
__out = {"ok": False, "error": "无法为这些视图找到保持手性的投影方向:" + ", ".join(_missing)}
|
|
2673
|
+
else:
|
|
2674
|
+
_need_w = max(_views[v]["box"][2] - _views[v]["box"][0] for v in _wanted) + _GAP
|
|
2675
|
+
_need_h = max(_views[v]["box"][3] - _views[v]["box"][1] for v in _wanted) + _GAP
|
|
2676
|
+
_avail_w = _SW - 2 * _M
|
|
2677
|
+
_avail_h = _SH - 2 * _M - _TBH - 6.0
|
|
2678
|
+
_fit = min(_avail_w / max(_need_w, 1e-6), _avail_h / max(_need_h, 1e-6))
|
|
2679
|
+
_given = float(${Number.isFinite(scale) && Number(scale) > 0 ? Number(scale) : 0})
|
|
2680
|
+
if _given > 0:
|
|
2681
|
+
_scale = _given
|
|
2682
|
+
else:
|
|
2683
|
+
_scale = 0.0
|
|
2684
|
+
for _cand in (2.0, 1.5, 1.0, 0.5, 0.4, 0.25, 0.2, 0.1, 0.05):
|
|
2685
|
+
if _cand <= _fit:
|
|
2686
|
+
_scale = _cand
|
|
2687
|
+
break
|
|
2688
|
+
if _scale <= 0:
|
|
2689
|
+
_scale = _fit
|
|
2690
|
+
|
|
2691
|
+
def _size(view):
|
|
2692
|
+
_bx = _views[view]["box"]
|
|
2693
|
+
return ((_bx[2] - _bx[0]) * _scale, (_bx[3] - _bx[1]) * _scale)
|
|
2694
|
+
|
|
2695
|
+
_first = str(${JSON.stringify(String(projection || 'first').toLowerCase())}).lower() != "third"
|
|
2696
|
+
_cells = {}
|
|
2697
|
+
_fw, _fh = _size("front") if "front" in _views else (0.0, 0.0)
|
|
2698
|
+
for _v in _wanted:
|
|
2699
|
+
_w, _h = _size(_v)
|
|
2700
|
+
if _v == "front":
|
|
2701
|
+
_cells[_v] = (0.0, 0.0, _w, _h)
|
|
2702
|
+
elif _v == "top":
|
|
2703
|
+
_cells[_v] = (0.0, (_fh + _GAP) if _first else -(_h + _GAP), _w, _h)
|
|
2704
|
+
else:
|
|
2705
|
+
_cells[_v] = ((_fw + _GAP) if not _first else -(_w + _GAP), 0.0, _w, _h)
|
|
2706
|
+
_minx = min(c[0] for c in _cells.values()); _miny = min(c[1] for c in _cells.values())
|
|
2707
|
+
_maxx = max(c[0] + c[2] for c in _cells.values()); _maxy = max(c[1] + c[3] for c in _cells.values())
|
|
2708
|
+
_offx = _M + (_avail_w - (_maxx - _minx)) / 2.0 - _minx
|
|
2709
|
+
_offy = _M + (_avail_h - (_maxy - _miny)) / 2.0 - _miny
|
|
2710
|
+
|
|
2711
|
+
_views_svg = []; _dims_svg = []; _labels = []; _dim_list = []
|
|
2712
|
+
_draw_dims = bool(${dims === false ? 'False' : 'True'})
|
|
2713
|
+
for _v in _wanted:
|
|
2714
|
+
_vv = _views[_v]
|
|
2715
|
+
_n0x, _n0y, _n1x, _n1y = _vv["box"]
|
|
2716
|
+
_bw = _n1x - _n0x; _bh = _n1y - _n0y
|
|
2717
|
+
_cx, _cy, _w, _h = _cells[_v]
|
|
2718
|
+
_px = _cx + _offx; _py = _cy + _offy
|
|
2719
|
+
# The paths are already in read-space (y down); place the bbox corner
|
|
2720
|
+
# at the cell corner and scale.
|
|
2721
|
+
_views_svg.append('<g fill="none" stroke="#111" stroke-width="0.25" stroke-linejoin="round" stroke-linecap="round" '
|
|
2722
|
+
'transform="translate(%r %r) scale(%r)">%s</g>' % (
|
|
2723
|
+
_px - _n0x * _scale, _py - _n0y * _scale, _scale,
|
|
2724
|
+
"".join('<path d="%s"/>' % _d for _d in _vv["paths"])))
|
|
2725
|
+
_labels.append('<text x="%r" y="%r" font-size="3.0" fill="#555" font-family="sans-serif" text-anchor="middle">%s</text>' % (
|
|
2726
|
+
_px + _w / 2.0, _py - 3.0, {"front": "主视图", "top": "俯视图", "right": "左视图"}.get(_v, _v)))
|
|
2727
|
+
_wm = round(_bw, 2); _hm = round(_bh, 2)
|
|
2728
|
+
_dim_list.append({"view": _v, "width_mm": _wm, "height_mm": _hm})
|
|
2729
|
+
if _draw_dims and _w > 1e-6 and _h > 1e-6:
|
|
2730
|
+
_yd = _py + _h + 9.0
|
|
2731
|
+
_xd = _px + _w + 9.0
|
|
2732
|
+
_dims_svg.append('<g stroke="#111" stroke-width="0.25" fill="none">'
|
|
2733
|
+
'<path d="M %r %r L %r %r" stroke-dasharray="1,1"/>'
|
|
2734
|
+
'<path d="M %r %r L %r %r" stroke-dasharray="1,1"/>'
|
|
2735
|
+
'<path d="M %r %r L %r %r"/>'
|
|
2736
|
+
'<path d="M %r %r L %r %r" stroke-dasharray="1,1"/>'
|
|
2737
|
+
'<path d="M %r %r L %r %r" stroke-dasharray="1,1"/>'
|
|
2738
|
+
'<path d="M %r %r L %r %r"/></g>' % (
|
|
2739
|
+
_px, _py + _h, _px, _yd + 2.0, _px + _w, _py + _h, _px + _w, _yd + 2.0,
|
|
2740
|
+
_px, _yd, _px + _w, _yd,
|
|
2741
|
+
_px + _w, _py, _xd + 2.0, _py, _px + _w, _py + _h, _xd + 2.0, _py + _h,
|
|
2742
|
+
_xd, _py, _xd, _py + _h))
|
|
2743
|
+
_dims_svg.append('<text x="%r" y="%r" font-size="3.2" fill="#111" text-anchor="middle" font-family="sans-serif">%s</text>' % (
|
|
2744
|
+
_px + _w / 2.0, _yd + 4.2, _wm))
|
|
2745
|
+
_dims_svg.append('<text x="%r" y="%r" font-size="3.2" fill="#111" text-anchor="middle" font-family="sans-serif" transform="rotate(90 %r %r)">%s</text>' % (
|
|
2746
|
+
_xd + 7.0, _py + _h / 2.0, _xd + 7.0, _py + _h / 2.0, _hm))
|
|
2747
|
+
|
|
2748
|
+
_frame = ('<g stroke="#111" fill="none" stroke-width="0.5">'
|
|
2749
|
+
'<rect x="%r" y="%r" width="%r" height="%r"/>'
|
|
2750
|
+
'<rect x="%r" y="%r" width="%r" height="%r"/></g>' % (
|
|
2751
|
+
_M, _M, _SW - 2 * _M, _SH - 2 * _M,
|
|
2752
|
+
_M + 2.0, _M + 2.0, _SW - 2 * _M - 4.0, _SH - 2 * _M - 4.0))
|
|
2753
|
+
_tb_x = _SW - _M - _TBW
|
|
2754
|
+
_tb_y = _SH - _M - _TBH
|
|
2755
|
+
_title = str(${JSON.stringify(typeof title === 'string' ? title : '')}) or os.path.splitext(os.path.basename(${JSON.stringify(target)}))[0]
|
|
2756
|
+
_number = str(${JSON.stringify(typeof number === 'string' ? number : '')})
|
|
2757
|
+
_material = str(${JSON.stringify(typeof material === 'string' ? material : '')})
|
|
2758
|
+
_scale_txt = ("1:%g" % round(1.0 / _scale, 4)) if _scale < 1.0 else (("%g:1" % _scale) if _scale > 1.0 else "1:1")
|
|
2759
|
+
_tb = ['<g stroke="#111" fill="none" stroke-width="0.4">'
|
|
2760
|
+
'<rect x="%r" y="%r" width="%r" height="%r"/>'
|
|
2761
|
+
'<path d="M %r %r L %r %r"/><path d="M %r %r L %r %r"/><path d="M %r %r L %r %r"/></g>' % (
|
|
2762
|
+
_tb_x, _tb_y, _TBW, _TBH,
|
|
2763
|
+
_tb_x, _tb_y + 12.0, _tb_x + _TBW, _tb_y + 12.0,
|
|
2764
|
+
_tb_x, _tb_y + 24.0, _tb_x + _TBW, _tb_y + 24.0,
|
|
2765
|
+
_tb_x + 100.0, _tb_y + 12.0, _tb_x + 100.0, _tb_y + _TBH)]
|
|
2766
|
+
_tb.append('<text x="%r" y="%r" font-size="4.4" font-weight="600" fill="#111" font-family="sans-serif">%s</text>' % (
|
|
2767
|
+
_tb_x + 3.0, _tb_y + 8.4, _title.replace("&", "&").replace("<", "<")))
|
|
2768
|
+
_tb.append('<text x="%r" y="%r" font-size="3.2" fill="#333" font-family="sans-serif">图号 %s</text>' % (
|
|
2769
|
+
_tb_x + 3.0, _tb_y + 19.4, (_number or "-")))
|
|
2770
|
+
_tb.append('<text x="%r" y="%r" font-size="3.2" fill="#333" font-family="sans-serif">材料 %s</text>' % (
|
|
2771
|
+
_tb_x + 3.0, _tb_y + 31.4, (_material or "-")))
|
|
2772
|
+
_tb.append('<text x="%r" y="%r" font-size="3.2" fill="#333" font-family="sans-serif">比例 %s</text>' % (
|
|
2773
|
+
_tb_x + 103.0, _tb_y + 19.4, _scale_txt))
|
|
2774
|
+
_tb.append('<text x="%r" y="%r" font-size="3.2" fill="#333" font-family="sans-serif">图幅 %s · 单位 mm</text>' % (
|
|
2775
|
+
_tb_x + 103.0, _tb_y + 31.4, str(${JSON.stringify(String(size || 'A3').toUpperCase())})))
|
|
2776
|
+
_tb.append('<text x="%r" y="%r" font-size="2.8" fill="#666" font-family="sans-serif">%s</text>' % (
|
|
2777
|
+
_tb_x + 103.0, _tb_y + 8.4, __import__("datetime").date.today().isoformat()))
|
|
2778
|
+
_svg = ('<svg xmlns="http://www.w3.org/2000/svg" width="%rmm" height="%rmm" viewBox="0 0 %r %r">'
|
|
2779
|
+
'<rect width="100%%" height="100%%" fill="white"/>%s%s%s%s%s</svg>') % (
|
|
2780
|
+
_SW, _SH, _SW, _SH, _frame, "".join(_views_svg), "".join(_dims_svg), "".join(_labels), "".join(_tb))
|
|
2781
|
+
os.makedirs(os.path.dirname(${JSON.stringify(target)}) or ".", exist_ok=True)
|
|
2782
|
+
open(${JSON.stringify(target)}, "w").write(_svg)
|
|
2783
|
+
__out = {"ok": True, "path": ${JSON.stringify(target)}, "bytes": os.path.getsize(${JSON.stringify(target)}),
|
|
2784
|
+
"sheet_mm": [_SW, _SH], "scale": round(_scale, 4), "views": _wanted,
|
|
2785
|
+
"projection": "first" if _first else "third", "dimensions": _dim_list,
|
|
2786
|
+
"directions": {v: list(_views[v]["dir"]) for v in _wanted}}
|
|
2787
|
+
`
|
|
2788
|
+
const out = await bridge.run(py, { title: `sheet → ${target}`, publishHint: false })
|
|
2789
|
+
if (out && out.ok && dxf) {
|
|
2790
|
+
const side = target.replace(/\.svg$/i, '.dxf')
|
|
2791
|
+
const py2 = `${PRELUDE}
|
|
2792
|
+
${src}
|
|
2793
|
+
import os, TechDraw
|
|
2794
|
+
_doc = FreeCAD.newDocument("sheet")
|
|
2795
|
+
_obj = _doc.addObject("Part::Feature", "S")
|
|
2796
|
+
_obj.Shape = _shapes[0] if len(_shapes) == 1 else Part.makeCompound(_shapes)
|
|
2797
|
+
_page = _doc.addObject("TechDraw::DrawPage", "Page")
|
|
2798
|
+
for _v, _dir in (("front", (0, -1, 0)), ("top", (0, 0, 1)), ("right", (1, 0, 0))):
|
|
2799
|
+
_view = _doc.addObject("TechDraw::DrawViewPart", "V" + _v)
|
|
2800
|
+
_page.addView(_view)
|
|
2801
|
+
_view.Source = [_obj]
|
|
2802
|
+
_view.Direction = _dir
|
|
2803
|
+
_doc.recompute()
|
|
2804
|
+
_side = ${JSON.stringify(side)}
|
|
2805
|
+
os.makedirs(os.path.dirname(_side) or ".", exist_ok=True)
|
|
2806
|
+
TechDraw.writeDXFPage(_page, _side)
|
|
2807
|
+
__out = {"ok": True, "path": _side, "bytes": os.path.getsize(_side)}
|
|
2808
|
+
`
|
|
2809
|
+
const d = await bridge.run(py2, { title: `sheet dxf → ${side}`, publishHint: false })
|
|
2810
|
+
if (d && d.ok) out.dxf = { path: d.path, bytes: d.bytes }
|
|
2811
|
+
}
|
|
2812
|
+
return out
|
|
2813
|
+
},
|
|
2814
|
+
})
|
|
2815
|
+
|
|
2417
2816
|
tool({
|
|
2418
2817
|
name: 'cad_studio_measure',
|
|
2419
2818
|
description: 'Measure a model: volume, surface area, bounding box, centroid, face/edge counts, and optionally the distance between two points.',
|
|
@@ -3050,6 +3449,74 @@ if _TARGET:
|
|
|
3050
3449
|
},
|
|
3051
3450
|
})
|
|
3052
3451
|
|
|
3452
|
+
tool({
|
|
3453
|
+
name: 'cad_studio_mate',
|
|
3454
|
+
description: 'Place an assembly instance against another with a mate: concentric (axes collinear, axial distance = offset), flush (faces touch), or distance (faces `offset` apart along the axis). A mate is solved once per republish and then holds — it is not a driven joint. Use cad_studio_drive for the moving degrees of freedom.',
|
|
3455
|
+
parameters: {
|
|
3456
|
+
type: 'object',
|
|
3457
|
+
properties: {
|
|
3458
|
+
assembly: { type: 'string' },
|
|
3459
|
+
action: { type: 'string', enum: ['set', 'list', 'remove'], description: 'Default: set.' },
|
|
3460
|
+
id: { type: 'string', description: 'Mate id (remove / replace). Default: mate-<n>.' },
|
|
3461
|
+
type: { type: 'string', enum: ['concentric', 'flush', 'distance'] },
|
|
3462
|
+
a: { type: 'string', description: 'Instance name that moves.' },
|
|
3463
|
+
b: { type: 'string', description: 'Instance name that stays put.' },
|
|
3464
|
+
axis: { type: 'array', items: { type: 'number' }, description: 'Mate axis. Default [0,0,1].' },
|
|
3465
|
+
offset: { type: 'number', description: 'mm: axial distance (concentric) or face gap (distance). flush requires 0.' },
|
|
3466
|
+
side: { type: 'number', description: '+1 puts `a` on the positive side of `b` (default), -1 the negative side.' },
|
|
3467
|
+
},
|
|
3468
|
+
additionalProperties: false,
|
|
3469
|
+
},
|
|
3470
|
+
output: {
|
|
3471
|
+
schema: { type: 'object', properties: { ok: { type: 'boolean' }, sceneId: { type: 'string' } } },
|
|
3472
|
+
render: (_a, v) => [{ type: 'text', text: JSON.stringify(v, null, 2) }],
|
|
3473
|
+
},
|
|
3474
|
+
execute: async ({ assembly, action, id, type, a, b, axis, offset, side }) => {
|
|
3475
|
+
let record
|
|
3476
|
+
try {
|
|
3477
|
+
record = findAssembly(assembly)
|
|
3478
|
+
} catch (error) {
|
|
3479
|
+
return { ok: false, error: String(error?.message ?? error) }
|
|
3480
|
+
}
|
|
3481
|
+
const list = () => (record.mates ?? []).map((m) => ({ ...m, axis: m.axis.map(round6) }))
|
|
3482
|
+
const want = action ?? 'set'
|
|
3483
|
+
if (want === 'list') {
|
|
3484
|
+
return { ok: true, assembly: record.id, sceneId: record.sceneId, mates: list(), instances: record.base.map((x) => x.name) }
|
|
3485
|
+
}
|
|
3486
|
+
if (want === 'remove') {
|
|
3487
|
+
const target = String(id ?? '')
|
|
3488
|
+
const edit = bridge.beginAssemblyEdit(record, `mate remove ${target}`)
|
|
3489
|
+
const gone = bridge.removeMate(record, target)
|
|
3490
|
+
if (!gone) {
|
|
3491
|
+
const have = (record.mates ?? []).map((m) => m.id).join(', ') || '(没有)'
|
|
3492
|
+
return { ok: false, error: `没有这个约束:${target}(现有 ${have})` }
|
|
3493
|
+
}
|
|
3494
|
+
const published = await bridge.republishAssembly(record)
|
|
3495
|
+
bridge.endAssemblyEdit(edit, record)
|
|
3496
|
+
return { ok: true, assembly: record.id, sceneId: published.id, removed: gone.id, mates: list(), instances: published.stats.instances }
|
|
3497
|
+
}
|
|
3498
|
+
let value
|
|
3499
|
+
try {
|
|
3500
|
+
value = normalizeMate(record, { id, type, a, b, axis, offset, side })
|
|
3501
|
+
} catch (error) {
|
|
3502
|
+
return { ok: false, error: String(error?.message ?? error) }
|
|
3503
|
+
}
|
|
3504
|
+
const edit = bridge.beginAssemblyEdit(record, `mate ${value.type} ${value.a}→${value.b}`)
|
|
3505
|
+
bridge.setMate(record, value)
|
|
3506
|
+
const published = await bridge.republishAssembly(record)
|
|
3507
|
+
bridge.endAssemblyEdit(edit, record)
|
|
3508
|
+
return {
|
|
3509
|
+
ok: true,
|
|
3510
|
+
assembly: record.id,
|
|
3511
|
+
sceneId: published.id,
|
|
3512
|
+
mate: { ...value, axis: value.axis.map(round6) },
|
|
3513
|
+
mates: list(),
|
|
3514
|
+
instances: published.stats.instances,
|
|
3515
|
+
volume: round6(published.stats.volume),
|
|
3516
|
+
}
|
|
3517
|
+
},
|
|
3518
|
+
})
|
|
3519
|
+
|
|
3053
3520
|
tool({
|
|
3054
3521
|
name: 'cad_studio_explode',
|
|
3055
3522
|
description: 'Exploded view: push every instance radially away from the assembly centre by `factor` (0 = assembled, 0.5 = half the distance outward). Republished scene only — geometry and exports are untouched.',
|
|
@@ -3821,6 +4288,18 @@ if _TARGET:
|
|
|
3821
4288
|
* the emitter. A feature model runs its own `featuresScript` (which already
|
|
3822
4289
|
* knows how to export); a script model gets three extra lines appended.
|
|
3823
4290
|
*/
|
|
4291
|
+
/** Python source that rebuilds a saved model's shapes into `_shapes`. */
|
|
4292
|
+
async function modelShapes(name) {
|
|
4293
|
+
const dirs = bridge.modelsCandidates()
|
|
4294
|
+
const dir = dirs.find((d) => existsSync(join(d, `${name}.json`))) || dirs[0]
|
|
4295
|
+
if (!existsSync(join(dir, `${name}.json`))) return ''
|
|
4296
|
+
const doc = await readModel(name, dir)
|
|
4297
|
+
bridge.noteModelsDir(dir)
|
|
4298
|
+
return doc.kind === 'features'
|
|
4299
|
+
? featuresScript(featureOps(doc), '', { sketches: doc.sketches })
|
|
4300
|
+
: `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}\n`
|
|
4301
|
+
}
|
|
4302
|
+
|
|
3824
4303
|
async function exportModelStep(doc, target) {
|
|
3825
4304
|
if (typeof target !== 'string' || !target) throw new Error('export 需要目标路径,例如 /path/model.step')
|
|
3826
4305
|
await mkdir(dirname(target), { recursive: true })
|