dsh-qizhoucnc-cam 1.3.4 → 1.3.6

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/client.js +457 -65
  2. package/index.js +195 -0
  3. package/package.json +1 -1
package/client.js CHANGED
@@ -55,6 +55,24 @@ window.__ModuleLoader__.load({
55
55
  return [x1, -y2]; // screen: X right, Y up (CNC Z-up)
56
56
  }
57
57
 
58
+ // 夹具/毛坯位姿:对点先绕 Z/Y/X 旋转(度),再平移(mm)。
59
+ function applyAssetTransform(p, t) {
60
+ if (!t) return p;
61
+ const tr = t.translate || [0, 0, 0];
62
+ const rt = t.rotate || [0, 0, 0];
63
+ let [x, y, z] = p;
64
+ // 绕 Z
65
+ const rz = (rt[2] || 0) * Math.PI / 180;
66
+ if (rz) { const c = Math.cos(rz), s = Math.sin(rz); const nx = x * c - y * s; const ny = x * s + y * c; x = nx; y = ny; }
67
+ // 绕 Y
68
+ const ry = (rt[1] || 0) * Math.PI / 180;
69
+ if (ry) { const c = Math.cos(ry), s = Math.sin(ry); const nx = x * c + z * s; const nz = -x * s + z * c; x = nx; z = nz; }
70
+ // 绕 X
71
+ const rx = (rt[0] || 0) * Math.PI / 180;
72
+ if (rx) { const c = Math.cos(rx), s = Math.sin(rx); const ny = y * c - z * s; const nz = y * s + z * c; y = ny; z = nz; }
73
+ return [x + (tr[0] || 0), y + (tr[1] || 0), z + (tr[2] || 0)];
74
+ }
75
+
58
76
  // six standard views + isometric default
59
77
  const VIEWS = [
60
78
  { id: 'iso', label: '等轴', yaw: 0.7, pitch: 0.55 },
@@ -252,12 +270,17 @@ window.__ModuleLoader__.load({
252
270
  // scene 来自 /dsh-cam/model:{ bounds:{min,max}, faces:[{id,vertices,triangles,center,area}], edges:[{id,points}] }
253
271
  // selected: { kind:'face'|'edge', id } | null;点击面/边时回传 onSelect。
254
272
  // pivot: [x,y,z] 旋转轴心;默认取模型包围盒中心。旋转/缩放都围绕该点。
255
- function ModelViewer3D({ scene, selected, onSelect, onAnnotate, pivot, features }) {
273
+ function ModelViewer3D({ scene, selected, onSelect, onAnnotate, pivot, features, locate, overlays, transform }) {
256
274
  const [view, setView] = React.useState(null);
257
275
  const drag = React.useRef(null);
258
- const suppressClick = React.useRef(false);
276
+ // 单击/双击判定:记录上次点击的目标与时间(同目标 350ms 内再次点击 = 双击标注)
277
+ const clickState = React.useRef({ time: 0, kind: null, id: null });
278
+ const clickTimer = React.useRef(null);
259
279
  const W = 600, H = 460, cx = W / 2, cy = H / 2;
260
280
  const pv = pivot || [0, 0, 0];
281
+ // 主体模型的位移/旋转(与夹具/毛坯同款 transform):{ translate:[x,y,z], rotate:[rx,ry,rz] }
282
+ const xf = transform || null;
283
+ const tpv = xf ? applyAssetTransform(pv, xf) : pv;
261
284
  // 已标注特征:kind+refId → feature 记录(用于橙色高亮)
262
285
  const featureKey = (f) => f.kind + ':' + f.refId;
263
286
  const featMap = React.useMemo(() => {
@@ -267,9 +290,10 @@ window.__ModuleLoader__.load({
267
290
  }, [features]);
268
291
 
269
292
  const toScreen = React.useCallback((p) => {
270
- const [sx, sy] = project3d([p[0] - pv[0], p[1] - pv[1], p[2] - pv[2]], view.yaw, view.pitch);
293
+ const q = xf ? applyAssetTransform(p, xf) : p;
294
+ const [sx, sy] = project3d([q[0] - tpv[0], q[1] - tpv[1], q[2] - tpv[2]], view.yaw, view.pitch);
271
295
  return [cx + sx * view.zoom + view.panX, cy + sy * view.zoom + view.panY];
272
- }, [view, pv[0], pv[1], pv[2]]);
296
+ }, [view, tpv[0], tpv[1], tpv[2], xf]);
273
297
 
274
298
  // fit the whole model into the viewport for a given yaw/pitch (relative to pivot)
275
299
  const fitView = React.useCallback((yaw, pitch) => {
@@ -283,14 +307,15 @@ window.__ModuleLoader__.load({
283
307
  ];
284
308
  let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
285
309
  for (const p of corners) {
286
- const [sx, sy] = project3d([p[0] - pv[0], p[1] - pv[1], p[2] - pv[2]], yaw, pitch);
310
+ const q = xf ? applyAssetTransform(p, xf) : p;
311
+ const [sx, sy] = project3d([q[0] - tpv[0], q[1] - tpv[1], q[2] - tpv[2]], yaw, pitch);
287
312
  if (sx < minX) minX = sx; if (sx > maxX) maxX = sx;
288
313
  if (sy < minY) minY = sy; if (sy > maxY) maxY = sy;
289
314
  }
290
315
  const w = maxX - minX, h = maxY - minY;
291
316
  const zoom = Math.min((W - 40) / Math.max(1e-6, w), (H - 40) / Math.max(1e-6, h));
292
317
  return { yaw, pitch, panX: 0, panY: 0, zoom: Math.max(0.05, Math.min(20, zoom)) };
293
- }, [scene, pv[0], pv[1], pv[2]]);
318
+ }, [scene, tpv[0], tpv[1], tpv[2], xf]);
294
319
 
295
320
  // (re)fit when the scene changes
296
321
  React.useEffect(() => { setView(fitView(0.7, 0.55)); }, [scene, fitView]);
@@ -328,6 +353,38 @@ window.__ModuleLoader__.load({
328
353
  const EDGE_COLOR = '#64748b';
329
354
  const EDGE_SELECTED = '#ff9a3d';
330
355
  const FEAT_FILL = 'rgba(255,154,61,0.72)'; // 已标注特征:橙色高亮
356
+ const LOCATE_FILL = 'rgba(34,197,94,0.85)'; // 点击标签定位:亮绿高亮
357
+ const LOCATE_STROKE = '#16a34a';
358
+
359
+ // 点击左侧标注列表某条 → 定位到模型对应面/边并高亮
360
+ const locateKey = locate ? (locate.kind + ':' + locate.id) : null;
361
+
362
+ // 光照着色:按面法向做朗伯明暗(Lambert),让每个面有明暗层次,立体感强、
363
+ // 与浅色/深色背景都能区分开,避免纯色与背景融合。
364
+ const LIGHT = (() => { const l = [0.42, 0.36, 0.83]; const m = Math.hypot(l[0], l[1], l[2]); return [l[0] / m, l[1] / m, l[2] / m]; })();
365
+ const rotateDir = (p, yaw, pitch) => {
366
+ const [x, y, z] = p;
367
+ const cy = Math.cos(yaw), sy = Math.sin(yaw);
368
+ const x1 = x * cy - y * sy, y1 = x * sy + y * cy;
369
+ const cp = Math.cos(pitch), sp = Math.sin(pitch);
370
+ return [x1, y1 * cp + z * sp, -y1 * sp + z * cp];
371
+ };
372
+ const faceNormal = (f) => {
373
+ for (const tri of f.triangles) {
374
+ const a = f.vertices[tri[0]], b = f.vertices[tri[1]], c = f.vertices[tri[2]];
375
+ const nx = (b[1] - a[1]) * (c[2] - a[2]) - (b[2] - a[2]) * (c[1] - a[1]);
376
+ const ny = (b[2] - a[2]) * (c[0] - a[0]) - (b[0] - a[0]) * (c[2] - a[2]);
377
+ const nz = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
378
+ const len = Math.hypot(nx, ny, nz);
379
+ if (len > 1e-9) return [nx / len, ny / len, nz / len];
380
+ }
381
+ return [0, 0, 1];
382
+ };
383
+ const shadeOf = (n) => {
384
+ const rn = rotateDir(n, view.yaw, view.pitch);
385
+ const nd = rn[0] * LIGHT[0] + rn[1] * LIGHT[1] + rn[2] * LIGHT[2];
386
+ return 0.34 + 0.66 * Math.max(0, nd);
387
+ };
331
388
 
332
389
  // faces → ONE <path> per face (merge all its triangles into a single path).
333
390
  // 每个三角形若独立成 <polygon>,复杂 STEP 会有上万 DOM 节点导致崩溃;
@@ -336,27 +393,30 @@ window.__ModuleLoader__.load({
336
393
  for (const f of scene.faces) {
337
394
  const isSel = selected && selected.kind === 'face' && selected.id === f.id;
338
395
  const isFeat = featMap['face:' + f.id];
396
+ const isLoc = locateKey === 'face:' + f.id;
397
+ const shade = shadeOf(faceNormal(f));
398
+ const r = Math.round(96 * shade), g = Math.round(116 * shade), b = Math.round(140 * shade);
399
+ const baseFill = 'rgb(' + r + ',' + g + ',' + b + ')';
400
+ const hoverFill = 'rgb(' + Math.min(255, r + 42) + ',' + Math.min(255, g + 42) + ',' + Math.min(255, b + 42) + ')';
401
+ const fillColor = isLoc ? LOCATE_FILL : (isFeat ? FEAT_FILL : (isSel ? FACE_SELECTED : baseFill));
339
402
  let d = '';
340
- let p0 = null;
341
403
  for (const tri of f.triangles) {
342
404
  const a = f.vertices[tri[0]], b = f.vertices[tri[1]], c = f.vertices[tri[2]];
343
405
  const [ax, ay] = toScreen(a), [bx, by] = toScreen(b), [cx2, cy2] = toScreen(c);
344
406
  d += 'M' + ax.toFixed(1) + ' ' + ay.toFixed(1)
345
407
  + 'L' + bx.toFixed(1) + ' ' + by.toFixed(1)
346
408
  + 'L' + cx2.toFixed(1) + ' ' + cy2.toFixed(1) + 'Z';
347
- if (p0 === null) p0 = [ax, ay];
348
409
  }
349
410
  faceEls.push(h('path', {
350
411
  key: 'f' + f.id,
351
412
  d,
352
- fill: isFeat ? FEAT_FILL : (isSel ? FACE_SELECTED : FACE_FILL),
353
- stroke: isFeat ? '#f97316' : (isSel ? '#f97316' : FACE_STROKE),
354
- strokeWidth: isFeat ? 0.8 : 0.4, strokeLinejoin: 'round',
413
+ fill: fillColor,
414
+ stroke: isLoc ? LOCATE_STROKE : (isFeat ? '#f97316' : (isSel ? '#f97316' : FACE_STROKE)),
415
+ strokeWidth: isLoc ? 2.4 : (isFeat ? 0.8 : 0.4), strokeLinejoin: 'round',
355
416
  style: { cursor: 'pointer' },
356
- onMouseEnter: (e) => { if (!isSel && !isFeat) e.currentTarget.setAttribute('fill', FACE_HOVER); },
357
- onMouseLeave: (e) => { if (!isSel && !isFeat) e.currentTarget.setAttribute('fill', FACE_FILL); },
358
- onClick: clickGuard(() => onSelect({ kind: 'face', id: f.id, center: f.center, area: f.area })),
359
- onDoubleClick: clickGuard(() => onAnnotate({ kind: 'face', id: f.id, center: f.center, area: f.area })),
417
+ 'data-hit': 'face', 'data-id': f.id,
418
+ onMouseEnter: (e) => { if (!isSel && !isFeat && !isLoc) e.currentTarget.setAttribute('fill', hoverFill); },
419
+ onMouseLeave: (e) => { if (!isSel && !isFeat && !isLoc) e.currentTarget.setAttribute('fill', baseFill); },
360
420
  }));
361
421
  }
362
422
  // edges as individual <polyline> for picking
@@ -364,55 +424,133 @@ window.__ModuleLoader__.load({
364
424
  for (const e of scene.edges) {
365
425
  const isSel = selected && selected.kind === 'edge' && selected.id === e.id;
366
426
  const isFeat = featMap['edge:' + e.id];
427
+ const isLoc = locateKey === 'edge:' + e.id;
367
428
  let pts = '';
368
429
  e.points.forEach((p, j) => { const [sx, sy] = toScreen(p); pts += (j === 0 ? '' : ' ') + sx.toFixed(1) + ',' + sy.toFixed(1); });
369
430
  edgeEls.push(h('polyline', {
370
431
  key: 'e' + e.id,
371
432
  points: pts,
372
433
  fill: 'none',
373
- stroke: isFeat ? '#f97316' : (isSel ? EDGE_SELECTED : EDGE_COLOR),
374
- strokeWidth: isFeat ? 3.2 : (isSel ? 3 : 1.4),
434
+ stroke: isLoc ? LOCATE_STROKE : (isFeat ? '#f97316' : (isSel ? EDGE_SELECTED : EDGE_COLOR)),
435
+ strokeWidth: isLoc ? 4.4 : (isFeat ? 3.2 : (isSel ? 3 : 1.4)),
375
436
  strokeLinejoin: 'round', strokeLinecap: 'round',
376
437
  style: { cursor: 'pointer' },
377
- onClick: clickGuard(() => onSelect({ kind: 'edge', id: e.id, points: e.points })),
378
- onDoubleClick: clickGuard(() => onAnnotate({ kind: 'edge', id: e.id, points: e.points })),
438
+ 'data-hit': 'edge', 'data-id': e.id,
379
439
  }));
380
440
  }
381
441
 
442
+ // ---- overlays (夹具/毛坯): render extra models with role-tinted colors, NOT pickable ----
443
+ const overlayEls = [];
444
+ const ROLE_COLORS = {
445
+ fixture: { face: 'rgba(99,102,241,0.30)', stroke: 'rgba(79,70,229,0.85)', edge: 'rgba(129,140,248,0.95)' },
446
+ blank: { face: 'rgba(16,185,129,0.22)', stroke: 'rgba(5,150,105,0.85)', edge: 'rgba(52,211,153,0.95)' },
447
+ };
448
+ for (const ov of (overlays || [])) {
449
+ const oscene = ov && ov.scene;
450
+ if (!oscene || !Array.isArray(oscene.faces)) continue;
451
+ const rc = ROLE_COLORS[ov.asset && ov.asset.role] || ROLE_COLORS.blank;
452
+ const xf = ov.asset && ov.asset.transform ? ov.asset.transform : null;
453
+ // faces: one path per face (semi-transparent role tint), with transform applied
454
+ for (const f of oscene.faces) {
455
+ let d = '';
456
+ for (const tri of f.triangles) {
457
+ const a = applyAssetTransform(f.vertices[tri[0]], xf), b = applyAssetTransform(f.vertices[tri[1]], xf), c = applyAssetTransform(f.vertices[tri[2]], xf);
458
+ const [ax, ay] = toScreen(a), [bx, by] = toScreen(b), [cx2, cy2] = toScreen(c);
459
+ d += 'M' + ax.toFixed(1) + ' ' + ay.toFixed(1) + 'L' + bx.toFixed(1) + ' ' + by.toFixed(1) + 'L' + cx2.toFixed(1) + ' ' + cy2.toFixed(1) + 'Z';
460
+ }
461
+ overlayEls.push(h('path', {
462
+ key: 'ov-' + ov.asset.id + '-f' + f.id,
463
+ d, fill: rc.face, stroke: rc.stroke, strokeWidth: 0.4, strokeLinejoin: 'round',
464
+ pointerEvents: 'none',
465
+ }));
466
+ }
467
+ // edges
468
+ for (const e of oscene.edges) {
469
+ let pts = '';
470
+ e.points.forEach((p, j) => { const q = applyAssetTransform(p, xf); const [sx, sy] = toScreen(q); pts += (j === 0 ? '' : ' ') + sx.toFixed(1) + ',' + sy.toFixed(1); });
471
+ overlayEls.push(h('polyline', {
472
+ key: 'ov-' + ov.asset.id + '-e' + e.id,
473
+ points: pts, fill: 'none', stroke: rc.edge, strokeWidth: 1.2,
474
+ strokeLinejoin: 'round', strokeLinecap: 'round', pointerEvents: 'none',
475
+ }));
476
+ }
477
+ }
478
+
479
+ // 命中测试:从指针下的元素向上找带 data-hit 的面/边(渲染时已给每个 path/polyline 打 data-hit/data-id)。
480
+ const hitTest = (clientX, clientY) => {
481
+ if (typeof document === 'undefined') return null;
482
+ let node = document.elementFromPoint(clientX, clientY);
483
+ while (node && node !== document.body && node !== document.documentElement) {
484
+ const hk = node.getAttribute && node.getAttribute('data-hit');
485
+ if (hk === 'face' || hk === 'edge') {
486
+ const id = Number(node.getAttribute('data-id'));
487
+ return { kind: hk, id };
488
+ }
489
+ node = node.parentNode;
490
+ }
491
+ return null;
492
+ };
493
+ // 单击/双击:同一面/边 350ms 内两次点击 = 双击(标注),否则单击(选中)。
494
+ const fireClick = (hit) => {
495
+ if (!hit) return;
496
+ const now = Date.now();
497
+ const prev = clickState.current;
498
+ if (prev && prev.kind === hit.kind && prev.id === hit.id && (now - prev.time) < 350) {
499
+ clearTimeout(clickTimer.current);
500
+ clickState.current = { time: 0, kind: null, id: null };
501
+ if (hit.kind === 'face') {
502
+ const f = scene.faces.find((x) => x.id === hit.id);
503
+ if (f) onAnnotate({ kind: 'face', id: f.id, center: f.center, area: f.area });
504
+ } else {
505
+ const ed = scene.edges.find((x) => x.id === hit.id);
506
+ if (ed) onAnnotate({ kind: 'edge', id: ed.id, points: ed.points });
507
+ }
508
+ return;
509
+ }
510
+ clickState.current = { time: now, kind: hit.kind, id: hit.id };
511
+ clearTimeout(clickTimer.current);
512
+ clickTimer.current = setTimeout(() => {
513
+ clickState.current = { time: 0, kind: null, id: null };
514
+ if (hit.kind === 'face') {
515
+ const f = scene.faces.find((x) => x.id === hit.id);
516
+ if (f) onSelect({ kind: 'face', id: f.id, center: f.center, area: f.area });
517
+ } else {
518
+ const ed = scene.edges.find((x) => x.id === hit.id);
519
+ if (ed) onSelect({ kind: 'edge', id: ed.id, points: ed.points });
520
+ }
521
+ }, 350);
522
+ };
523
+
524
+ // 用与刀路 Viewer3D 相同的 setPointerCapture 拖拽模式:可靠旋转/平移(Electron 下最稳)。
382
525
  const onPointerDown = (e) => {
383
526
  if (e.button !== 0 && e.button !== 1 && e.button !== 2) return;
384
- suppressClick.current = false;
527
+ e.preventDefault();
528
+ e.currentTarget.setPointerCapture(e.pointerId);
385
529
  drag.current = {
386
530
  x: e.clientX, y: e.clientY,
387
531
  yaw: view.yaw, pitch: view.pitch, panX: view.panX, panY: view.panY,
388
532
  mode: (e.button === 2 || e.shiftKey) ? 'pan' : 'rotate',
389
533
  moved: false,
390
534
  };
391
- const move = (ev) => {
392
- const d = drag.current; if (!d) return;
393
- const dx = ev.clientX - d.x, dy = ev.clientY - d.y;
394
- if (!d.moved && Math.abs(dx) + Math.abs(dy) > 3) d.moved = true;
395
- if (!d.moved) return;
396
- suppressClick.current = true;
397
- if (d.mode === 'pan') setView((v) => ({ ...v, panX: d.panX + dx, panY: d.panY + dy }));
398
- else setView((v) => ({ ...v, yaw: d.yaw + dx * 0.01, pitch: Math.max(-Math.PI / 2, Math.min(Math.PI / 2, d.pitch + dy * 0.01)) }));
399
- };
400
- const up = () => {
401
- drag.current = null;
402
- window.removeEventListener('pointermove', move);
403
- window.removeEventListener('pointerup', up);
404
- window.removeEventListener('pointercancel', up);
405
- };
406
- window.addEventListener('pointermove', move);
407
- window.addEventListener('pointerup', up);
408
- window.addEventListener('pointercancel', up);
409
535
  };
410
- const onWheel = (e) => { e.preventDefault(); setView((v) => ({ ...v, zoom: Math.max(0.05, Math.min(20, v.zoom * (e.deltaY < 0 ? 1.12 : 0.9))) })); };
411
- const clickGuard = (fn) => (e) => {
412
- e.stopPropagation();
413
- if (suppressClick.current) { suppressClick.current = false; return; }
414
- fn();
536
+ const onPointerMove = (e) => {
537
+ const d = drag.current;
538
+ if (!d) return;
539
+ const dx = e.clientX - d.x, dy = e.clientY - d.y;
540
+ if (!d.moved && Math.abs(dx) + Math.abs(dy) > 3) d.moved = true;
541
+ if (!d.moved) return;
542
+ if (d.mode === 'pan') setView((v) => ({ ...v, panX: d.panX + dx, panY: d.panY + dy }));
543
+ else setView((v) => ({ ...v, yaw: d.yaw + dx * 0.01, pitch: Math.max(-Math.PI / 2, Math.min(Math.PI / 2, d.pitch + dy * 0.01)) }));
544
+ };
545
+ const onPointerUp = (e) => {
546
+ const d = drag.current;
547
+ drag.current = null;
548
+ if (d && !d.moved) {
549
+ // 未拖拽 = 一次点击:命中面/边则触发单击/双击判定
550
+ fireClick(hitTest(e.clientX, e.clientY));
551
+ }
415
552
  };
553
+ const onWheel = (e) => { e.preventDefault(); setView((v) => ({ ...v, zoom: Math.max(0.05, Math.min(20, v.zoom * (e.deltaY < 0 ? 1.12 : 0.9))) })); };
416
554
 
417
555
  const applyView = (v) => setView((cur) => fitView(v.yaw, v.pitch));
418
556
  const viewBtn = (v, active) => h('button', {
@@ -438,13 +576,14 @@ window.__ModuleLoader__.load({
438
576
  h('svg', {
439
577
  viewBox: '0 0 ' + W + ' ' + H, width: '100%', height: '100%',
440
578
  style: { background: 'var(--dsw-alias-bg-base, #fff)', borderRadius: 8, border: '1px solid var(--dsw-alias-border-l1, #e5e7eb)', touchAction: 'none', cursor: 'grab', flex: 1, minHeight: 0 },
441
- onPointerDown, onWheel, onContextMenu: (e) => e.preventDefault(),
442
- onMouseDown: (e) => { if (e.target === e.currentTarget) onSelect(null); },
579
+ onPointerDown, onPointerMove, onPointerUp, onPointerCancel: onPointerUp,
580
+ onWheel, onContextMenu: (e) => e.preventDefault(),
443
581
  },
444
582
  gridLines.map((g, i) => line(g, 'var(--dsw-alias-border-l1, #e5e7eb)', 0.5)),
445
583
  axes.map((a, i) => line(a.pts, a.color, 1.2)),
446
584
  h('g', null, faceEls),
447
- h('g', null, edgeEls)),
585
+ h('g', null, edgeEls),
586
+ h('g', null, overlayEls)),
448
587
  h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, fontSize: 11 } },
449
588
  h('span', { style: { flex: 1, color: selected ? 'var(--dsw-alias-brand-primary, #2563eb)' : 'var(--dsw-alias-label-tertiary, #9ca3af)', fontWeight: selected ? 600 : 400 } }, selText),
450
589
  h('span', { style: { color: 'var(--dsw-alias-label-tertiary, #9ca3af)' } },
@@ -706,7 +845,7 @@ window.__ModuleLoader__.load({
706
845
  };
707
846
  const btn = { display: 'inline-flex', alignItems: 'center', gap: 4, padding: '3px 10px', fontSize: 12, cursor: 'pointer', borderRadius: 6, border: '1px solid var(--dsw-alias-border-l1, #e5e7eb)', background: 'var(--dsw-alias-interactive-bg, transparent)', color: 'var(--dsw-alias-label-primary, #111)' };
708
847
  const btnPrimary = { display: 'inline-flex', alignItems: 'center', gap: 4, padding: '3px 12px', fontSize: 12, cursor: 'pointer', fontWeight: 600, borderRadius: 6, border: '1px solid transparent', background: 'var(--dsw-alias-state-business-primary, #2563eb)', color: '#fff' };
709
- const input = { flex: 1, minWidth: 0, padding: '5px 8px', fontSize: 12, border: '1px solid var(--dsw-alias-border-l1, #e5e7eb)', borderRadius: 6, background: 'var(--dsw-alias-surface, #fff)', color: 'var(--dsw-alias-label-primary, #111)' };
848
+ const input = { flex: 1, minWidth: 0, padding: '6px 10px', fontSize: 13, border: '1px solid #d1d5db', borderRadius: 6, background: '#ffffff', color: '#111827' };
710
849
 
711
850
  function ToolpathPanel({ useSessions }) {
712
851
  const [open, setOpen] = React.useState(true);
@@ -734,11 +873,30 @@ window.__ModuleLoader__.load({
734
873
  const [modelFeatures, setModelFeatures] = React.useState([]);
735
874
  const [featureName, setFeatureName] = React.useState('');
736
875
  const [featureNote, setFeatureNote] = React.useState('');
876
+ // 二次修改:正在编辑的标注 id(null=新建);双击标注项进入重命名态
877
+ const [editingFeatureId, setEditingFeatureId] = React.useState(null);
737
878
  // 模型视窗的旋转轴心(默认为 null → 用模型包围盒中心);用户可设自定义轴心
738
879
  const [modelPivot, setModelPivot] = React.useState(null);
880
+ // 主体(被加工零件)的位移/旋转,与夹具/毛坯同款 transform
881
+ const [mainTransform, setMainTransform] = React.useState(null); // { translate:[x,y,z], rotate:[rx,ry,rz] } | null
882
+ const [mainTf, setMainTf] = React.useState({ translate: [0, 0, 0], rotate: [0, 0, 0] }); // 输入框暂存
883
+ // 点击左侧标注列表项 → 定位到模型对应面/边并高亮({ kind, id })
884
+ const [locateTarget, setLocateTarget] = React.useState(null);
885
+ // 夹具 / 毛坯(额外叠加到模型视窗的模型,供 AI 了解夹持与毛坯形状)
886
+ const [assets, setAssets] = React.useState([]); // [{ id, name, role:'fixture'|'blank', path }]
887
+ const [assetScenes, setAssetScenes] = React.useState({}); // id -> scene
888
+ const [assetName, setAssetName] = React.useState('');
889
+ const [assetPath, setAssetPath] = React.useState('');
890
+ const [assetRole, setAssetRole] = React.useState('blank'); // 'blank' | 'fixture'
891
+ // 夹具/毛坯位姿调整:选中的 asset id + 其 translate(mm)/rotate(deg)
892
+ const [editingAssetId, setEditingAssetId] = React.useState(null);
893
+ const [assetTransform, setAssetTransform] = React.useState({ translate: [0, 0, 0], rotate: [0, 0, 0] });
739
894
  // 打赏二维码弹窗
740
895
  const [showReward, setShowReward] = React.useState(false);
896
+ // 底部设置区(主体零件位移/旋转 + 夹具/毛坯)折叠/展开
897
+ const [setupCollapsed, setSetupCollapsed] = React.useState(false);
741
898
  const panelRef = React.useRef(null);
899
+ const assetFileRef = React.useRef(null); // 隐藏的 <input type=file>,用于原生「打开文件」对话框选择 STEP
742
900
  // 可拖拽调节的面板宽度(像素),持久化到 localStorage
743
901
  const [panelWidth, setPanelWidth] = React.useState(() => {
744
902
  try {
@@ -891,9 +1049,12 @@ window.__ModuleLoader__.load({
891
1049
  setModelScene(d);
892
1050
  setModelSelected(null);
893
1051
  setAnnotating(false);
1052
+ setMainTransform(null);
1053
+ setMainTf({ translate: [0, 0, 0], rotate: [0, 0, 0] });
894
1054
  setViewMode('model');
895
1055
  setModelFile(p);
896
1056
  loadFeatures(p);
1057
+ loadAssets(p);
897
1058
  } else {
898
1059
  setErr((d && d.error) || '模型加载失败');
899
1060
  }
@@ -916,23 +1077,171 @@ window.__ModuleLoader__.load({
916
1077
  const name = featureName.trim();
917
1078
  if (!name) { setErr('请为这个加工位置填写名称'); return; }
918
1079
  setBusy(true); setErr(null);
919
- post('/dsh-cam/feature', {
1080
+ const body = {
920
1081
  model: modelFile,
921
1082
  name,
922
1083
  kind: modelSelected.kind,
923
1084
  refId: modelSelected.id,
924
1085
  note: featureNote.trim(),
925
- })
1086
+ };
1087
+ // 二次修改:若正在编辑某条已有标注,走 update;否则新增
1088
+ if (editingFeatureId) body.op = 'update', body.id = editingFeatureId;
1089
+ post('/dsh-cam/feature', body)
926
1090
  .then((d) => {
927
1091
  if (d.ok && Array.isArray(d.features)) {
928
1092
  setModelFeatures(d.features);
929
1093
  setFeatureName('');
930
1094
  setFeatureNote('');
1095
+ setEditingFeatureId(null);
1096
+ setAnnotating(false);
1097
+ setModelSelected(null);
931
1098
  } else setErr(d.error || '标注写入失败');
932
1099
  })
933
1100
  .catch((e) => setErr(String(e)))
934
1101
  .finally(() => setBusy(false));
935
- }, [post, modelFile, modelSelected, featureName, featureNote]);
1102
+ }, [post, modelFile, modelSelected, featureName, featureNote, editingFeatureId]);
1103
+
1104
+ // 从已有标注列表开始「二次修改」(重命名 / 改备注 / 重选目标)
1105
+ const startEditFeature = React.useCallback((f) => {
1106
+ setModelSelected({ kind: f.kind, id: f.refId });
1107
+ setFeatureName(f.name || '');
1108
+ setFeatureNote(f.note || '');
1109
+ setEditingFeatureId(f.id);
1110
+ setAnnotating(true);
1111
+ }, []);
1112
+
1113
+ // 删除一条已有标注
1114
+ const removeFeature = React.useCallback((f) => {
1115
+ if (!modelFile) return;
1116
+ setBusy(true); setErr(null);
1117
+ post('/dsh-cam/feature', { model: modelFile, op: 'delete', id: f.id })
1118
+ .then((d) => { if (d.ok && Array.isArray(d.features)) setModelFeatures(d.features); else setErr(d.error || '删除失败'); })
1119
+ .catch((e) => setErr(String(e)))
1120
+ .finally(() => setBusy(false));
1121
+ }, [post, modelFile]);
1122
+
1123
+ // ---- 夹具 / 毛坯(上传后叠加到模型视窗,供 AI 了解夹持与毛坯) ----
1124
+ const loadAssets = React.useCallback((modelPath) => {
1125
+ if (!modelPath) return;
1126
+ fetch('/dsh-cam/assets?model=' + encodeURIComponent(modelPath))
1127
+ .then((r) => r.json())
1128
+ .then((d) => {
1129
+ if (!d.ok || !Array.isArray(d.assets)) return;
1130
+ setAssets(d.assets);
1131
+ // 逐个拉取已网格化的夹具/毛坯场景
1132
+ for (const a of d.assets) {
1133
+ fetch('/dsh-cam/asset-scene?id=' + encodeURIComponent(a.id) + '&model=' + encodeURIComponent(modelPath))
1134
+ .then((r2) => r2.json())
1135
+ .then((d2) => {
1136
+ if (d2.ok && d2.scene) setAssetScenes((prev) => ({ ...prev, [a.id]: d2.scene }));
1137
+ })
1138
+ .catch(() => {});
1139
+ }
1140
+ })
1141
+ .catch(() => {});
1142
+ }, []);
1143
+ const addAsset = React.useCallback(() => {
1144
+ const p = assetPath.trim();
1145
+ if (!p) { setErr('请选择夹具/毛坯的 STEP 模型文件'); return; }
1146
+ if (!modelFile) { setErr('请先加载主模型(零件)'); return; }
1147
+ setBusy(true); setErr(null);
1148
+ post('/dsh-cam/assets', { model: modelFile, name: assetName.trim(), role: assetRole, path: p })
1149
+ .then((d) => {
1150
+ if (d.ok && Array.isArray(d.assets)) {
1151
+ setAssets(d.assets);
1152
+ setAssetName('');
1153
+ setAssetPath('');
1154
+ // 重新拉取场景(新增的这条可能刚网格化完成)
1155
+ loadAssets(modelFile);
1156
+ } else setErr(d.error || '上传失败');
1157
+ })
1158
+ .catch((e) => setErr(String(e)))
1159
+ .finally(() => setBusy(false));
1160
+ }, [post, modelFile, assetName, assetPath, assetRole, loadAssets]);
1161
+ // 打开原生文件对话框选 STEP,读字节 POST 到 host 存盘,返回绝对路径填入 assetPath
1162
+ const pickAssetFile = React.useCallback(() => {
1163
+ const el = assetFileRef.current;
1164
+ if (el) el.click();
1165
+ }, []);
1166
+ const onAssetFileChosen = React.useCallback((e) => {
1167
+ const file = e.target.files && e.target.files[0];
1168
+ if (!file) return;
1169
+ const name = file.name || 'upload.step';
1170
+ const reader = new FileReader();
1171
+ reader.onload = () => {
1172
+ const base64 = String(reader.result || '').split(',')[1] || '';
1173
+ if (!base64) { setErr('读取文件失败'); return; }
1174
+ setBusy(true); setErr(null);
1175
+ post('/dsh-cam/upload', { name, data: base64 })
1176
+ .then((d) => {
1177
+ if (d.ok && d.path) {
1178
+ setAssetPath(d.path);
1179
+ if (!assetName.trim()) setAssetName(name.replace(/\.[^.]+$/, ''));
1180
+ } else setErr(d.error || '上传失败');
1181
+ })
1182
+ .catch((err) => setErr(String(err)))
1183
+ .finally(() => setBusy(false));
1184
+ };
1185
+ reader.onerror = () => setErr('读取文件失败');
1186
+ reader.readAsDataURL(file);
1187
+ e.target.value = '';
1188
+ }, [post, assetName]);
1189
+ const removeAsset = React.useCallback((a) => {
1190
+ if (!modelFile) return;
1191
+ setBusy(true); setErr(null);
1192
+ post('/dsh-cam/assets', { model: modelFile, op: 'delete', id: a.id })
1193
+ .then((d) => {
1194
+ if (d.ok && Array.isArray(d.assets)) {
1195
+ setAssets(d.assets);
1196
+ setAssetScenes((prev) => { const n = { ...prev }; delete n[a.id]; return n; });
1197
+ } else setErr(d.error || '删除失败');
1198
+ })
1199
+ .catch((e) => setErr(String(e)))
1200
+ .finally(() => setBusy(false));
1201
+ }, [post, modelFile]);
1202
+ // 夹具/毛坯位姿调整:选中某条后,编辑 translate(mm)/rotate(deg) 并保存
1203
+ const startEditAsset = React.useCallback((a) => {
1204
+ setEditingAssetId(a.id);
1205
+ const t = a.transform || { translate: [0, 0, 0], rotate: [0, 0, 0] };
1206
+ setAssetTransform({
1207
+ translate: Array.isArray(t.translate) ? t.translate.slice(0, 3) : [0, 0, 0],
1208
+ rotate: Array.isArray(t.rotate) ? t.rotate.slice(0, 3) : [0, 0, 0],
1209
+ });
1210
+ }, []);
1211
+ const saveAssetTransform = React.useCallback(() => {
1212
+ if (!modelFile || !editingAssetId) return;
1213
+ setBusy(true); setErr(null);
1214
+ post('/dsh-cam/assets', { model: modelFile, op: 'transform', id: editingAssetId, transform: assetTransform })
1215
+ .then((d) => {
1216
+ if (d.ok && Array.isArray(d.assets)) {
1217
+ setAssets(d.assets);
1218
+ setEditingAssetId(null);
1219
+ // 更新叠加渲染用的 transform(asset-scene 里已带 transform,重拉即可)
1220
+ loadAssets(modelFile);
1221
+ } else setErr(d.error || '保存位姿失败');
1222
+ })
1223
+ .catch((e) => setErr(String(e)))
1224
+ .finally(() => setBusy(false));
1225
+ }, [post, modelFile, editingAssetId, assetTransform, loadAssets]);
1226
+ const tfInput = () => ({ ...input, width: 58, padding: '4px 6px', fontSize: 12, textAlign: 'center' });
1227
+ const setTf = (axis, idx, val) => setAssetTransform((prev) => {
1228
+ const n = prev[axis].slice();
1229
+ n[idx] = Number(val) || 0;
1230
+ return { ...prev, [axis]: n };
1231
+ });
1232
+ // 主体(被加工零件)位姿:临时输入 + 应用
1233
+ const setMainTfAxis = (axis, idx, val) => setMainTf((prev) => {
1234
+ const n = prev[axis].slice();
1235
+ n[idx] = Number(val) || 0;
1236
+ return { ...prev, [axis]: n };
1237
+ });
1238
+ const applyMainTransform = React.useCallback(() => {
1239
+ setMainTransform({ translate: mainTf.translate.slice(0, 3), rotate: mainTf.rotate.slice(0, 3) });
1240
+ }, [mainTf]);
1241
+ const resetMainTransform = React.useCallback(() => {
1242
+ setMainTransform(null);
1243
+ setMainTf({ translate: [0, 0, 0], rotate: [0, 0, 0] });
1244
+ }, []);
936
1245
 
937
1246
  const ncCount = files.nc.length;
938
1247
 
@@ -1157,19 +1466,35 @@ window.__ModuleLoader__.load({
1157
1466
  ? h('div', { style: { display: 'flex', flexDirection: 'column', gap: 4, flex: 1, overflowY: 'auto' } },
1158
1467
  modelFeatures.map((f) => h('div', {
1159
1468
  key: f.id,
1160
- style: { display: 'flex', alignItems: 'center', gap: 6, padding: '5px 7px', fontSize: 12, borderRadius: 6, background: 'rgba(255,154,61,0.14)', border: '1px solid rgba(249,115,22,0.35)' },
1469
+ title: '单击定位到模型 · 双击重命名 · 点击 ✕ 删除',
1470
+ style: { display: 'flex', alignItems: 'center', gap: 6, padding: '5px 7px', fontSize: 12, borderRadius: 6, background: 'rgba(255,154,61,0.14)', border: '1px solid rgba(249,115,22,0.35)', cursor: 'pointer' },
1471
+ onClick: () => setLocateTarget({ kind: f.kind, id: f.refId }),
1472
+ onDoubleClick: () => startEditFeature(f),
1161
1473
  },
1162
1474
  h('span', { style: { fontSize: 12, color: '#f97316' } }, f.kind === 'face' ? '▨' : '╱'),
1163
1475
  h('div', { style: { display: 'flex', flexDirection: 'column', minWidth: 0, flex: 1 } },
1164
1476
  h('span', { style: { fontWeight: 600, color: 'var(--dsw-alias-label-primary, #111)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, f.name),
1165
- h('span', { style: { fontSize: 10, color: 'var(--dsw-alias-label-secondary, #6b7280)' } }, (f.kind === 'face' ? '面' : '边') + ' #' + f.refId + (f.note ? ' · ' + f.note : ''))))))
1477
+ h('span', { style: { fontSize: 10, color: 'var(--dsw-alias-label-secondary, #6b7280)' } }, (f.kind === 'face' ? '面' : '边') + ' #' + f.refId + (f.note ? ' · ' + f.note : ''))),
1478
+ h('button', {
1479
+ onClick: () => removeFeature(f),
1480
+ title: '删除此标注',
1481
+ style: { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 16, height: 16, fontSize: 11, lineHeight: 1, cursor: 'pointer', borderRadius: '50%', border: 'none', background: 'transparent', color: '#f97316', padding: 0 },
1482
+ }, '✕'))))
1166
1483
  : h('div', { style: { fontSize: 11, color: 'var(--dsw-alias-label-tertiary, #9ca3af)', textAlign: 'center', padding: '12px 0' } }, '暂无标注\n双击面/边线添加')),
1167
1484
  // 右侧:模型视窗 + 轴心 + 标注输入
1168
1485
  h('div', { style: { flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' } },
1169
1486
  h(ModelViewer3D, {
1170
- scene: modelScene, selected: modelSelected, pivot: modelPivot, features: modelFeatures,
1487
+ scene: modelScene, selected: modelSelected, pivot: modelPivot, features: modelFeatures, locate: locateTarget,
1488
+ transform: mainTransform,
1489
+ overlays: assets.filter((a) => assetScenes[a.id]).map((a) => ({ asset: a, scene: assetScenes[a.id] })),
1171
1490
  onSelect: (sel) => { setModelSelected(sel); setAnnotating(false); },
1172
- onAnnotate: (sel) => { setModelSelected(sel); setAnnotating(true); },
1491
+ onAnnotate: (sel) => {
1492
+ setModelSelected(sel);
1493
+ setFeatureName('');
1494
+ setFeatureNote('');
1495
+ setEditingFeatureId(null);
1496
+ setAnnotating(true);
1497
+ },
1173
1498
  }),
1174
1499
  h('div', { style: { display: 'flex', gap: 6, alignItems: 'center', marginTop: 6 } },
1175
1500
  h('span', { style: { fontSize: 11, color: 'var(--dsw-alias-label-secondary, #6b7280)' } }, '旋转轴心'),
@@ -1193,17 +1518,84 @@ window.__ModuleLoader__.load({
1193
1518
  ? h('span', { style: { fontSize: 11, color: 'var(--dsw-alias-label-tertiary, #9ca3af)' } },
1194
1519
  '当前 (' + modelPivot.map((v) => Math.round(v)).join(', ') + ')')
1195
1520
  : null),
1521
+ // ---- 底部设置区折叠开关:折叠/展开 主体零件位移旋转 + 夹具/毛坯 ----
1522
+ h('button', {
1523
+ onClick: () => setSetupCollapsed((v) => !v),
1524
+ title: setupCollapsed ? '展开设置' : '收起设置',
1525
+ style: { ...btn, width: '100%', fontSize: 11, padding: '6px 10px', marginTop: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, cursor: 'pointer' },
1526
+ },
1527
+ h('span', { style: { fontSize: 11 } }, setupCollapsed ? '▶' : '▼'),
1528
+ '设置面板 ' + (setupCollapsed ? '(已折叠)' : '(主体零件 · 位移旋转 / 夹具 / 毛坯)')),
1529
+ !setupCollapsed && h('div', { style: { display: 'flex', flexDirection: 'column', gap: 6, padding: 8, marginTop: 6, borderRadius: 8, background: 'var(--dsw-alias-bg-layer-2, #f3f4f6)', border: '1px solid var(--dsw-alias-border-l1, #e5e7eb)' } },
1530
+ h('div', { style: { fontSize: 11, fontWeight: 700, color: 'var(--dsw-alias-label-primary, #111)' } }, '主体零件 · 位移 / 旋转'),
1531
+ h('div', { style: { fontSize: 10, color: 'var(--dsw-alias-label-tertiary, #9ca3af)' } }, '平移(mm) 与 旋转(度),应用到被加工零件模型'),
1532
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, color: 'var(--dsw-alias-label-secondary, #6b7280)' } },
1533
+ h('span', { style: { width: 34 } }, '平移X'), h('input', { type: 'number', step: 0.5, style: tfInput(), value: mainTf.translate[0], onChange: (e) => setMainTfAxis('translate', 0, e.target.value) }),
1534
+ h('span', { style: { width: 34 } }, '平移Y'), h('input', { type: 'number', step: 0.5, style: tfInput(), value: mainTf.translate[1], onChange: (e) => setMainTfAxis('translate', 1, e.target.value) }),
1535
+ h('span', { style: { width: 34 } }, '平移Z'), h('input', { type: 'number', step: 0.5, style: tfInput(), value: mainTf.translate[2], onChange: (e) => setMainTfAxis('translate', 2, e.target.value) })),
1536
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, color: 'var(--dsw-alias-label-secondary, #6b7280)' } },
1537
+ h('span', { style: { width: 34 } }, '旋转X'), h('input', { type: 'number', step: 1, style: tfInput(), value: mainTf.rotate[0], onChange: (e) => setMainTfAxis('rotate', 0, e.target.value) }),
1538
+ h('span', { style: { width: 34 } }, '旋转Y'), h('input', { type: 'number', step: 1, style: tfInput(), value: mainTf.rotate[1], onChange: (e) => setMainTfAxis('rotate', 1, e.target.value) }),
1539
+ h('span', { style: { width: 34 } }, '旋转Z'), h('input', { type: 'number', step: 1, style: tfInput(), value: mainTf.rotate[2], onChange: (e) => setMainTfAxis('rotate', 2, e.target.value) })),
1540
+ h('div', { style: { display: 'flex', gap: 6 } },
1541
+ h('button', { style: btnPrimary, onClick: applyMainTransform }, '应用到位'),
1542
+ h('button', { style: btn, onClick: resetMainTransform }, '复位'))),
1196
1543
  modelSelected && annotating
1197
1544
  ? h('div', { style: { display: 'flex', flexDirection: 'column', gap: 6, padding: 8, marginTop: 6, borderRadius: 8, background: 'var(--dsw-alias-bg-layer-2, #f3f4f6)', border: '1px solid var(--dsw-alias-border-l1, #e5e7eb)' } },
1198
1545
  h('div', { style: { fontSize: 11, fontWeight: 600, color: 'var(--dsw-alias-label-primary, #111)' } },
1199
- (modelSelected.kind === 'face' ? '标注加工面' : '标注加工边线') + ' · 已选 #' + modelSelected.id),
1546
+ (editingFeatureId ? '修改加工位置' : (modelSelected.kind === 'face' ? '标注加工面' : '标注加工边线')) + ' · 已选 #' + modelSelected.id),
1200
1547
  h('div', { style: { display: 'flex', gap: 6 } },
1201
1548
  h('input', { style: input, value: featureName, placeholder: '加工位置名称(必填)', onChange: (e) => setFeatureName(e.target.value), onKeyDown: (e) => { if (e.key === 'Enter') addFeature(); } }),
1202
1549
  h('input', { style: input, value: featureNote, placeholder: '备注(可选,如钻孔/铣面)', onChange: (e) => setFeatureNote(e.target.value), onKeyDown: (e) => { if (e.key === 'Enter') addFeature(); } })),
1203
1550
  h('div', { style: { display: 'flex', gap: 6, alignItems: 'center' } },
1204
- h('button', { style: btnPrimary, onClick: addFeature, disabled: busy }, '写入识别文件'),
1205
- h('button', { style: btn, onClick: () => { setModelSelected(null); setAnnotating(false); } }, '取消')))
1206
- : null))
1551
+ h('button', { style: btnPrimary, onClick: addFeature, disabled: busy }, editingFeatureId ? '保存修改' : '写入识别文件'),
1552
+ h('button', { style: btn, onClick: () => { setModelSelected(null); setAnnotating(false); setEditingFeatureId(null); } }, '取消')))
1553
+ : null,
1554
+ // ---- 上传夹具 / 毛坯(供 AI 了解夹持与毛坯形状) ----
1555
+ !setupCollapsed && h('div', { style: { display: 'flex', flexDirection: 'column', gap: 6, padding: 8, marginTop: 8, borderRadius: 8, background: 'var(--dsw-alias-bg-layer-2, #f3f4f6)', border: '1px solid var(--dsw-alias-border-l1, #e5e7eb)' } },
1556
+ h('div', { style: { fontSize: 11, fontWeight: 700, color: 'var(--dsw-alias-label-primary, #111)' } }, '夹具 / 毛坯'),
1557
+ h('div', { style: { fontSize: 10, color: 'var(--dsw-alias-label-tertiary, #9ca3af)' } }, '上传毛坯/夹具 STEP,叠加显示,让 AI 了解夹持与加工区域'),
1558
+ assets.length > 0
1559
+ ? h('div', { style: { display: 'flex', flexDirection: 'column', gap: 3 } },
1560
+ assets.map((a) => h('div', {
1561
+ key: a.id,
1562
+ style: { display: 'flex', alignItems: 'center', gap: 6, padding: '3px 6px', fontSize: 11, borderRadius: 5, background: a.role === 'fixture' ? 'rgba(99,102,241,0.12)' : 'rgba(16,185,129,0.12)', border: '1px solid ' + (a.role === 'fixture' ? 'rgba(79,70,229,0.35)' : 'rgba(5,150,105,0.35)') },
1563
+ },
1564
+ h('span', { style: { fontSize: 12 } }, a.role === 'fixture' ? '🔧' : '🧱'),
1565
+ h('span', { style: { flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', color: 'var(--dsw-alias-label-primary, #111)', cursor: 'pointer' }, onClick: () => startEditAsset(a), title: '点击调整位姿' },
1566
+ (a.name || (a.role === 'fixture' ? '夹具' : '毛坯')) + (a.role === 'fixture' ? '(夹具)' : '(毛坯)')),
1567
+ h('button', {
1568
+ onClick: () => removeAsset(a), title: '删除此夹具/毛坯',
1569
+ style: { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 16, height: 16, fontSize: 11, lineHeight: 1, cursor: 'pointer', borderRadius: '50%', border: 'none', background: 'transparent', color: '#f97316', padding: 0 },
1570
+ }, '✕'))))
1571
+ : h('div', { style: { fontSize: 11, color: 'var(--dsw-alias-label-tertiary, #9ca3af)' } }, '尚未上传夹具/毛坯'),
1572
+ // 位姿调整面板(选中某条夹具/毛坯后出现)
1573
+ editingAssetId
1574
+ ? h('div', { style: { display: 'flex', flexDirection: 'column', gap: 4, padding: 6, borderRadius: 6, background: 'var(--dsw-alias-bg-base, #fff)', border: '1px dashed #f59e0b' } },
1575
+ h('div', { style: { fontSize: 11, fontWeight: 700, color: '#b45309' } }, '调整位姿(选中:#' + editingAssetId + ')'),
1576
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, color: 'var(--dsw-alias-label-secondary, #6b7280)' } },
1577
+ h('span', { style: { width: 34 } }, '平移X'), h('input', { type: 'number', step: 0.5, style: tfInput(), value: assetTransform.translate[0], onChange: (e) => setTf('translate', 0, e.target.value) }),
1578
+ h('span', { style: { width: 34 } }, '平移Y'), h('input', { type: 'number', step: 0.5, style: tfInput(), value: assetTransform.translate[1], onChange: (e) => setTf('translate', 1, e.target.value) }),
1579
+ h('span', { style: { width: 34 } }, '平移Z'), h('input', { type: 'number', step: 0.5, style: tfInput(), value: assetTransform.translate[2], onChange: (e) => setTf('translate', 2, e.target.value) })),
1580
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, color: 'var(--dsw-alias-label-secondary, #6b7280)' } },
1581
+ h('span', { style: { width: 34 } }, '旋转X'), h('input', { type: 'number', step: 1, style: tfInput(), value: assetTransform.rotate[0], onChange: (e) => setTf('rotate', 0, e.target.value) }),
1582
+ h('span', { style: { width: 34 } }, '旋转Y'), h('input', { type: 'number', step: 1, style: tfInput(), value: assetTransform.rotate[1], onChange: (e) => setTf('rotate', 1, e.target.value) }),
1583
+ h('span', { style: { width: 34 } }, '旋转Z'), h('input', { type: 'number', step: 1, style: tfInput(), value: assetTransform.rotate[2], onChange: (e) => setTf('rotate', 2, e.target.value) })),
1584
+ h('div', { style: { display: 'flex', gap: 6 } },
1585
+ h('button', { style: btnPrimary, onClick: saveAssetTransform, disabled: busy }, '保存位姿'),
1586
+ h('button', { style: btn, onClick: () => setEditingAssetId(null) }, '取消')))
1587
+ : null,
1588
+ h('div', { style: { display: 'flex', gap: 6 } },
1589
+ h('select', { style: { ...input, width: 74, flexShrink: 0 }, value: assetRole, onChange: (e) => setAssetRole(e.target.value) },
1590
+ h('option', { value: 'blank' }, '毛坯'),
1591
+ h('option', { value: 'fixture' }, '夹具')),
1592
+ h('input', { style: input, value: assetName, placeholder: '名称(可选)', onChange: (e) => setAssetName(e.target.value) }),
1593
+ h('input', { style: input, value: assetPath, placeholder: 'STEP 路径(点右侧按钮选择)', onChange: (e) => setAssetPath(e.target.value), onKeyDown: (e) => { if (e.key === 'Enter') addAsset(); } })),
1594
+ h('div', { style: { display: 'flex', gap: 6 } },
1595
+ h('button', { style: btn, onClick: pickAssetFile, disabled: busy }, '📂 打开文件选择'),
1596
+ h('button', { style: btnPrimary, onClick: addAsset, disabled: busy }, '上传并叠加显示')),
1597
+ // 隐藏的原生文件选择框(选单个 STEP,读字节上传后回填路径)
1598
+ h('input', { type: 'file', accept: '.step,.stp,.brep,.iges,.igs', ref: assetFileRef, style: { display: 'none' }, onChange: onAssetFileChosen }))))
1207
1599
  : h(Viewer3D, { data })),
1208
1600
  // 打赏 footer(左下角)
1209
1601
  h('div', {
@@ -1249,21 +1641,21 @@ window.__ModuleLoader__.load({
1249
1641
  },
1250
1642
  onClick: (e) => e.stopPropagation(),
1251
1643
  },
1252
- h('div', { style: { fontSize: 15, fontWeight: 700, color: 'var(--dsw-alias-label-primary, #111)' } }, '制作不易,打赏随心'),
1644
+ h('div', { style: { fontSize: 17, fontWeight: 700, color: '#1f2937', letterSpacing: '0.5px' } }, '制作不易,打赏随心'),
1253
1645
  h('div', {
1254
1646
  style: {
1255
- textAlign: 'center', fontSize: 13.5, lineHeight: '24px', color: '#92400e',
1647
+ textAlign: 'center', fontSize: 14, lineHeight: '26px', color: '#92400e',
1256
1648
  background: 'linear-gradient(135deg, #fef3c7, #fde68a)', borderRadius: 10,
1257
- padding: '10px 14px', fontWeight: 600, letterSpacing: '0.5px',
1649
+ padding: '12px 16px', fontWeight: 600, letterSpacing: '1px',
1258
1650
  boxShadow: 'inset 0 0 0 1px rgba(217,119,6,0.25)',
1259
1651
  },
1260
1652
  },
1261
1653
  '莫愁前路无知己,天下谁人不识君。', h('br', null), '起舟扬帆难不畏,越是当下最好时。'),
1262
- h('img', { src: '/dsh-cam/qrcode', alt: '微信收款二维码', style: { width: 224, height: 'auto', borderRadius: 8, display: 'block' } }),
1263
- h('div', { style: { fontSize: 13, fontWeight: 700, color: '#d97706' } }, '微信扫码 · 支持鼓励一下'),
1264
- h('div', { style: { textAlign: 'center', fontSize: 12, lineHeight: '18px', color: 'var(--dsw-alias-label-secondary, #6b7280)', padding: '0 6px' } },
1654
+ h('img', { src: '/dsh-cam/qrcode', alt: '微信收款二维码', style: { width: 112, height: 'auto', borderRadius: 8, display: 'block' } }),
1655
+ h('div', { style: { fontSize: 15, fontWeight: 700, color: '#d97706', letterSpacing: '0.5px' } }, '微信扫码 · 支持鼓励一下'),
1656
+ h('div', { style: { textAlign: 'center', fontSize: 13, lineHeight: '20px', color: '#4b5563', padding: '0 8px' } },
1265
1657
  '如果觉得对你有帮助,打赏一下,让我知道帮助到了又一个同道中人。'),
1266
- h('button', { onClick: () => setShowReward(false), style: { ...btn, fontSize: 12 } }, '关闭')))
1658
+ h('button', { onClick: () => setShowReward(false), style: { ...btn, fontSize: 13, padding: '4px 16px' } }, '关闭')))
1267
1659
  : null,
1268
1660
  )));
1269
1661
  }
package/index.js CHANGED
@@ -212,6 +212,7 @@ function scanFiles(rootDir, extRe, maxDepth = 5) {
212
212
  // ---- tessellate a STEP/BREP/IGES model into renderable faces + edges via FreeCAD ----
213
213
  const MODEL_EXT = /\.(step|stp|brep|iges|igs)$/i;
214
214
  const FEATURE_FILE = join(homedir(), '.dsh', 'storages', 'dsh-cam-features.json');
215
+ const ASSETS_FILE = join(homedir(), '.dsh', 'storages', 'dsh-cam-assets.json');
215
216
 
216
217
  function assertModelPath(modelPath) {
217
218
  const p = resolvePath(modelPath);
@@ -278,6 +279,107 @@ function appendFeature(modelPath, feature) {
278
279
  return list;
279
280
  }
280
281
 
282
+ // update an existing feature by id (rename / re-note / re-target); returns the updated list
283
+ function updateFeature(modelPath, feature) {
284
+ const p = resolvePath(modelPath);
285
+ const all = loadFeatures();
286
+ const list = Array.isArray(all[p]) ? all[p] : [];
287
+ const idx = list.findIndex((x) => x && x.id === feature.id);
288
+ if (idx < 0) return list;
289
+ const cur = list[idx];
290
+ list[idx] = {
291
+ ...cur,
292
+ name: feature.name !== undefined ? String(feature.name) : cur.name,
293
+ note: feature.note !== undefined ? String(feature.note) : cur.note,
294
+ kind: feature.kind === 'edge' ? 'edge' : (feature.kind === 'face' ? 'face' : cur.kind),
295
+ refId: feature.refId !== undefined ? Number(feature.refId) : cur.refId,
296
+ };
297
+ all[p] = list;
298
+ saveFeatures(all);
299
+ return list;
300
+ }
301
+
302
+ // remove a feature by id; returns the updated list
303
+ function deleteFeature(modelPath, featureId) {
304
+ const p = resolvePath(modelPath);
305
+ const all = loadFeatures();
306
+ const list = Array.isArray(all[p]) ? all[p] : [];
307
+ const next = list.filter((x) => !x || x.id !== featureId);
308
+ all[p] = next;
309
+ saveFeatures(all);
310
+ return next;
311
+ }
312
+
313
+ // ---- fixtures & blanks (毛坯/夹具): extra models overlaid on the part, with a role ----
314
+ const ASSETS_DIR = join(homedir(), '.dsh', 'storages', 'dsh-cam-assets');
315
+ function loadAssets() {
316
+ try { return JSON.parse(readFileSync(ASSETS_FILE, 'utf8')) || {}; } catch { return {}; }
317
+ }
318
+ function saveAssets(all) {
319
+ try {
320
+ mkdirSync(dirname(ASSETS_FILE), { recursive: true });
321
+ writeFileSync(ASSETS_FILE, JSON.stringify(all, null, 2), 'utf8');
322
+ } catch { /* ignore */ }
323
+ }
324
+ function assetSceneFile(id) { return join(ASSETS_DIR, id + '.json'); }
325
+ // 夹具/毛坯相对零件的位姿:平移(mm) + 旋转(绕 X/Y/Z 度)。缺省 = 无平移无旋转。
326
+ function normalizeTransform(t) {
327
+ if (!t || typeof t !== 'object') return { translate: [0, 0, 0], rotate: [0, 0, 0] };
328
+ const to3 = (v, dflt) => Array.isArray(v) ? v.slice(0, 3).map((n) => Number(n) || 0) : dflt;
329
+ return { translate: to3(t.translate, [0, 0, 0]), rotate: to3(t.rotate, [0, 0, 0]) };
330
+ }
331
+ // add or replace a fixture/blank by tessellating its STEP now; returns the updated list
332
+ function upsertAsset(modelPath, asset, opts = {}) {
333
+ const p = resolvePath(modelPath);
334
+ const all = loadAssets();
335
+ const list = Array.isArray(all[p]) ? all[p] : [];
336
+ const item = {
337
+ id: asset.id ?? (Date.now().toString(36) + Math.random().toString(36).slice(2, 6)),
338
+ name: String(asset.name || (asset.role === 'fixture' ? '夹具' : '毛坯')),
339
+ role: asset.role === 'fixture' ? 'fixture' : 'blank',
340
+ path: resolvePath(asset.path),
341
+ createdAt: asset.createdAt ?? new Date().toISOString(),
342
+ transform: normalizeTransform(asset.transform),
343
+ };
344
+ let scene = null;
345
+ try { scene = tessellateModel(item.path, opts); } catch { scene = null; }
346
+ if (scene) {
347
+ try { mkdirSync(ASSETS_DIR, { recursive: true }); writeFileSync(assetSceneFile(item.id), JSON.stringify(scene), 'utf8'); } catch { /* ignore */ }
348
+ }
349
+ const idx = list.findIndex((x) => x && x.id === item.id);
350
+ if (idx >= 0) list[idx] = item; else list.push(item);
351
+ all[p] = list;
352
+ saveAssets(all);
353
+ return list;
354
+ }
355
+ function deleteAsset(modelPath, assetId) {
356
+ const p = resolvePath(modelPath);
357
+ const all = loadAssets();
358
+ const list = Array.isArray(all[p]) ? all[p] : [];
359
+ const next = list.filter((x) => !x || x.id !== assetId);
360
+ all[p] = next;
361
+ saveAssets(all);
362
+ try { unlinkSync(assetSceneFile(assetId)); } catch { /* ignore */ }
363
+ return next;
364
+ }
365
+ // update only the pose (translate/rotate) of one asset; scene stays cached
366
+ function updateAssetTransform(modelPath, assetId, transform) {
367
+ const p = resolvePath(modelPath);
368
+ const all = loadAssets();
369
+ const list = Array.isArray(all[p]) ? all[p] : [];
370
+ const idx = list.findIndex((x) => x && x.id === assetId);
371
+ if (idx >= 0) {
372
+ list[idx] = { ...list[idx], transform: normalizeTransform(transform) };
373
+ all[p] = list;
374
+ saveAssets(all);
375
+ }
376
+ return list;
377
+ }
378
+ // read an asset's cached tessellation scene (or null if not yet tessellated)
379
+ function assetSceneOf(asset) {
380
+ try { return JSON.parse(readFileSync(assetSceneFile(asset.id), 'utf8')) || null; } catch { return null; }
381
+ }
382
+
281
383
  // ---- generate a G-code toolpath from a STEP/BREP/IGES model via FreeCAD CAM ----
282
384
  function generateToolpathFromModel(modelPath, opts = {}) {
283
385
  const freecadBin = opts.freecadBin ?? FREECAD_BIN;
@@ -524,6 +626,16 @@ export function apply(ctx, config = {}) {
524
626
  if (req.method === 'POST') {
525
627
  const parsed = await readBody(req);
526
628
  const model = parsed.model ?? url.searchParams.get('model');
629
+ if (parsed.op === 'update') {
630
+ const list = updateFeature(model, parsed);
631
+ send(res, { ok: true, model: resolvePath(model), features: list });
632
+ return;
633
+ }
634
+ if (parsed.op === 'delete') {
635
+ const list = deleteFeature(model, parsed.id);
636
+ send(res, { ok: true, model: resolvePath(model), features: list });
637
+ return;
638
+ }
527
639
  const list = appendFeature(model, parsed);
528
640
  send(res, { ok: true, model: resolvePath(model), features: list });
529
641
  return;
@@ -537,6 +649,89 @@ export function apply(ctx, config = {}) {
537
649
  }
538
650
  },
539
651
  }));
652
+
653
+ // list / add / remove fixture & blank (毛坯/夹具) models overlaid on the part
654
+ routeDisposers.push(server.register({
655
+ kind: 'prefix',
656
+ path: '/dsh-cam/assets',
657
+ handler: async (req, res) => {
658
+ try {
659
+ const url = new URL(req.url ?? '/', 'http://localhost');
660
+ const model = url.searchParams.get('model');
661
+ if (req.method === 'POST') {
662
+ const parsed = await readBody(req);
663
+ const key = parsed.model ?? url.searchParams.get('model');
664
+ if (!key) { send(res, { ok: false, error: 'model query param required' }, 400); return; }
665
+ if (parsed.op === 'delete') {
666
+ const list = deleteAsset(key, parsed.id);
667
+ send(res, { ok: true, model: resolvePath(key), assets: list });
668
+ return;
669
+ }
670
+ if (parsed.op === 'transform') {
671
+ const list = updateAssetTransform(key, parsed.id, parsed.transform);
672
+ send(res, { ok: true, model: resolvePath(key), assets: list });
673
+ return;
674
+ }
675
+ const list = upsertAsset(key, parsed, { freecadBin });
676
+ send(res, { ok: true, model: resolvePath(key), assets: list });
677
+ return;
678
+ }
679
+ if (!model) { send(res, { ok: false, error: 'model query param required' }, 400); return; }
680
+ const all = loadAssets();
681
+ const p = resolvePath(model);
682
+ send(res, { ok: true, model: p, assets: Array.isArray(all[p]) ? all[p] : [] });
683
+ } catch (e) {
684
+ send(res, { ok: false, error: String(e && e.message ? e.message : e) }, 400);
685
+ }
686
+ },
687
+ }));
688
+
689
+ // read one asset's tessellated scene (for overlay rendering)
690
+ routeDisposers.push(server.register({
691
+ kind: 'prefix',
692
+ path: '/dsh-cam/asset-scene',
693
+ handler: async (req, res) => {
694
+ try {
695
+ const url = new URL(req.url ?? '/', 'http://localhost');
696
+ const id = url.searchParams.get('id');
697
+ const model = url.searchParams.get('model');
698
+ if (!id || !model) { send(res, { ok: false, error: 'id and model query params required' }, 400); return; }
699
+ const all = loadAssets();
700
+ const p = resolvePath(model);
701
+ const list = Array.isArray(all[p]) ? all[p] : [];
702
+ const asset = list.find((x) => x && x.id === id);
703
+ if (!asset) { send(res, { ok: false, error: 'asset not found' }, 404); return; }
704
+ const scene = assetSceneOf(asset);
705
+ if (!scene) { send(res, { ok: false, error: 'asset scene not tessellated' }, 404); return; }
706
+ send(res, { ok: true, asset: { id: asset.id, name: asset.name, role: asset.role, path: asset.path, transform: asset.transform }, scene });
707
+ } catch (e) {
708
+ send(res, { ok: false, error: String(e && e.message ? e.message : e) }, 400);
709
+ }
710
+ },
711
+ }));
712
+
713
+ // 上传单个 STEP 文件(浏览器 <input type=file> 拿不到绝对路径,改为把文件字节 POST 上来,落到项目 uploads/ 目录并返回绝对路径)
714
+ routeDisposers.push(server.register({
715
+ kind: 'prefix',
716
+ path: '/dsh-cam/upload',
717
+ handler: async (req, res) => {
718
+ if (req.method !== 'POST') { send(res, { ok: false, error: 'POST only' }, 405); return; }
719
+ try {
720
+ const parsed = await readBody(req);
721
+ const name = String(parsed.name || '').replace(/[\\/]/g, '_');
722
+ const data = parsed.data; // base64 string
723
+ if (!name || !data) { send(res, { ok: false, error: 'name and data(base64) required' }, 400); return; }
724
+ const buf = Buffer.from(data, 'base64');
725
+ const dir = join(ASSETS_DIR, 'uploads');
726
+ mkdirSync(dir, { recursive: true });
727
+ const dest = join(dir, Date.now().toString(36) + '-' + name);
728
+ writeFileSync(dest, buf);
729
+ send(res, { ok: true, path: dest, name });
730
+ } catch (e) {
731
+ send(res, { ok: false, error: String(e && e.message ? e.message : e) }, 400);
732
+ }
733
+ },
734
+ }));
540
735
  };
541
736
  ensureRoutes();
542
737
  const retry = setInterval(() => { if (routeDisposers.length === 0) ensureRoutes(); }, 100);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-qizhoucnc-cam",
3
- "version": "1.3.4",
3
+ "version": "1.3.6",
4
4
  "description": "CNC program (NC/CNC/G-code) toolpath recognition, 3D toolpath + 3D STEP model viewport (face/edge machining-position annotation), and a large editing view with quote-to-composer, for DeepSeek Harness (DSH). Made by Chengdu Qizhou Machinery Technology Co., Ltd., for research and study only.",
5
5
  "type": "module",
6
6
  "license": "MIT",