dsh-cad-studio 0.6.0 → 0.7.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 +12 -0
- package/client.js +2 -1
- package/index.js +146 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -69,6 +69,18 @@ npm 包:<https://www.npmjs.com/package/dsh-cad-studio>(`dsh plugin` / DSH
|
|
|
69
69
|
|
|
70
70
|
选不中会**报错并在面板标红**:`选择器没有选中任何边:{"axis":"Z","type":"circle"}(当前形状有 12 条边)`。设计取舍见 `docs/RESEARCH-SELECTORS.md`。
|
|
71
71
|
|
|
72
|
+
## 增量重算
|
|
73
|
+
|
|
74
|
+
改一条特征不需要重跑整条链:每一步的 BREP 快照按「前缀哈希」缓存在 `$TMPDIR/dsh-cad-studio/cache/`,重算从最深命中的前缀恢复。
|
|
75
|
+
|
|
76
|
+
```
|
|
77
|
+
首次 17 条特征 354 ms
|
|
78
|
+
无改动的重建 1 ms (完全不起内核进程,revalidated: true)
|
|
79
|
+
只改最后一条 264 ms (16/17 来自缓存)
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
面板的特征页头会显示 `· 缓存 16/17`。缓存按 400 文件 / 14 天淘汰;`EMITTER_VERSION` 一变即整体失效(防止旧快照复活错误几何)。
|
|
83
|
+
|
|
72
84
|
## 接口约定与踩过的坑
|
|
73
85
|
|
|
74
86
|
- **导出只走 `cad_studio_export`**。在 `cad_studio_run` 里直接 `Part.export([compound], path)` 会写出一个 1.6 KB 的 STEP 壳子,读回来是空形状,而脚本本身不报错。要么用 `cad_studio_export`,要么给 `cad_studio_run` 传 `check: ["/path/out.step"]`——它会在跑完后把这个文件读回来,回报 `{bytes, solids, volume, valid}`,壳子会显示 `valid:false`。
|
package/client.js
CHANGED
|
@@ -1749,6 +1749,7 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
|
|
|
1749
1749
|
// the new scene replaces the old one in the tab being looked at.
|
|
1750
1750
|
const featureList = payload && Array.isArray(payload.features) ? payload.features : []
|
|
1751
1751
|
const featureModel = (payload && payload.model) || ''
|
|
1752
|
+
const cacheChip = payload && payload.cache && payload.cache.cached > 0 ? payload.cache : null
|
|
1752
1753
|
// A script model publishes its params (no feature list); they are editable
|
|
1753
1754
|
// the same way — one number, one rebuild of the same document.
|
|
1754
1755
|
const modelParams = payload && payload.params && typeof payload.params === 'object' ? payload.params : {}
|
|
@@ -1930,7 +1931,7 @@ const FILE_EXTS = ['step', 'stp', 'iges', 'igs', 'brep', 'stl']
|
|
|
1930
1931
|
: '当前场景不是特征模型。用 cad_studio_doc create kind="features" 建一个(features 里每个 {kind,params}),就能在这里逐条改数值。')]
|
|
1931
1932
|
: [
|
|
1932
1933
|
h('div', { key: 'h', style: { ...styles.treeHint, display: 'flex', gap: 6, alignItems: 'center' } }, [
|
|
1933
|
-
h('span', { key: 'm', style: { flex: '1 1 auto', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, `${featureModel} · ${featureList.length}
|
|
1934
|
+
h('span', { key: 'm', style: { flex: '1 1 auto', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', title: cacheChip ? `本次重算:${cacheChip.cached}/${cacheChip.of} 步来自缓存` : undefined } }, `${featureModel} · ${featureList.length} 特征${cacheChip ? ` · 缓存 ${cacheChip.cached}/${cacheChip.of}` : ''}`),
|
|
1934
1935
|
h('button', {
|
|
1935
1936
|
key: 'a',
|
|
1936
1937
|
type: 'button',
|
package/index.js
CHANGED
|
@@ -14,7 +14,8 @@
|
|
|
14
14
|
* GET /cad-studio/client.js the panel bundle (dev-mode serving)
|
|
15
15
|
*/
|
|
16
16
|
import { spawn, spawnSync } from 'node:child_process'
|
|
17
|
-
import { existsSync } from 'node:fs'
|
|
17
|
+
import { existsSync, readdirSync, statSync, rmSync } from 'node:fs'
|
|
18
|
+
import crypto from 'node:crypto'
|
|
18
19
|
import { mkdtemp, mkdir, readdir, readFile, rm, stat, unlink, writeFile } from 'node:fs/promises'
|
|
19
20
|
import { tmpdir } from 'node:os'
|
|
20
21
|
import { fileURLToPath } from 'node:url'
|
|
@@ -855,10 +856,58 @@ def describe(path):
|
|
|
855
856
|
* `kind:'features'` model document — so a typed list and an edited-and-rebuilt
|
|
856
857
|
* one cannot drift apart.
|
|
857
858
|
*/
|
|
858
|
-
|
|
859
|
+
/**
|
|
860
|
+
* Bump whenever the emitter's meaning changes: the BREP cache is keyed by
|
|
861
|
+
* (version, op-chain), so a stale entry from an older emitter would silently
|
|
862
|
+
* resurrect wrong geometry.
|
|
863
|
+
*/
|
|
864
|
+
const EMITTER_VERSION = 'e1'
|
|
865
|
+
|
|
866
|
+
/** One hash per prefix: hashes[i] = ops[0..i] applied. Skip markers reuse the
|
|
867
|
+
* previous hash, so toggling a suppressed feature does not invalidate
|
|
868
|
+
* anything upstream of it. */
|
|
869
|
+
function chainHashes(ops) {
|
|
870
|
+
const out = []
|
|
871
|
+
let h = crypto.createHash('sha1').update(`cad-studio:${EMITTER_VERSION}`).digest('hex').slice(0, 16)
|
|
872
|
+
for (const op of Array.isArray(ops) ? ops : []) {
|
|
873
|
+
if (op && op.kind === '__skip__') { out.push(h); continue }
|
|
874
|
+
const bare = { ...op }
|
|
875
|
+
delete bare._id
|
|
876
|
+
delete bare._label
|
|
877
|
+
h = crypto.createHash('sha1').update(h).update(JSON.stringify(bare)).digest('hex').slice(0, 16)
|
|
878
|
+
out.push(h)
|
|
879
|
+
}
|
|
880
|
+
return out
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
function brepCacheDir() { return join(FreeCadBridge.dataDir, 'cache') }
|
|
884
|
+
|
|
885
|
+
/** Content-addressed BREP snapshots are cheap to keep and cheap to prune:
|
|
886
|
+
* drop them oldest-first once the directory grows past a cap. */
|
|
887
|
+
function pruneBrepCache(dir, { maxFiles = 400, maxAgeDays = 14 } = {}) {
|
|
888
|
+
let names = []
|
|
889
|
+
try { names = readdirSync(dir).filter((n) => /^f_[0-9a-f]{16}\.brep$/.test(n)) } catch { return 0 }
|
|
890
|
+
const now = Date.now()
|
|
891
|
+
const kept = []
|
|
892
|
+
for (const n of names) {
|
|
893
|
+
try {
|
|
894
|
+
const st = statSync(join(dir, n))
|
|
895
|
+
if (now - st.mtimeMs > maxAgeDays * 86400_000) rmSync(join(dir, n), { force: true })
|
|
896
|
+
else kept.push({ n, at: st.mtimeMs })
|
|
897
|
+
} catch {}
|
|
898
|
+
}
|
|
899
|
+
kept.sort((a, b) => b.at - a.at)
|
|
900
|
+
let dropped = 0
|
|
901
|
+
for (const { n } of kept.slice(maxFiles)) { try { rmSync(join(dir, n), { force: true }); dropped += 1 } catch {} }
|
|
902
|
+
return dropped
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
const featuresScript = (ops, exportPath, opts = {}) => `${PRELUDE}
|
|
859
906
|
import os
|
|
860
907
|
_OPS = json.loads(${JSON.stringify(JSON.stringify(Array.isArray(ops) ? ops : []))})
|
|
861
908
|
_EXPORT = ${exportPath ? JSON.stringify(exportPath) : 'None'}
|
|
909
|
+
_CACHE = json.loads(${JSON.stringify(JSON.stringify(opts.cache && opts.cache.hashes ? { dir: opts.cache.dir, hashes: opts.cache.hashes } : null))})
|
|
910
|
+
_RESUME = json.loads(${JSON.stringify(JSON.stringify(opts.resume && opts.resume.brep ? { index: opts.resume.index, brep: opts.resume.brep } : null))})
|
|
862
911
|
|
|
863
912
|
def _v3(x, d=(0.0, 0.0, 0.0)):
|
|
864
913
|
if not x:
|
|
@@ -936,6 +985,20 @@ def _match_dir(_d, _ax, _mode, _sign):
|
|
|
936
985
|
return _c > 0.999 if _sign != "-" else _c < -0.999
|
|
937
986
|
|
|
938
987
|
|
|
988
|
+
def _core_of(s):
|
|
989
|
+
# A shape read back from a BREP cache is a Compound, and Compound has no
|
|
990
|
+
# CenterOfMass (only Solid does) — use the lone solid when there is one and
|
|
991
|
+
# the bounding box otherwise. It only has to be a point *inside* the body.
|
|
992
|
+
try:
|
|
993
|
+
if len(s.Solids) == 1:
|
|
994
|
+
return s.Solids[0].CenterOfMass
|
|
995
|
+
except Exception:
|
|
996
|
+
pass
|
|
997
|
+
try:
|
|
998
|
+
return s.BoundBox.Center
|
|
999
|
+
except Exception:
|
|
1000
|
+
return Vector(0.0, 0.0, 0.0)
|
|
1001
|
+
|
|
939
1002
|
def _center_of(_it):
|
|
940
1003
|
_b = _it.BoundBox
|
|
941
1004
|
return Vector((_b.XMin + _b.XMax) / 2.0, (_b.YMin + _b.YMax) / 2.0, (_b.ZMin + _b.ZMax) / 2.0)
|
|
@@ -1002,7 +1065,24 @@ def _sel(_shape, _kind, _spec):
|
|
|
1002
1065
|
_shape = None
|
|
1003
1066
|
_errors = []
|
|
1004
1067
|
_executed = 0
|
|
1068
|
+
_start = 0
|
|
1069
|
+
# Incremental recompute: resume from the deepest cached prefix instead of
|
|
1070
|
+
# replaying the whole chain. The cache is content-addressed by the op chain,
|
|
1071
|
+
# so an entry is only used when every upstream feature is byte-identical.
|
|
1072
|
+
if _RESUME and os.path.exists(_RESUME["brep"]):
|
|
1073
|
+
try:
|
|
1074
|
+
_cached = Part.Shape()
|
|
1075
|
+
_cached.read(_RESUME["brep"])
|
|
1076
|
+
if _cached.isValid() and not _cached.isNull():
|
|
1077
|
+
_shape = _cached
|
|
1078
|
+
_start = int(_RESUME["index"])
|
|
1079
|
+
_executed = _start
|
|
1080
|
+
except Exception as _e:
|
|
1081
|
+
_shape = None
|
|
1082
|
+
_start = 0
|
|
1005
1083
|
for _idx, _op in enumerate(_OPS):
|
|
1084
|
+
if _idx < _start:
|
|
1085
|
+
continue
|
|
1006
1086
|
_k = _op.get("kind")
|
|
1007
1087
|
if _k == "__skip__":
|
|
1008
1088
|
continue
|
|
@@ -1047,7 +1127,7 @@ for _idx, _op in enumerate(_OPS):
|
|
|
1047
1127
|
# stored orientation can point inward; cutting inward would
|
|
1048
1128
|
# remove nothing (the interior is already hollow), and
|
|
1049
1129
|
# cutting both ways would punch a hole clean through.
|
|
1050
|
-
_away = _center_of(_f) - _shape
|
|
1130
|
+
_away = _center_of(_f) - _core_of(_shape)
|
|
1051
1131
|
if _dot(_nrm, _away) < 0:
|
|
1052
1132
|
_nrm = Vector(0.0 - _nrm.x, 0.0 - _nrm.y, 0.0 - _nrm.z)
|
|
1053
1133
|
# Cut the wall itself: start a hair outside the plane and go
|
|
@@ -1106,6 +1186,15 @@ for _idx, _op in enumerate(_OPS):
|
|
|
1106
1186
|
})
|
|
1107
1187
|
break
|
|
1108
1188
|
_executed = _idx + 1
|
|
1189
|
+
if _CACHE and _idx < len(_CACHE.get("hashes") or []):
|
|
1190
|
+
try:
|
|
1191
|
+
_p = os.path.join(_CACHE["dir"], "f_%s.brep" % _CACHE["hashes"][_idx])
|
|
1192
|
+
if not os.path.exists(_p):
|
|
1193
|
+
_tmp = "%s.tmp%d" % (_p, os.getpid())
|
|
1194
|
+
_shape.exportBrep(_tmp)
|
|
1195
|
+
os.replace(_tmp, _p)
|
|
1196
|
+
except Exception:
|
|
1197
|
+
pass
|
|
1109
1198
|
|
|
1110
1199
|
if _shape is None:
|
|
1111
1200
|
raise RuntimeError(_errors[0]["message"] if _errors else "ops 为空:至少给一个图元")
|
|
@@ -1114,6 +1203,8 @@ scene = _shape
|
|
|
1114
1203
|
__out = {
|
|
1115
1204
|
"ok": True,
|
|
1116
1205
|
"features": len(_OPS),
|
|
1206
|
+
"cached": _start,
|
|
1207
|
+
"computed": max(0, _executed - _start),
|
|
1117
1208
|
"volume": round(_shape.Volume, 3),
|
|
1118
1209
|
"area": round(_shape.Area, 3),
|
|
1119
1210
|
"faces": len(_shape.Faces),
|
|
@@ -2152,7 +2243,13 @@ if _TARGET:
|
|
|
2152
2243
|
doc.tip = typeof doc.tip === 'string' && doc.tip ? doc.tip : null
|
|
2153
2244
|
doc.undo = Array.isArray(doc.undo) ? doc.undo : []
|
|
2154
2245
|
doc.redo = Array.isArray(doc.redo) ? doc.redo : []
|
|
2155
|
-
for (const f of doc.features)
|
|
2246
|
+
for (const f of doc.features) {
|
|
2247
|
+
if (!f || typeof f !== 'object') continue
|
|
2248
|
+
if (typeof f.suppressed === 'boolean') f.enabled = f.suppressed !== true
|
|
2249
|
+
// Older docs picked up a stray params.suppressed from a normalizer bug;
|
|
2250
|
+
// it changed the op hash for no geometric reason, so drop it on read.
|
|
2251
|
+
if (f.params && typeof f.params === 'object' && 'suppressed' in f.params) delete f.params.suppressed
|
|
2252
|
+
}
|
|
2156
2253
|
return doc
|
|
2157
2254
|
}
|
|
2158
2255
|
|
|
@@ -2211,7 +2308,7 @@ if _TARGET:
|
|
|
2211
2308
|
return ops
|
|
2212
2309
|
}
|
|
2213
2310
|
|
|
2214
|
-
const FEATURE_FIELDS = ['id', 'kind', 'label', 'params', 'enabled']
|
|
2311
|
+
const FEATURE_FIELDS = ['id', 'kind', 'label', 'params', 'enabled', 'suppressed']
|
|
2215
2312
|
|
|
2216
2313
|
/**
|
|
2217
2314
|
* Accept both shapes: `{kind:'box', params:{size:…}}` and the flatter
|
|
@@ -2310,8 +2407,37 @@ if _TARGET:
|
|
|
2310
2407
|
|
|
2311
2408
|
const rebuild = async (doc, dir, { note } = {}) => {
|
|
2312
2409
|
const isFeatures = doc.kind === 'features'
|
|
2410
|
+
// Incremental recompute (DESIGN §5.3): hash the op chain once, find the
|
|
2411
|
+
// deepest BREP prefix already on disk, and let the kernel start there.
|
|
2412
|
+
// A rebuild of an unchanged document skips the kernel entirely.
|
|
2413
|
+
let cache = null
|
|
2414
|
+
let resume = null
|
|
2415
|
+
let hashes = []
|
|
2416
|
+
if (isFeatures) {
|
|
2417
|
+
const ops = featureOps(doc)
|
|
2418
|
+
hashes = chainHashes(ops)
|
|
2419
|
+
const cacheDir = brepCacheDir()
|
|
2420
|
+
try { await mkdir(cacheDir, { recursive: true }) } catch {}
|
|
2421
|
+
cache = { dir: cacheDir, hashes }
|
|
2422
|
+
for (let k = hashes.length - 1; k >= 0; k -= 1) {
|
|
2423
|
+
const candidate = join(cacheDir, `f_${hashes[k]}.brep`)
|
|
2424
|
+
if (existsSync(candidate)) { resume = { index: k + 1, brep: candidate }; break }
|
|
2425
|
+
}
|
|
2426
|
+
const fullHash = hashes[hashes.length - 1] ?? ''
|
|
2427
|
+
const keep = doc.stats?.sceneId && bridge.scenes?.has(doc.stats.sceneId)
|
|
2428
|
+
if (fullHash && keep && doc.stats?.hash === fullHash) {
|
|
2429
|
+
// Nothing changed and the scene is still live: no kernel run at all.
|
|
2430
|
+
return {
|
|
2431
|
+
ok: true, evaluated: true, cached: hashes.length, computed: 0, name: doc.name, dir,
|
|
2432
|
+
graph: graphView(doc, { errors: [], executed: hashes.length }),
|
|
2433
|
+
errors: [], run: doc.run, params: doc.params, volume: doc.stats.volume,
|
|
2434
|
+
triangles: doc.stats.triangles, sceneId: doc.stats.sceneId, bounds: doc.stats.bounds,
|
|
2435
|
+
note: doc.note, revalidated: true,
|
|
2436
|
+
}
|
|
2437
|
+
}
|
|
2438
|
+
}
|
|
2313
2439
|
const code = isFeatures
|
|
2314
|
-
? featuresScript(featureOps(doc))
|
|
2440
|
+
? featuresScript(featureOps(doc), null, { cache, resume })
|
|
2315
2441
|
: `${PRELUDE}\nP = ${JSON.stringify(doc.params ?? {})}\n${doc.script}`
|
|
2316
2442
|
const meta = isFeatures ? { model: doc.name, features: publicFeatures(doc), tip: doc.tip ?? null } : { model: doc.name, params: doc.params ?? {} }
|
|
2317
2443
|
doc.run = (doc.run ?? 0) + 1
|
|
@@ -2334,6 +2460,8 @@ if _TARGET:
|
|
|
2334
2460
|
bounds: out.bounds ?? null,
|
|
2335
2461
|
sceneId,
|
|
2336
2462
|
at: doc.updatedAt,
|
|
2463
|
+
hash: hashes[hashes.length - 1] ?? '',
|
|
2464
|
+
cached: out.cached ?? 0,
|
|
2337
2465
|
}
|
|
2338
2466
|
if (note) doc.note = note
|
|
2339
2467
|
// The scene was published before the kernel reported which nodes failed, so
|
|
@@ -2342,15 +2470,23 @@ if _TARGET:
|
|
|
2342
2470
|
const scene = sceneId ? bridge.scenes?.get(sceneId) : null
|
|
2343
2471
|
if (scene) {
|
|
2344
2472
|
scene.graph = graph
|
|
2473
|
+
scene.cache = { cached: out.cached ?? 0, computed: out.computed ?? null, of: hashes.length }
|
|
2345
2474
|
try { await bridge.persist() } catch {}
|
|
2346
2475
|
}
|
|
2347
2476
|
await writeModel(doc, dir)
|
|
2477
|
+
if (isFeatures && hashes.length) {
|
|
2478
|
+
// Cheap housekeeping, off the hot path: a 400-file / 14-day cap keeps the
|
|
2479
|
+
// cache from growing without bound in a long-lived install.
|
|
2480
|
+
try { pruneBrepCache(brepCacheDir()) } catch {}
|
|
2481
|
+
}
|
|
2348
2482
|
return {
|
|
2349
2483
|
ok: true,
|
|
2350
2484
|
evaluated: !(Array.isArray(out.errors) && out.errors.length > 0),
|
|
2351
2485
|
name: doc.name,
|
|
2352
2486
|
dir,
|
|
2353
2487
|
graph,
|
|
2488
|
+
cached: out.cached ?? 0,
|
|
2489
|
+
computed: out.computed ?? null,
|
|
2354
2490
|
errors: Array.isArray(out.errors) ? out.errors : [],
|
|
2355
2491
|
run: doc.run,
|
|
2356
2492
|
params: doc.params,
|
|
@@ -2530,6 +2666,10 @@ if _TARGET:
|
|
|
2530
2666
|
triangles: doc.stats?.triangles ?? null,
|
|
2531
2667
|
sceneId: doc.stats?.sceneId ?? '',
|
|
2532
2668
|
run: doc.run,
|
|
2669
|
+
// How much of the chain came from the BREP cache vs the kernel this time.
|
|
2670
|
+
cached: result.cached ?? doc.stats?.cached ?? 0,
|
|
2671
|
+
computed: result.computed ?? null,
|
|
2672
|
+
revalidated: result.revalidated === true,
|
|
2533
2673
|
}
|
|
2534
2674
|
}
|
|
2535
2675
|
|