import * as THREE from 'three'; import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; import { STLLoader } from 'three/addons/loaders/STLLoader.js'; import { OBJLoader } from 'three/addons/loaders/OBJLoader.js'; import { PLYLoader } from 'three/addons/loaders/PLYLoader.js'; // ---------------------------------------------------------------- scene setup const viewport = document.getElementById('viewport'); const scene = new THREE.Scene(); scene.background = new THREE.Color(0x0b0d10); const camera = new THREE.PerspectiveCamera(45, 1, 0.01, 1e6); // CAD convention: Z is up, XY is the ground plane (the grid). Must be set before // OrbitControls is built — it captures camera.up at construction. camera.up.set(0, 0, 1); camera.position.set(60, -60, 45); const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setPixelRatio(window.devicePixelRatio); viewport.appendChild(renderer.domElement); const controls = new OrbitControls(camera, renderer.domElement); controls.enableDamping = true; controls.screenSpacePanning = true; // pan in screen plane (CAD-style) controls.zoomToCursor = true; // scroll zooms toward the cursor controls.panSpeed = 0.9; // Mac trackpad pinch/scroll sends tiny deltaY, so OrbitControls' delta-proportional // zoom crawls. Boost zoomSpeed for small deltas (trackpad) vs large (mouse wheel). // Capture phase runs before OrbitControls' own wheel handler, so the new speed applies. renderer.domElement.addEventListener('wheel', (ev) => { const ad = Math.abs(ev.deltaY); controls.zoomSpeed = ad < 50 ? 9 : 1.5; }, { capture: true, passive: true }); // ---- rotation: free trackball about a pivot -------------------------------- // OrbitControls is a turntable (Z pinned up, stops at the poles), which is wrong // for CAD: SolidWorks-style rotation has no stops. So left-drag is ours: // horizontal drag spins about the screen's vertical axis, vertical drag about // its horizontal axis, both through `pivot` — camera, target and camera.up all // rotate together, so it never hits a pole. OrbitControls keeps pan + zoom. // The pivot is the world origin (the datum — and the part's centre until it's // aligned); double-click the part to pivot somewhere else, double-click empty // space / a view button / F to go back to the origin. const ORBIT_OFF = -1; // OrbitControls: no action on that button const pivot = new THREE.Vector3(); // world origin by default // 'origin' (default), 'center' (middle of the part's X/Y/Z bounding box — // once aligned, the box squared to the datum planes), or 'point' (picked). // Fit and the view buttons keep the mode; 'center' is recomputed each time. let pivotMode = 'origin'; let rotating = null; // {x, y} last pointer position while rotating const _q = new THREE.Quaternion(), _q2 = new THREE.Quaternion(); const _ax = new THREE.Vector3(), _ay = new THREE.Vector3(), _off = new THREE.Vector3(); function rotateView(dx, dy) { const k = 2 * Math.PI / (renderer.domElement.clientHeight || 1); camera.updateMatrixWorld(); _ax.setFromMatrixColumn(camera.matrixWorld, 1); // screen up _ay.setFromMatrixColumn(camera.matrixWorld, 0); // screen right _q.setFromAxisAngle(_ax, -dx * k); _q2.setFromAxisAngle(_ay, -dy * k); _q.multiply(_q2); _off.copy(camera.position).sub(pivot).applyQuaternion(_q); camera.position.copy(pivot).add(_off); _off.copy(controls.target).sub(pivot).applyQuaternion(_q); controls.target.copy(pivot).add(_off); camera.up.copy(_ax).applyQuaternion(_q); camera.lookAt(controls.target); } renderer.domElement.addEventListener('pointerdown', (ev) => { if (ev.button !== 0 || ev.shiftKey || panKey || flyAnim) return; rotating = { x: ev.clientX, y: ev.clientY }; }); window.addEventListener('pointermove', (ev) => { if (!rotating) return; // a paint stroke that started on the mesh owns this drag (it disables controls) if (!controls.enabled || paint.active) { rotating = null; return; } rotateView(ev.clientX - rotating.x, ev.clientY - rotating.y); rotating.x = ev.clientX; rotating.y = ev.clientY; }); window.addEventListener('pointerup', () => { rotating = null; }); // mouse: left=rotate (ours, above), right=pan, wheel=zoom (two-finger trackpad pans) controls.mouseButtons = { LEFT: ORBIT_OFF, MIDDLE: THREE.MOUSE.DOLLY, RIGHT: THREE.MOUSE.PAN, }; // ---- keyboard panning ---- // Hold SPACE and just move the mouse/trackpad to pan (no click needed). // Holding SHIFT remaps left-drag to pan as well. let panKey = false; let panLast = null; function typingInField(e) { const t = e.target && e.target.tagName; return t === 'INPUT' || t === 'SELECT' || t === 'TEXTAREA'; } window.addEventListener('keydown', (e) => { if (typingInField(e)) return; if (e.code === 'Space') { e.preventDefault(); if (!panKey) { panKey = true; panLast = null; renderer.domElement.style.cursor = 'grabbing'; } } else if (e.key === 'Shift') { controls.mouseButtons.LEFT = THREE.MOUSE.PAN; } else if ((e.key === '[' || e.key === ']') && isPaintMode()) { paint.radius = brushR() * (e.key === ']' ? 1.25 : 0.8); if (brushRing && brushRing.visible) brushRing.scale.setScalar(brushR()); setHud(`Brush Ø ${(brushR() * 2).toFixed(1)} mm`); } }); window.addEventListener('keyup', (e) => { if (e.code === 'Space') { panKey = false; panLast = null; renderer.domElement.style.cursor = ''; } else if (e.key === 'Shift') { controls.mouseButtons.LEFT = ORBIT_OFF; } }); window.addEventListener('blur', () => { // releasing the key outside the window panKey = false; panLast = null; renderer.domElement.style.cursor = ''; controls.mouseButtons.LEFT = ORBIT_OFF; }); renderer.domElement.addEventListener('pointermove', (ev) => { if (!panKey) { panLast = null; return; } if (panLast) panView(ev.clientX - panLast.x, ev.clientY - panLast.y); panLast = { x: ev.clientX, y: ev.clientY }; }); // Screen-space pan: shift camera + target by the pixel delta projected to the // target-distance plane, so the model tracks the cursor 1:1. function panView(dx, dy) { const dist = camera.position.distanceTo(controls.target); const h = renderer.domElement.clientHeight || 1; const scale = 2 * dist * Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)) / h; const off = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0).multiplyScalar(-dx * scale) .add(new THREE.Vector3().setFromMatrixColumn(camera.matrix, 1).multiplyScalar(dy * scale)); camera.position.add(off); controls.target.add(off); } const hemi = new THREE.HemisphereLight(0xffffff, 0x444455, 1.1); hemi.position.set(0, 0, 1); // sky is +Z scene.add(hemi); const dir = new THREE.DirectionalLight(0xffffff, 1.4); dir.position.set(1, -1.5, 2); scene.add(dir); const grid = new THREE.GridHelper(400, 40, 0x2b343f, 0x1c232d); grid.rotation.x = Math.PI / 2; // GridHelper lies in XZ; turn it into the XY ground scene.add(grid); { // red X / green Y lines across the ground, like a CAD workspace const g = new THREE.BufferGeometry().setFromPoints([ new THREE.Vector3(-200, 0, 0), new THREE.Vector3(200, 0, 0), new THREE.Vector3(0, -200, 0), new THREE.Vector3(0, 200, 0)]); g.setAttribute('color', new THREE.Float32BufferAttribute( [0.55, 0.2, 0.2, 0.55, 0.2, 0.2, 0.2, 0.45, 0.25, 0.2, 0.45, 0.25], 3)); scene.add(new THREE.LineSegments(g, new THREE.LineBasicMaterial({ vertexColors: true }))); } scene.add(new THREE.AxesHelper(20)); // Pivot marker — shows the current orbit/rotation centre. Double-click the model // to move it; rotation then orbits around this point. const pivotMarker = new THREE.Mesh( new THREE.SphereGeometry(1, 16, 12), new THREE.MeshBasicMaterial({ color: 0xff7b72, depthTest: false, transparent: true, opacity: 0.9 })); pivotMarker.renderOrder = 999; pivotMarker.visible = false; scene.add(pivotMarker); function showPivot() { pivotMarker.position.copy(pivot); pivotMarker.visible = true; pivotMarker.userData.shownAt = performance.now(); // auto-hides shortly after } function resize() { const w = viewport.clientWidth, h = viewport.clientHeight; // updateStyle must stay on: with pixelRatio > 1 (Retina), the canvas attribute // size is 2x the CSS size, and without an explicit style the canvas lays out at // attribute size — overflowing #app and pushing the side panel off-screen. renderer.setSize(w, h); camera.aspect = w / h; camera.updateProjectionMatrix(); } window.addEventListener('resize', resize); resize(); let flyAnim = null; // {fromPos,toPos,fromTgt,toTgt,t0,dur} function flyTo(target, dist, dirHint) { const tgt = target.clone(); let dir = dirHint ? dirHint.clone() : camera.position.clone().sub(controls.target); if (dir.lengthSq() < 1e-9) dir.set(1, -1, 0.8); dir.normalize(); const toPos = tgt.clone().add(dir.clone().multiplyScalar(dist)); safeUp(dir); pivot.copy(tgt); // inspecting a feature: rotate around it pivotMode = 'point'; camera.near = Math.max(0.02, dist * 0.02); camera.far = Math.max(camera.far, dist * 50); camera.updateProjectionMatrix(); flyAnim = { fromPos: camera.position.clone(), toPos, fromTgt: controls.target.clone(), toTgt: tgt, t0: performance.now(), dur: 550 }; } // Set the orbit pivot to a point without zooming: keep the camera where it is and // re-aim it to look at the new centre, so subsequent rotation orbits around it. function setPivot(point, note, mode = 'point') { pivot.copy(point); pivotMode = mode; flyAnim = { fromPos: camera.position.clone(), toPos: camera.position.clone(), fromTgt: controls.target.clone(), toTgt: point.clone(), t0: performance.now(), dur: 350 }; safeUp(camera.position.clone().sub(point)); showPivot(); setHud(note || `Pivot set — rotation now orbits (${point.x.toFixed(1)}, ${point.y.toFixed(1)}, ${point.z.toFixed(1)}). ` + 'Double-click empty space to go back to the origin.'); } // Keep camera.up perpendicular to the view direction `dir` (target → camera) so // lookAt never degenerates — free rotation means the old up can be anything. function safeUp(dir) { const d = dir.clone().normalize(); const up = camera.up.clone().sub(d.clone().multiplyScalar(camera.up.dot(d))); if (up.lengthSq() < 1e-8) up.set(0, 0, 1).sub(d.clone().multiplyScalar(d.z)); if (up.lengthSq() < 1e-8) up.set(0, 1, 0); camera.up.copy(up.normalize()); } const AXIS_COLOR_TRI = { X: 0xf85149, Y: 0x3fb950, Z: 0x2f81f7 }; const AXIS_CSS_TRI = { X: '#ff7b72', Y: '#56d364', Z: '#58a6ff' }; // Defined then scheduled (not an immediately-invoked IIFE): the first frame must run // after module evaluation completes, or updateHoleLabels() hits `holes` in its TDZ // and the whole module dies before the file-input handler is registered. function loop() { requestAnimationFrame(loop); if (pivotMarker.visible) { pivotMarker.position.copy(pivot); // constant *screen* size (not model size — a 1.7m scan would make it a boulder), // and fade out a moment after the pivot was set so it never blocks the work const d = camera.position.distanceTo(pivotMarker.position); pivotMarker.scale.setScalar(Math.max(d * 0.006, 0.05)); const age = performance.now() - (pivotMarker.userData.shownAt || 0); pivotMarker.material.opacity = age < 1200 ? 0.9 : Math.max(0, 0.9 - (age - 1200) / 500); if (pivotMarker.material.opacity <= 0) pivotMarker.visible = false; } // mesh-gap centre dots keep a constant screen size if (meshMarkers.visible) { for (const g of meshMarkers.children) { const dot = g.userData.dot; if (!dot) continue; const d = camera.position.distanceTo(dot.position); dot.scale.setScalar(Math.max(d * 0.004, 0.05)); } } // pick markers keep a constant screen size too for (const mk of markers.concat(align321Obj ? align321Obj.children : [])) { const d = camera.position.distanceTo(mk.position); mk.scale.setScalar(Math.max(d * 0.005, 0.05)); } if (flyAnim) { // Drive the camera directly during the tween; OrbitControls' damping would // otherwise fight the per-frame position set and the camera wouldn't move. const k = Math.min(1, (performance.now() - flyAnim.t0) / flyAnim.dur); const e = k < 0.5 ? 2 * k * k : 1 - Math.pow(-2 * k + 2, 2) / 2; // easeInOutQuad camera.position.lerpVectors(flyAnim.fromPos, flyAnim.toPos, e); controls.target.lerpVectors(flyAnim.fromTgt, flyAnim.toTgt, e); camera.lookAt(controls.target); if (k >= 1) flyAnim = null; } else { controls.update(); } renderer.render(scene, camera); renderTriad(); updateHoleLabels(); updateAlign321Labels(); } // Orientation triad in the bottom-left corner (like ZEISS / CAD view cubes): // world X/Y/Z as seen from the current camera, so you always know which way // the part sits. Rendered as a second pass into a small corner viewport. const triScene = new THREE.Scene(); const triCam = new THREE.OrthographicCamera(-1.45, 1.45, 1.45, -1.45, 0.1, 20); [['X', 1, 0, 0], ['Y', 0, 1, 0], ['Z', 0, 0, 1]].forEach(([l, x, y, z]) => { const d = new THREE.Vector3(x, y, z); triScene.add(new THREE.ArrowHelper(d, new THREE.Vector3(), 0.95, AXIS_COLOR_TRI[l], 0.3, 0.16)); const s = labelSprite(l, AXIS_CSS_TRI[l]); s.position.copy(d.multiplyScalar(1.22)); s.scale.set(0.9, 0.45, 1); triScene.add(s); }); function renderTriad() { const size = 150, w = viewport.clientWidth, h = viewport.clientHeight; triCam.position.copy(camera.position).sub(controls.target).normalize().multiplyScalar(5); triCam.up.copy(camera.up); triCam.lookAt(0, 0, 0); renderer.autoClear = false; renderer.clearDepth(); renderer.setScissorTest(true); renderer.setScissor(10, 10, size, size); renderer.setViewport(10, 10, size, size); renderer.render(triScene, triCam); renderer.setScissorTest(false); renderer.setViewport(0, 0, w, h); renderer.autoClear = true; } requestAnimationFrame(loop); // Project each hole's centre to screen and place its numbered label there. const _lp = new THREE.Vector3(); function updateHoleLabels() { if (!holes.length) return; const w = viewport.clientWidth, vh = viewport.clientHeight; for (const hole of holes) { if (!hole.labelEl) continue; _lp.set(hole.center[0], hole.center[1], hole.center[2]).project(camera); if (_lp.z > 1 || _lp.z < -1) { hole.labelEl.style.display = 'none'; continue; } hole.labelEl.style.display = 'block'; hole.labelEl.style.left = ((_lp.x * 0.5 + 0.5) * w) + 'px'; hole.labelEl.style.top = ((-_lp.y * 0.5 + 0.5) * vh) + 'px'; } } // Frame a single hole looking straight down its axis, from the side the camera is // already on, zoomed so the hole fills a good part of the view. function flyToHole(h) { const c = v3(h.center); const axis = v3(h.axis).normalize(); const sign = camera.position.clone().sub(c).dot(axis) >= 0 ? 1 : -1; const dia = effectiveDiameter(h); const dist = Math.max(dia * 3.5, 6); flyTo(c, dist, axis.multiplyScalar(sign)); setHud(`Hole ${holes.indexOf(h) + 1}: Ø${dia.toFixed(2)} mm — looking down the bore axis`); } // Select a hole and sync the highlight between the list and the 3D markers. function selectHole(h) { selectedHole = h; holes.forEach(o => { const sel = o === h; const base = o.locked ? 0.7 : 0.42; if (o.gizmo) o.gizmo.traverse(ch => { if (ch.material && ch.material.transparent) ch.material.opacity = sel ? 0.92 : base; }); if (o.labelEl) o.labelEl.classList.toggle('sel', sel); }); renderHoles(); if (h) { const row = document.querySelector(`.hole[data-id="${h.id}"]`); if (row) row.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); } } // ---------------------------------------------------------------- state let meshObject = null; // THREE.Mesh or Group for raycasting let meshTargets = []; // raycast targets let modelScale = 1; let datum = null; // {origin, normal, u, v} — legacy plate build only let seat = null; // surface datum {origin, normal, u, v} — locks hole axes let seatGizmo = null; let patchObj = null; // THREE.Points painting the accepted surface patch let surfacePicks = []; // 1–3 clicked surface points (seat seeds) let lastSeatQuery = null; // last fit_seat body, re-sent for the parallel lock let seatScanned = false; // has the current seat been auto-scanned for holes? let cloudObj = null; // THREE.Points of the raw scanner cloud const frameShift = new THREE.Vector3(); // cumulative mesh recenter + origin shifts const holes = []; // {id, center, axis, diameterFit, measured, thread, through, depth, gizmo, color} let nextId = 1; const gizmos = new THREE.Group(); scene.add(gizmos); let datumGizmo = null; let bossPreview = null; // resolved mount bosses from the last interface export let selectedHole = null; const markers = []; // transient click markers (surface picks / hole assist) // 3-2-1 point alignment state (see "3-2-1 points" below); declared up here // because the render loop and setStep read align321Obj. let alignMode = 'faces'; // Faces method: one click per axis (wand + plane fit). `order` is datum // precedence — first pick is primary — and survives a re-pick of that axis. const alignFaces = { X: null, Y: null, Z: null, active: 'X', seq: 1 }; const align321 = { pts: Array(6).fill(null), normals: Array(6).fill(null), active: 0, rule: 'ZZZ-YY-X', values: [0, 0, 0, 0, 0, 0], planePositive: true, linePositive: true }; let align321Labels = []; // DOM tags ("✕ X1:") following the picked points let align321Obj = null; let previewOn = false; // XYZ preview of a pending alignment (see applyRigid) let seatPatchId = null; // blobCache key of the accepted surface patch (see undo / redo) let restoring = false; // applying a history snapshot: no auto-actions, no new commits // The pick intent decides what a *click* does. Drag always orbits; steps set the // default intent; armed buttons (refine / parallel / datum / origin / assist) // override it until satisfied or cancelled. const pick = { armed: null, pts: [] }; const THREADS = { // coarse-pitch tap-drill diameter (mm) used as the modeled hole 'M2': 1.6, 'M2.5': 2.05, 'M3': 2.5, 'M4': 3.3, 'M5': 4.2, 'M6': 5.0, 'M8': 6.8, 'M10': 8.5, 'M12': 10.2, }; const PALETTE = [0xf85149, 0x3fb950, 0xd29922, 0xa371f7, 0x2f81f7, 0xff7b72, 0x39c5cf]; const SEAT_COLOR = 0xff8b3d; const PINK = 0xff2d9b; const $ = (id) => document.getElementById(id); const hud = $('hud'); function setHud(t) { hud.textContent = t; } function directive(text, calm) { $('dirtext').innerHTML = text; $('directive').classList.toggle('calm', !!calm); } // ---------------------------------------------------------------- step manager let step = 1; function canEnter(n) { if (n === 1) return true; if (n === 2) return !!meshObject; // mesh cleanup (optional) if (n === 3) return !!meshObject; // primitives (optional) if (n === 4) return !!meshObject; // surface — mesh/prims steps are skippable if (n === 5) return !!seat; if (n === 6) return !!meshObject; // holes optional — planes-only export is fine return false; } function refreshStepper() { document.querySelectorAll('.stept').forEach(el => { const n = parseInt(el.dataset.step, 10); el.classList.toggle('active', n === step); el.classList.toggle('locked', !canEnter(n)); el.classList.toggle('done', n < step && canEnter(n + 1)); }); $('to2').disabled = !canEnter(2); $('to3').disabled = !canEnter(3); $('to4').disabled = !canEnter(4); $('to5').disabled = !canEnter(5); $('to6').disabled = !canEnter(6); } function setStep(n) { if (!canEnter(n)) return; const entering = n !== step; step = n; disarm(); if (n !== 3) exitPreview(true); document.querySelectorAll('.step').forEach(el => el.classList.remove('active')); $('step' + n).classList.add('active'); refreshStepper(); // the surface patch is a step-4 confirmation aid; past that it hides the work if (patchObj) patchObj.visible = (n === 4); meshMarkers.visible = (n === 2); // scan-gap rings only matter while editing the mesh if (selObj) selObj.visible = (n === 3); // wand/paint selection likewise primGizmos.visible = (n >= 3); // reference geometry stays useful downstream if (alignGizmo) alignGizmo.visible = (n === 3 && !previewOn); // the preview shows the real frame if (align321Obj) align321Obj.visible = (n === 3 && alignMode === 'points'); drawDatumPlanes(); // step 3 hides them while an alignment is pending if (n === 1) directive(meshObject ? 'Scan loaded. Add the raw point cloud too, if you have it.' : 'Load a scan to begin.', !!meshObject); if (n === 2) { directive('Checking the mesh — clean it up below if it needs it, or skip straight to the surface.', true); refreshMeshStatus(); } if (n === 3) directive('Click a face to select it (Shift-click adds), then fit a ' + 'plane / cylinder / cone / sphere to it — or skip ahead. Reference geometry made here ' + 'drives alignment later.', true); if (n === 4) directive(seat ? 'Click once on the next surface to switch to it — staged holes keep theirs. ' + 'Or refine this one, or ⧉ extend it across coplanar surfaces.' : 'Click once on the surface the holes pass through.'); if (n === 5) { if (entering && !seatScanned && !restoring) autoScan(); // a fresh/changed surface: scan it else if (holes.length) directive(`${holes.length} hole${holes.length === 1 ? '' : 's'} staged. Not seeing yours? Click inside it.`); else if (restoring) directive('No holes staged. Click inside a hole, or ⟳ re-scan the surface.'); else directive('Scanning this surface for round holes…'); } if (n === 6) { drawDatumPlanes(); directive(holes.length ? 'Set the coordinate system, then export.' : 'No holes needed — move the datum planes if you like, then download them. ' + '(Find holes in step 5 to also export mount solids.)', true); } } document.querySelectorAll('.stept').forEach(el => el.addEventListener('click', () => setStep(parseInt(el.dataset.step, 10)))); $('to2').addEventListener('click', () => setStep(2)); $('to3').addEventListener('click', () => setStep(3)); $('to4').addEventListener('click', () => setStep(4)); $('to5').addEventListener('click', () => setStep(5)); $('to6').addEventListener('click', () => setStep(6)); $('skipexport').addEventListener('click', () => setStep(6)); function disarm() { const wasAlign321 = pick.armed === 'align321' || pick.armed === 'alignface'; pick.armed = null; pick.pts = []; clearMarkers(); endPaintMode(); ['refine', 'addcoplanar', 'paintsurf', 'parallelpick', 'datumpick', 'setorigin', 'setpivot', 'primpaint', 'align321pick'] .forEach(id => $(id).classList.remove('armed')); if (wasAlign321) renderAlignSlots(); } // ---------------------------------------------------------------- markers function addMarker(p, color) { // unit sphere; the render loop rescales it to a constant screen size const mk = new THREE.Mesh( new THREE.SphereGeometry(1, 12, 10), new THREE.MeshBasicMaterial({ color, depthTest: false, transparent: true, opacity: 0.85 })); mk.renderOrder = 998; mk.position.copy(p); gizmos.add(mk); markers.push(mk); } function clearMarkers() { markers.forEach(mk => gizmos.remove(mk)); markers.length = 0; } // ---------------------------------------------------------------- file load $('file').addEventListener('change', (e) => { if (e.target.files[0]) loadFile(e.target.files[0]); }); const overlay = $('overlay'); window.__appBooted = true; // module + imports loaded; silences the loader-error overlay overlay.textContent = 'Load an STL, OBJ, or PLY to begin'; ['dragenter', 'dragover'].forEach(ev => viewport.addEventListener(ev, e => { e.preventDefault(); overlay.classList.add('drag'); overlay.textContent = 'Drop to load'; })); ['dragleave', 'drop'].forEach(ev => viewport.addEventListener(ev, e => { e.preventDefault(); overlay.classList.remove('drag'); })); viewport.addEventListener('drop', e => { const f = e.dataTransfer.files[0]; if (f) loadFile(f); }); // World-space bounding box of all the mesh triangles. function meshBox() { const box = new THREE.Box3(); for (const t of meshTargets) { t.geometry.computeBoundingBox(); if (t.geometry.boundingBox) box.union(t.geometry.boundingBox.clone().applyMatrix4(t.matrixWorld)); } return box; } // Fit the mesh triangles to the viewport (aspect-aware), keeping the current angle. function fitView() { if (!meshObject) return; meshObject.updateWorldMatrix(true, true); const box = meshBox(); if (box.isEmpty()) return; const size = box.getSize(new THREE.Vector3()); modelScale = Math.hypot(size.x, size.y, size.z) || 1; // sizes gizmos, brushes // Frame around the rotation pivot (the origin unless the user chose another), // far enough out that the whole part fits from there. (Uploads recentre the // scan on the origin, so before alignment the origin is the part's centre.) if (pivotMode === 'origin') pivot.set(0, 0, 0); else if (pivotMode === 'center') box.getCenter(pivot); const center = pivot.clone(); let sphereR = 0; for (const x of [box.min.x, box.max.x]) for (const y of [box.min.y, box.max.y]) for (const z of [box.min.z, box.max.z]) sphereR = Math.max(sphereR, center.distanceTo(new THREE.Vector3(x, y, z))); sphereR = sphereR || 1; const vfov = THREE.MathUtils.degToRad(camera.fov); const hfov = 2 * Math.atan(Math.tan(vfov / 2) * camera.aspect); const dist = Math.max(sphereR / Math.sin(vfov / 2), sphereR / Math.sin(hfov / 2)) * 1.06; const dirv = camera.position.clone().sub(controls.target); if (dirv.lengthSq() < 1e-9) dirv.set(1, -1, 0.8); dirv.normalize(); controls.target.copy(center); safeUp(dirv); camera.position.copy(center).add(dirv.multiplyScalar(dist)); camera.near = Math.max(dist / 5000, sphereR / 1000); camera.far = dist + sphereR * 20; camera.updateProjectionMatrix(); controls.update(); showPivot(); } window.fitView = fitView; // Standard CAD views (Z up). Top looks down -Z with +Y up the screen. const VIEWS = { iso: new THREE.Vector3(1, -1, 0.8), top: new THREE.Vector3(0, 0, 1), front: new THREE.Vector3(0, -1, 0), right: new THREE.Vector3(1, 0, 0), }; const VIEW_UP = { iso: [0, 0, 1], top: [0, 1, 0], front: [0, 0, 1], right: [0, 0, 1] }; function setView(name) { camera.up.fromArray(VIEW_UP[name]); // standard views come back upright camera.position.copy(controls.target).add(VIEWS[name].clone().normalize()); fitView(); } document.querySelectorAll('#viewtools [data-view]').forEach(b => b.addEventListener('click', () => setView(b.dataset.view))); // World datum planes — XY (⊥Z), YZ (⊥X), XZ (⊥Y) through the origin, sized to // the part. This is exactly what the planes export writes, so what you see here // is what lands in CAD. `datumPlanes.position` previews a pending move. let datumPlanes = null; let showPlanes = true; function labelSprite(text, color) { const c = document.createElement('canvas'); c.width = 128; c.height = 64; const g = c.getContext('2d'); g.font = 'bold 40px sans-serif'; g.fillStyle = color; g.textAlign = 'center'; g.textBaseline = 'middle'; g.fillText(text, 64, 32); const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: new THREE.CanvasTexture(c), depthTest: false, transparent: true })); s.renderOrder = 997; return s; } function drawDatumPlanes() { const keep = datumPlanes ? datumPlanes.position.clone() : new THREE.Vector3(); if (datumPlanes) { scene.remove(datumPlanes); datumPlanes = null; } if (!meshObject || !showPlanes) return; // a pending alignment draws its own planes until previewed — don't show two sets if (step === 3 && alignFrame && !previewOn) return; meshObject.updateWorldMatrix(true, true); // a preview may have just set its matrix const box = meshBox(); if (box.isEmpty()) return; box.expandByPoint(new THREE.Vector3()); // always reach the origin const pad = box.getSize(new THREE.Vector3()).length() * 0.06; box.min.addScalar(-pad); box.max.addScalar(pad); const lo = box.min, hi = box.max; const g = new THREE.Group(); const P = [ { name: 'XY', color: 0x2f81f7, css: '#58a6ff', a: 'x', b: 'y' }, { name: 'YZ', color: 0xf85149, css: '#ff7b72', a: 'y', b: 'z' }, { name: 'XZ', color: 0x3fb950, css: '#56d364', a: 'x', b: 'z' }, ]; for (const p of P) { const corner = (u, v) => { const q = new THREE.Vector3(); q[p.a] = u; q[p.b] = v; return q; }; const pts = [corner(lo[p.a], lo[p.b]), corner(hi[p.a], lo[p.b]), corner(hi[p.a], hi[p.b]), corner(lo[p.a], hi[p.b])]; const geo = new THREE.BufferGeometry().setFromPoints([pts[0], pts[1], pts[2], pts[0], pts[2], pts[3]]); g.add(new THREE.Mesh(geo, new THREE.MeshBasicMaterial({ color: p.color, transparent: true, opacity: 0.08, side: THREE.DoubleSide, depthWrite: false }))); g.add(new THREE.LineLoop(new THREE.BufferGeometry().setFromPoints(pts), new THREE.LineBasicMaterial({ color: p.color, transparent: true, opacity: 0.5 }))); const lab = labelSprite(p.name, p.css); lab.position.copy(pts[2]); const s = (hi[p.a] - lo[p.a] + hi[p.b] - lo[p.b]) * 0.05; lab.scale.set(s * 2, s, 1); g.add(lab); } g.position.copy(keep); scene.add(g); datumPlanes = g; } $('planestoggle').addEventListener('click', () => { showPlanes = !showPlanes; $('planestoggle').classList.toggle('armed', showPlanes); drawDatumPlanes(); }); // Debug/testing handle: lets headless tests project world→screen and assert state. window.__scan2cad = { camera, controls, gizmos, addHole, flipHole, fitView, get seat() { return seat; }, get holes() { return holes; }, get datum() { return datum; }, get step() { return step; }, get surfacePicks() { return surfacePicks; }, get meshObject() { return meshObject; }, get paint() { return paint; }, get meshStatus() { return meshStatus; }, get meshBusy() { return meshBusy; }, get prims() { return prims; }, get selCount() { return selCount; }, get alignFrame() { return alignFrame; }, get align321() { return align321; }, get alignFaces() { return alignFaces; }, get previewOn() { return previewOn; }, wandSelect, undo: () => travel('undo'), redo: () => travel('redo'), goto: (i) => travel('goto', i), get pivot() { return pivot; }, get pivotMode() { return pivotMode; }, get history() { return hist; }, get busy() { return inFlight > 0 || histBusy; }, setStep }; // Load-pipeline logger: prefixed, timestamped console output so every step of a load // is traceable from the browser console (and via read_console_messages). const LOG = (...a) => console.log(`[scan2cad load +${(performance.now() - (LOG._t0 || 0)).toFixed(0)}ms]`, ...a); async function loadFile(file) { LOG._t0 = performance.now(); LOG('start:', file.name, `${(file.size / 1e6).toFixed(2)} MB`, 'type=' + (file.type || 'n/a')); overlay.textContent = 'Loading…'; const ext = file.name.split('.').pop().toLowerCase(); LOG('extension:', ext); // clear previous exitPreview(true); resetHistoryUI(); // the server starts a fresh history on upload if (meshObject) { scene.remove(meshObject); LOG('removed previous mesh'); } clearAllFeatures(); clearSeat(); meshTargets = []; meshStatus = null; // new scan: stale topology readout + rings drawMeshHoleMarkers(); $('decinfo').textContent = ''; clearAllPrims(); // server drops its registry on upload too try { const buf = await file.arrayBuffer(); LOG('arrayBuffer read:', buf.byteLength, 'bytes'); const mat = new THREE.MeshStandardMaterial({ color: 0x9aa7b4, metalness: 0.1, roughness: 0.75, side: THREE.DoubleSide, flatShading: false }); if (ext === 'obj') { LOG('parsing OBJ…'); const obj = new OBJLoader().parse(new TextDecoder().decode(buf)); obj.traverse(c => { if (c.isMesh) { c.material = mat; meshTargets.push(c); } }); meshObject = obj; } else if (ext === 'ply') { LOG('parsing PLY…'); const geo = new PLYLoader().parse(buf); LOG('PLY parsed:', geo.attributes.position ? geo.attributes.position.count : 0, 'verts,', geo.index ? geo.index.count / 3 : 0, 'tris, normals=' + !!geo.attributes.normal); if (!geo.attributes.normal) { geo.computeVertexNormals(); LOG('computed vertex normals'); } const m = new THREE.Mesh(geo, mat); meshObject = m; meshTargets.push(m); } else if (ext === 'stl') { LOG('parsing STL…'); const geo = new STLLoader().parse(buf); LOG('STL parsed:', geo.attributes.position ? geo.attributes.position.count : 0, 'verts'); geo.computeVertexNormals(); const m = new THREE.Mesh(geo, mat); meshObject = m; meshTargets.push(m); } else { throw new Error(`unsupported file type ".${ext}" — use STL, OBJ, or PLY`); } if (!meshTargets.length || !meshTargets[0].geometry.attributes.position) { throw new Error('file parsed but contained no geometry'); } scene.add(meshObject); LOG('added to scene'); // Recenter scan coordinates at the origin. Raw scans live far from (0,0,0) in // scanner space; we translate every mesh geometry by -bboxCenter so the part // sits on the grid. The backend recenters by the same bbox-center (recenter=1 // below) so picks/fits stay in the same frame. const rawBox = new THREE.Box3().setFromObject(meshObject); const rawCenter = new THREE.Vector3(); rawBox.getCenter(rawCenter); const rawSize = new THREE.Vector3(); rawBox.getSize(rawSize); LOG('bbox size(mm):', `${rawSize.x.toFixed(1)}x${rawSize.y.toFixed(1)}x${rawSize.z.toFixed(1)}`, 'center:', `(${rawCenter.x.toFixed(1)},${rawCenter.y.toFixed(1)},${rawCenter.z.toFixed(1)})`); for (const t of meshTargets) { t.geometry.translate(-rawCenter.x, -rawCenter.y, -rawCenter.z); t.geometry.computeBoundingBox(); } frameShift.copy(rawCenter); if (cloudObj) { // a new mesh defines a new frame; the old cloud is stale scene.remove(cloudObj); cloudObj = null; $('cloudinfo').textContent = 'Reload the point cloud for this mesh.'; } fitView(); drawDatumPlanes(); LOG('fitView done, modelScale=' + modelScale.toFixed(1)); } catch (err) { console.error('[scan2cad] load failed:', err); overlay.textContent = 'Could not load ' + file.name + ': ' + err.message; setHud('Load failed: ' + err.message); $('meshinfo').textContent = 'Load failed: ' + err.message; return; } overlay.textContent = ''; setHud('Uploading to fitter…'); LOG('uploading to /api/upload…'); // upload to backend for fitting (recenter so its mesh shares this frame) const fd = new FormData(); fd.append('file', file); fd.append('recenter', '1'); try { const res = await fetch('/api/upload', { method: 'POST', body: fd }); LOG('upload HTTP', res.status); const j = await res.json(); if (!j.ok) throw new Error(j.error || 'upload failed'); LOG('backend parsed:', j.nverts, 'verts,', j.ntris, 'tris'); $('meshinfo').innerHTML = `${j.name} · ${j.nverts.toLocaleString()} verts · ${j.ntris.toLocaleString()} tris`; setHud(''); LOG('done — ready.'); setDocName(j.name, j.ntris); refreshStepper(); setStep(2); await commit('Load mesh', `${j.ntris.toLocaleString()} tris`); } catch (err) { console.error('[scan2cad] upload failed:', err); LOG('upload FAILED:', err.message); setHud('Upload error: ' + err.message); $('meshinfo').textContent = 'Backend upload failed: ' + err.message; } refreshBuildEnabled(); } // ---------------------------------------------------------------- point cloud $('cloudfile').addEventListener('change', (e) => { if (e.target.files[0]) loadCloud(e.target.files[0]); }); async function loadCloud(file) { if (!meshObject) { setHud('Load the mesh first — the cloud aligns to its frame.'); return; } $('cloudinfo').textContent = 'Loading cloud…'; try { const buf = await file.arrayBuffer(); const geo = new PLYLoader().parse(buf); const n = geo.attributes.position ? geo.attributes.position.count : 0; if (!n) throw new Error('no points in file'); geo.translate(-frameShift.x, -frameShift.y, -frameShift.z); if (cloudObj) scene.remove(cloudObj); cloudObj = new THREE.Points(geo, new THREE.PointsMaterial({ color: 0x39c5cf, size: Math.max(modelScale * 0.0012, 0.05), sizeAttenuation: true, transparent: true, opacity: 0.5 })); scene.add(cloudObj); const fd = new FormData(); fd.append('file', file); const res = await fetch('/api/upload_cloud', { method: 'POST', body: fd }); const j = await res.json(); if (!j.ok) throw new Error(j.error || 'upload failed'); $('cloudinfo').innerHTML = `${j.name} · ${j.npts.toLocaleString()} points merged into fits`; setHud(`Point cloud loaded: ${j.npts.toLocaleString()} points now sharpen every fit.`); await commit('Add point cloud', `${j.npts.toLocaleString()} pts`); } catch (err) { console.error('[scan2cad] cloud load failed:', err); if (cloudObj) { scene.remove(cloudObj); cloudObj = null; } $('cloudinfo').textContent = 'Cloud load failed: ' + err.message; setHud('Cloud load failed: ' + err.message); } } // ---------------------------------------------------------------- mesh edit (02) // QuickSurface-style cleanup: floating-debris removal, hole filling, decimation. // The server owns the mesh; every op returns a fresh topology status and the // viewer re-downloads the mesh so what you see is exactly what gets fitted. let meshStatus = null; let meshBusy = false; const meshMarkers = new THREE.Group(); // red rings on open boundary loops meshMarkers.visible = false; scene.add(meshMarkers); async function refreshMeshStatus() { if (!meshObject) return; $('meshstat').textContent = 'Checking the mesh…'; try { const r = await fetch('/api/mesh/status'); const j = await r.json(); if (!j.ok) throw new Error(j.error || 'server'); meshStatus = j.status; renderMeshPanel(); } catch (err) { $('meshstat').textContent = 'Mesh check failed: ' + err.message; } } function renderMeshPanel() { const s = meshStatus; if (!s) return; $('meshhealth').textContent = s.watertight ? 'watertight' : 'open'; $('meshhealth').className = 'pill ' + (s.watertight ? 'on' : 'off'); $('meshstat').innerHTML = `${s.ntris.toLocaleString()} tris · ${s.nverts.toLocaleString()} verts` + (s.nonManifoldEdges ? ` · ${s.nonManifoldEdges} non-manifold edge${s.nonManifoldEdges === 1 ? '' : 's'}` : ''); const nc = s.components.length; $('compcount').textContent = nc; $('keeplargest').disabled = nc < 2; $('removesmall').disabled = nc < 2; $('compinfo').innerHTML = nc > 1 ? `Main mesh: ${s.components[0].ntris.toLocaleString()} tris — plus ${nc - 1} floating island${nc === 2 ? '' : 's'}.` : 'One connected mesh — nothing floating.'; const nh = s.holes.length; $('mholecount').textContent = nh; $('fillall').disabled = nh === 0; $('mholeinfo').innerHTML = nh ? `${nh} gap${nh === 1 ? '' : 's'} traced in red. Click a red dot to fill just that gap — ` + `leave real bores open if you'll detect them as holes later.` : 'No open boundaries — every gap is closed.'; $('decimate').disabled = !s.ntris; drawMeshHoleMarkers(); // step-2 directive reflects what actually needs doing if (step === 2) { const todo = []; if (nc > 1) todo.push(`${nc - 1} floating part${nc === 2 ? '' : 's'}`); if (nh) todo.push(`${nh} gap${nh === 1 ? '' : 's'}`); directive(todo.length ? `The scan has ${todo.join(' and ')} — clean it up below, or skip straight to the surface.` : 'Mesh is clean' + (s.watertight ? ' and watertight' : '') + ' — reduce polygons if it\'s heavy, or continue.', !todo.length); } refreshStepper(); } function drawMeshHoleMarkers() { while (meshMarkers.children.length) meshMarkers.remove(meshMarkers.children[0]); if (!meshStatus) return; for (const h of meshStatus.holes) { const g = new THREE.Group(); // the actual rim, traced in red — a center+radius disc would drown the view // on long thin seam gaps if (h.loop && h.loop.length >= 3) { const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.Float32BufferAttribute(h.loop.flat(), 3)); g.add(new THREE.LineLoop(geo, new THREE.LineBasicMaterial({ color: 0xf85149, transparent: true, opacity: 0.9 }))); } // small screen-constant dot at the centre: the click target for "fill this one" const dot = new THREE.Mesh( new THREE.SphereGeometry(1, 10, 8), new THREE.MeshBasicMaterial({ color: 0xf85149, depthTest: false, transparent: true, opacity: 0.9 })); dot.renderOrder = 995; dot.position.set(h.center[0], h.center[1], h.center[2]); g.add(dot); g.userData.holeId = h.id; g.userData.dot = dot; meshMarkers.add(g); } } // Run a mutating mesh op, then swap in the server's updated mesh so the view, // the fitter, and the topology readout can never disagree. const MESH_BTNS = ['keeplargest', 'removesmall', 'fillall', 'decimate']; async function meshOp(url, body, busyMsg) { if (meshBusy) { setHud('Still working on the previous mesh edit…'); return null; } meshBusy = true; MESH_BTNS.forEach(id => { $(id).disabled = true; }); // one op at a time, visibly setHud(busyMsg || 'Working on the mesh…'); try { const j = await post(url, body); if (!j.ok) { setHud('Mesh edit failed: ' + (j.error || 'server')); return null; } await reloadMeshFromServer(); // status flips only after the new mesh is actually on screen, so anything // watching it (or the user) can't race ahead of the reload meshStatus = j.status; setDocName(null, j.status.ntris); $('meshinfo').innerHTML = `edited mesh · ${j.status.nverts.toLocaleString()} verts · ` + `${j.status.ntris.toLocaleString()} tris`; setHud(''); return j; } catch (err) { setHud('Mesh edit failed: ' + err.message); return null; } finally { meshBusy = false; renderMeshPanel(); // recomputes every button's enabled state } } async function reloadMeshFromServer() { const r = await fetch('/api/mesh/current'); if (!r.ok) throw new Error('mesh download failed (' + r.status + ')'); const buf = await r.arrayBuffer(); const geo = new STLLoader().parse(buf); geo.computeVertexNormals(); // Server and viewer share one frame (upload recentered both identically, and // set_origin shifts both), so the STL drops in with no transform. const mat = meshTargets[0] ? meshTargets[0].material : new THREE.MeshStandardMaterial({ color: 0x9aa7b4, metalness: 0.1, roughness: 0.75, side: THREE.DoubleSide, flatShading: false }); if (meshObject) scene.remove(meshObject); for (const t of meshTargets) t.geometry.dispose(); const m = new THREE.Mesh(geo, mat); meshObject = m; meshTargets = [m]; scene.add(m); } $('keeplargest').addEventListener('click', async () => { const j = await meshOp('/api/mesh/remove_components', { keepLargest: true }, 'Removing floating parts…'); if (!j) return; setHud(`Removed ${j.removed} floating part${j.removed === 1 ? '' : 's'}.`); if (j.removed) await commit('Keep largest part', `−${j.removed} part${j.removed === 1 ? '' : 's'}`); }); $('removesmall').addEventListener('click', async () => { const minTris = parseInt($('minTris').value, 10) || 100; const j = await meshOp('/api/mesh/remove_components', { minTris }, 'Removing small parts…'); if (!j) return; setHud(`Removed ${j.removed} part${j.removed === 1 ? '' : 's'} under ${minTris} triangles.`); if (j.removed) await commit('Remove small parts', `−${j.removed} part${j.removed === 1 ? '' : 's'}`); }); $('fillall').addEventListener('click', async () => { const method = $('fillmethod').value; const j = await meshOp('/api/mesh/fill_holes', { holes: 'all', method }, 'Filling all holes…'); if (!j) return; setHud(`Filled ${j.filled} hole${j.filled === 1 ? '' : 's'} (${method})` + (j.status.holes.length ? ` — ${j.status.holes.length} could not be filled.` : ' — mesh is closed.')); if (j.filled) await commit('Fill all holes', `${j.filled} filled`); }); $('decimate').addEventListener('click', async () => { const percent = Math.min(99, Math.max(1, parseFloat($('decPct').value) || 50)); const body = { percent }; const tol = parseFloat($('decTol').value); if (tol > 0) body.tolerance = tol; const before = meshStatus ? meshStatus.ntris : 0; const j = await meshOp('/api/mesh/decimate', body, `Reducing to ${percent}% …`); if (!j) return; let msg = `${before.toLocaleString()} → ${j.status.ntris.toLocaleString()} tris`; if (j.deviation) { msg += ` · deviation vs original: max ${j.deviation.max.toFixed(3)} mm, ` + `rms ${j.deviation.rms.toFixed(3)} mm, ${j.deviation.pctWithin.toFixed(1)}% within ±${tol} mm`; } $('decinfo').innerHTML = msg; setHud(`Reduced. ${keyLabel('mod+Z')} brings the previous mesh back.`); await commit('Reduce polygons', `${before.toLocaleString()} → ${j.status.ntris.toLocaleString()}`); }); // ---------------------------------------------------------------- primitives (03) // QuickSurface-style extraction: wand/paint a region server-side, fit a // plane/cylinder/cone/sphere to exactly that selection, and construct reference // lines/points from the fitted primitives (these drive alignment later). let selCount = 0; let selObj = null; // amber points showing the server-side selection const prims = []; // {id, kind, …params, checked, gizmo} const primGizmos = new THREE.Group(); scene.add(primGizmos); const PRIM_GLYPH = { plane: '▱', cylinder: '⌭', cone: '◺', sphere: '◯', line: '╱', point: '⊙' }; function drawSelection(preview) { if (selObj) { scene.remove(selObj); selObj.geometry.dispose(); selObj = null; } if (!preview || preview.length < 3) return; const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.Float32BufferAttribute(preview, 3)); selObj = new THREE.Points(geo, new THREE.PointsMaterial({ color: 0xd29922, size: Math.max(modelScale * 0.002, 0.3), sizeAttenuation: true, transparent: true, opacity: 0.9 })); selObj.visible = (step === 3); scene.add(selObj); } function refreshSelUI() { $('selcount').textContent = selCount.toLocaleString(); const has = selCount > 0; ['selclear', 'fitplane', 'fitcyl', 'fitcone', 'fitsphere', 'fitsurf'].forEach(id => { $(id).disabled = !has; }); } async function applySelect(body, note, label) { const j = await post('/api/prim/select', body); if (!j.ok) { setHud('Select failed: ' + (j.error || 'server')); return; } selCount = j.nsel; drawSelection(j.preview); refreshSelUI(); setHud(note ? `${note} — ${j.nsel.toLocaleString()} vertices.` : ''); await commit(label, `${j.nsel.toLocaleString()} verts`); } async function wandSelect(point, add) { const angleDeg = parseFloat($('wandDeg').value) || 15; await applySelect({ mode: 'wand', seed: [point.x, point.y, point.z], angleDeg, add: !!add }, add ? 'Added to selection' : 'Selected', add ? 'Add to selection' : 'Select surface'); } // Each stroke adds only itself: the server already holds earlier strokes // (add: true), so the trail is handed off and cleared — resending it would // re-select regions the user has since cleared. async function primPaintSelect() { const centers = paint.samples.slice(); paint.samples = []; paintDotsRefresh(); await applySelect({ mode: 'paint', centers, radius: brushR(), add: true }, 'Painted into selection', 'Paint selection'); } function clearSelection() { paint.samples = []; // an unfinished brush trail is part of what's being cleared paintDotsRefresh(); return applySelect({ mode: 'clear' }, 'Selection cleared', 'Clear selection'); } $('selclear').addEventListener('click', clearSelection); $('primpaint').addEventListener('click', () => { if (!meshObject) { setHud('Load a mesh first.'); return; } const arming = pick.armed !== 'primpaint'; disarm(); if (arming) { pick.armed = 'primpaint'; $('primpaint').classList.add('armed'); ensureBrush(); directive('Drag across the surface to add it to the selection — strokes accumulate. ' + '[ ] brush size · drag from empty space to orbit'); } else { directive('Paint finished. Fit a primitive to the selection, or keep selecting.', true); } }); function primColor(p) { return PALETTE[p.id % PALETTE.length]; } function drawPrimGizmo(p) { const g = new THREE.Group(); const color = primColor(p); const surf = { color, transparent: true, opacity: 0.3, side: THREE.DoubleSide }; if (p.kind === 'plane' && p.rect) { const c = p.rect; const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.Float32BufferAttribute( [...c[0], ...c[1], ...c[2], ...c[0], ...c[2], ...c[3]], 3)); geo.computeVertexNormals(); g.add(new THREE.Mesh(geo, new THREE.MeshBasicMaterial(surf))); const line = new THREE.BufferGeometry(); line.setAttribute('position', new THREE.Float32BufferAttribute(c.flat(), 3)); g.add(new THREE.LineLoop(line, new THREE.LineBasicMaterial({ color }))); const r = Math.max(v3(c[0]).distanceTo(v3(c[2])) * 0.2, 2); g.add(new THREE.ArrowHelper(v3(p.normal), v3(p.origin), r, color, r * 0.3, r * 0.15)); } else if (p.kind === 'cylinder') { const p1 = v3(p.p1), p2 = v3(p.p2); const axis = v3(p.axis).normalize(); const len = Math.max(p1.distanceTo(p2), p.radius * 0.5); const cyl = new THREE.Mesh( new THREE.CylinderGeometry(p.radius, p.radius, len, 40, 1, true), new THREE.MeshBasicMaterial(surf)); cyl.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), axis); cyl.position.copy(p1.clone().add(p2).multiplyScalar(0.5)); g.add(cyl); const ext = len * 0.3 + modelScale * 0.05; const a = p1.clone().sub(axis.clone().multiplyScalar(ext)); const b = p2.clone().add(axis.clone().multiplyScalar(ext)); const lg = new THREE.BufferGeometry().setFromPoints([a, b]); g.add(new THREE.Line(lg, new THREE.LineBasicMaterial({ color }))); } else if (p.kind === 'cone') { const apex = v3(p.apex), axis = v3(p.axis).normalize(); const t = Math.tan(p.halfAngleDeg * Math.PI / 180); const h1 = Math.max(p.h1, 0), h2 = Math.max(p.h2, h1 + 1e-3); const c1 = apex.clone().add(axis.clone().multiplyScalar(h1)); const c2 = apex.clone().add(axis.clone().multiplyScalar(h2)); const fr = new THREE.Mesh( // frustum: +Y end (radiusTop) sits at c2 new THREE.CylinderGeometry(t * h2, t * h1, h2 - h1, 40, 1, true), new THREE.MeshBasicMaterial(surf)); fr.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), axis); fr.position.copy(c1.clone().add(c2).multiplyScalar(0.5)); g.add(fr); const lg = new THREE.BufferGeometry().setFromPoints([apex, c2]); g.add(new THREE.Line(lg, new THREE.LineBasicMaterial({ color }))); } else if (p.kind === 'sphere') { const s = new THREE.Mesh(new THREE.SphereGeometry(p.radius, 32, 24), new THREE.MeshBasicMaterial(surf)); s.position.copy(v3(p.center)); g.add(s); } else if (p.kind === 'line') { const d = v3(p.d).normalize().multiplyScalar(modelScale * 0.8); const lg = new THREE.BufferGeometry().setFromPoints( [v3(p.p).sub(d), v3(p.p).add(d)]); g.add(new THREE.Line(lg, new THREE.LineBasicMaterial({ color, linewidth: 2 }))); } else if (p.kind === 'point') { const mk = new THREE.Mesh(new THREE.OctahedronGeometry(Math.max(modelScale * 0.008, 0.4)), new THREE.MeshBasicMaterial({ color, depthTest: false, transparent: true, opacity: 0.95 })); mk.renderOrder = 994; mk.position.copy(v3(p.p)); g.add(mk); } primGizmos.add(g); return g; } function primSummary(p) { if (p.kind === 'plane') return `n (${fmt(p.normal)})`; if (p.kind === 'cylinder') return `Ø ${(p.radius * 2).toFixed(2)} mm · axis (${fmt(p.axis)})`; if (p.kind === 'cone') return `half-angle ${p.halfAngleDeg.toFixed(2)}° · axis (${fmt(p.axis)})`; if (p.kind === 'sphere') return `Ø ${(p.radius * 2).toFixed(2)} mm @ (${fmt(p.center)})`; if (p.kind === 'line') return `(${fmt(p.p)}) → (${fmt(p.d)})`; if (p.kind === 'point') return `(${fmt(p.p)})`; if (p.kind === 'surface') return `${p.u}×${p.v} ctrl · max ${p.max.toFixed(3)} mm · ${p.pctWithin.toFixed(1)}% in tol`; return ''; } function addPrim(p) { prims.push({ ...p, checked: false, gizmo: drawPrimGizmo(p) }); renderPrims(); } function removePrim(p) { if (p.gizmo) primGizmos.remove(p.gizmo); const i = prims.indexOf(p); if (i >= 0) prims.splice(i, 1); renderPrims(); } function renderPrims() { $('primcount').textContent = prims.length; const wrap = $('prims'); wrap.innerHTML = ''; prims.forEach(p => { const el = document.createElement('div'); el.className = 'hole'; // reuse the card styling of the holes list el.innerHTML = `
${PRIM_GLYPH[p.kind] || ''} ${p.kind} ${p.id} ${p.rms !== undefined ? `rms ${p.rms.toFixed(3)}` : ''}
${primSummary(p)}${p.npts ? ` · ${p.npts.toLocaleString()} pts` : ''}
${p.kind === 'surface' ? `
⬇ STEP
` : ''}`; const devtg = el.querySelector('.devtg'); if (devtg) devtg.onclick = (e) => { e.stopPropagation(); p.devOn = !p.devOn; colorSurfaceGizmo(p); renderPrims(); }; el.querySelector('.p-ck').onchange = (e) => { p.checked = e.target.checked; refreshConstructUI(); }; el.querySelector('.x').onclick = async () => { const j = await post('/api/prim/delete', { id: p.id }); if (!j.ok) return; removePrim(p); await commit(`Delete ${p.kind} ${p.id}`); }; el.addEventListener('click', (e) => { if (e.target.closest('input,button')) return; const ck = el.querySelector('.p-ck'); ck.checked = !ck.checked; p.checked = ck.checked; refreshConstructUI(); }); wrap.appendChild(el); }); refreshConstructUI(); refreshDevLegend(); renderAlignSlots(); } // Which construction the checked set supports — mirrors the server's rules so the // buttons light up only for meaningful combinations. function inferHow(kind, checked) { const kinds = checked.map(p => p.kind); const n = k => kinds.filter(x => x === k).length; if (kind === 'line') { if (checked.length === 2 && n('plane') === 2) return 'planes'; if (checked.length === 1 && (n('cylinder') === 1 || n('cone') === 1)) return 'axis'; if (checked.length === 2 && n('line') === 1 && n('plane') === 1) return 'project'; if (checked.length >= 2 && checked.every(p => p.kind === 'cylinder' || p.kind === 'line')) return 'average'; } else { if (checked.length === 2 && n('line') === 1 && n('plane') === 1) return 'lineplane'; if (checked.length === 3 && n('plane') === 3) return 'threeplanes'; if ((checked.length === 2 && n('point') === 2) || (checked.length === 1 && n('line') === 1)) return 'midpoint'; if (checked.length === 1 && n('sphere') === 1) return 'center'; } return null; } function refreshConstructUI() { const checked = prims.filter(p => p.checked); $('mkline').disabled = !inferHow('line', checked); $('mkpoint').disabled = !inferHow('point', checked); } async function constructPrim(kind) { const checked = prims.filter(p => p.checked); const how = inferHow(kind, checked); if (!how) return; const j = await post('/api/prim/construct', { kind, how, ids: checked.map(p => p.id) }); if (!j.ok) { setHud('Construct failed: ' + (j.error || 'server')); return; } prims.forEach(p => { p.checked = false; }); addPrim(j.prim); setHud(`Reference ${kind} created (${how}).`); await commit(`Ref ${kind} ${j.prim.id}`, how); } $('mkline').addEventListener('click', () => constructPrim('line')); $('mkpoint').addEventListener('click', () => constructPrim('point')); async function fitPrim(type) { setHud(`Fitting ${type}…`); const j = await post('/api/prim/fit', { type }); if (!j.ok) { setHud('Fit failed: ' + (j.error || 'server')); return; } addPrim(j.prim); setHud(`${type} fitted — rms ${j.prim.rms.toFixed(3)} mm over ${j.prim.npts.toLocaleString()} pts.`); directive(`${type} ${j.prim.id} extracted (rms ${j.prim.rms.toFixed(3)} mm). ` + 'Select another region, or check primitives to construct reference geometry.', true); await commit(`Fit ${type} ${j.prim.id}`, `rms ${j.prim.rms.toFixed(3)}`); } $('fitplane').addEventListener('click', () => fitPrim('plane')); $('fitcyl').addEventListener('click', () => fitPrim('cylinder')); $('fitcone').addEventListener('click', () => fitPrim('cone')); $('fitsphere').addEventListener('click', () => fitPrim('sphere')); // ---- free-form Fit Surface + deviation colormap -------------------------- // The fitted B-spline preview is coloured by signed deviation to the scan: // green within ±tol, gradient out to ±5·tol, saturated beyond, neutral grey in // the extended skirt where there is no scan data. Recolouring on a tolerance // change is pure client-side — that's the "real-time" part. function devColor(d, tol, out) { if (d === null || d === undefined || Number.isNaN(d)) { out.setRGB(0.35, 0.37, 0.4); return; } const a = Math.abs(d); if (a <= tol) { out.setHex(0x3fb950); return; } const t = Math.min((a - tol) / (4 * tol), 1); if (d > 0) out.setHSL(0.33 * (1 - t), 0.85, 0.5 - 0.22 * t); // green → red → dark else out.setHSL(0.33 + 0.33 * t, 0.85, 0.5 - 0.22 * t); // green → blue → dark } function surfTol() { return Math.max(parseFloat($('surfTol').value) || 0.05, 1e-4); } function colorSurfaceGizmo(p) { const mesh = p.gizmo && p.gizmo.userData.surfMesh; if (!mesh || !p.preview) return; const tol = surfTol(); const dev = p.preview.dev; const colors = mesh.geometry.getAttribute('color'); const c = new THREE.Color(); for (let i = 0; i < dev.length; i++) { devColor(p.devOn ? dev[i] : null, tol, c); if (!p.devOn) c.setHex(primColor(p)); colors.setXYZ(i, c.r, c.g, c.b); } colors.needsUpdate = true; mesh.material.opacity = p.devOn ? 0.95 : 0.35; } function drawSurfaceGizmo(p) { const { nu, nv, pos } = p.preview; const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3)); geo.setAttribute('color', new THREE.Float32BufferAttribute(new Float32Array(nu * nv * 3), 3)); const idx = []; for (let i = 0; i < nu - 1; i++) for (let j = 0; j < nv - 1; j++) { const a = i * nv + j, b = a + nv; idx.push(a, b, a + 1, b, b + 1, a + 1); } geo.setIndex(idx); geo.computeVertexNormals(); const mesh = new THREE.Mesh(geo, new THREE.MeshBasicMaterial({ vertexColors: true, transparent: true, opacity: 0.95, side: THREE.DoubleSide })); const g = new THREE.Group(); g.add(mesh); g.userData.surfMesh = mesh; primGizmos.add(g); return g; } function refreshDevLegend() { const anySurf = prims.some(p => p.kind === 'surface'); $('devlegend').style.display = anySurf ? '' : 'none'; if (anySurf) { const t = surfTol(); $('devlo').textContent = `−${(5 * t).toFixed(2)}`; $('devhi').textContent = `+${(5 * t).toFixed(2)}`; } } $('surfTol').addEventListener('input', () => { prims.forEach(p => { if (p.kind === 'surface') colorSurfaceGizmo(p); }); refreshDevLegend(); }); $('fitsurf').addEventListener('click', async () => { const auto = $('surfAuto').checked; const body = { smooth: (parseFloat($('surfSmooth').value) || 0) / 100, tol: surfTol(), auto, }; if (!auto) { body.u = Math.min(50, Math.max(4, parseInt($('surfU').value, 10) || 10)); body.v = Math.min(50, Math.max(4, parseInt($('surfV').value, 10) || 10)); } $('fitsurf').disabled = true; setHud(auto ? 'Fitting surface (auto-growing the control net)…' : 'Fitting surface…'); try { const j = await post('/api/surface/fit', body); if (!j.ok) { setHud('Surface fit failed: ' + (j.error || 'server')); return; } const p = { ...j.prim, preview: j.preview, devOn: true, checked: false }; p.gizmo = drawSurfaceGizmo(p); prims.push(p); colorSurfaceGizmo(p); renderPrims(); $('surfU').value = j.prim.u; // show what auto-fit actually reached $('surfV').value = j.prim.v; $('surfinfo').innerHTML = `${j.prim.u}×${j.prim.v} control pts · ` + `rms ${j.prim.rms.toFixed(3)} mm · max ${j.prim.max.toFixed(3)} · ` + `${j.prim.pctWithin.toFixed(1)}% within ±${surfTol()} mm`; setHud(''); directive(`Surface fitted — the colour map shows deviation (green = within ±${surfTol()} mm). ` + 'Tighten Tolerance to recolour live, raise Smoothness and refit to trade accuracy for fairness.', true); await commit(`Fit surface ${j.prim.id}`, `${j.prim.u}×${j.prim.v}`); } finally { $('fitsurf').disabled = selCount === 0; refreshDevLegend(); } }); // ---- Align by Coordinate System (3-2-1 datum alignment) ------------------- // Up to three primitives map to world roles; the server builds the rigid // transform and reports per-DOF lock state. The triad preview shows where the // world frame will land on the part: locked axes in full colour, free ones grey. const ALIGN_DIR_KINDS = ['plane', 'cylinder', 'cone', 'line']; const ALIGN_PT_KINDS = ['point', 'sphere']; const alignSlots = [ { id: -1, target: 'Z', flip: false }, { id: -1, target: 'X', flip: false }, { id: -1, target: 'Y', flip: false }, ]; let alignFrame = null; // last /api/align/frame response let alignGizmo = null; const SLOT_NAMES = ['Primary', 'Secondary', 'Tertiary']; function renderAlignSlots() { const wrap = $('alignslots'); wrap.innerHTML = ''; $('align321pick').style.display = alignMode === 'prims' ? 'none' : ''; if (alignMode === 'points') { renderAlign321(wrap); return; } if (alignMode === 'faces') { renderFaces(wrap); return; } const eligible = prims.filter(p => ALIGN_DIR_KINDS.includes(p.kind) || ALIGN_PT_KINDS.includes(p.kind)); alignSlots.forEach((slot, i) => { if (slot.id >= 0 && !eligible.some(p => p.id === slot.id)) slot.id = -1; // deleted prim const row = document.createElement('div'); row.className = 'grid3'; row.style.marginTop = '4px'; const opts = [''].concat(eligible.map(p => ``)); const chosen = eligible.find(p => p.id === slot.id); const isDir = chosen && ALIGN_DIR_KINDS.includes(chosen.kind); const targetSel = !chosen ? '' : isDir ? `` : '→ origin'; row.innerHTML = ` `; row.querySelector('.a-p').onchange = (e) => { slot.id = parseInt(e.target.value, 10); autoFlip(slot); renderAlignSlots(); previewAlign(); }; const t = row.querySelector('.a-t'); if (t) t.onchange = (e) => { slot.target = e.target.value; previewAlign(); }; const f = row.querySelector('.a-f'); if (f) f.onchange = (e) => { slot.flip = e.target.checked !== !!slot.auto; previewAlign(); }; wrap.appendChild(row); }); } // Engineers draw from the part's corner outward: by default a datum plane's // axis points into the part, so the part sits on the + side of every plane. // (A fitted normal's sign is arbitrary, so 'flip' starts from this instead.) function partCenter() { const box = new THREE.Box3(); for (const t of meshTargets) { t.geometry.computeBoundingBox(); box.union(t.geometry.boundingBox); } return box.isEmpty() ? null : box.getCenter(new THREE.Vector3()); } // `slot.auto` is that into-the-part default; `slot.flip` (sent to the server) // is relative to the fitted normal. The checkbox shows flip ≠ auto, so it // starts unticked and ticking it points the axis away from the part. function autoFlip(slot) { slot.auto = false; const p = prims.find(x => x.id === slot.id); const c = partCenter(); if (p && p.kind === 'plane' && c) slot.auto = c.sub(v3(p.origin)).dot(v3(p.normal)) < 0; slot.flip = slot.auto; } function primDir(p) { return v3(p.kind === 'plane' ? p.normal : p.kind === 'line' ? p.d : p.axis).normalize(); } // With three direction slots, the first two fix the rotation and the third axis // follows from the right-hand rule. If the third's requested direction points // the other way, say so and offer the swap that honours all three. // The direction slots in precedence order, for either slot-based method. function dirSlots() { const list = alignMode === 'faces' ? orderedFaces() : alignMode === 'prims' ? alignSlots : []; return list.map(sl => ({ sl, p: prims.find(x => x.id === sl.id) })) .filter(o => o.sl.id >= 0 && o.p && ALIGN_DIR_KINDS.includes(o.p.kind)); } function swapFirstTwo() { const d = dirSlots(); const a = d[0].sl.target, b = d[1].sl.target; if (alignMode === 'faces') { [alignFaces[a], alignFaces[b]] = [alignFaces[b], alignFaces[a]]; alignFaces[a].target = a; alignFaces[b].target = b; } else { d[0].sl.target = b; d[1].sl.target = a; } renderAlignSlots(); return previewAlign().then(livePreview).then(() => commit(`Swap ${a} and ${b}`)); } function handednessNote(j) { const dirs = dirSlots(); if (dirs.length < 3) return ''; const third = dirs[2]; const want = primDir(third.p).multiplyScalar(third.sl.flip ? -1 : 1); const got = v3(j.axes[third.sl.target.toLowerCase()]); if (want.dot(got) >= 0) return ''; const a = dirs[0].sl.target, b = dirs[1].sl.target, c = third.sl.target; return `
⚠ ${c} is set by ${a} and ${b} (right-hand rule), so it points the other way ` + `from ${third.p.kind} ${third.p.id}. To put the part on the + side of all three, swap ${a} and ${b}.` + `
`; } function alignBody() { if (alignMode === 'points') return align321Body(); const slots = []; for (const s of alignMode === 'faces' ? orderedFaces() : alignSlots) { if (s.id < 0) continue; const p = prims.find(x => x.id === s.id); if (!p) continue; const entry = { id: s.id, flip: !!s.flip }; if (ALIGN_DIR_KINDS.includes(p.kind)) entry.target = s.target; slots.push(entry); } const translate = [parseFloat($('alignTx').value) || 0, parseFloat($('alignTy').value) || 0, parseFloat($('alignTz').value) || 0]; return { slots, translate }; } function drawAlignGizmo(j) { if (alignGizmo) { scene.remove(alignGizmo); alignGizmo = null; } if (!j) return; const g = new THREE.Group(); const o = v3(j.origin); const len = Math.max(modelScale * 0.28, 10); const axes = [ { d: j.axes.x, c: 0xf85149, rot: [1, 2] }, // rot about y,z lock the X direction { d: j.axes.y, c: 0x3fb950, rot: [0, 2] }, { d: j.axes.z, c: 0x2f81f7, rot: [0, 1] }, ]; axes.forEach((a, i) => { const locked = j.rotLocked[a.rot[0]] && j.rotLocked[a.rot[1]]; const color = locked ? a.c : 0x59606a; g.add(new THREE.ArrowHelper(v3(a.d).normalize(), o, len, color, len * 0.18, len * 0.07)); }); // Datum planes, once both their normal direction and their offset are locked: // XY ⊥ Z, YZ ⊥ X, XZ ⊥ Y, tinted by the normal axis. const dirLocked = [0, 1, 2].map(k => axes[k].rot.every(r => j.rotLocked[r])); const AX = [j.axes.x, j.axes.y, j.axes.z].map(a => v3(a).normalize()); [0, 1, 2].forEach(k => { if (!dirLocked[k] || !j.transLocked[k]) return; const u = AX[(k + 1) % 3], w = AX[(k + 2) % 3]; const quad = new THREE.Mesh(new THREE.PlaneGeometry(len * 1.6, len * 1.6), new THREE.MeshBasicMaterial({ color: axes[k].c, transparent: true, opacity: 0.13, side: THREE.DoubleSide, depthWrite: false })); quad.matrixAutoUpdate = false; quad.matrix.makeBasis(u, w, AX[k]).setPosition(o); g.add(quad); const edge = new THREE.LineSegments(new THREE.EdgesGeometry(quad.geometry), new THREE.LineBasicMaterial({ color: axes[k].c, transparent: true, opacity: 0.6 })); edge.matrixAutoUpdate = false; edge.matrix.copy(quad.matrix); g.add(edge); }); const dot = new THREE.Mesh(new THREE.SphereGeometry(len * 0.03, 12, 10), new THREE.MeshBasicMaterial({ color: 0xffffff })); dot.position.copy(o); g.add(dot); g.visible = (step === 3); scene.add(g); alignGizmo = g; } async function previewAlign() { const body = alignBody(); if (body.points ? !body.points.length : !body.slots.length) { alignFrame = null; drawAlignGizmo(null); drawDatumPlanes(); $('alignapply').disabled = true; $('alignpreview').disabled = true; exitPreview(); $('alignstat').textContent = 'free'; $('alignstat').className = 'pill off'; return; } const j = await post('/api/align/frame', body); if (!j.ok) { alignFrame = null; drawAlignGizmo(null); $('alignapply').disabled = true; $('alignpreview').disabled = true; exitPreview(); $('aligninfo').innerHTML = '⚠ ' + (j.error || 'frame failed'); return; } alignFrame = j; drawAlignGizmo(j); drawDatumPlanes(); $('alignapply').disabled = false; $('alignpreview').disabled = false; syncPreview(); const rot = j.rotLocked.filter(Boolean).length, tr = j.transLocked.filter(Boolean).length; $('alignstat').textContent = j.fullyDefined ? 'defined' : `${rot}/3 rot · ${tr}/3 trans`; $('alignstat').className = 'pill ' + (j.fullyDefined ? 'on' : 'off'); $('aligninfo').innerHTML = (j.fullyDefined ? 'Coordinate system fully defined — Apply moves the part into it.' : 'Partially constrained — free DOF stay put. ' + (alignMode === 'faces' ? 'Pick the remaining faces to pin them.' : 'Add more slots to pin them.')) + (j.overconstrained && j.overconstrained.length ? `
⚠ ignored: ${j.overconstrained.join('; ')}` : '') + handednessNote(j); const sw = $('handswap'); if (sw) sw.onclick = swapFirstTwo; } // ---- Faces: click the +X, +Y, +Z faces ------------------------------------ // One click per axis: magic-wand the face, fit a plane (it joins the primitives // list), point that axis into the part, and move the part into the frame // defined so far — so after X and Y you can see which face should be Z. // Each pick is one history step; ✕ clears just that axis for a re-pick. const FACE_AXES = ['X', 'Y', 'Z']; const PRECEDENCE = ['primary', 'secondary', 'tertiary']; function orderedFaces() { return FACE_AXES.filter(a => alignFaces[a]).map(a => ({ ...alignFaces[a], target: a })) .sort((u, v) => u.order - v.order); } function faceCount() { return FACE_AXES.filter(a => alignFaces[a]).length; } function clearFaces() { FACE_AXES.forEach(a => { alignFaces[a] = null; }); alignFaces.active = 'X'; alignFaces.seq = 1; } function renderFaces(wrap) { FACE_AXES.forEach(a => { // a face plane deleted from the primitives list if (alignFaces[a] && !prims.some(p => p.id === alignFaces[a].id)) alignFaces[a] = null; }); const ord = orderedFaces(); const armed = pick.armed === 'alignface'; wrap.innerHTML = FACE_AXES.map(a => { const f = alignFaces[a], act = armed && alignFaces.active === a; const rank = f ? PRECEDENCE[ord.findIndex(o => o.target === a)] : ''; return `
${act ? '▶ ' : ''}+${a} ${f ? ` ` : ''}
`; }).join(''); wrap.querySelectorAll('.a3pick').forEach(b => b.onclick = () => armFace(b.dataset.ax)); wrap.querySelectorAll('.f-f').forEach(c => c.onchange = async () => { const f = alignFaces[c.dataset.ax]; f.flip = c.checked !== !!f.auto; await previewAlign(); livePreview(); commit(`${c.checked ? 'Flip' : 'Unflip'} +${c.dataset.ax}`); }); wrap.querySelectorAll('.faceopts .x').forEach(b => b.onclick = () => clearFace(b.dataset.ax)); const n = faceCount(); $('align321pick').textContent = armed ? `◎ Picking +${alignFaces.active}… (click to stop)` : n === 0 ? '◎ Pick faces' : n < 3 ? `◎ Pick remaining faces (${n}/3)` : '◎ Re-pick a face…'; } function faceDirective() { if (pick.armed !== 'alignface') { if (faceCount() === 3) directive('All three faces set — the preview shows the part in X/Y/Z. Apply when it looks right.', true); return; } const a = alignFaces.active; directive(`Click the face that will be +${a} — the part goes on its + side. ` + (faceCount() ? 'The part has moved to show the frame so far.' : 'One click picks the whole face.')); } function armFace(a) { disarm(); alignFaces.active = a; pick.armed = 'alignface'; $('align321pick').classList.add('armed'); renderAlignSlots(); faceDirective(); } async function deletePrimQuiet(id) { const p = prims.find(x => x.id === id); if (!p) return; const j = await post('/api/prim/delete', { id }); if (j.ok) removePrim(p); } async function pickAlignFace(hit) { const a = alignFaces.active; const q = hit.object.worldToLocal(hit.point.clone()); // model coords, even mid-preview setHud(`Fitting the +${a} face…`); const angleDeg = parseFloat($('wandDeg').value) || 15; const sel = await post('/api/prim/select', { mode: 'wand', seed: [q.x, q.y, q.z], angleDeg, add: false }); const fit = sel.ok && sel.nsel ? await post('/api/prim/fit', { type: 'plane' }) : null; await post('/api/prim/select', { mode: 'clear' }); selCount = 0; drawSelection(null); refreshSelUI(); if (!fit || !fit.ok) { setHud(`Couldn't read a flat face there — try another spot on the +${a} face.`); return; } const old = alignFaces[a]; if (old) await deletePrimQuiet(old.id); // re-pick replaces that axis's plane addPrim(fit.prim); const f = { id: fit.prim.id, order: old ? old.order : alignFaces.seq++ }; autoFlip(f); alignFaces[a] = f; const next = FACE_AXES.find(x => !alignFaces[x]); if (next) alignFaces.active = next; else { pick.armed = null; $('align321pick').classList.remove('armed'); } renderAlignSlots(); await previewAlign(); livePreview(); faceDirective(); setHud(`+${a} face: plane ${fit.prim.id}, rms ${fit.prim.rms.toFixed(3)} mm.`); await commit(`Pick +${a} face`, `plane ${fit.prim.id}`); } async function clearFace(a) { const f = alignFaces[a]; if (!f) return; alignFaces[a] = null; await deletePrimQuiet(f.id); armFace(a); await previewAlign(); livePreview(); await commit(`Clear +${a} face`); } // Faces and 3-2-1 points preview live: after each pick the part moves into // the frame defined so far. The first time it also turns to the iso view. function livePreview() { if (step !== 3 || alignMode === 'prims') return; if (!alignFrame) { exitPreview(true); return; } if (previewOn) { syncPreview(); fitView(); return; } previewOn = true; $('alignpreview').classList.add('armed'); $('alignpreview').textContent = '👁 Previewing — click to exit'; syncPreview(); setView('iso'); } // ---- 3-2-1 points (ZEISS INSPECT style) ----------------------------------- // Rule "AAA-BB-C": three plane points set coordinate A (the plane is ⊥ A), // two line points set B (the line runs along C), one point sets C. Each point // has its own nominal value. Points live in fixed slots so any one can be // re-picked or removed; the active slot (▶) takes the next click on the mesh. // The server previews after 3 and 5 points and fully defines the frame at 6. const A321_RULES = ['ZZZ-YY-X', 'ZZZ-XX-Y', 'XXX-YY-Z', 'XXX-ZZ-Y', 'YYY-XX-Z', 'YYY-ZZ-X']; const AXIS_COLOR = { X: 0xf85149, Y: 0x3fb950, Z: 0x2f81f7 }; const AXIS_CSS = { X: '#ff7b72', Y: '#56d364', Z: '#58a6ff' }; function a321Axis(i) { const r = align321.rule; return i < 3 ? r[0] : i < 5 ? r[4] : r[7]; } function a321Name(i) { return a321Axis(i) + (i < 3 ? i + 1 : i < 5 ? i - 2 : ''); } function a321Count() { return align321.pts.filter(Boolean).length; } function drawAlign321Points() { if (align321Obj) { scene.remove(align321Obj); align321Obj = null; } align321Labels.forEach(el => el.remove()); align321Labels = []; const g = new THREE.Group(); align321.pts.forEach((p, i) => { if (!p) return; const mk = new THREE.Mesh(new THREE.SphereGeometry(1, 12, 10), new THREE.MeshBasicMaterial({ color: AXIS_COLOR[a321Axis(i)], depthTest: false, transparent: true, opacity: 0.95 })); mk.renderOrder = 998; mk.position.copy(v3(p)); g.add(mk); // ZEISS-style tag: leader line from the point to "✕ X1:" (✕ removes it) const el = document.createElement('div'); el.className = 'ptag'; el.style.setProperty('--c', AXIS_CSS[a321Axis(i)]); el.innerHTML = `✕${a321Name(i)}:`; el.querySelector('.xbtn').addEventListener('click', (ev) => { ev.stopPropagation(); removeAlign321Point(i); }); el.userData = { p }; viewport.appendChild(el); align321Labels.push(el); }); g.visible = (step === 3 && alignMode === 'points'); scene.add(g); align321Obj = g; syncPreview(); } const _tp = new THREE.Vector3(); function updateAlign321Labels() { if (!align321Labels.length) return; const show = step === 3 && alignMode === 'points'; const w = viewport.clientWidth, vh = viewport.clientHeight; if (align321Obj) align321Obj.updateMatrixWorld(); for (const el of align321Labels) { const p = el.userData.p; _tp.set(p[0], p[1], p[2]); if (align321Obj) _tp.applyMatrix4(align321Obj.matrixWorld); // follows the XYZ preview _tp.project(camera); if (!show || _tp.z > 1 || _tp.z < -1) { el.style.display = 'none'; continue; } el.style.display = 'block'; el.style.left = ((_tp.x * 0.5 + 0.5) * w) + 'px'; el.style.top = ((-_tp.y * 0.5 + 0.5) * vh) + 'px'; } } function align321Directive() { if (pick.armed !== 'align321') { if (a321Count() === 6) directive('All 6 points set — 👁 Preview to check the part in X/Y/Z, then Apply.', true); return; } const i = align321.active; const where = i < 3 ? 'on the plane face — spread the three out' : i < 5 ? `along the line face — +${align321.rule[7]} runs from ${a321Name(3)} to ${a321Name(4)}` : `on the face that sets ${align321.rule[7]}`; directive(`Click ${a321Name(i)} ${where}.`); } function renderAlign321(wrap) { const r = align321.rule; const row = (i) => { const has = !!align321.pts[i], act = pick.armed === 'align321' && align321.active === i; return `
${act ? '▶ ' : ''}${a321Name(i)}:
`; }; wrap.innerHTML = `
Plane — ${r[0]}1–${r[0]}3 set ${r[0]} (plane ⊥ ${r[0]})
${row(0)}${row(1)}${row(2)}
Line — ${r[4]}1–${r[4]}2 set ${r[4]} (line along ${r[7]})
${row(3)}${row(4)}
Point — sets ${r[7]}
${row(5)}`; wrap.querySelector('.a3-rule').onchange = (e) => { align321.rule = e.target.value; drawAlign321Points(); renderAlignSlots(); align321Directive(); previewAlign(); }; wrap.querySelector('.a3-pp').onchange = (e) => { align321.planePositive = e.target.checked; previewAlign(); }; wrap.querySelector('.a3-lp').onchange = (e) => { align321.linePositive = e.target.checked; previewAlign(); }; wrap.querySelectorAll('.a3pick').forEach(b => b.onclick = () => armAlign321(parseInt(b.dataset.i, 10))); wrap.querySelectorAll('.a3val input').forEach(inp => inp.onchange = () => { align321.values[parseInt(inp.dataset.i, 10)] = parseFloat(inp.value) || 0; previewAlign(); }); const n = a321Count(); $('align321pick').textContent = pick.armed === 'align321' ? `◎ Picking ${a321Name(align321.active)}… (click to stop)` : n === 0 ? '◎ Pick 3-2-1 points' : n < 6 ? `◎ Pick remaining (${n}/6)` : '◎ Re-pick all points'; } function align321Body() { // the server only takes complete stages: 3 (plane), 5 (+line), 6 (+point) const p = align321.pts; const usable = p.every(Boolean) ? 6 : p.slice(0, 5).every(Boolean) ? 5 : p.slice(0, 3).every(Boolean) ? 3 : 0; const hint = align321.normals.slice(0, 3).filter(Boolean) .reduce((s, n) => [s[0] + n[0], s[1] + n[1], s[2] + n[2]], [0, 0, 0]); return { points: p.slice(0, usable), rule: align321.rule, values: align321.values.slice(), flipPlane: !align321.planePositive, flipLine: !align321.linePositive, planeHint: hint, // "plane positive" = out of the clicked face }; } function clearAlign321() { align321.pts = Array(6).fill(null); align321.normals = Array(6).fill(null); align321.active = 0; drawAlign321Points(); } function armAlign321(i) { disarm(); align321.active = i; pick.armed = 'align321'; $('align321pick').classList.add('armed'); renderAlignSlots(); align321Directive(); } async function removeAlign321Point(i) { align321.pts[i] = null; align321.normals[i] = null; drawAlign321Points(); armAlign321(i); await previewAlign(); livePreview(); await commit(`Remove point ${a321Name(i)}`); } async function addAlign321Point(hit) { // geometry-local = model coordinates, so picking works mid-preview too const n = hit.face ? hit.face.normal.clone() : new THREE.Vector3(); const q = hit.object.worldToLocal(hit.point.clone()); const i = align321.active; align321.pts[i] = [q.x, q.y, q.z]; align321.normals[i] = [n.x, n.y, n.z]; // advance to the next empty slot after this one (wrapping); none left → done const next = [1, 2, 3, 4, 5].map(k => (i + k) % 6).find(k => !align321.pts[k]); if (next === undefined) { pick.armed = null; $('align321pick').classList.remove('armed'); } else align321.active = next; drawAlign321Points(); renderAlignSlots(); align321Directive(); await previewAlign(); livePreview(); await commit(`Pick point ${a321Name(i)}`); } $('alignmode').addEventListener('change', (e) => { alignMode = e.target.value; disarm(); $('aligninfo').innerHTML = ALIGN_INFO[alignMode]; $('aligndelta').style.display = alignMode === 'points' ? 'none' : ''; // per-point values replace Δ if (align321Obj) align321Obj.visible = alignMode === 'points' && step === 3; renderAlignSlots(); previewAlign(); }); const ALIGN_INFO = { faces: 'Click the faces at the part\'s corner: the one for +X, +Y, then +Z. ' + 'The part moves into place after each pick, on the + side of every face.', points: 'Pick points on the mesh like ZEISS 3-2-1: 3 on the plane face, 2 along the ' + 'line face, 1 for the last axis. Each point can carry a nominal value.', prims: 'Map primitives to the world frame — a plane ⇒ Z puts OXY on it, a cylinder ⇒ X pins ' + 'that axis line, a point pins the origin.', }; $('align321pick').addEventListener('click', () => { if (alignMode === 'faces') { if (pick.armed === 'alignface') { disarm(); faceDirective(); return; } armFace(FACE_AXES.find(a => !alignFaces[a]) || 'X'); return; } if (pick.armed === 'align321') { disarm(); return; } if (a321Count() === 6) clearAlign321(); armAlign321(align321.pts.findIndex(p => !p)); previewAlign(); }); // Rigidly move every piece of client-side state into the new frame so nothing // staged (seat, holes, gizmos) has to be re-picked after an alignment. function applyRT(a, R, t) { return [R[0] * a[0] + R[1] * a[1] + R[2] * a[2] + t[0], R[3] * a[0] + R[4] * a[1] + R[5] * a[2] + t[1], R[6] * a[0] + R[7] * a[1] + R[8] * a[2] + t[2]]; } function applyR(a, R) { return [R[0] * a[0] + R[1] * a[1] + R[2] * a[2], R[3] * a[0] + R[4] * a[1] + R[5] * a[2], R[6] * a[0] + R[7] * a[1] + R[8] * a[2]]; } // ---- XYZ preview: show the part where Apply will put it ------------------- // Everything drawn in model coordinates gets the pending transform as its object // matrix, so the part (and its gizmos) sit in the world frame against the datum // planes and grid. Nothing moves server-side until Apply. (`previewOn` is // declared up top: handleClick and setStep read it.) function previewTargets() { return [meshObject, primGizmos, gizmos, selObj, align321Obj, cloudObj, patchObj, meshMarkers] .filter(Boolean); } function syncPreview() { if (!previewOn) return; if (!alignFrame) { exitPreview(); return; } const { R, t } = alignFrame; const M = new THREE.Matrix4().set(R[0], R[1], R[2], t[0], R[3], R[4], R[5], t[1], R[6], R[7], R[8], t[2], 0, 0, 0, 1); for (const o of previewTargets()) { o.matrixAutoUpdate = false; o.matrix.copy(M); o.matrixWorldNeedsUpdate = true; } if (alignGizmo) alignGizmo.visible = false; // the world datum planes show the same frame drawDatumPlanes(); } function enterPreview() { if (!alignFrame) return; disarm(); previewOn = true; $('alignpreview').classList.add('armed'); $('alignpreview').textContent = '👁 Previewing — click to exit'; syncPreview(); setView('iso'); directive('Preview: the part as it will sit in X/Y/Z — Z up, the grid is the XY plane. ' + 'Flip axes to fix it, then Apply.', true); } function exitPreview(keepCamera) { if (!previewOn) return; previewOn = false; for (const o of previewTargets()) { o.matrixAutoUpdate = true; o.updateMatrix(); o.matrixWorldNeedsUpdate = true; } if (alignGizmo) alignGizmo.visible = (step === 3); $('alignpreview').classList.remove('armed'); $('alignpreview').textContent = '👁 Preview in XYZ'; drawDatumPlanes(); if (!keepCamera) fitView(); } $('alignpreview').addEventListener('click', () => (previewOn ? exitPreview() : enterPreview())); // Commit a rigid transform server-side, then carry every piece of client state // into the new frame. Used by alignment Apply and by the datum-plane moves. async function applyRigid(body, R, t) { setHud('Moving the part…'); const j = await post('/api/align/apply', body); if (!j.ok) { setHud('Move failed: ' + (j.error || 'server')); return false; } await reloadMeshFromServer(); // registry entries come back transformed; keep client-only fields, rebuild gizmos const byId = new Map((j.prims || []).map(p => [p.id, p])); prims.forEach(p => { const np = byId.get(p.id); if (np) Object.assign(p, np); if (p.kind === 'surface' && p.preview) { // rigid ⇒ deviations unchanged, positions move const pos = p.preview.pos; for (let i = 0; i < pos.length; i += 3) { const q = applyRT([pos[i], pos[i + 1], pos[i + 2]], R, t); pos[i] = q[0]; pos[i + 1] = q[1]; pos[i + 2] = q[2]; } } if (p.gizmo) primGizmos.remove(p.gizmo); p.gizmo = p.kind === 'surface' ? drawSurfaceGizmo(p) : drawPrimGizmo(p); if (p.kind === 'surface') colorSurfaceGizmo(p); }); // staged seat / holes / datum move with the part if (seat) { seat.origin = applyRT(seat.origin, R, t); seat.normal = applyR(seat.normal, R); if (seat.u) seat.u = applyR(seat.u, R); if (seat.v) seat.v = applyR(seat.v, R); drawSeatGizmo({ normal: seat.normal, origin: seat.origin, patch: null }); } if (datum) { datum.origin = applyRT(datum.origin, R, t); datum.normal = applyR(datum.normal, R); } holes.forEach(h => { h.center = applyRT(h.center, R, t); h.axis = applyR(h.axis, R); h.p1 = applyRT(h.p1, R, t); h.p2 = applyRT(h.p2, R, t); if (h.gizmo) gizmos.remove(h.gizmo); h.gizmo = drawHoleGizmo({ p1: h.p1, p2: h.p2, axis: h.axis, diameter: effectiveDiameter(h) }, h.color, h.locked); }); surfacePicks = surfacePicks.map(p2 => applyRT(p2, R, t)); lastSeatQuery = null; if (patchObj) { scene.remove(patchObj); patchObj = null; } // stale decimated patch drawSelection(null); selCount = 0; refreshSelUI(); // selection indices are stale if (cloudObj) await reloadCloudFromServer(j.moved ? j.moved.ncloud : 0); // server moved it with the part meshStatus = null; // canUndo changed server-side alignSlots.forEach(s => { s.id = -1; s.flip = false; s.auto = false; }); clearFaces(); clearAlign321(); ['alignTx', 'alignTy', 'alignTz'].forEach(id => { $(id).value = 0; }); alignFrame = null; drawAlignGizmo(null); $('alignpreview').disabled = true; renderPrims(); renderAlignSlots(); drawDatumPlanes(); setHud(''); return true; } $('alignapply').addEventListener('click', async () => { if (!alignFrame) return; exitPreview(true); $('alignapply').disabled = true; const how = alignMode === 'points' ? '3-2-1 points' : 'primitives'; const ok = await applyRigid(alignBody(), alignFrame.R, alignFrame.t); if (!ok) { $('alignapply').disabled = false; return; } setView('iso'); $('alignstat').textContent = 'applied ✓'; $('alignstat').className = 'pill on'; directive('Part aligned — Z up, the grid is the XY plane. Everything staged moved with it. ' + 'Only need the planes? Skip to export to move them or download.', true); await commit('Apply alignment', how); }); $('alignreset').addEventListener('click', () => { alignSlots.forEach((s, i) => { s.id = -1; s.target = ['Z', 'X', 'Y'][i]; s.flip = false; s.auto = false; }); if (pick.armed === 'align321' || pick.armed === 'alignface') disarm(); exitPreview(); clearAlign321(); clearFaces(); Object.assign(align321, { rule: 'ZZZ-YY-X', values: [0, 0, 0, 0, 0, 0], planePositive: true, linePositive: true }); ['alignTx', 'alignTy', 'alignTz'].forEach(id => { $(id).value = 0; }); alignFrame = null; drawAlignGizmo(null); renderAlignSlots(); $('alignapply').disabled = true; $('alignstat').textContent = 'free'; $('alignstat').className = 'pill off'; }); ['alignTx', 'alignTy', 'alignTz'].forEach(id => $(id).addEventListener('change', previewAlign)); function clearAllPrims() { clearFaces(); prims.forEach(p => { if (p.gizmo) primGizmos.remove(p.gizmo); }); prims.length = 0; selCount = 0; drawSelection(null); alignSlots.forEach((s, i) => { s.id = -1; s.target = ['Z', 'X', 'Y'][i]; s.flip = false; s.auto = false; }); alignFrame = null; drawAlignGizmo(null); renderPrims(); refreshSelUI(); } // ---------------------------------------------------------------- click routing // Drag = orbit, always. A clean click (little movement, quick) acts according to // the step / armed tool. No mode buttons. const ray = new THREE.Raycaster(); const ndc = new THREE.Vector2(); let downAt = null; renderer.domElement.addEventListener('pointerdown', (ev) => { if (ev.button === 0) downAt = { x: ev.clientX, y: ev.clientY, t: performance.now() }; }); renderer.domElement.addEventListener('pointerup', (ev) => { if (ev.button !== 0 || !downAt) return; const moved = Math.hypot(ev.clientX - downAt.x, ev.clientY - downAt.y); const dt = performance.now() - downAt.t; downAt = null; if (panKey) return; // space-panning, not picking if (moved > 6 || dt > 600) return; // that was an orbit drag handleClick(ev); }); function raycastEvent(ev) { const rect = renderer.domElement.getBoundingClientRect(); ndc.x = ((ev.clientX - rect.left) / rect.width) * 2 - 1; ndc.y = -((ev.clientY - rect.top) / rect.height) * 2 + 1; ray.setFromCamera(ndc, camera); return ray.intersectObjects(meshTargets, true)[0] || null; } // The hint for hole detection: prefer a mesh hit near the seat plane (clicked the // face), else the ray∩plane point (clicked into the bore's void). function holeHint(ev, hit) { const plane = new THREE.Plane().setFromNormalAndCoplanarPoint(v3(seat.normal), v3(seat.origin)); const pp = ray.ray.intersectPlane(plane, new THREE.Vector3()); if (hit && Math.abs(plane.distanceToPoint(hit.point)) < 2.5) return [hit.point.x, hit.point.y, hit.point.z]; return pp ? [pp.x, pp.y, pp.z] : null; } async function handleClick(ev) { if (!meshObject) return; // the rotation center is a world point, so it can be picked on the previewed part too if (pick.armed === 'pivot') { const hit = raycastEvent(ev); disarm(); if (!hit) { setHud('No surface there — rotation stays around the part\'s center.'); return; } setPivot(hit.point, `Rotating around the clicked point (${hit.point.x.toFixed(1)}, ${hit.point.y.toFixed(1)}, ${hit.point.z.toFixed(1)}). ` + 'Double-click empty space to go back to the origin.'); return; } // alignment picks work on the previewed part (hits map back to model coords) if (pick.armed === 'align321' || pick.armed === 'alignface') { const h = raycastEvent(ev); if (!h) { setHud('No surface there — try again.'); return; } await (pick.armed === 'alignface' ? pickAlignFace(h) : addAlign321Point(h)); return; } if (previewOn) { setHud('Previewing the aligned part — exit the preview to pick.'); return; } if (isPaintMode()) return; // strokes (incl. single taps) are handled by the paint listeners const hit = raycastEvent(ev); if (pick.armed === 'origin') { disarm(); if (!hit) { setHud('No surface there — try again.'); return; } await setOrigin(hit.point); return; } if (pick.armed === 'parallel') { disarm(); if (!hit || !lastSeatQuery) { setHud('No surface there — try again.'); return; } if (await fitSeat({ ...lastSeatQuery, parallelTo: { point: [hit.point.x, hit.point.y, hit.point.z], radius: 0 } })) await commit('Lock parallel'); return; } if (pick.armed === 'datum') { disarm(); if (!hit) { setHud('No surface there — try again.'); return; } await pickDatum(hit.point); return; } if (pick.armed === 'refine') { if (!hit) { setHud('No surface there — try again.'); return; } surfacePicks.push([hit.point.x, hit.point.y, hit.point.z]); addMarker(hit.point, SEAT_COLOR); const left = 3 - surfacePicks.length; if (left > 0) directive(`Refining — click ${left} more point${left === 1 ? '' : 's'} on the same surface.`); else { pick.armed = null; $('refine').classList.remove('armed'); } if (await fitSeat({ points: surfacePicks.slice() })) await commit('Refine surface', `${surfacePicks.length} pts`); return; } if (pick.armed === 'coplanar') { // Open-ended: each click adds a surface to the SAME plane — one joint fit // through every picked island. Stays armed until the user clicks the button // again (or leaves the step), so any number of coplanar faces can join. if (!hit) { setHud('No surface there — try again.'); return; } surfacePicks.push([hit.point.x, hit.point.y, hit.point.z]); addMarker(hit.point, SEAT_COLOR); const ok = await fitSeat({ points: surfacePicks.slice() }); // Not coplanar within tolerance → the fitter silently ignored the new pick's // seeds. Catch it by the pick's distance to the fitted plane and say so. const off = ok ? Math.abs(hit.point.clone().sub(v3(seat.origin)).dot(v3(seat.normal))) : 0; if (!ok || off > 1.0) { surfacePicks.pop(); const mk = markers.pop(); if (mk) gizmos.remove(mk); directive(ok ? `That surface sits ${off.toFixed(2)} mm off this plane — not coplanar, so it wasn't added. Use ∥ parallel instead if it's a different level.` : 'That point didn\'t read as part of the same plane — try another spot on the surface.'); if (ok) await fitSeat({ points: surfacePicks.slice() }); // restore the plane without it pick.armed = 'coplanar'; return; } pick.armed = 'coplanar'; // fitSeat rewrote the directive; re-assert the mode directive(`One plane through ${surfacePicks.length} pick${surfacePicks.length === 1 ? '' : 's'} — ` + `click more coplanar surfaces to add them, or press ⧉ again to finish.`); await commit('Extend coplanar', `${surfacePicks.length} picks`); return; } if (pick.armed === 'assist') { const hint = seat ? holeHint(ev, hit) : null; if (!hint) { setHud('Click inside the hole area.'); return; } pick.pts.push(hint); addMarker(new THREE.Vector3(...hint), PINK); const left = 3 - pick.pts.length; if (left > 0) { directive(`Got it — click ${left} more point${left === 1 ? '' : 's'} inside the hole.`); return; } const pts = pick.pts.slice(); disarm(); directive('Solving the hole from your 3 points…'); const ok = await detectHole(null, 0, 'Hole', pts); if (!ok) directive('Still no round gap there. Check the Ø bounds, or refine the surface and retry.', true); else directive(`${holes.length} hole${holes.length === 1 ? '' : 's'} staged. Not seeing another? Click inside it.`); return; } // step-default actions if (step === 2) { // Mesh edit: clicking a red gap ring fills that hole. raycastEvent above // already aimed `ray`, so reuse it against the markers (their invisible // centre discs give the ring a solid hit area). const mh = ray.intersectObjects(meshMarkers.children, true)[0]; if (!mh) return; let g = mh.object; while (g && g.userData.holeId === undefined) g = g.parent; if (!g) return; const method = $('fillmethod').value; const j = await meshOp('/api/mesh/fill_holes', { holes: [g.userData.holeId], method }, 'Filling the hole…'); if (!j) return; setHud(`Hole filled (${method}) — ${j.status.holes.length} remaining. ${keyLabel('mod+Z')} undoes it if that was a real bore.`); if (j.filled) await commit('Fill hole', method); } else if (step === 3) { // Primitives: click = magic-wand select (Shift adds to the selection) if (!hit) { setHud('Click on the model surface to select it.'); return; } await wandSelect(hit.point, ev.shiftKey); } else if (step === 4) { if (!hit) { setHud('Click on the model surface.'); return; } surfacePicks = [[hit.point.x, hit.point.y, hit.point.z]]; clearMarkers(); addMarker(hit.point, SEAT_COLOR); if (await fitSeat({ points: surfacePicks.slice() })) await commit('Pick surface'); } else if (step === 5) { if (!seat) return; const hint = holeHint(ev, hit); if (!hint) { setHud('Click the hole (or the surface near it).'); return; } directive('Looking for a round gap there…'); if (await detectHole(hint, 0, 'Hole')) { directive(`${holes.length} hole${holes.length === 1 ? '' : 's'} staged. Not seeing another? Click inside it.`); return; } // gated wall-fit fallback (only when the bore itself scanned) if (hit && await lockedWallFit(hit.point)) { directive(`${holes.length} hole${holes.length === 1 ? '' : 's'} staged. Not seeing another? Click inside it.`); return; } // escalate: ask the user for more evidence pick.armed = 'assist'; pick.pts = [hint]; addMarker(new THREE.Vector3(...hint), PINK); directive(`Couldn't confirm it from one point — click 2 more points inside the hole.`); } } // ---------------------------------------------------------------- paint select // Geomagic-style brush: while armed, dragging on the mesh paints a circular // stamp trail; the seat plane is fitted from exactly the painted vertices // (server rejects brushed-over walls/bores). Strokes accumulate — including on // other coplanar surfaces — and every stroke release refits. Dragging from // empty space still orbits, so you can turn the part between strokes. const paint = { samples: [], radius: 0, active: false, dots: null }; let brushRing = null; // The brush serves two masters: 'paint' fits the seat plane, 'primpaint' feeds // the primitives selection. Same stroke mechanics, different release handler. function isPaintMode() { return pick.armed === 'paint' || pick.armed === 'primpaint'; } function brushR() { return paint.radius > 0 ? paint.radius : Math.max(modelScale * 0.012, 1.5); } function ensureBrush() { if (!brushRing) { brushRing = new THREE.Mesh( new THREE.TorusGeometry(1, 0.035, 10, 48), new THREE.MeshBasicMaterial({ color: SEAT_COLOR, depthTest: false, transparent: true, opacity: 0.9 })); brushRing.renderOrder = 997; scene.add(brushRing); } return brushRing; } function updateBrush(hit) { const ring = ensureBrush(); ring.visible = !!hit; if (!hit) return; ring.position.copy(hit.point); const n = hit.face ? hit.face.normal.clone().transformDirection(hit.object.matrixWorld) : camera.getWorldDirection(new THREE.Vector3()).negate(); ring.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), n); ring.scale.setScalar(brushR()); } function paintDotsRefresh() { if (paint.dots) { scene.remove(paint.dots); paint.dots = null; } if (!paint.samples.length) return; const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.Float32BufferAttribute(paint.samples.flat(), 3)); paint.dots = new THREE.Points(geo, new THREE.PointsMaterial({ color: SEAT_COLOR, size: Math.max(modelScale * 0.004, 0.6), sizeAttenuation: true, transparent: true, opacity: 0.9, depthTest: false })); paint.dots.renderOrder = 996; scene.add(paint.dots); } function endPaintMode() { paint.active = false; paint.samples = []; controls.enabled = true; if (brushRing) brushRing.visible = false; if (paint.dots) { scene.remove(paint.dots); paint.dots = null; } } function addPaintSample(p) { paint.samples.push([p.x, p.y, p.z]); paintDotsRefresh(); } async function fitPaintedSeat() { const ok = await fitSeat({ paint: { centers: paint.samples.slice(), radius: brushR() } }); if (!ok) { directive('Couldn\'t fit a plane to the painted area yet — keep painting on the surface.'); return; } surfacePicks = [paint.samples[0].slice()]; // seed for the step-3 hole scan directive(`Painted plane locked from ${paint.samples.length} stamps. Keep painting to add area — ` + `even on other coplanar surfaces — or press 🖌 again to finish. ` + `[ and ] resize the brush.`); await commit('Paint surface', `${paint.samples.length} stamps`); } renderer.domElement.addEventListener('pointerdown', (ev) => { if (!isPaintMode() || ev.button !== 0 || panKey) return; const hit = raycastEvent(ev); if (!hit) return; // empty space: leave the drag to OrbitControls paint.active = true; controls.enabled = false; // this drag paints; it must not orbit addPaintSample(hit.point); }); let lastBrushCast = 0; renderer.domElement.addEventListener('pointermove', (ev) => { if (!isPaintMode() || panKey) return; // Raycasts are O(tris); at move frequency on a multi-million-tri scan they'd // freeze the UI. ~30 Hz is plenty for a brush. const now = performance.now(); if (now - lastBrushCast < 33) return; lastBrushCast = now; const hit = raycastEvent(ev); updateBrush(hit); if (!paint.active || !hit) return; const last = paint.samples[paint.samples.length - 1]; if (last && hit.point.distanceTo(new THREE.Vector3(last[0], last[1], last[2])) < brushR() * 0.45) return; addPaintSample(hit.point); }); renderer.domElement.addEventListener('pointerup', async (ev) => { if (!isPaintMode() || !paint.active || ev.button !== 0) return; paint.active = false; controls.enabled = true; if (!paint.samples.length) return; if (pick.armed === 'primpaint') await primPaintSelect(); else await fitPaintedSeat(); }); $('paintsurf').addEventListener('click', () => { if (!meshObject) { setHud('Load a mesh first.'); return; } const arming = pick.armed !== 'paint'; disarm(); // also clears any previous paint session if (arming) { pick.armed = 'paint'; $('paintsurf').classList.add('armed'); ensureBrush(); directive('Drag across the surface to paint it — the plane is fitted from exactly ' + 'the painted points. Paint several coplanar surfaces to join them. ' + '[ ] brush size · drag from empty space to orbit'); } else { directive(seat ? 'Painted plane kept. Find holes when ready.' : 'Paint cancelled.', !!seat); } }); // double-click the model to set the orbit pivot at that point (rotation centre) renderer.domElement.addEventListener('dblclick', (ev) => { if (!meshObject) return; const hit = raycastEvent(ev); if (!hit) { setPivot(new THREE.Vector3(), 'Rotation center back on the origin. Double-click the part to rotate around a point on it.', 'origin'); return; } setPivot(hit.point); }); // fit-to-view: button + 'f' key $('fitview').addEventListener('click', () => fitView()); window.addEventListener('keydown', (e) => { if (e.key === 'f' && meshObject && e.target.tagName !== 'INPUT') fitView(); }); // ---- rotation center ------------------------------------------------------ // One click: rotate around the middle of the part's X/Y/Z bounding box (after // alignment, the box squared to the datum planes). The button stays armed so // the next click on the model can pick a point instead; Esc keeps the center. $('setpivot').addEventListener('click', () => { if (!meshObject) { setHud('Load a mesh first.'); return; } if (pick.armed === 'pivot') { disarm(); setHud('Rotation center kept.'); return; } const box = meshBox(); if (box.isEmpty()) return; setPivot(box.getCenter(new THREE.Vector3()), 'Rotating around the center of the part. Click the model to rotate around a point instead.', 'center'); disarm(); pick.armed = 'pivot'; $('setpivot').classList.add('armed'); }); // ---- redefine the origin -------------------------------------------------- $('setorigin').addEventListener('click', () => { if (!meshObject) { setHud('Load a mesh first.'); return; } disarm(); pick.armed = 'origin'; $('setorigin').classList.add('armed'); setHud('Click a point on the model to set it as the origin (0,0,0).'); }); async function setOrigin(p) { const off = p.clone(); const j = await post('/api/set_origin', { point: [off.x, off.y, off.z] }); if (!j || !j.ok) { setHud('Set origin failed: ' + ((j && j.error) || 'server')); return; } // shift everything by -off; view is preserved because the camera moves too for (const t of meshTargets) { t.geometry.translate(-off.x, -off.y, -off.z); t.geometry.computeBoundingBox(); } gizmos.children.forEach(c => c.position.sub(off)); holes.forEach(h => { h.center = [h.center[0] - off.x, h.center[1] - off.y, h.center[2] - off.z]; }); if (datum) datum.origin = [datum.origin[0] - off.x, datum.origin[1] - off.y, datum.origin[2] - off.z]; if (seat) seat.origin = [seat.origin[0] - off.x, seat.origin[1] - off.y, seat.origin[2] - off.z]; surfacePicks = surfacePicks.map(p2 => [p2[0] - off.x, p2[1] - off.y, p2[2] - off.z]); lastSeatQuery = null; // its coords are in the old frame if (cloudObj) cloudObj.geometry.translate(-off.x, -off.y, -off.z); if (patchObj) { patchObj.geometry.translate(-off.x, -off.y, -off.z); seatPatchId = cacheBlob(Array.from(patchObj.geometry.attributes.position.array)); } frameShift.add(off); camera.position.sub(off); controls.target.sub(off); controls.update(); showPivot(); drawDatumPlanes(); setHud('Origin moved to the clicked point. Exports and picks now use this frame.'); await commit('Set origin'); } // ---------------------------------------------------------------- surface (02) async function fitSeat(query) { setHud('Analysing the surface…'); const vd = camera.getWorldDirection(new THREE.Vector3()).negate(); const body = { ...query, viewDir: [vd.x, vd.y, vd.z] }; const j = await post('/api/fit_seat', body); if (!j.ok) { setHud(''); directive('Couldn\'t read a flat surface there — try another point.', false); $('seatinfo').textContent = 'Surface fit failed: ' + (j.error || ''); return false; } seat = { origin: j.origin, normal: j.normal, u: j.u, v: j.v }; seatPatchId = j.patch && j.patch.length >= 9 ? cacheBlob(j.patch) : null; seatScanned = false; // new plane — step 3 will scan it lastSeatQuery = query.paint ? { paint: query.paint } : { points: query.points || lastSeatQuery?.points || surfacePicks.slice() }; drawSeatGizmo(j); drawPatch(j.patch); $('seatstat').textContent = j.parallel ? 'set ∥' : 'set'; $('seatstat').className = 'pill on'; $('parallelpick').disabled = false; $('refine').disabled = false; $('addcoplanar').disabled = false; $('seatredo').disabled = false; $('seatinfo').innerHTML = `n = (${fmt(j.normal)})
rms ${j.rms.toFixed(3)} mm · ${j.npts.toLocaleString()} mesh pts` + (j.ncloud ? ` + ${j.ncloud.toLocaleString()} cloud` : '') + (j.npatch ? ` · patch ${j.npatch.toLocaleString()} verts` : '') + (j.parallel ? `
∥-locked to picked face (rms ${j.parallel.rms.toFixed(3)})` : ''); setHud(''); directive(`Surface locked — the highlighted patch is what I'll use (rms ${j.rms.toFixed(2)} mm). ` + `Wrong patch? Click a different point, or refine. Otherwise find holes.`, true); refreshStepper(); return true; } function drawPatch(flat) { if (patchObj) { scene.remove(patchObj); patchObj = null; } if (!flat || flat.length < 9) return; const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.Float32BufferAttribute(flat, 3)); patchObj = new THREE.Points(geo, new THREE.PointsMaterial({ color: SEAT_COLOR, size: Math.max(modelScale * 0.002, 0.3), sizeAttenuation: true, transparent: true, opacity: 0.85, depthTest: true })); scene.add(patchObj); } function drawSeatGizmo(j) { if (seatGizmo) gizmos.remove(seatGizmo); let r = Math.max(modelScale * 0.015, 2); if (j.patch && j.patch.length >= 9) { const g2 = new THREE.BufferGeometry(); g2.setAttribute('position', new THREE.Float32BufferAttribute(j.patch, 3)); g2.computeBoundingSphere(); if (g2.boundingSphere) r = Math.min(Math.max(g2.boundingSphere.radius * 0.4, 1.5), 60); } const g = new THREE.Group(); g.add(new THREE.ArrowHelper(v3(j.normal), v3(j.origin), r * 1.4, SEAT_COLOR, r * 0.35, r * 0.18)); seatGizmo = g; gizmos.add(g); } function clearSeat() { if (seatGizmo) { gizmos.remove(seatGizmo); seatGizmo = null; } if (patchObj) { scene.remove(patchObj); patchObj = null; } seat = null; lastSeatQuery = null; surfacePicks = []; seatPatchId = null; clearMarkers(); $('seatstat').textContent = 'none'; $('seatstat').className = 'pill off'; $('parallelpick').disabled = true; $('refine').disabled = true; $('addcoplanar').disabled = true; $('seatredo').disabled = true; $('seatinfo').textContent = 'Rotate so you can see the face, then click once on it.'; refreshStepper(); } $('seatredo').addEventListener('click', () => { disarm(); // also tears down an in-progress paint session if (!seat) return; clearSeat(); directive('Click once on the surface the holes pass through.'); commit('Clear surface'); }); $('refine').addEventListener('click', () => { if (!seat) return; disarm(); pick.armed = 'refine'; $('refine').classList.add('armed'); directive('Refining — click 2 more points on the same surface.'); }); $('addcoplanar').addEventListener('click', () => { if (!seat) return; const arming = pick.armed !== 'coplanar'; disarm(); if (arming) { pick.armed = 'coplanar'; $('addcoplanar').classList.add('armed'); directive('Click each surface that lies on this same plane — one plane is fitted ' + 'through all of them, and holes on any of them will share it. Press ⧉ again to finish.'); } else { directive(`Plane locked across ${surfacePicks.length} pick${surfacePicks.length === 1 ? '' : 's'}. Find holes when ready.`, true); } }); $('parallelpick').addEventListener('click', () => { if (!seat || !lastSeatQuery) return; const arming = pick.armed !== 'parallel'; disarm(); if (arming) { pick.armed = 'parallel'; $('parallelpick').classList.add('armed'); directive('Click the face this surface must be parallel to.'); } }); // ---------------------------------------------------------------- holes (03) function diaWindow() { return { minDiameterMM: parseFloat($('minDia').value) || 0, maxDiameterMM: parseFloat($('maxDia').value) || 0 }; } async function autoScan() { if (!seat || !surfacePicks.length) return; seatScanned = true; directive('Scanning this surface for round holes…'); const j = await post('/api/detect_holes_auto', { seed: surfacePicks[0], origin: seat.origin, normal: seat.normal, ...diaWindow() }); if (!j.ok) { directive('Scan failed: ' + (j.error || 'server'), true); return; } let added = 0; for (const h of j.holes) if (mergeHole(h)) added++; if (holes.length) directive(`${holes.length} hole${holes.length === 1 ? '' : 's'} found on this surface. ` + `Not seeing yours? Click inside it.`, false); else directive('No holes found automatically within the Ø bounds. Click inside the hole you can see.'); setHud(added ? `${added} hole${added === 1 ? '' : 's'} auto-detected.` : ''); refreshBuildEnabled(); if (added) await commit('Find holes', `${added} found`); } $('rescan').addEventListener('click', autoScan); $('nextsurface').addEventListener('click', () => setStep(4)); // Detect a hole around `hint` (or from `insidePts`) as a circular data gap. async function detectHole(hint, searchR, label, insidePts) { if (!seat) return false; const body = { origin: seat.origin, normal: seat.normal, ...diaWindow() }; if (insidePts) body.points = insidePts; else { body.point = hint; body.radius = searchR || 0; } const j = await post('/api/detect_hole', body); if (!j.ok) return false; if (!mergeHole(j)) { setHud('That hole is already staged.'); return true; } setHud(`${label || 'Hole'}: Ø${j.diameter.toFixed(2)} mm, ${Math.round(j.coverage * 100)}% rim` + (j.depthMeasured ? `, depth ${j.depth.toFixed(1)}` : ', depth unseen — set it if blind') + '. Set caliper Ø / thread to refine.'); refreshBuildEnabled(); await commit(`Add hole ${holes.length}`, `Ø ${j.diameter.toFixed(2)}`); return true; } // Gated fallback when the bore wall actually scanned: axis-locked cylinder fit, // accepted only if clean and inside the Ø window — never invent a hole. async function lockedWallFit(p) { const j = await post('/api/fit_cylinder', { point: [p.x, p.y, p.z], radius: 0, axisLock: seat.normal, axisOrigin: seat.origin }); if (!j.ok) return false; const { minDiameterMM: minD, maxDiameterMM: maxD } = diaWindow(); if (j.rms > Math.max(0.25, 0.04 * j.diameter)) return false; if (minD > 0 && j.diameter < minD * 0.85) return false; if (maxD > 0 && j.diameter > maxD * 1.15) return false; if (!mergeHole(j)) return true; setHud(`Hole fitted from its wall: Ø${j.diameter.toFixed(2)} mm, rms ${j.rms.toFixed(3)} — axis locked.`); refreshBuildEnabled(); await commit(`Add hole ${holes.length}`, `Ø ${j.diameter.toFixed(2)} wall fit`); return true; } // Add a discovered hole unless one already exists at ~the same place. function mergeHole(c) { const nc = v3(c.center); for (const h of holes) { const d = nc.distanceTo(v3(h.center)); if (d < Math.max(c.diameter * 0.5, 1.5)) return false; } addHole(c); return true; } let inFlight = 0; // requests still running — undo waits for the action to land async function post(url, body) { inFlight++; try { const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); return await r.json(); } finally { inFlight--; } } // ---------------------------------------------------------------- undo / redo // Whole-document history. After every action that changes the model the browser // commits: the server snapshots its state (mesh, cloud, primitives, selection, // frame) and stores this page's state (`docState`) beside it. Undo / redo / goto // restore a snapshot on the server and hand the page state back to `restoreDoc`. // View changes (camera, planes toggle, step tabs) are not history. const isMac = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent); function keyLabel(k) { return k.split('+').map(p => ({ mod: isMac ? '⌘' : 'Ctrl', shift: isMac ? '⇧' : 'Shift', alt: isMac ? '⌥' : 'Alt' }[p] || p)).join(isMac ? '' : '+'); } const STEP_NAMES = ['Scan', 'Mesh', 'Prims', 'Surface', 'Holes', 'Export']; let hist = { cursor: -1, entries: [], canUndo: false, canRedo: false, dropped: 0 }; let histBusy = false; // Large immutable arrays (the accepted surface patch) stay in the page and are // referenced from snapshots by key, so history doesn't copy them per step. const blobCache = new Map(); let blobSeq = 1; function cacheBlob(v) { const k = blobSeq++; blobCache.set(k, v); return k; } function docState() { return { step, frameShift: frameShift.toArray(), meshinfo: $('meshinfo').innerHTML, cloudinfo: $('cloudinfo').innerHTML, decinfo: $('decinfo').innerHTML, surfinfo: $('surfinfo').innerHTML, prims: Object.fromEntries(prims.map(p => [p.id, { checked: !!p.checked, devOn: !!p.devOn }])), seat: seat ? { ...seat, picks: surfacePicks, query: lastSeatQuery, scanned: seatScanned, patchId: seatPatchId, stat: $('seatstat').textContent, info: $('seatinfo').innerHTML, } : null, holes: holes.map(h => ({ id: h.id, center: h.center, axis: h.axis, diameterFit: h.diameterFit, measured: h.measured, thread: h.thread, through: h.through, depth: h.depth, p1: h.p1, p2: h.p2, locked: h.locked, bossDir: h.bossDir, color: h.color })), nextId, selectedHole: selectedHole ? selectedHole.id : null, datum: datum ? { ...datum, info: $('datuminfo').innerHTML } : null, align: { mode: alignMode, slots: alignSlots.map(x => ({ ...x })), faces: JSON.parse(JSON.stringify(alignFaces)), a321: { pts: align321.pts.slice(), normals: align321.normals.slice(), active: align321.active, rule: align321.rule, values: align321.values.slice(), planePositive: align321.planePositive, linePositive: align321.linePositive }, delta: ['alignTx', 'alignTy', 'alignTz'].map(id => $(id).value), stat: $('alignstat').textContent, statClass: $('alignstat').className, info: $('aligninfo').innerHTML, }, }; } async function commit(label, detail = '') { if (restoring || !meshObject) return; try { const j = await post('/api/history/commit', { label, step: STEP_NAMES[step - 1], detail, ui: docState() }); if (j.ok) setHistory(j.history); else console.warn('[scan2cad] history commit failed:', j.error); } catch (err) { console.warn('[scan2cad] history commit failed:', err); } } function resetHistoryUI() { setHistory({ cursor: -1, entries: [], canUndo: false, canRedo: false, dropped: 0 }); blobCache.clear(); seatPatchId = null; } function setHistory(h) { hist = h; const undoE = h.canUndo ? h.entries[h.cursor] : null; const redoE = h.canRedo ? h.entries[h.cursor + 1] : null; $('b-undo').disabled = !undoE; $('m-undo').disabled = !undoE; $('b-redo').disabled = !redoE; $('m-redo').disabled = !redoE; $('b-hist').disabled = !h.entries.length; $('b-undo').title = undoE ? `Undo ${undoE.label} (${keyLabel('mod+Z')})` : 'Nothing to undo'; $('b-redo').title = redoE ? `Redo ${redoE.label} (${keyLabel('shift+mod+Z')})` : 'Nothing to redo'; $('b-hist').title = `History (${keyLabel('alt+mod+Z')})`; $('m-undo').querySelector('.what').textContent = undoE ? undoE.label : ''; $('m-redo').querySelector('.what').textContent = redoE ? redoE.label : ''; const last = $('lastact'); last.textContent = ''; if (undoE) { last.append('Last: '); const b = document.createElement('b'); b.textContent = undoE.label; last.append(b); } renderTape(); } function renderTape() { const list = $('tapelist'); list.innerHTML = ''; if (hist.dropped) { const li = document.createElement('li'); li.className = 'ent dropped'; li.textContent = `${hist.dropped} older step${hist.dropped === 1 ? '' : 's'} dropped to stay under the memory limit`; list.appendChild(li); } hist.entries.forEach((e, i) => { const li = document.createElement('li'); li.className = 'ent' + (i === hist.cursor ? ' now' : i > hist.cursor ? ' future' : ''); li.tabIndex = 0; for (const [cls, text] of [['stp', e.step], ['act', e.label], ['det', e.detail]]) { const sp = document.createElement('span'); sp.className = cls; sp.textContent = text || ''; li.appendChild(sp); } li.title = i === hist.cursor ? 'Current state' : `Go ${i < hist.cursor ? 'back' : 'forward'} to here`; li.onclick = () => { closeMenus(); travel('goto', i); }; li.onkeydown = (ev) => { if (ev.key === 'Enter') { closeMenus(); travel('goto', i); } else if (ev.key === 'ArrowDown' && li.nextElementSibling) { ev.preventDefault(); (li.nextElementSibling.classList.contains('cursorline') ? li.nextElementSibling.nextElementSibling : li.nextElementSibling)?.focus(); } else if (ev.key === 'ArrowUp' && li.previousElementSibling) { ev.preventDefault(); (li.previousElementSibling.classList.contains('cursorline') ? li.previousElementSibling.previousElementSibling : li.previousElementSibling)?.focus(); } }; list.appendChild(li); if (i === hist.cursor && i < hist.entries.length - 1) { const c = document.createElement('li'); c.className = 'cursorline'; c.setAttribute('aria-hidden', 'true'); list.appendChild(c); } }); const mb = (hist.bytes || 0) / 1048576, cap = (hist.budget || 0) / 1048576; $('tapefoot').textContent = 'Redo steps are kept until you make a new change.' + (cap ? ` History uses ${mb < 10 ? mb.toFixed(1) : Math.round(mb)} of ${Math.round(cap)} MB.` : ''); } let toastTimer = null; function toast(text, action) { const t = $('toast'); t.textContent = ''; const sp = document.createElement('span'); sp.textContent = text; t.appendChild(sp); if (action) { const b = document.createElement('button'); b.textContent = action.label + ' '; const k = document.createElement('kbd'); k.textContent = keyLabel(action.key); b.appendChild(k); b.onclick = () => travel(action.kind); t.appendChild(b); } t.classList.add('show'); clearTimeout(toastTimer); toastTimer = setTimeout(() => t.classList.remove('show'), 3500); } function flashBtn(id) { const b = $(id); b.classList.remove('flash'); void b.offsetWidth; b.classList.add('flash'); } // kind: 'undo' | 'redo' | 'goto' (index). One at a time: presses that arrive // while a restore is running are dropped, not queued, so a held or doubled ⌘Z // can never run past where the user meant to stop. Also refused while an // action's request is still in flight (its commit hasn't landed yet). function travel(kind, index) { if (!meshObject || histBusy) return Promise.resolve(); if (inFlight > 0) { setHud('Still working on the last action…'); return Promise.resolve(); } return travelNow(kind, index); } async function travelNow(kind, index) { if (kind === 'undo' && !hist.canUndo) return; if (kind === 'redo' && !hist.canRedo) return; if (kind === 'goto' && (index === hist.cursor || index < 0 || index >= hist.entries.length)) return; const from = hist.cursor; histBusy = true; ['b-undo', 'b-redo', 'b-hist'].forEach(id => { $(id).disabled = true; }); // visibly busy try { const j = await post('/api/history/' + kind, kind === 'goto' ? { index } : {}); if (!j.ok) { setHud((kind === 'undo' ? 'Undo' : kind === 'redo' ? 'Redo' : 'History') + ' failed: ' + (j.error || 'server')); return; } const to = j.history.cursor; // the step whose change was undone / redone, so its controls are in view const touched = kind === 'undo' ? hist.entries[from] : j.history.entries[to]; await restoreDoc(j, touched ? STEP_NAMES.indexOf(touched.step) + 1 : 0); setHistory(j.history); if (kind === 'undo') { flashBtn('b-undo'); toast(`Undid ${touched.label}`, { label: 'Redo', key: 'shift+mod+Z', kind: 'redo' }); } else if (kind === 'redo') { flashBtn('b-redo'); toast(`Redid ${touched.label}`, { label: 'Undo', key: 'mod+Z', kind: 'undo' }); } else { const n = Math.abs(to - from); toast(`Went ${to < from ? 'back' : 'forward'} ${n} step${n === 1 ? '' : 's'} to ${touched.label}`); } } catch (err) { console.error('[scan2cad] history travel failed:', err); setHud('History failed: ' + err.message); } finally { histBusy = false; setHistory(hist); // re-enable the arrows for whatever state we ended in } } async function reloadCloudFromServer(n) { if (cloudObj) { scene.remove(cloudObj); cloudObj.geometry.dispose(); cloudObj = null; } if (!n) return; const r = await fetch('/api/cloud/current'); if (!r.ok) return; const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.Float32BufferAttribute(new Float32Array(await r.arrayBuffer()), 3)); cloudObj = new THREE.Points(geo, new THREE.PointsMaterial({ color: 0x39c5cf, size: Math.max(modelScale * 0.0012, 0.05), sizeAttenuation: true, transparent: true, opacity: 0.5 })); scene.add(cloudObj); } async function surfacePreview(id) { try { const r = await fetch('/api/surface/preview?id=' + id); const j = await r.json(); return j.ok ? j.preview : null; } catch { return null; } } // Put the page back exactly as it was when snapshot `j` was committed, then // show `focusStep` (the step the undone/redone change belongs to). async function restoreDoc(j, focusStep) { const ui = j.ui || {}; restoring = true; try { exitPreview(true); disarm(); setHud(''); // status lines describe the state we're leaving if (j.meshChanged) await reloadMeshFromServer(); meshStatus = null; drawMeshHoleMarkers(); frameShift.fromArray(ui.frameShift || [0, 0, 0]); if (j.cloudChanged || !!cloudObj !== j.ncloud > 0) await reloadCloudFromServer(j.ncloud); $('meshinfo').innerHTML = ui.meshinfo ?? ''; $('cloudinfo').innerHTML = ui.cloudinfo ?? ''; $('decinfo').innerHTML = ui.decinfo ?? ''; $('surfinfo').innerHTML = ui.surfinfo ?? ''; setDocName(null, j.ntris); // primitives: the server registry is the truth; checkbox / dev-map state is ours prims.forEach(p => { if (p.gizmo) primGizmos.remove(p.gizmo); }); prims.length = 0; const ext = ui.prims || {}; for (const sp of j.prims || []) { const e = ext[sp.id] || {}; const p = { ...sp, checked: !!e.checked, devOn: e.devOn ?? true }; if (p.kind === 'surface') { p.preview = await surfacePreview(p.id); if (p.preview) { p.gizmo = drawSurfaceGizmo(p); colorSurfaceGizmo(p); } } else { p.gizmo = drawPrimGizmo(p); } prims.push(p); } selCount = j.nsel || 0; drawSelection(j.selPreview); refreshSelUI(); // surface datum if (seatGizmo) { gizmos.remove(seatGizmo); seatGizmo = null; } if (patchObj) { scene.remove(patchObj); patchObj = null; } clearMarkers(); const st = ui.seat; if (!st) { clearSeat(); seatScanned = false; } else { seat = { origin: st.origin, normal: st.normal, u: st.u, v: st.v }; surfacePicks = st.picks || []; lastSeatQuery = st.query || null; seatScanned = !!st.scanned; seatPatchId = st.patchId && blobCache.has(st.patchId) ? st.patchId : null; const patch = seatPatchId ? blobCache.get(seatPatchId) : null; drawSeatGizmo({ normal: seat.normal, origin: seat.origin, patch }); drawPatch(patch); $('seatstat').textContent = st.stat || 'set'; $('seatstat').className = 'pill on'; $('seatinfo').innerHTML = st.info || ''; ['parallelpick', 'refine', 'addcoplanar', 'seatredo'].forEach(id => { $(id).disabled = false; }); } // holes holes.forEach(h => { if (h.gizmo) gizmos.remove(h.gizmo); if (h.labelEl) h.labelEl.remove(); }); holes.length = 0; if (bossPreview) { gizmos.remove(bossPreview); bossPreview = null; } for (const d of ui.holes || []) makeHole(d); nextId = ui.nextId || holes.length + 1; selectedHole = holes.find(h => h.id === ui.selectedHole) || null; renderHoles(); // legacy plate datum if (datumGizmo) { gizmos.remove(datumGizmo); datumGizmo = null; } datum = null; if (ui.datum) { const { info, ...d } = ui.datum; datum = d; drawDatum(d, Math.max(modelScale * 0.02, 3)); $('datumstat').textContent = 'set'; $('datumstat').className = 'pill on'; $('datuminfo').innerHTML = info || ''; } else { $('datumstat').textContent = 'none'; $('datumstat').className = 'pill off'; $('datuminfo').textContent = 'Needed only for the plate rebuild.'; } // alignment setup const al = ui.align; if (al) { alignMode = al.mode; $('alignmode').value = al.mode; $('aligndelta').style.display = alignMode === 'points' ? 'none' : ''; al.slots.forEach((x, i) => Object.assign(alignSlots[i], { auto: false }, x)); clearFaces(); if (al.faces) Object.assign(alignFaces, JSON.parse(JSON.stringify(al.faces))); Object.assign(align321, { ...al.a321, pts: al.a321.pts.slice(), normals: al.a321.normals.slice(), values: al.a321.values.slice() }); ['alignTx', 'alignTy', 'alignTz'].forEach((id, i) => { $(id).value = al.delta[i]; }); $('alignstat').textContent = al.stat; $('alignstat').className = al.statClass; $('aligninfo').innerHTML = al.info; } alignFrame = null; drawAlignGizmo(null); $('alignapply').disabled = true; $('alignpreview').disabled = true; drawAlign321Points(); renderPrims(); // also re-renders the alignment slots const pendingAlign = alignMode === 'points' ? align321.pts.some(Boolean) : alignMode === 'faces' ? faceCount() > 0 : alignSlots.some(x => x.id >= 0); if (pendingAlign) await previewAlign(); refreshBuildEnabled(); const target = focusStep && canEnter(focusStep) ? focusStep : ui.step && canEnter(ui.step) ? ui.step : 1; setStep(target); if (step === 3 && alignFrame) livePreview(); // faces / 3-2-1 keep showing the frame drawDatumPlanes(); } finally { restoring = false; } } function setDocName(name, ntris) { if (name) $('docfile').textContent = name; const t = $('doctris'); if (ntris != null) { t.textContent = ntris.toLocaleString() + ' tris'; t.hidden = false; } } // ---------------------------------------------------------------- menu bar const menus = [...document.querySelectorAll('#menubar .menu')]; function closeMenus() { menus.forEach(m => { m.classList.remove('open'); m.querySelector('.mtop').setAttribute('aria-expanded', 'false'); }); $('tape').classList.remove('open'); $('b-hist').setAttribute('aria-expanded', 'false'); } function refreshMenuState() { document.querySelectorAll('#menubar [data-needs="mesh"]').forEach(b => { b.disabled = !meshObject; }); $('m-clearsel').disabled = !(step === 3 && selCount > 0); $('m-delhole').disabled = !(selectedHole && !selectedHole.locked); document.querySelector('[data-cmd="planes"]').classList.toggle('on', showPlanes); if (!hist.canUndo) $('m-undo').disabled = true; if (!hist.canRedo) $('m-redo').disabled = true; } function openMenu(m) { closeMenus(); refreshMenuState(); m.classList.add('open'); m.querySelector('.mtop').setAttribute('aria-expanded', 'true'); } menus.forEach(m => { const top = m.querySelector('.mtop'); top.addEventListener('click', (e) => { e.stopPropagation(); m.classList.contains('open') ? closeMenus() : openMenu(m); }); // once a menu is open, hovering the others slides between them top.addEventListener('mouseenter', () => { if (menus.some(o => o !== m && o.classList.contains('open'))) openMenu(m); }); }); function openTape() { if (!hist.entries.length) return; closeMenus(); const qa = $('qa').getBoundingClientRect(), bar = $('menubar').getBoundingClientRect(); const tape = $('tape'); tape.style.left = Math.max(0, Math.min(qa.left - bar.left, bar.width - 388)) + 'px'; tape.classList.add('open'); $('b-hist').setAttribute('aria-expanded', 'true'); const now = tape.querySelector('.ent.now'); if (now) { now.scrollIntoView({ block: 'nearest' }); now.focus(); } } $('b-hist').addEventListener('click', (e) => { e.stopPropagation(); $('tape').classList.contains('open') ? closeMenus() : openTape(); }); $('tape').addEventListener('click', (e) => e.stopPropagation()); document.addEventListener('click', closeMenus); $('b-undo').addEventListener('click', () => travel('undo')); $('b-redo').addEventListener('click', () => travel('redo')); function showKeys(on) { $('keyhelp').hidden = !on; if (on) $('khclose').focus(); } $('khclose').addEventListener('click', () => showKeys(false)); $('keyhelp').addEventListener('click', (e) => { if (e.target.id === 'keyhelp') showKeys(false); }); document.querySelectorAll('[data-k]').forEach(el => { el.textContent = keyLabel(el.dataset.k); }); function runCommand(cmd) { if (cmd.startsWith('view:')) { if (meshObject) setView(cmd.slice(5)); return; } switch (cmd) { case 'open': $('file').click(); break; case 'cloud': $('cloudfile').click(); break; case 'dlmesh': { const a = document.createElement('a'); a.href = '/api/mesh/current'; a.download = 'scan2cad_mesh.stl'; document.body.appendChild(a); a.click(); a.remove(); break; } case 'export': setStep(6); break; case 'undo': travel('undo'); break; case 'redo': travel('redo'); break; case 'history': setTimeout(openTape, 0); break; case 'clearsel': if (step === 3 && selCount > 0) clearSelection(); break; case 'delhole': deleteHole(selectedHole); break; case 'fit': fitView(); break; case 'planes': $('planestoggle').click(); break; case 'keys': showKeys(true); break; } } document.querySelectorAll('#menubar .mi').forEach(b => b.addEventListener('click', (e) => { e.stopPropagation(); closeMenus(); runCommand(b.dataset.cmd); })); window.addEventListener('keydown', (e) => { if (e.key === 'Escape') { if (!$('keyhelp').hidden) { showKeys(false); return; } if ($('tape').classList.contains('open') || menus.some(m => m.classList.contains('open'))) { closeMenus(); return; } if (pick.armed) { const what = pick.armed; disarm(); setHud(what === 'pivot' ? 'Rotating around the center of the part.' : 'Pick cancelled.'); } return; } if (typingInField(e)) return; // text fields keep their own native undo const mod = isMac ? e.metaKey : e.ctrlKey; const k = e.key.toLowerCase(); if (mod && e.altKey && e.code === 'KeyZ') { e.preventDefault(); openTape(); return; } if (mod && e.code === 'KeyZ') { e.preventDefault(); travel(e.shiftKey ? 'redo' : 'undo'); return; } if (mod && !isMac && k === 'y') { e.preventDefault(); travel('redo'); return; } if (mod && k === 'o') { e.preventDefault(); $('file').click(); return; } if (mod || e.altKey) return; if (k === '?') { showKeys($('keyhelp').hidden); return; } if (!meshObject) return; const views = { 1: 'iso', 2: 'top', 3: 'front', 4: 'right' }; if (views[e.key]) setView(views[e.key]); else if (k === 'p') $('planestoggle').click(); else if ((e.key === 'Backspace' || e.key === 'Delete') && step === 5 && selectedHole) { e.preventDefault(); deleteHole(selectedHole); } }); // ---------------------------------------------------------------- gizmos function v3(a) { return new THREE.Vector3(a[0], a[1], a[2]); } function fmt(a) { return a.map(x => x.toFixed(3)).join(', '); } async function pickDatum(p) { setHud('Fitting datum plane…'); const vd = camera.getWorldDirection(new THREE.Vector3()).negate(); const j = await post('/api/fit_plane', { point: [p.x, p.y, p.z], radius: 0, viewDir: [vd.x, vd.y, vd.z], }); if (!j.ok) { setHud('Plane fit failed: ' + j.error); return; } datum = { origin: j.origin, normal: j.normal, u: j.u, v: j.v }; drawDatum(j, Math.max(modelScale * 0.02, 3)); $('datumstat').textContent = 'set'; $('datumstat').className = 'pill on'; $('datuminfo').innerHTML = `n = (${fmt(j.normal)}) · rms ${j.rms.toFixed(3)} mm · ${j.npts} pts`; setHud('Datum set.'); refreshBuildEnabled(); await commit('Pick datum face'); } $('datumpick').addEventListener('click', () => { if (!meshObject) return; disarm(); pick.armed = 'datum'; $('datumpick').classList.add('armed'); setHud('Click the flat mounting face.'); }); function drawDatum(j, radius) { if (datumGizmo) gizmos.remove(datumGizmo); const g = new THREE.Group(); const disk = new THREE.Mesh( new THREE.CircleGeometry(radius, 48), new THREE.MeshBasicMaterial({ color: 0x2f81f7, transparent: true, opacity: 0.28, side: THREE.DoubleSide })); const q = new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 0, 1), v3(j.normal)); disk.quaternion.copy(q); disk.position.copy(v3(j.origin)); g.add(disk); g.add(new THREE.ArrowHelper(v3(j.normal), v3(j.origin), radius * 0.9, 0x2f81f7, radius * 0.25, radius * 0.14)); datumGizmo = g; gizmos.add(g); } // The hole gizmo is a *barrel*: it runs the bore's depth AND sticks out above the // opening, so the fitted cylinder is obvious against the surface. A bright ring // marks exactly where the bore pierces the seat surface; a thin rim outlines the // protruding top. Locked holes render green and more solid. function drawHoleGizmo(j, color, locked) { const p1 = v3(j.p1), p2 = v3(j.p2); // p2 = outer opening (on the surface) const axis = v3(j.axis).normalize(); const r = j.diameter / 2; const depth = Math.max(p1.distanceTo(p2), j.diameter * 0.6); const stick = Math.max(j.diameter * 0.7, 3); // protrusion above the surface const top = p2.clone().add(axis.clone().multiplyScalar(stick)); const bottom = p2.clone().sub(axis.clone().multiplyScalar(depth)); const len = depth + stick; const mid = bottom.clone().add(top).multiplyScalar(0.5); const ringColor = locked ? 0x43c06a : PINK; const q = new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), axis); const g = new THREE.Group(); const cyl = new THREE.Mesh( new THREE.CylinderGeometry(r, r, len, 32, 1, true), new THREE.MeshBasicMaterial({ color, transparent: true, opacity: locked ? 0.7 : 0.45, side: THREE.DoubleSide })); cyl.quaternion.copy(q); cyl.position.copy(mid); g.add(cyl); // ring at the surface intersection (the opening), snug on the bore const ring = new THREE.Mesh( new THREE.TorusGeometry(r * 1.12, Math.max(r * 0.14, 0.3), 12, 48), new THREE.MeshBasicMaterial({ color: ringColor })); ring.quaternion.copy(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 0, 1), axis)); ring.position.copy(p2); g.add(ring); // thin rim at the protruding top so the barrel reads in 3D const rim = new THREE.Mesh( new THREE.TorusGeometry(r, Math.max(r * 0.07, 0.15), 10, 40), new THREE.MeshBasicMaterial({ color })); rim.quaternion.copy(ring.quaternion); rim.position.copy(top); g.add(rim); gizmos.add(g); return g; } // Preview the mount bosses exactly as the export resolved them (seat, direction, // size), so a wrong-way boss is visible before the STEP ever reaches SolidWorks. function drawBossPreview(mounts) { if (bossPreview) gizmos.remove(bossPreview); bossPreview = new THREE.Group(); mounts.forEach((m, i) => { const seat = v3(m.seat), axis = v3(m.axis).normalize(); const r = m.bossDiameter / 2, hgt = m.bossHeight; const color = holes[i] ? holes[i].color : 0xd29922; const cyl = new THREE.Mesh( new THREE.CylinderGeometry(r, r, hgt, 32), new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.5 })); cyl.quaternion.copy(new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), axis)); cyl.position.copy(seat.clone().add(axis.clone().multiplyScalar(hgt / 2))); bossPreview.add(cyl); bossPreview.add(new THREE.ArrowHelper(axis, seat, hgt * 1.6, color, hgt * 0.4, r * 0.5)); }); gizmos.add(bossPreview); } // ---------------------------------------------------------------- holes UI function addHole(j) { const id = nextId++; makeHole({ id, center: j.center, axis: j.axis, diameterFit: j.diameter, measured: null, thread: '', through: true, depth: j.depth, p1: j.p1, p2: j.p2, locked: false, bossDir: 0, color: PALETTE[(id - 1) % PALETTE.length], }); renderHoles(); } // Build a hole (gizmo + floating label) from its plain data — new or restored. function makeHole(d) { const h = { ...d }; h.gizmo = drawHoleGizmo({ p1: h.p1, p2: h.p2, axis: h.axis, diameter: effectiveDiameter(h) }, h.color, h.locked); const lab = document.createElement('div'); lab.className = 'holelabel' + (h.locked ? ' locked' : ''); lab.style.borderColor = '#' + h.color.toString(16).padStart(6, '0'); lab.onclick = () => { selectHole(h); flyToHole(h); }; viewport.appendChild(lab); h.labelEl = lab; holes.push(h); return h; } function removeHole(h) { if (h.gizmo) gizmos.remove(h.gizmo); if (h.labelEl) h.labelEl.remove(); if (bossPreview) { gizmos.remove(bossPreview); bossPreview = null; } // stale after edits const i = holes.indexOf(h); if (i >= 0) holes.splice(i, 1); if (selectedHole === h) selectedHole = null; renderHoles(); refreshBuildEnabled(); } // User-initiated delete (card ✕, ⌫): one history step. function deleteHole(h) { if (!h || h.locked) return; const n = holes.indexOf(h) + 1; removeHole(h); commit(`Remove hole ${n}`); } function effectiveDiameter(h) { return h.measured != null ? h.measured : h.diameterFit; } function renderHoles() { $('holecount').textContent = holes.length; const wrap = $('holes'); wrap.innerHTML = ''; holes.forEach((h, i) => { if (h.labelEl) { h.labelEl.textContent = i + 1; h.labelEl.classList.toggle('sel', h === selectedHole); } const el = document.createElement('div'); el.className = 'hole' + (h === selectedHole ? ' active' : '') + (h.locked ? ' locked' : ''); el.dataset.id = h.id; const dis = h.locked ? 'disabled' : ''; const threadOpts = ['', ...Object.keys(THREADS)] .map(t => ``).join(''); const [x, y, z] = h.center; let spacing = ''; if (h === selectedHole && holes.length > 1) { const others = holes.filter(o => o !== h) .map(o => `#${holes.indexOf(o) + 1}: ${v3(h.center).distanceTo(v3(o.center)).toFixed(2)}`); spacing = `
centre-to-centre → ${others.join(' · ')} mm
`; } el.innerHTML = `
Hole ${i + 1} ⤓ fly
Ø ${effectiveDiameter(h).toFixed(2)} mm${h.measured != null ? ' (measured)' : ' (fitted)'} · depth ${h.depth.toFixed(2)} mm
XYZ  ${x.toFixed(2)}, ${y.toFixed(2)}, ${z.toFixed(2)} mm
${spacing}
`; el.querySelector('.hfly').onclick = () => { selectHole(h); flyToHole(h); }; el.querySelector('.flip').onclick = (e) => { e.stopPropagation(); flipHole(h); }; el.querySelector('.lock').onclick = (e) => { e.stopPropagation(); lockHole(h, !h.locked); }; const n = i + 1; el.querySelector('.x').onclick = (e) => { e.stopPropagation(); deleteHole(h); }; el.querySelector('.m-d').onchange = async (e) => { h.measured = e.target.value === '' ? null : parseFloat(e.target.value); await refitHole(h); await commit(`Set hole ${n} Ø`, h.measured == null ? 'fitted' : `Ø ${h.measured.toFixed(2)}`); }; el.querySelector('.m-t').onchange = async (e) => { h.thread = e.target.value; if (h.thread && THREADS[h.thread]) { h.measured = THREADS[h.thread]; } renderHoles(); await refitHole(h); await commit(`Set hole ${n} thread`, h.thread || 'none'); }; el.querySelector('.m-th').onchange = (e) => { h.through = e.target.value === '1'; renderHoles(); commit(`Make hole ${n} ${h.through ? 'through' : 'blind'}`); }; el.querySelector('.m-dep').onchange = (e) => { h.depth = parseFloat(e.target.value); commit(`Set hole ${n} depth`, `${h.depth.toFixed(2)} mm`); }; el.addEventListener('click', (e) => { if (e.target.closest('input,select,button,.hfly')) return; selectHole(h); }); wrap.appendChild(el); }); refreshBuildEnabled(); } // Re-fit with the now-known diameter to tighten the centre, and update the gizmo. async function refitHole(h) { let j; if (seat) { // Known-diameter gap detection solves center-only in the seat plane — exact // even when the bore itself never scanned. j = await post('/api/detect_hole', { point: h.center, radius: effectiveDiameter(h) * 1.2, origin: seat.origin, normal: seat.normal, knownDiameter: effectiveDiameter(h) }); if (!j.ok) { j = await post('/api/fit_cylinder', { point: h.center, radius: 0, knownDiameter: effectiveDiameter(h), axisLock: seat.normal, axisOrigin: seat.origin }); } } else { const body = { point: h.center, radius: 0, knownDiameter: effectiveDiameter(h) }; if (datum) body.axisHint = datum.normal; j = await post('/api/fit_cylinder', body); } if (!j.ok) return; // A user-flipped direction survives refits: keep the refit axis in the same // world hemisphere the user chose. if (h.bossDir !== 0 && v3(j.axis).dot(v3(h.axis)) < 0) { const d = Math.max(v3(j.p1).distanceTo(v3(j.p2)), 0.1); j.axis = [-j.axis[0], -j.axis[1], -j.axis[2]]; j.p1 = v3(j.p2).sub(v3(j.axis).multiplyScalar(d)).toArray(); } // A diameter/thread refit tightens center/axis only. Depth is a user-entered blind // measurement, so never overwrite it here. h.center = j.center; h.axis = j.axis; h.p1 = j.p1; h.p2 = j.p2; gizmos.remove(h.gizmo); h.gizmo = drawHoleGizmo({ ...j, diameter: effectiveDiameter(h) }, h.color, h.locked); renderHoles(); } // Flip a hole's direction when the scan guessed the wrong side: mirror the barrel // about its opening and remember the choice as an explicit boss-direction // override — the displayed axis points out of the surface, so the exported boss // thickens against it, into the part. Allowed on locked holes too: direction is // orientation, not a measured dimension. function flipHole(h) { h.axis = [-h.axis[0], -h.axis[1], -h.axis[2]]; const depth = Math.max(v3(h.p1).distanceTo(v3(h.p2)), 0.1); h.p1 = v3(h.p2).sub(v3(h.axis).normalize().multiplyScalar(depth)).toArray(); h.bossDir = -1; // user-defined: boss goes against the displayed axis gizmos.remove(h.gizmo); h.gizmo = drawHoleGizmo({ p1: h.p1, p2: h.p2, axis: h.axis, diameter: effectiveDiameter(h) }, h.color, h.locked); if (bossPreview) { gizmos.remove(bossPreview); bossPreview = null; } // stale renderHoles(); setHud(`Hole ${holes.indexOf(h) + 1} flipped — the barrel stick marks the outside; the boss will thicken into the surface.`); commit(`Flip hole ${holes.indexOf(h) + 1}`); } // Lock a hole in: freeze its card, restyle the gizmo green, and move the user on // to the next unlocked hole (or to Export when they're all confirmed). function lockHole(h, lock) { h.locked = lock; gizmos.remove(h.gizmo); h.gizmo = drawHoleGizmo({ p1: h.p1, p2: h.p2, axis: h.axis, diameter: effectiveDiameter(h) }, h.color, h.locked); if (h.labelEl) h.labelEl.classList.toggle('locked', h.locked); renderHoles(); commit(`${lock ? 'Lock' : 'Unlock'} hole ${holes.indexOf(h) + 1}`); if (!lock) return; const next = holes.find(o => !o.locked); if (next) { selectHole(next); flyToHole(next); directive(`Hole ${holes.indexOf(h) + 1} locked ✓ — inspect hole ${holes.indexOf(next) + 1}, or click inside another.`); } else { selectHole(null); directive(`All ${holes.length} hole${holes.length === 1 ? '' : 's'} locked ✓ — ` + `Next surface… for more mounts, or Export.`, true); } } $('clearall').addEventListener('click', () => { if (!holes.length) return; clearAllFeatures(); directive('Holes cleared. Click inside a hole, or re-scan the surface.'); refreshBuildEnabled(); commit('Clear all holes'); }); function clearAllFeatures() { holes.forEach(h => { if (h.labelEl) h.labelEl.remove(); }); holes.length = 0; nextId = 1; datum = null; selectedHole = null; while (gizmos.children.length) gizmos.remove(gizmos.children[0]); datumGizmo = null; markers.length = 0; if (seat) drawSeatGizmo({ normal: seat.normal, origin: seat.origin, patch: null }); renderHoles(); $('datumstat').textContent = 'none'; $('datumstat').className = 'pill off'; $('datuminfo').textContent = 'Needed only for the plate rebuild.'; } // ---------------------------------------------------------------- export (04) function refreshBuildEnabled() { $('build').disabled = !(datum && holes.length > 0); $('iface').disabled = holes.length === 0; refreshCSOptions(); refreshStepper(); } // Populate the coordinate-system dropdowns from the current holes, preserving the // user's selection across re-renders where the choice still exists. function refreshCSOptions() { const fill = (id, autoLabel, axis) => { const sel = $(id); const prev = sel.value; let html = ``; holes.forEach((h, i) => { html += ``; }); sel.innerHTML = html; if ([...sel.options].some(o => o.value === prev)) sel.value = prev; }; fill('csOrigin', 'Pattern centroid', false); fill('csX', 'Auto (farthest hole)', false); fill('csZ', 'Average of hole axes', true); } // Export the mounting-hole interface (reference geometry for bracket design). async function exportInterface() { if (!holes.length) return; $('ifacestat').textContent = 'Exporting interface…'; $('ifacedown').innerHTML = ''; const exported = holes.slice(); // snapshot: mounts come back in this order const body = { holes: exported.map((h, i) => ({ center: h.center, axis: h.axis, diameter: effectiveDiameter(h), thread: h.thread, label: `hole${i + 1}`, bossDir: h.bossDir || 0, })), originHole: parseInt($('csOrigin').value, 10), // -1 = pattern centroid xHole: parseInt($('csX').value, 10), // -1 = farthest hole zHole: parseInt($('csZ').value, 10), // -1 = average of hole axes winDir: $('windir').value || 'C:\\temp', // where the assembly macro finds the files }; try { const j = await post('/api/interface', body); if (!j.ok) { $('ifacestat').textContent = 'Export failed: ' + j.error; return; } const spans = holes.length > 1 ? holes.flatMap((_, a) => holes.slice(a + 1).map((_, b) => v3(holes[a].center).distanceTo(v3(holes[a + 1 + b].center)))).map(d => d.toFixed(1)) : []; drawBossPreview(j.mounts || []); // Per-mount boss direction, with a flip control. The probe decides from the // scan ("auto"); an ambiguous mount needs the user to look at the preview // and choose. A flip becomes an explicit per-hole override and re-exports. const ambiguous = (j.mounts || []).filter(m => m.dir !== 'material' && m.dir !== 'normals' && m.dir !== 'user').length; const dirRows = (j.mounts || []).map((m, i) => { const badge = m.dir === 'material' ? 'auto — into scanned material' : m.dir === 'normals' ? 'auto — into material (from surface normals)' : m.dir === 'user' ? 'set manually' : '⚠ unknown — check the preview arrow'; return `boss ${i + 1}: ${badge} ` + ``; }).join('
'); // Coplanar snap report: which bosses were seated on one shared plane. const planeRows = (j.planes || []).map((p, i) => `plane ${String.fromCharCode(65 + i)}: bosses ` + `${p.members.map(m => m + 1).join(' + ')} snapped coplanar (joint rms ${p.rms.toFixed(3)} mm)` ).join('
'); $('ifacestat').innerHTML = `✓ ${j.holes} mount(s) exported as solid bosses + holes.` + (planeRows ? `
${planeRows}` : '') + (dirRows ? `
${dirRows}` : '') + (j.meshTris ? `
frame region: ${j.meshTris.toLocaleString()} tris` : '') + (spans.length ? `
bolt pattern (mm): ${spans.join(' · ')}` : ''); $('ifacestat').querySelectorAll('.bossflip').forEach(btn => btn.addEventListener('click', () => { const m = j.mounts[parseInt(btn.dataset.i, 10)]; const h = exported[parseInt(btn.dataset.i, 10)]; if (!m || !h || !holes.includes(h)) return; // flip relative to what was just exported, as an explicit override h.bossDir = v3(m.axis).dot(v3(h.axis).normalize()) >= 0 ? -1 : 1; commit(`Flip boss ${parseInt(btn.dataset.i, 10) + 1}`); exportInterface(); })); // One package with everything, pre-named for the assembly macro; the // individual files stay reachable for anyone who wants just one. $('ifacedown').innerHTML = `⬇ SolidWorks package (.zip)` + `
individual files…` + `⬇ Mounts STEP` + `⬇ Scan mesh` + (j.mesh ? `⬇ Frame crop` : '') + (j.asm ? `⬇ Assembly macro` : '') + `⬇ Interface macro
`; directive(ambiguous ? 'Check the boss arrows: the scan could not decide a direction for every mount — flip any that point out of the part, then re-download.' : 'Exported. Download the package, extract it into the Windows folder, and run ' + 'scan2cad_assembly.vba in SolidWorks — solids + scan, already aligned.', true); } catch (err) { $('ifacestat').textContent = 'Export error: ' + err.message; } } $('iface').addEventListener('click', exportInterface); // ---- Datum planes card: move / rotate the planes, download planes-only ---- // Moving a plane by +d along its normal = moving the part by -d. The ghost // planes follow the inputs live; "Move planes" commits. function mvValues() { return ['mvX', 'mvY', 'mvZ'].map(id => parseFloat($(id).value) || 0); } ['mvX', 'mvY', 'mvZ'].forEach(id => $(id).addEventListener('input', () => { const d = mvValues(); if (datumPlanes) datumPlanes.position.set(d[0], d[1], d[2]); $('mvapply').disabled = d.every(v => v === 0); })); $('mvapply').addEventListener('click', async () => { const d = mvValues(); if (d.every(v => v === 0)) return; $('mvapply').disabled = true; if (datumPlanes) datumPlanes.position.set(0, 0, 0); const ok = await applyRigid({ rigid: { shift: [-d[0], -d[1], -d[2]] } }, [1, 0, 0, 0, 1, 0, 0, 0, 1], [-d[0], -d[1], -d[2]]); if (!ok) { $('mvapply').disabled = false; return; } ['mvX', 'mvY', 'mvZ'].forEach(id => { $(id).value = 0; }); await commit('Move planes', d.map(v => v.toFixed(1)).join(' / ') + ' mm'); }); const ROT90 = { X: [1, 0, 0, 0, 0, -1, 0, 1, 0], Y: [0, 0, 1, 0, 1, 0, -1, 0, 0], Z: [0, -1, 0, 1, 0, 0, 0, 0, 1], }; document.querySelectorAll('[data-rot90]').forEach(b => b.addEventListener('click', async () => { const a = b.dataset.rot90; if (!await applyRigid({ rigid: { rot90: a } }, ROT90[a], [0, 0, 0])) return; fitView(); await commit(`Rotate 90° about ${a}`); })); $('build').addEventListener('click', async () => { if (!datum || !holes.length) return; $('buildstat').textContent = 'Building B-rep in OpenCASCADE…'; $('downloads').innerHTML = ''; const body = { datum, thickness: parseFloat($('thickness').value), margin: parseFloat($('margin').value), stepWinPath: $('stepwin').value, holes: holes.map((h, i) => ({ center: h.center, axis: h.axis, diameter: effectiveDiameter(h), through: h.through, depth: h.depth, thread: h.thread, label: `hole${i + 1}`, })), }; try { const j = await post('/api/build', body); if (!j.ok) { $('buildstat').textContent = 'Build failed: ' + j.error; return; } $('buildstat').innerHTML = `✓ Built solid with ${j.holesCut} hole(s).`; $('downloads').innerHTML = `⬇ STEP (.step)⬇ SW macro (.vba)`; setHud('Done. Download the STEP, or run the macro in SolidWorks.'); } catch (err) { $('buildstat').textContent = 'Build error: ' + err.message; } }); refreshStepper(); renderAlignSlots();