From f00a4802574f47b5b430015450e39083c7c3f6c8 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 10:45:06 -0700 Subject: [PATCH 01/34] Parametric: CAM engine (drop-cutter, clearing, contours, drilling, simulation, G-code posts) --- src/parametric/src/cam/dropcutter.ts | 304 ++++++++ src/parametric/src/cam/engine.ts | 63 ++ src/parametric/src/cam/frame.ts | 124 +++ src/parametric/src/cam/grid.ts | 236 ++++++ src/parametric/src/cam/ops.ts | 951 ++++++++++++++++++++++++ src/parametric/src/cam/post.ts | 301 ++++++++ src/parametric/src/cam/simulate.ts | 214 ++++++ src/parametric/src/cam/toolpath.ts | 155 ++++ src/parametric/src/model/cam.ts | 427 +++++++++++ src/parametric/src/model/document.ts | 5 +- src/parametric/src/model/types.ts | 3 + src/parametric/tests/cam-engine.test.ts | 358 +++++++++ 12 files changed, 3140 insertions(+), 1 deletion(-) create mode 100644 src/parametric/src/cam/dropcutter.ts create mode 100644 src/parametric/src/cam/engine.ts create mode 100644 src/parametric/src/cam/frame.ts create mode 100644 src/parametric/src/cam/grid.ts create mode 100644 src/parametric/src/cam/ops.ts create mode 100644 src/parametric/src/cam/post.ts create mode 100644 src/parametric/src/cam/simulate.ts create mode 100644 src/parametric/src/cam/toolpath.ts create mode 100644 src/parametric/src/model/cam.ts create mode 100644 src/parametric/tests/cam-engine.test.ts diff --git a/src/parametric/src/cam/dropcutter.ts b/src/parametric/src/cam/dropcutter.ts new file mode 100644 index 000000000..2d99f78f0 --- /dev/null +++ b/src/parametric/src/cam/dropcutter.ts @@ -0,0 +1,304 @@ +// Drop-cutter: the lowest height the tip of a cutter can go down to at a +// point without cutting into the part (a triangle mesh in work coordinates). +// The cutter touches a triangle on its face, along an edge or at a corner; +// each is solved for the cutter's shape (flat, ball, bull nose or cone), +// exactly where a closed form exists and by golden-section search otherwise +// (the height along an edge is concave in its parameter for these shapes). + +import type { CamTool } from '../model/cam'; + +/** A rotationally symmetric cutter: the height of its surface above the tip at a radius. */ +export interface Cutter { + /** Radius (beyond it the cutter is a vertical shank). */ + r: number; + kind: 'flat' | 'ball' | 'bull' | 'cone'; + /** Corner radius (ball: r; bull: the corner). */ + rc: number; + /** Cone: height gained per unit of radius (1 / tan of the half angle). */ + k: number; + h(rr: number): number; +} + +/** A cutter of the tool's shape, grown by a radial and lowered by an axial allowance. */ +export function cutterOf(tool: Pick, radial = 0): Cutter { + const r = tool.diameter / 2 + radial; + switch (tool.type) { + case 'ball': return makeCutter('ball', r, r, 0); + case 'bull': { + const rc = Math.min(Math.max(tool.cornerRadius ?? 0, 0), tool.diameter / 2) + radial; + return rc > 1e-9 ? makeCutter('bull', r, Math.min(rc, r), 0) : makeCutter('flat', r, 0, 0); + } + case 'drill': + case 'chamfer': { + const half = Math.max(1, Math.min(179, tool.tipAngle ?? (tool.type === 'drill' ? 118 : 90))) / 2; + return makeCutter('cone', r, 0, 1 / Math.tan((half * Math.PI) / 180)); + } + default: return makeCutter('flat', r, 0, 0); + } +} + +export function makeCutter(kind: Cutter['kind'], r: number, rc: number, k: number): Cutter { + const r0 = r - rc; + let h: (rr: number) => number; + switch (kind) { + case 'ball': h = (rr) => r - Math.sqrt(Math.max(0, r * r - rr * rr)); break; + case 'bull': h = (rr) => (rr <= r0 ? 0 : rc - Math.sqrt(Math.max(0, rc * rc - (rr - r0) * (rr - r0)))); break; + case 'cone': h = (rr) => rr * k; break; + default: h = () => 0; + } + return { r, kind, rc, k, h }; +} + +/** Triangles bucketed on a grid in XY for neighbourhood queries. */ +export class TriIndex { + readonly n: number; + readonly x0: number; + readonly y0: number; + readonly cell: number; + readonly nx: number; + readonly ny: number; + readonly zMin: number; + readonly zMax: number; + private starts: Int32Array; + private items: Int32Array; + private stamp: Int32Array; + private stampId = 0; + /** Per triangle: xy bounds and the plane (normal with nz >= 0, and d) used by the facet test. */ + readonly bounds: Float64Array; + readonly planes: Float64Array; + + constructor(readonly tris: Float64Array) { + const n = (this.n = Math.floor(tris.length / 9)); + this.bounds = new Float64Array(n * 4); + this.planes = new Float64Array(n * 4); + let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity, z0 = Infinity, z1 = -Infinity; + let area = 0; + for (let t = 0; t < n; t++) { + const o = t * 9; + const ax = tris[o], ay = tris[o + 1], az = tris[o + 2], bx = tris[o + 3], by = tris[o + 4], bz = tris[o + 5], cx = tris[o + 6], cy = tris[o + 7], cz = tris[o + 8]; + const mnx = Math.min(ax, bx, cx), mny = Math.min(ay, by, cy), mxx = Math.max(ax, bx, cx), mxy = Math.max(ay, by, cy); + this.bounds.set([mnx, mny, mxx, mxy], t * 4); + x0 = Math.min(x0, mnx); y0 = Math.min(y0, mny); x1 = Math.max(x1, mxx); y1 = Math.max(y1, mxy); + z0 = Math.min(z0, az, bz, cz); z1 = Math.max(z1, az, bz, cz); + const ux = bx - ax, uy = by - ay, uz = bz - az, vx = cx - ax, vy = cy - ay, vz = cz - az; + let nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx; + const l = Math.hypot(nx, ny, nz); + if (l > 0) { nx /= l; ny /= l; nz /= l; } + if (nz < 0) { nx = -nx; ny = -ny; nz = -nz; } + this.planes.set([nx, ny, nz, nx * ax + ny * ay + nz * az], t * 4); + area += (mxx - mnx) * (mxy - mny); + } + if (!n) { x0 = y0 = 0; x1 = y1 = 1; z0 = z1 = 0; } + this.zMin = z0; + this.zMax = z1; + // Buckets about the size of a typical triangle, at most ~1M of them. + const w = Math.max(x1 - x0, 1e-6), hgt = Math.max(y1 - y0, 1e-6); + const typical = n ? Math.sqrt(area / n) : 1; + let cell = Math.max(typical * 1.5, Math.sqrt((w * hgt) / 1e6), 0.05); + cell = Math.max(cell, Math.max(w, hgt) / 2048); + this.cell = cell; + this.x0 = x0; + this.y0 = y0; + this.nx = Math.max(1, Math.ceil(w / cell) + 1); + this.ny = Math.max(1, Math.ceil(hgt / cell) + 1); + const counts = new Int32Array(this.nx * this.ny + 1); + const span = (t: number) => { + const b = t * 4; + return [ + Math.floor((this.bounds[b] - x0) / cell), Math.floor((this.bounds[b + 1] - y0) / cell), + Math.floor((this.bounds[b + 2] - x0) / cell), Math.floor((this.bounds[b + 3] - y0) / cell), + ]; + }; + for (let t = 0; t < n; t++) { + const [i0, j0, i1, j1] = span(t); + for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) counts[j * this.nx + i + 1]++; + } + for (let k = 1; k < counts.length; k++) counts[k] += counts[k - 1]; + this.starts = counts; + this.items = new Int32Array(counts[counts.length - 1]); + const fill = counts.slice(0, -1); + for (let t = 0; t < n; t++) { + const [i0, j0, i1, j1] = span(t); + for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) this.items[fill[j * this.nx + i]++] = t; + } + this.stamp = new Int32Array(n); + } + + /** Calls fn with each triangle whose XY bounds overlap the box (once each). */ + query(x0: number, y0: number, x1: number, y1: number, fn: (t: number) => void) { + const c = this.cell; + const i0 = Math.max(0, Math.floor((x0 - this.x0) / c)), j0 = Math.max(0, Math.floor((y0 - this.y0) / c)); + const i1 = Math.min(this.nx - 1, Math.floor((x1 - this.x0) / c)), j1 = Math.min(this.ny - 1, Math.floor((y1 - this.y0) / c)); + if (i0 > i1 || j0 > j1) return; + let id = ++this.stampId; + if (id >= 0x7fffffff) { this.stamp.fill(0); id = this.stampId = 1; } + const b = this.bounds; + for (let j = j0; j <= j1; j++) { + for (let i = i0; i <= i1; i++) { + const cellIdx = j * this.nx + i; + for (let k = this.starts[cellIdx], e = this.starts[cellIdx + 1]; k < e; k++) { + const t = this.items[k]; + if (this.stamp[t] === id) continue; + this.stamp[t] = id; + const o = t * 4; + if (b[o] > x1 || b[o + 2] < x0 || b[o + 1] > y1 || b[o + 3] < y0) continue; + fn(t); + } + } + } + } +} + +/** Height reported where the cutter touches nothing. */ +export const NO_CONTACT = -1e9; + +const GOLDEN = (Math.sqrt(5) - 1) / 2; + +/** + * Drop-cutter queries for one cutter on one mesh. Not reentrant: it keeps + * scratch state between calls for speed. + */ +export class DropCutter { + private best = NO_CONTACT; + private px = 0; + private py = 0; + private readonly visit: (t: number) => void; + /** Number of triangles tested (for diagnostics). */ + tested = 0; + + constructor(readonly index: TriIndex, readonly cutter: Cutter) { + this.visit = (t) => this.testTriangle(t); + } + + /** Lowest tip height at (x, y), or `floor` where the cutter touches nothing higher. */ + drop(x: number, y: number, floor = NO_CONTACT): number { + this.best = floor; + this.px = x; + this.py = y; + const r = this.cutter.r; + this.index.query(x - r, y - r, x + r, y + r, this.visit); + return this.best; + } + + private testTriangle(t: number) { + this.tested++; + const T = this.index.tris; + const o = t * 9; + const px = this.px, py = this.py; + const c = this.cutter; + const r = c.r, r2 = r * r; + // Quick reject: the triangle's top is below the best height found. + const top = Math.max(T[o + 2], T[o + 5], T[o + 8]); + if (top <= this.best) return; + // Corners. + for (let k = 0; k < 9; k += 3) { + const dx = T[o + k] - px, dy = T[o + k + 1] - py; + const d2 = dx * dx + dy * dy; + if (d2 <= r2) { + const z = T[o + k + 2] - c.h(Math.sqrt(d2)); + if (z > this.best) this.best = z; + } + } + // Face. + const pl = this.index.planes, q = t * 4; + const nx = pl[q], ny = pl[q + 1], nz = pl[q + 2], d = pl[q + 3]; + if (nz > 1e-9) { + const gx = -nx / nz, gy = -ny / nz; + const s = Math.hypot(gx, gy); + let rr = 0, ux = 0, uy = 0; + if (s > 1e-12) { + ux = gx / s; uy = gy / s; + rr = contactRadius(c, s); + } + const cx = px + ux * rr, cy = py + uy * rr; + if (inTriangle(T, o, cx, cy)) { + const zc = (d - nx * cx - ny * cy) / nz; + const z = zc - c.h(rr); + if (z > this.best) this.best = z; + } + } + // Edges. + this.edge(T[o], T[o + 1], T[o + 2], T[o + 3], T[o + 4], T[o + 5]); + this.edge(T[o + 3], T[o + 4], T[o + 5], T[o + 6], T[o + 7], T[o + 8]); + this.edge(T[o + 6], T[o + 7], T[o + 8], T[o], T[o + 1], T[o + 2]); + } + + private edge(ax: number, ay: number, az: number, bx: number, by: number, bz: number) { + const c = this.cutter; + if (Math.max(az, bz) <= this.best) return; + const px = this.px, py = this.py, r = c.r; + const ex = bx - ax, ey = by - ay; + const L2 = ex * ex + ey * ey; + if (L2 < 1e-18) return; + // Parameter range of the edge within the cutter's radius. + const fx = ax - px, fy = ay - py; + const B = 2 * (fx * ex + fy * ey), C = fx * fx + fy * fy - r * r; + const disc = B * B - 4 * L2 * C; + if (disc < 0) return; + const sq = Math.sqrt(disc); + let t0 = (-B - sq) / (2 * L2), t1 = (-B + sq) / (2 * L2); + if (t1 < 0 || t0 > 1) return; + t0 = Math.max(0, t0); + t1 = Math.min(1, t1); + const ez = bz - az; + const zAt = (t: number) => { + const x = ax + ex * t - px, y = ay + ey * t - py; + return az + ez * t - c.h(Math.sqrt(x * x + y * y)); + }; + let z: number; + if (c.kind === 'flat') { + z = Math.max(az + ez * t0, az + ez * t1); + } else if (c.kind === 'ball') { + // In the vertical plane through the edge the ball is a circle of radius + // R' = sqrt(R² - d²), d the distance from the cutter axis to the edge's line. + const L = Math.sqrt(L2); + const tf = -(fx * ex + fy * ey) / L2; // foot of the perpendicular + const dx = ax + ex * tf - px, dy = ay + ey * tf - py; + const d2 = dx * dx + dy * dy; + const rp2 = r * r - d2; + if (rp2 <= 0) return; + const rp = Math.sqrt(rp2); + const m = ez / L; // slope along the edge + const k = Math.sqrt(1 + m * m); + const tc = tf + (rp * m) / k / L; // contact point + if (tc < t0 || tc > t1) { + z = Math.max(zAt(t0), zAt(t1)); + } else { + const zl = az + ez * tf; + z = zl + rp * k - r; + } + } else { + // Concave in t: golden-section search. + let lo = t0, hi = t1; + let a = hi - GOLDEN * (hi - lo), b = lo + GOLDEN * (hi - lo); + let fa = zAt(a), fb = zAt(b); + for (let i = 0; i < 40 && hi - lo > 1e-7; i++) { + if (fa < fb) { lo = a; a = b; fa = fb; b = lo + GOLDEN * (hi - lo); fb = zAt(b); } + else { hi = b; b = a; fb = fa; a = hi - GOLDEN * (hi - lo); fa = zAt(a); } + } + z = Math.max(fa, fb, zAt(t0), zAt(t1)); + } + if (z > this.best) this.best = z; + } +} + +/** Radius at which a cutter touches a plane of slope s (rise per run). */ +function contactRadius(c: Cutter, s: number): number { + switch (c.kind) { + case 'flat': return c.r; + case 'ball': return (c.r * s) / Math.sqrt(1 + s * s); + case 'bull': return c.r - c.rc + (c.rc * s) / Math.sqrt(1 + s * s); + case 'cone': return s > c.k ? c.r : 0; + } +} + +function inTriangle(T: Float64Array, o: number, x: number, y: number): boolean { + const ax = T[o], ay = T[o + 1], bx = T[o + 3], by = T[o + 4], cx = T[o + 6], cy = T[o + 7]; + const d1 = (x - bx) * (ay - by) - (ax - bx) * (y - by); + const d2 = (x - cx) * (by - cy) - (bx - cx) * (y - cy); + const d3 = (x - ax) * (cy - ay) - (cx - ax) * (y - ay); + const eps = 1e-12; + const neg = d1 < -eps || d2 < -eps || d3 < -eps; + const pos = d1 > eps || d2 > eps || d3 > eps; + return !(neg && pos); +} diff --git a/src/parametric/src/cam/engine.ts b/src/parametric/src/cam/engine.ts new file mode 100644 index 000000000..592b64626 --- /dev/null +++ b/src/parametric/src/cam/engine.ts @@ -0,0 +1,63 @@ +// What the CAM worker (and the tests) run: the part placed in a setup's +// machine frame, an operation's toolpath, and the simulation of a setup. + +import type { Vec3 } from '../math/vec'; +import type { CamOperation, CamSetup, CamTool } from '../model/cam'; +import { TriIndex } from './dropcutter'; +import { type MachineFrame, dirToWork, machineFrame, pointToWork, toWork } from './frame'; +import { type CamPart, type Cylinder, generate } from './ops'; +import { type SimResult, simulate } from './simulate'; +import type { Toolpath } from './toolpath'; + +/** A cylindrical face of the part in model coordinates (a hole candidate). */ +export interface ModelCylinder { + name: string; + p: Vec3; + d: Vec3; + radius: number; + tris: Float32Array; +} + +export function placePart(setup: Pick, tris: Float32Array): CamPart | null { + const frame = machineFrame(setup, tris); + if (!frame) return null; + const work = toWork(tris, frame); + return { frame, tris: work, index: new TriIndex(work) }; +} + +export function workCylinders(frame: MachineFrame, cyl: ModelCylinder[], picked: Set): Cylinder[] { + return cyl.map((c) => ({ name: c.name, p: pointToWork(frame, c.p), d: dirToWork(frame, c.d), radius: c.radius, tris: toWork(c.tris, frame), picked: picked.has(c.name) })); +} + +export interface GenerateJob { + setup: CamSetup; + op: CamOperation; + tool: CamTool; + /** Pocket floors (model coordinates). */ + floors?: Float32Array[]; + cylinders?: ModelCylinder[]; + /** Names of the cylinders picked in the operation. */ + picked?: string[]; +} + +export function generateFor(part: CamPart, job: GenerateJob, progress?: (f: number) => void, cancelled?: () => boolean): Toolpath { + return generate({ + part, + setup: job.setup, + op: job.op, + tool: job.tool, + floors: job.floors?.map((t) => toWork(t, part.frame)), + cylinders: job.cylinders ? workCylinders(part.frame, job.cylinders, new Set(job.picked ?? [])) : undefined, + progress, + cancelled, + }); +} + +export interface SimulateJob { + steps: { toolpath: Toolpath; tool: CamTool; feed: number; plunge: number }[]; + rapidFeed: number; +} + +export function simulateFor(part: CamPart, job: SimulateJob, progress?: (f: number) => void, cancelled?: () => boolean): SimResult { + return simulate({ stock: part.frame.stock, part: part.index, steps: job.steps, rapidFeed: job.rapidFeed, progress, cancelled }); +} diff --git a/src/parametric/src/cam/frame.ts b/src/parametric/src/cam/frame.ts new file mode 100644 index 000000000..977e2178e --- /dev/null +++ b/src/parametric/src/cam/frame.ts @@ -0,0 +1,124 @@ +// The machine frame of a setup: the part as it sits on the machine, with Z +// toward the spindle, and the work origin on the stock. The CAM engine works +// in work coordinates (millimetres from the work origin); toolpaths are drawn +// in the model by mapping them back. + +import type { Vec3 } from '../math/vec'; +import type { CamAxis, CamSetup } from '../model/cam'; + +export interface Box3 { min: Vec3; max: Vec3 } + +export interface MachineFrame { + /** Model directions of the machine's X, Y and Z axes. */ + x: Vec3; + y: Vec3; + z: Vec3; + /** Work origin in model coordinates. */ + origin: Vec3; + /** The stock in work coordinates. */ + stock: Box3; + /** The part's bounding box in work coordinates. */ + part: Box3; +} + +const AXIS: Record = { + // X runs left to right as the part is seen from the spindle (as in the + // model's standard view from that side), so Y = Z × X points away from the operator. + '+Y': { z: [0, 1, 0], x: [1, 0, 0] }, + '-Y': { z: [0, -1, 0], x: [1, 0, 0] }, + '+Z': { z: [0, 0, 1], x: [1, 0, 0] }, + '-Z': { z: [0, 0, -1], x: [-1, 0, 0] }, + '+X': { z: [1, 0, 0], x: [0, 0, -1] }, + '-X': { z: [-1, 0, 0], x: [0, 0, 1] }, +}; + +const cross = (a: Vec3, b: Vec3): Vec3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; +const dot = (a: Vec3, b: Vec3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + +/** Machine axes of a setup (before the work origin is placed). */ +export function setupAxes(axis: CamAxis, rotation: number): { x: Vec3; y: Vec3; z: Vec3 } { + const a = AXIS[axis]; + const z = a.z; + const x0 = a.x; + const y0 = cross(z, x0); + const t = (rotation * Math.PI) / 180; + const c = Math.round(Math.cos(t) * 1e12) / 1e12, s = Math.round(Math.sin(t) * 1e12) / 1e12; + const x: Vec3 = [c * x0[0] + s * y0[0], c * x0[1] + s * y0[1], c * x0[2] + s * y0[2]]; + return { x, y: cross(z, x), z }; +} + +/** Bounding box of triangles (9 numbers each) seen along the given axes. */ +export function boxAlong(tris: ArrayLike, axes: { x: Vec3; y: Vec3; z: Vec3 }): Box3 | null { + const min: Vec3 = [Infinity, Infinity, Infinity], max: Vec3 = [-Infinity, -Infinity, -Infinity]; + for (let i = 0; i + 2 < tris.length; i += 3) { + const p: Vec3 = [tris[i], tris[i + 1], tris[i + 2]]; + const q = [dot(p, axes.x), dot(p, axes.y), dot(p, axes.z)]; + for (let k = 0; k < 3; k++) { if (q[k] < min[k]) min[k] = q[k]; if (q[k] > max[k]) max[k] = q[k]; } + } + return Number.isFinite(min[0]) ? { min, max } : null; +} + +/** The machine frame of a setup for a part with these triangles (model coordinates). */ +export function machineFrame(setup: Pick, tris: ArrayLike): MachineFrame | null { + const axes = setupAxes(setup.axis, setup.rotation); + const b = boxAlong(tris, axes); + if (!b) return null; + const st = setup.stock; + let smin: Vec3, smax: Vec3; + if (st.mode === 'fixed') { + const cx = (b.min[0] + b.max[0]) / 2, cy = (b.min[1] + b.max[1]) / 2; + const [w, d, hgt] = st.size.map((v, k) => Math.max(v, b.max[k] - b.min[k])) as Vec3; + const top = b.max[2] + st.top; + smin = [cx - w / 2, cy - d / 2, Math.min(top - hgt, b.min[2])]; + smax = [cx + w / 2, cy + d / 2, top]; + } else { + smin = [b.min[0] - st.side, b.min[1] - st.side, b.min[2] - st.bottom]; + smax = [b.max[0] + st.side, b.max[1] + st.side, b.max[2] + st.top]; + } + let o: Vec3; + switch (setup.origin) { + case 'topCenter': o = [(smin[0] + smax[0]) / 2, (smin[1] + smax[1]) / 2, smax[2]]; break; + case 'topFrontLeft': o = [smin[0], smin[1], smax[2]]; break; + case 'topBackLeft': o = [smin[0], smax[1], smax[2]]; break; + case 'bottomFrontLeft': o = [smin[0], smin[1], smin[2]]; break; + default: o = [0, 0, 0]; + } + const origin: Vec3 = [ + axes.x[0] * o[0] + axes.y[0] * o[1] + axes.z[0] * o[2], + axes.x[1] * o[0] + axes.y[1] * o[1] + axes.z[1] * o[2], + axes.x[2] * o[0] + axes.y[2] * o[1] + axes.z[2] * o[2], + ]; + const sub = (p: Vec3): Vec3 => [p[0] - o[0], p[1] - o[1], p[2] - o[2]]; + return { ...axes, origin, stock: { min: sub(smin), max: sub(smax) }, part: { min: sub(b.min), max: sub(b.max) } }; +} + +/** Triangles in work coordinates (a new array). */ +export function toWork(tris: ArrayLike, f: MachineFrame): Float64Array { + const out = new Float64Array(tris.length); + for (let i = 0; i + 2 < tris.length; i += 3) { + const px = tris[i] - f.origin[0], py = tris[i + 1] - f.origin[1], pz = tris[i + 2] - f.origin[2]; + out[i] = px * f.x[0] + py * f.x[1] + pz * f.x[2]; + out[i + 1] = px * f.y[0] + py * f.y[1] + pz * f.y[2]; + out[i + 2] = px * f.z[0] + py * f.z[1] + pz * f.z[2]; + } + return out; +} + +/** A point in work coordinates to model coordinates. */ +export function toModel(f: MachineFrame, x: number, y: number, z: number): Vec3 { + return [ + f.origin[0] + f.x[0] * x + f.y[0] * y + f.z[0] * z, + f.origin[1] + f.x[1] * x + f.y[1] * y + f.z[1] * z, + f.origin[2] + f.x[2] * x + f.y[2] * y + f.z[2] * z, + ]; +} + +/** A model direction in work coordinates. */ +export function dirToWork(f: MachineFrame, d: Vec3): Vec3 { + return [dot(d, f.x), dot(d, f.y), dot(d, f.z)]; +} + +export function pointToWork(f: MachineFrame, p: Vec3): Vec3 { + const q: Vec3 = [p[0] - f.origin[0], p[1] - f.origin[1], p[2] - f.origin[2]]; + return [dot(q, f.x), dot(q, f.y), dot(q, f.z)]; +} diff --git a/src/parametric/src/cam/grid.ts b/src/parametric/src/cam/grid.ts new file mode 100644 index 000000000..4bc03ba78 --- /dev/null +++ b/src/parametric/src/cam/grid.ts @@ -0,0 +1,236 @@ +// Sampled fields on a regular XY grid and the curves read from them: +// contours by marching squares (oriented with the inside on the left, with an +// optional exact refinement of each crossing), Euclidean distance transforms +// and polyline simplification. + +export interface GridSpec { + x0: number; + y0: number; + /** Node spacing. */ + c: number; + nx: number; + ny: number; +} + +/** A polyline as x, y pairs (or x, y, z triples for 3D paths). */ +export interface Polyline { + pts: number[]; + closed: boolean; +} + +export function gridOver(x0: number, y0: number, x1: number, y1: number, c: number, maxNodes = 600_000): GridSpec { + let cell = c; + const w = Math.max(x1 - x0, 1e-6), h = Math.max(y1 - y0, 1e-6); + if ((w / cell + 1) * (h / cell + 1) > maxNodes) cell = Math.sqrt((w * h) / maxNodes) * 1.02; + const nx = Math.max(2, Math.ceil(w / cell) + 1), ny = Math.max(2, Math.ceil(h / cell) + 1); + return { x0, y0, c: cell, nx, ny }; +} + +/** + * Contours where `v` crosses `level`, the region v >= level kept on the left. + * `refine(ax, ay, bx, by, t)` may move a crossing found at fraction t of the + * way from node a (inside) to node b (outside) and returns the new fraction. + */ +export function contours(g: GridSpec, v: ArrayLike, level: number, refine?: (ax: number, ay: number, bx: number, by: number, t: number) => number): Polyline[] { + const { nx, ny, x0, y0, c } = g; + const inside = (i: number, j: number) => v[j * nx + i] >= level; + // Edge ids: horizontal edge (i,j)-(i+1,j): j*(nx-1)+i; vertical (i,j)-(i,j+1): H + j*nx + i. + const H = (nx - 1) * ny; + const edgeCount = H + nx * (ny - 1); + const px = new Float64Array(edgeCount), py = new Float64Array(edgeCount); + const done = new Uint8Array(edgeCount); + const point = (e: number) => { + if (done[e]) return; + done[e] = 1; + let ai: number, aj: number, bi: number, bj: number; + if (e < H) { aj = Math.floor(e / (nx - 1)); ai = e - aj * (nx - 1); bi = ai + 1; bj = aj; } + else { const k = e - H; aj = Math.floor(k / nx); ai = k - aj * nx; bi = ai; bj = aj + 1; } + let va = v[aj * nx + ai], vb = v[bj * nx + bi]; + // From the inside node to the outside one. + if (va < level) { [ai, aj, bi, bj] = [bi, bj, ai, aj]; [va, vb] = [vb, va]; } + let t = va === vb ? 0.5 : (va - level) / (va - vb); + t = Math.max(0, Math.min(1, t)); + const ax = x0 + ai * c, ay = y0 + aj * c, bx = x0 + bi * c, by = y0 + bj * c; + if (refine) t = Math.max(0, Math.min(1, refine(ax, ay, bx, by, t))); + px[e] = ax + (bx - ax) * t; + py[e] = ay + (by - ay) * t; + }; + // next[e]: the edge the contour goes to after entering at edge e (-1 none). + const next = new Int32Array(edgeCount).fill(-1); + const hasPrev = new Uint8Array(edgeCount); + const starts: number[] = []; + for (let j = 0; j < ny - 1; j++) { + for (let i = 0; i < nx - 1; i++) { + const a = inside(i, j), b = inside(i + 1, j), cc = inside(i + 1, j + 1), d = inside(i, j + 1); + if (a === b && b === cc && cc === d) continue; + // Corners and edges counter-clockwise: 00 -e0- 10 -e1- 11 -e2- 01 -e3- 00. + const corners = [a, b, cc, d]; + const edges = [j * (nx - 1) + i, H + j * nx + i + 1, (j + 1) * (nx - 1) + i, H + j * nx + i]; + const crossing: { e: number; out: boolean }[] = []; + for (let k = 0; k < 4; k++) { + const p = corners[k], q = corners[(k + 1) % 4]; + if (p !== q) crossing.push({ e: edges[k], out: p }); + } + let centerIn = true; + if (crossing.length === 4) { + const m = (v[j * nx + i] + v[j * nx + i + 1] + v[(j + 1) * nx + i + 1] + v[(j + 1) * nx + i]) / 4; + centerIn = m >= level; + } + for (let k = 0; k < crossing.length; k++) { + if (!crossing[k].out) continue; + const to = crossing.length === 2 ? crossing[(k + 1) % 2] : crossing[centerIn ? (k + 1) % 4 : (k + 3) % 4]; + // Leaving across edge `from` into... the segment runs from the in->out edge to the out->in edge. + const from = crossing[k].e; + next[from] = to.e; + hasPrev[to.e] = 1; + starts.push(from); + } + } + } + const out: Polyline[] = []; + const used = new Uint8Array(edgeCount); + const trace = (s: number) => { + const pts: number[] = []; + let e = s; + while (e >= 0 && !used[e]) { + used[e] = 1; + point(e); + pts.push(px[e], py[e]); + e = next[e]; + } + const closed = e === s; + if (pts.length >= 4) out.push({ pts, closed }); + }; + // Open chains first (they start on the border), then loops. + for (const s of starts) if (!hasPrev[s] && !used[s]) trace(s); + for (const s of starts) if (!used[s]) trace(s); + return out; +} + +const INF = 1e20; + +/** Squared distance transform (in cells²) of the nodes where `feature` is set, to the nearest such node. */ +export function edt(g: GridSpec, feature: (k: number) => boolean): Float64Array { + const { nx, ny } = g; + const d = new Float64Array(nx * ny); + for (let k = 0; k < d.length; k++) d[k] = feature(k) ? 0 : INF; + const n = Math.max(nx, ny); + const f = new Float64Array(n), z = new Float64Array(n + 1), vv = new Int32Array(n), out = new Float64Array(n); + const pass = (len: number, get: (i: number) => number, set: (i: number, x: number) => void) => { + for (let i = 0; i < len; i++) f[i] = get(i); + let k = 0; + vv[0] = 0; + z[0] = -INF; + z[1] = INF; + for (let q = 1; q < len; q++) { + let s = ((f[q] + q * q) - (f[vv[k]] + vv[k] * vv[k])) / (2 * q - 2 * vv[k]); + while (s <= z[k]) { + k--; + s = ((f[q] + q * q) - (f[vv[k]] + vv[k] * vv[k])) / (2 * q - 2 * vv[k]); + } + k++; + vv[k] = q; + z[k] = s; + z[k + 1] = INF; + } + k = 0; + for (let q = 0; q < len; q++) { + while (z[k + 1] < q) k++; + out[q] = (q - vv[k]) * (q - vv[k]) + f[vv[k]]; + } + for (let i = 0; i < len; i++) set(i, out[i]); + }; + for (let i = 0; i < nx; i++) pass(ny, (j) => d[j * nx + i], (j, x) => { d[j * nx + i] = x; }); + for (let j = 0; j < ny; j++) pass(nx, (i) => d[j * nx + i], (i, x) => { d[j * nx + i] = x; }); + return d; +} + +/** + * Signed distance (model units) to the boundary of a region of nodes: + * positive inside, negative outside, the boundary halfway between nodes. + */ +export function signedDistance(g: GridSpec, inside: Uint8Array): Float64Array { + const dOut = edt(g, (k) => !inside[k]); + const dIn = edt(g, (k) => !!inside[k]); + const s = new Float64Array(inside.length); + for (let k = 0; k < s.length; k++) s[k] = inside[k] ? (Math.sqrt(dOut[k]) - 0.5) * g.c : -(Math.sqrt(dIn[k]) - 0.5) * g.c; + return s; +} + +/** Bilinear sample of a node field at a point (clamped to the grid). */ +export function sample(g: GridSpec, v: ArrayLike, x: number, y: number): number { + const fx = Math.max(0, Math.min(g.nx - 1.000001, (x - g.x0) / g.c)); + const fy = Math.max(0, Math.min(g.ny - 1.000001, (y - g.y0) / g.c)); + const i = Math.floor(fx), j = Math.floor(fy); + const tx = fx - i, ty = fy - j; + const k = j * g.nx + i; + return (v[k] * (1 - tx) + v[k + 1] * tx) * (1 - ty) + (v[k + g.nx] * (1 - tx) + v[k + g.nx + 1] * tx) * ty; +} + +/** Douglas-Peucker simplification of a polyline with `dim` numbers per point. */ +export function simplify(pts: number[], tol: number, dim: 2 | 3 = 2, closed = false): number[] { + const n = pts.length / dim; + if (n <= 2) return pts.slice(); + const keep = new Uint8Array(n); + const dist2 = (p: number, a: number, b: number) => { + let ab2 = 0, t = 0; + for (let k = 0; k < dim; k++) { const e = pts[b * dim + k] - pts[a * dim + k]; ab2 += e * e; t += (pts[p * dim + k] - pts[a * dim + k]) * e; } + t = ab2 > 0 ? Math.max(0, Math.min(1, t / ab2)) : 0; + let d2 = 0; + for (let k = 0; k < dim; k++) { const q = pts[a * dim + k] + (pts[b * dim + k] - pts[a * dim + k]) * t - pts[p * dim + k]; d2 += q * q; } + return d2; + }; + // Simplifies the run of points idx[0..] (indices into pts), marking those kept. + const run = (idx: number[]) => { + const tol2 = tol * tol; + keep[idx[0]] = keep[idx[idx.length - 1]] = 1; + const stack = [0, idx.length - 1]; + while (stack.length) { + const e = stack.pop()!, s = stack.pop()!; + let best = -1, bd = tol2; + for (let p = s + 1; p < e; p++) { const d = dist2(idx[p], idx[s], idx[e]); if (d > bd) { bd = d; best = p; } } + if (best >= 0) { keep[idx[best]] = 1; stack.push(s, best, best, e); } + } + }; + const range = (a: number, b: number) => Array.from({ length: b - a + 1 }, (_, i) => a + i); + if (closed) { + // Split the loop at the point farthest from the first; the second half closes back to it. + let far = 0, fd = -1; + for (let p = 1; p < n; p++) { let d = 0; for (let k = 0; k < dim; k++) { const e = pts[p * dim + k] - pts[k]; d += e * e; } if (d > fd) { fd = d; far = p; } } + run(range(0, far)); + run([...range(far, n - 1), 0]); + } else run(range(0, n - 1)); + const out: number[] = []; + for (let p = 0; p < n; p++) if (keep[p]) for (let k = 0; k < dim; k++) out.push(pts[p * dim + k]); + return out; +} + +/** Signed area of a closed 2D polyline (positive counter-clockwise). */ +export function area(pts: number[]): number { + let a = 0; + const n = pts.length / 2; + for (let i = 0, j = n - 1; i < n; j = i++) a += pts[j * 2] * pts[i * 2 + 1] - pts[i * 2] * pts[j * 2 + 1]; + return a / 2; +} + +export function pointInPolygon(pts: number[], x: number, y: number): boolean { + let inside = false; + const n = pts.length / 2; + for (let i = 0, j = n - 1; i < n; j = i++) { + const xi = pts[i * 2], yi = pts[i * 2 + 1], xj = pts[j * 2], yj = pts[j * 2 + 1]; + if ((yi > y) !== (yj > y) && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside; + } + return inside; +} + +export function polyLength(pts: number[], dim: 2 | 3 = 2, closed = false): number { + let l = 0; + const n = pts.length / dim; + for (let i = 1; i < n + (closed ? 1 : 0); i++) { + const a = (i - 1) * dim, b = (i % n) * dim; + let d = 0; + for (let k = 0; k < dim; k++) { const e = pts[b + k] - pts[a + k]; d += e * e; } + l += Math.sqrt(d); + } + return l; +} diff --git a/src/parametric/src/cam/ops.ts b/src/parametric/src/cam/ops.ts new file mode 100644 index 000000000..ff038c3c1 --- /dev/null +++ b/src/parametric/src/cam/ops.ts @@ -0,0 +1,951 @@ +// Toolpath generation for each kind of operation, in work coordinates. +// +// Everything is derived from drop-cutter heights (cl): where the tool may be +// at height z is where cl <= z. Clearing works level by level on that region: +// its boundary is found exactly (each grid crossing refined by bisection on +// the drop-cutter), the passes inside it are offsets from a distance +// transform of the region, cut from the innermost out so each pass takes one +// stepover of material. Waterline finishing follows the same exact +// boundaries; parallel finishing follows drop-cutter heights along lines. + +import type { BoreOp, CamOperation, CamSetup, CamTool, ContourOp, DrillOp, FaceOp, ParallelOp, PocketOp, RoughOp, WaterlineOp } from '../model/cam'; +import type { Vec3 } from '../math/vec'; +import { type Cutter, cutterOf, DropCutter, NO_CONTACT, TriIndex, makeCutter } from './dropcutter'; +import type { MachineFrame } from './frame'; +import { type GridSpec, type Polyline, area, contours, edt, gridOver, pointInPolygon, polyLength, sample, signedDistance, simplify } from './grid'; +import { PathBuilder, type Toolpath } from './toolpath'; + +export interface CamPart { + frame: MachineFrame; + /** Triangles in work coordinates. */ + tris: Float64Array; + index: TriIndex; +} + +/** A cylindrical face of the part (a hole candidate), in work coordinates. */ +export interface Cylinder { + name: string; + /** A point on the axis and its direction. */ + p: Vec3; + d: Vec3; + radius: number; + /** Its triangles. */ + tris: Float64Array; + /** Picked in the operation (else it is a candidate only). */ + picked: boolean; +} + +export interface OpInput { + part: CamPart; + setup: Pick; + op: CamOperation; + tool: CamTool; + /** Pocket floors: the triangles of each picked face. */ + floors?: Float64Array[]; + cylinders?: Cylinder[]; + progress?: (fraction: number) => void; + /** Checked between steps; generation stops when it returns true. */ + cancelled?: () => boolean; +} + +export class CamError extends Error {} + +class Cancelled extends Error {} + +export function generate(input: OpInput): Toolpath { + const { part, setup, op } = input; + const top = part.frame.stock.max[2]; + const b = new PathBuilder(top + setup.clearance, top + setup.retract); + const g = new Gen(input, b); + switch (op.type) { + case 'face': g.face(op); break; + case 'contour': g.contour(op); break; + case 'pocket': g.pocket(op); break; + case 'drill': g.drill(op); break; + case 'bore': g.bore(op); break; + case 'rough': g.rough(op); break; + case 'parallel': g.parallel(op); break; + case 'waterline': g.waterline(op); break; + } + if (b.length === 0 && !b.warnings.length) b.warnings.push('The operation has nothing to cut.'); + return b.build(); +} + +const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v)); + +/** Heights from just below `top` down to `bottom` (included), `step` apart, with `extra` heights in between. */ +export function stepLevels(top: number, bottom: number, step: number, extra: number[] = []): number[] { + const out: number[] = []; + if (!(top > bottom + 1e-9)) return [bottom]; + const n = Math.max(1, Math.ceil((top - bottom) / Math.max(step, 1e-3) - 1e-9)); + for (let i = 1; i <= n; i++) out.push(i === n ? bottom : top - i * step); + for (const e of extra) if (e < top - 1e-6 && e > bottom + 1e-6 && out.every((z) => Math.abs(z - e) > 0.01)) out.push(e); + return out.sort((a, c) => c - a); +} + +interface Region { + grid: GridSpec; + /** Drop-cutter heights at the grid's nodes. */ + cl: Float64Array; + /** Extra limit at the nodes (>= 0 where allowed), or null. */ + limit: Float64Array | null; + limitAt: ((x: number, y: number) => number) | null; + dc: DropCutter; + /** Height added to drop-cutter heights (floor allowance). */ + lift: number; +} + +class Gen { + private readonly b: PathBuilder; + private readonly part: CamPart; + private readonly tool: CamTool; + private readonly R: number; + private steps = 0; + private done = 0; + + constructor(private readonly input: OpInput, b: PathBuilder) { + this.b = b; + this.part = input.part; + this.tool = input.tool; + this.R = input.tool.diameter / 2; + } + + private get stockTop() { return this.part.frame.stock.max[2]; } + private get partTop() { return this.part.frame.part.max[2]; } + private get partBottom() { return this.part.frame.part.min[2]; } + + private tick() { + this.done++; + if (this.input.cancelled?.()) throw new Cancelled('cancelled'); + this.input.progress?.(this.steps ? Math.min(1, this.done / this.steps) : 0); + } + + // ---------- regions ---------- + + /** Drop-cutter heights over a box, at a spacing fitting the tool. */ + private region(x0: number, y0: number, x1: number, y1: number, cutter: Cutter, lift = 0, cell?: number): Region { + const c = cell ?? clamp(this.R / 5, 0.05, 0.5); + const grid = gridOver(x0, y0, x1, y1, c, 450_000); + const dc = new DropCutter(this.part.index, cutter); + const cl = new Float64Array(grid.nx * grid.ny); + for (let j = 0; j < grid.ny; j++) { + const y = grid.y0 + j * grid.c; + for (let i = 0; i < grid.nx; i++) cl[j * grid.nx + i] = dc.drop(grid.x0 + i * grid.c, y) + lift; + if (j % 16 === 0 && this.input.cancelled?.()) throw new Cancelled('cancelled'); + } + return { grid, cl, limit: null, limitAt: null, dc, lift }; + } + + /** Where the tool can be at height z (1) in a region. */ + private mask(r: Region, z: number): Uint8Array { + const m = new Uint8Array(r.cl.length); + for (let k = 0; k < m.length; k++) m[k] = r.cl[k] <= z + 1e-7 && (!r.limit || r.limit[k] >= 0) ? 1 : 0; + return m; + } + + /** + * The boundary of where the tool can be at height z, exact: each crossing of + * the grid is refined by bisection on the drop-cutter. Inside on the left. + */ + private boundary(r: Region, z: number, tol: number): Polyline[] { + const g = r.grid; + const f = new Float64Array(r.cl.length); + for (let k = 0; k < f.length; k++) f[k] = Math.min(z - r.cl[k], r.limit ? r.limit[k] : Infinity); + const at = (x: number, y: number) => Math.min(z - (r.dc.drop(x, y) + r.lift), r.limitAt ? r.limitAt(x, y) : Infinity); + const loops = contours(g, f, 0, (ax, ay, bx, by, t) => { + // Bracket [lo, hi] with f(lo) >= 0 > f(hi). + let lo = 0, hi = 1; + const fa = at(ax + (bx - ax) * t, ay + (by - ay) * t); + if (fa >= 0) lo = t; else hi = t; + for (let i = 0; i < 16 && (hi - lo) * g.c > 1e-5; i++) { + const m = (lo + hi) / 2; + if (at(ax + (bx - ax) * m, ay + (by - ay) * m) >= 0) lo = m; else hi = m; + } + return lo; + }); + return loops.filter((l) => polyLength(l.pts, 2, l.closed) > g.c * 1.5).map((l) => ({ pts: simplify(l.pts, tol, 2, l.closed), closed: l.closed })); + } + + // ---------- path pieces ---------- + + /** Rotates a closed loop to start at its point nearest (x, y). */ + private startNear(pts: number[], x: number, y: number): number[] { + let best = 0, bd = Infinity; + for (let i = 0; i < pts.length; i += 2) { + const d = (pts[i] - x) ** 2 + (pts[i + 1] - y) ** 2; + if (d < bd) { bd = d; best = i; } + } + return [...pts.slice(best), ...pts.slice(0, best)]; + } + + /** Cuts a closed loop at height z from its first point, back to it. */ + private loop(pts: number[], z: number) { + const b = this.b; + for (let i = 0; i < pts.length; i += 2) b.feed(pts[i], pts[i + 1], z); + b.feed(pts[0], pts[1], z); + } + + /** + * Down along a closed loop from zFrom to z at the ramp angle, then once + * round at z and on to the loop's first point. + */ + private rampLoop(pts: number[], zFrom: number, z: number, angle: number) { + const b = this.b; + const n = pts.length / 2; + const slope = Math.tan((clamp(angle, 0.5, 89) * Math.PI) / 180); + let zc = zFrom; + b.plunge(pts[0], pts[1], zc); + let i = 0, guard = 0; + // Ramp (possibly several laps on short loops). + while (zc > z + 1e-9 && guard++ < n * 200) { + const a = i % n, c = (i + 1) % n; + const l = Math.hypot(pts[c * 2] - pts[a * 2], pts[c * 2 + 1] - pts[a * 2 + 1]); + const dz = l * slope; + if (zc - dz <= z) { + const t = l > 0 ? (zc - z) / dz : 1; + const x = pts[a * 2] + (pts[c * 2] - pts[a * 2]) * t, y = pts[a * 2 + 1] + (pts[c * 2 + 1] - pts[a * 2 + 1]) * t; + b.plunge(x, y, z); + zc = z; + // Once round at depth from here, and on to the first point. + for (let k = 1; k <= n; k++) { const q = (a + k) % n; b.feed(pts[q * 2], pts[q * 2 + 1], z); } + b.feed(x, y, z); + for (let q = (a + 1) % n; ; q = (q + 1) % n) { + b.feed(pts[q * 2], pts[q * 2 + 1], z); + if (q === 0) break; + } + return; + } + zc -= dz; + b.plunge(pts[c * 2], pts[c * 2 + 1], zc); + i++; + } + this.loop(pts, z); + } + + /** A helix of radius rh around (cx, cy) from zFrom down to z, ending with one circle at z. */ + private helix(cx: number, cy: number, rh: number, zFrom: number, z: number, pitch: number, ccw: boolean, a0 = 0) { + const b = this.b; + const steps = 72; + const turns = Math.max(0, (zFrom - z) / Math.max(pitch, 1e-3)); + const total = Math.ceil(turns * steps); + const dir = ccw ? 1 : -1; + b.plunge(cx + rh * Math.cos(a0), cy + rh * Math.sin(a0), zFrom); + for (let s = 1; s <= total; s++) { + const a = a0 + (dir * 2 * Math.PI * s) / steps; + b.plunge(cx + rh * Math.cos(a), cy + rh * Math.sin(a), zFrom - ((zFrom - z) * s) / total); + } + const aEnd = a0 + (dir * 2 * Math.PI * total) / steps; + for (let s = 1; s <= steps; s++) { + const a = aEnd + (dir * 2 * Math.PI * s) / steps; + b.feed(cx + rh * Math.cos(a), cy + rh * Math.sin(a), z); + } + } + + /** Down to the start of a cut at (x, y): rapid to just above the material (top), then the plunge feed. */ + private enter(x: number, y: number, top: number, z: number) { + const b = this.b; + const above = Math.min(b.retract, top + Math.min(1, b.retract)); + if (b.z > b.retract || Number.isNaN(b.z) || Math.hypot(b.x - x, b.y - y) > 1e-6) { + b.rapidTo(x, y, b.retract); + b.hop(b.retract, x, y, Math.max(above, z)); + } + b.plunge(x, y, z); + } + + /** Is the straight move from a to b inside the region (signed distance >= -slack)? */ + private insideAlong(g: GridSpec, s: Float64Array, ax: number, ay: number, bx: number, by: number, slack: number): boolean { + const l = Math.hypot(bx - ax, by - ay); + const n = Math.max(2, Math.ceil(l / (g.c * 0.5))); + for (let i = 0; i <= n; i++) { + const t = i / n; + if (sample(g, s, ax + (bx - ax) * t, ay + (by - ay) * t) < -slack) return false; + } + return true; + } + + // ---------- clearing ---------- + + private clear(r: Region, levels: number[], o: { stepover: number; pattern: 'offset' | 'zigzag'; climb: boolean; entry: 'helix' | 'ramp' | 'plunge'; rampAngle: number; tol: number; materialTop: number }) { + const g = r.grid; + let zPrev = o.materialTop; + for (const z of levels) { + this.tick(); + const m = this.mask(r, z); + if (!m.some((v) => v)) { zPrev = z; continue; } + const s = signedDistance(g, m); + const finish = this.boundary(r, z, o.tol).filter((l) => l.closed); + if (!o.climb) for (const l of finish) reverse2(l.pts); + const rings: { pts: number[]; level: number; comp: number }[] = []; + const label = components(g, m); + const compOf = (pts: number[]) => { + // A point just to the left of the loop (inside the region). + for (let i = 0; i + 3 < pts.length; i += 2) { + const dx = pts[i + 2] - pts[i], dy = pts[i + 3] - pts[i + 1]; + const l = Math.hypot(dx, dy); + if (l < 1e-9) continue; + const sgn = o.climb ? 1 : -1; + const x = (pts[i] + pts[i + 2]) / 2 - (dy / l) * g.c * 0.75 * sgn, y = (pts[i + 1] + pts[i + 3]) / 2 + (dx / l) * g.c * 0.75 * sgn; + const ii = Math.round((x - g.x0) / g.c), jj = Math.round((y - g.y0) / g.c); + if (ii >= 0 && jj >= 0 && ii < g.nx && jj < g.ny && label[jj * g.nx + ii]) return label[jj * g.nx + ii]; + } + return 0; + }; + for (const l of finish) rings.push({ pts: l.pts, level: 0, comp: compOf(l.pts) }); + if (o.pattern === 'offset') { + for (let k = 1; ; k++) { + const lv = k * o.stepover; + const ls = contours(g, s, lv).filter((l) => l.closed && polyLength(l.pts, 2, true) > g.c * 2); + if (!ls.length) break; + for (const l of ls) { + const pts = simplify(l.pts, Math.min(g.c * 0.25, 0.02), 2, true); + if (!o.climb) reverse2(pts); + rings.push({ pts, level: k, comp: compOf(pts) }); + } + if (k > 100000) break; + } + this.offsetPasses(g, s, label, rings, z, zPrev, o); + } else { + this.zigzagPasses(g, s, z, zPrev, o); + // Then the walls. + for (const ring of rings) { + const pts = this.startNear(ring.pts, this.b.x, this.b.y); + this.enter(pts[0], pts[1], zPrev, z); + this.loop(pts, z); + } + } + zPrev = z; + } + } + + private offsetPasses(g: GridSpec, s: Float64Array, label: Int32Array, rings: { pts: number[]; level: number; comp: number }[], z: number, zPrev: number, o: { stepover: number; climb: boolean; entry: 'helix' | 'ramp' | 'plunge'; rampAngle: number }) { + const b = this.b; + const comps = new Map(); + for (const r of rings) { + const list = comps.get(r.comp) ?? []; + list.push(r); + comps.set(r.comp, list); + } + const left = new Set(comps.keys()); + while (left.size) { + // The component nearest to the tool. + let next = -1, bd = Infinity; + for (const c of left) { + const rs = comps.get(c)!; + for (const r of rs) { + const d = Number.isNaN(b.x) ? 0 : (r.pts[0] - b.x) ** 2 + (r.pts[1] - b.y) ** 2; + if (d < bd) { bd = d; next = c; } + } + } + left.delete(next); + const rs = comps.get(next)!; + const maxLevel = Math.max(...rs.map((r) => r.level)); + let first = true; + for (let lv = maxLevel; lv >= 0; lv--) { + const pending = rs.filter((r) => r.level === lv); + while (pending.length) { + // Nearest loop of this level. + let bi = 0, bdist = Infinity; + pending.forEach((r, i) => { + for (let k = 0; k < r.pts.length; k += 2) { + const d = Number.isNaN(b.x) ? 0 : (r.pts[k] - b.x) ** 2 + (r.pts[k + 1] - b.y) ** 2; + if (d < bdist) { bdist = d; bi = i; } + } + }); + const ring = pending.splice(bi, 1)[0]; + const pts = Number.isNaN(b.x) ? ring.pts : this.startNear(ring.pts, b.x, b.y); + if (first) { + first = false; + this.entryInto(g, s, label, next, pts, z, zPrev, o); + } else if (Math.sqrt(bdist) <= o.stepover * 1.6 + g.c && b.z === z && this.insideAlong(g, s, b.x, b.y, pts[0], pts[1], g.c * 0.25)) { + b.feed(pts[0], pts[1], z); + this.loop(pts, z); + } else { + this.enter(pts[0], pts[1], zPrev, z); + this.loop(pts, z); + } + } + } + } + } + + /** Into the material at the first pass of a region: a helix at its deepest point, a ramp or a plunge. */ + private entryInto(g: GridSpec, s: Float64Array, label: Int32Array, comp: number, pts: number[], z: number, zPrev: number, o: { climb: boolean; entry: 'helix' | 'ramp' | 'plunge'; rampAngle: number }) { + const b = this.b; + const zFrom = Math.min(zPrev + 0.5, b.retract); + // Outside the stock: no material to enter. + const st = this.part.frame.stock; + const outside = (x: number, y: number) => x < st.min[0] - this.R || x > st.max[0] + this.R || y < st.min[1] - this.R || y > st.max[1] + this.R; + if (outside(pts[0], pts[1])) { + this.enter(pts[0], pts[1], zPrev, z); + this.loop(pts, z); + return; + } + if (o.entry === 'helix') { + // The deepest point of the region. + let best = -1, bv = -Infinity; + for (let k = 0; k < s.length; k++) if (label[k] === comp && s[k] > bv) { bv = s[k]; best = k; } + const rh = Math.min(bv * 0.9, this.R * 0.9); + if (best >= 0 && rh >= this.R * 0.15) { + const cx = g.x0 + (best % g.nx) * g.c, cy = g.y0 + Math.floor(best / g.nx) * g.c; + const pitch = 2 * Math.PI * rh * Math.tan((clamp(o.rampAngle, 0.5, 45) * Math.PI) / 180); + b.rapidTo(cx + rh, cy, b.retract); + b.hop(b.retract, cx + rh, cy, Math.max(zFrom, z)); + this.helix(cx, cy, rh, Math.max(zFrom, z), z, pitch, o.climb); + const start = this.startNear(pts, b.x, b.y); + b.feed(start[0], start[1], z); + this.loop(start, z); + return; + } + } + if (o.entry !== 'plunge' && polyLength(pts, 2, true) > this.R) { + b.rapidTo(pts[0], pts[1], b.retract); + b.hop(b.retract, pts[0], pts[1], Math.max(zFrom, z)); + this.rampLoop(pts, Math.max(zFrom, z), z, o.rampAngle); + return; + } + this.enter(pts[0], pts[1], zPrev, z); + this.loop(pts, z); + } + + private zigzagPasses(g: GridSpec, s: Float64Array, z: number, zPrev: number, o: { stepover: number; entry: 'helix' | 'ramp' | 'plunge'; rampAngle: number }) { + const b = this.b; + const y0 = g.y0, y1 = g.y0 + (g.ny - 1) * g.c; + let row = 0, prevEnd: [number, number] | null = null; + for (let y = y0 + o.stepover * 0.5; y <= y1; y += o.stepover, row++) { + // Runs along the row where the region is. + const runs: [number, number][] = []; + let start: number | null = null; + const step = g.c * 0.5; + const x1 = g.x0 + (g.nx - 1) * g.c; + for (let x = g.x0; x <= x1 + 1e-9; x += step) { + const v = sample(g, s, x, y); + if (v >= 0 && start === null) start = x; + if ((v < 0 || x + step > x1 + 1e-9) && start !== null) { + const end = v < 0 ? x - step : x; + if (end - start > g.c) runs.push([start, end]); + start = null; + } + } + if (row % 2) runs.reverse(); + for (const [ra, rb] of runs) { + const [xa, xb] = row % 2 ? [rb, ra] : [ra, rb]; + if (prevEnd && b.z === z && Math.abs(prevEnd[1] - y) <= o.stepover * 1.01 + 1e-9 && this.insideAlong(g, s, prevEnd[0], prevEnd[1], xa, y, g.c * 0.25)) { + b.feed(xa, y, z); + } else if (o.entry !== 'plunge' && Math.abs(xb - xa) > this.R) { + // Ramp back and forth along the start of the run. + const zFrom = Math.max(Math.min(zPrev + 0.5, b.retract), z); + b.rapidTo(xa, y, b.retract); + b.hop(b.retract, xa, y, zFrom); + const slope = Math.tan((clamp(o.rampAngle, 0.5, 89) * Math.PI) / 180); + const len = Math.min(Math.abs(xb - xa), Math.max(this.R * 2, 1)); + const dir = Math.sign(xb - xa); + let zc = zFrom, fwd = true, guard = 0; + while (zc > z + 1e-9 && guard++ < 1000) { + const nz = Math.max(z, zc - len * slope); + const frac = (zc - nz) / (len * slope); + const x = fwd ? xa + dir * len * frac : xa + dir * len * (1 - frac); + b.plunge(x, y, nz); + zc = nz; + fwd = !fwd; + } + b.feed(xa, y, z); + } else { + this.enter(xa, y, zPrev, z); + } + b.feed(xb, y, z); + prevEnd = [xb, y]; + } + } + } + + // ---------- operations ---------- + + face(op: FaceOp) { + const b = this.b; + const st = this.part.frame.stock; + const R = this.R; + const zEnd = this.partTop + (op.leave ?? 0); + const levels = stepLevels(this.stockTop, zEnd, op.stepdown); + const a = (op.angle * Math.PI) / 180; + const ca = Math.cos(a), sa = Math.sin(a); + // Stock corners in the pass frame (u along the passes, v across). + const corners = [[st.min[0], st.min[1]], [st.max[0], st.min[1]], [st.max[0], st.max[1]], [st.min[0], st.max[1]]]; + const us = corners.map(([x, y]) => x * ca + y * sa), vs = corners.map(([x, y]) => -x * sa + y * ca); + const u0 = Math.min(...us) - R - 2, u1 = Math.max(...us) + R + 2; + const v0 = Math.min(...vs), v1 = Math.max(...vs); + const lo = v0 + 0.4 * R, hi = v1 - 0.4 * R; + const n = hi > lo ? Math.ceil((hi - lo) / Math.max(op.stepover, 0.01)) + 1 : 1; + const vAt = (i: number) => (n === 1 ? (v0 + v1) / 2 : lo + ((hi - lo) * i) / (n - 1)); + const xy = (u: number, v: number): [number, number] => [u * ca - v * sa, u * sa + v * ca]; + this.steps = levels.length; + for (const z of levels) { + this.tick(); + for (let i = 0; i < n; i++) { + const v = vAt(i); + const [ua, ub] = i % 2 ? [u1, u0] : [u0, u1]; + const [xa, ya] = xy(ua, v), [xb, yb] = xy(ub, v); + if (i === 0) { + // Off the stock: straight down. + b.rapidTo(xa, ya, b.retract); + b.plunge(xa, ya, z); + } else b.feed(xa, ya, z); + b.feed(xb, yb, z); + } + b.rapidTo(b.x, b.y, b.retract); + } + } + + contour(op: ContourOp) { + const b = this.b; + const R = this.R; + const pb = this.part.frame.part; + const lead = Math.max(0, op.lead ?? 0); + const margin = R + op.leave + lead * 2 + 3; + const cutter = cutterOf(this.tool, op.leave); + const bottom = this.partBottom - Math.max(0, op.breakthrough); + const levels = stepLevels(this.stockTop, bottom, op.stepdown); + this.steps = levels.length + 1; + const r = this.region(pb.min[0] - margin, pb.min[1] - margin, pb.max[0] + margin, pb.max[1] + margin, cutter, 0, clamp(R / 6, 0.05, 0.4)); + this.tick(); + const climb = op.direction !== 'conventional'; + const tabTop = this.partBottom + Math.max(0, op.tabs?.height ?? 0); + const tabs = (op.tabs?.count ?? 0) > 0; + let zPrev = this.stockTop; + for (const z of levels) { + this.tick(); + const all = this.boundary(r, z, 0.005).filter((l) => l.closed); + // Loops round the part (clockwise, the part on the right), outermost only. + const around = all.filter((l) => area(l.pts) < 0); + const outer = around.filter((l) => !around.some((o) => o !== l && Math.abs(area(o.pts)) > Math.abs(area(l.pts)) && pointInPolygon(o.pts, l.pts[0], l.pts[1]))); + const pending = outer.map((l) => (climb ? l.pts : reverse2(l.pts.slice()))); + while (pending.length) { + let bi = 0, bd = Infinity; + pending.forEach((p, i) => { const d = Number.isNaN(b.x) ? 0 : (p[0] - b.x) ** 2 + (p[1] - b.y) ** 2; if (d < bd) { bd = d; bi = i; } }); + let pts = pending.splice(bi, 1)[0]; + pts = Number.isNaN(b.x) ? pts : this.startNear(pts, b.x, b.y); + pts = startOnStraight(pts); + const withTabs = tabs && z < tabTop - 1e-6; + this.contourPass(pts, z, zPrev, lead, climb, op.rampAngle, withTabs ? { ...op.tabs, top: tabTop } : null); + } + zPrev = z; + } + } + + private contourPass(pts: number[], z: number, zPrev: number, lead: number, climb: boolean, rampAngle: number, tabs: { count: number; width: number; top: number } | null) { + const b = this.b; + const n = pts.length / 2; + const x0 = pts[0], y0 = pts[1]; + const tx = pts[2] - x0, ty = pts[3] - y0; + const tl = Math.hypot(tx, ty) || 1; + const T = [tx / tl, ty / tl]; + // Air is on the left when climbing (the part on the right), on the right otherwise. + const side = climb ? 1 : -1; + const N = [-T[1] * side, T[0] * side]; + const zStart = Math.min(zPrev, this.stockTop) + 0.5; + const arc = (cx: number, cy: number, from: number, sweep: number, zz: number, kind: 'feed' | 'plunge') => { + const steps = 12; + for (let i = 1; i <= steps; i++) { + const a = from + (sweep * i) / steps; + const px = cx + lead * Math.cos(a), py = cy + lead * Math.sin(a); + if (kind === 'feed') b.feed(px, py, zz); else b.plunge(px, py, zz); + } + }; + // Lead-in: a quarter arc from the air side, tangent at the start. + if (lead > 1e-6) { + const cx = x0 + N[0] * lead, cy = y0 + N[1] * lead; + const aStart = Math.atan2(-T[1], -T[0]); + const sx = cx + lead * Math.cos(aStart), sy = cy + lead * Math.sin(aStart); + b.rapidTo(sx, sy, b.retract); + b.hop(b.retract, sx, sy, zStart); + b.plunge(sx, sy, zStart); + const aEnd = Math.atan2(-N[1], -N[0]); + let sweep = aEnd - aStart; + while (sweep > Math.PI) sweep -= 2 * Math.PI; + while (sweep < -Math.PI) sweep += 2 * Math.PI; + arc(cx, cy, aStart, sweep, zStart, 'feed'); + } else { + b.rapidTo(x0, y0, b.retract); + b.hop(b.retract, x0, y0, zStart); + } + // Ramp down along the loop, then once round at depth. + if (!tabs) this.rampLoop(pts, zStart, z, rampAngle); + else { + this.rampLoop(pts, zStart, Math.max(z, tabs.top), rampAngle); + // Lifted over the tabs on the last levels. + const len = polyLength(pts, 2, true); + const span = tabs.width + this.R * 2; + const centers = Array.from({ length: tabs.count }, (_, i) => ((i + 0.5) * len) / tabs.count); + const inTab = (s: number) => centers.some((c) => Math.abs(s - c) < span / 2); + const zAt = (s: number) => (inTab(s) ? Math.max(z, tabs.top) : z); + let s = 0; + b.plunge(x0, y0, zAt(0)); + for (let i = 1; i <= n; i++) { + const a = (i - 1) % n, c = i % n; + const ax = pts[a * 2], ay = pts[a * 2 + 1], cx = pts[c * 2], cy = pts[c * 2 + 1]; + const l = Math.hypot(cx - ax, cy - ay); + // Split the segment where it enters or leaves a tab. + const cuts = [0, 1]; + for (const ct of centers) for (const e of [ct - span / 2, ct + span / 2]) { const t = (e - s) / (l || 1); if (t > 0 && t < 1) cuts.push(t); } + cuts.sort((p, q) => p - q); + for (let k = 1; k < cuts.length; k++) { + const t0 = cuts[k - 1], t1 = cuts[k]; + const zz = zAt(s + l * (t0 + t1) / 2); + const px = ax + (cx - ax) * t0, py = ay + (cy - ay) * t0; + if (Math.abs(b.z - zz) > 1e-9) b.plunge(px, py, zz); + b.feed(ax + (cx - ax) * t1, ay + (cy - ay) * t1, zz); + } + s += l; + } + } + // Lead-out: a quarter arc back to the air side. + if (lead > 1e-6) { + const ex = b.x, ey = b.y; + const cx = ex + N[0] * lead, cy = ey + N[1] * lead; + const aStart = Math.atan2(-N[1], -N[0]); + const aEnd = Math.atan2(T[1], T[0]); + let sweep = aEnd - aStart; + while (sweep > Math.PI) sweep -= 2 * Math.PI; + while (sweep < -Math.PI) sweep += 2 * Math.PI; + arc(cx, cy, aStart, sweep, b.z, 'feed'); + } + b.rapid(b.x, b.y, b.retract); + } + + pocket(op: PocketOp) { + const floors = this.input.floors ?? []; + if (!floors.length) throw new CamError('Pick the floor faces of the pockets.'); + const R = this.R; + // Group the floors by height. + const groups = new Map(); + for (const t of floors) { + let zs = 0, n = 0, flat = true; + for (let i = 0; i < t.length; i += 9) { + const ux = t[i + 3] - t[i], uy = t[i + 4] - t[i + 1], uz = t[i + 5] - t[i + 2], vx = t[i + 6] - t[i], vy = t[i + 7] - t[i + 1], vz = t[i + 8] - t[i + 2]; + const nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx; + const l = Math.hypot(nx, ny, nz); + if (l > 1e-12 && Math.abs(nz) / l < 0.999) flat = false; + zs += t[i + 2] + t[i + 5] + t[i + 8]; + n += 3; + } + if (!flat || !n) { this.b.warnings.push('A picked face is not flat and facing the tool; it was skipped.'); continue; } + const z = Math.round((zs / n) * 1e4) / 1e4; + const key = [...groups.keys()].find((k) => Math.abs(k - z) < 1e-3) ?? z; + groups.set(key, [...(groups.get(key) ?? []), t]); + } + const order = [...groups.keys()].sort((a, c) => c - a); + this.steps = order.reduce((s, z) => s + stepLevels(this.stockTop, z + op.floorLeave, op.stepdown).length + 1, 0); + for (const zf of order) { + const tris = groups.get(zf)!; + let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity; + for (const t of tris) for (let i = 0; i < t.length; i += 3) { x0 = Math.min(x0, t[i]); x1 = Math.max(x1, t[i]); y0 = Math.min(y0, t[i + 1]); y1 = Math.max(y1, t[i + 1]); } + const m = R + 2; + const r = this.region(x0 - m, y0 - m, x1 + m, y1 + m, cutterOf(this.tool, op.leave), 0); + this.tick(); + // Near the floor: the tool must reach over it. + const g = r.grid; + const on = new Uint8Array(g.nx * g.ny); + for (const t of tris) rasterTriangles(g, t, on); + const d2 = edt(g, (k) => !!on[k]); + const dist = new Float64Array(d2.length); + for (let k = 0; k < d2.length; k++) dist[k] = Math.sqrt(d2[k]) * g.c; + const reach = R * 0.98; + r.limit = dist.map((d) => reach - d); + r.limitAt = (x, y) => reach - sample(g, dist, x, y); + const levels = stepLevels(this.stockTop, zf + op.floorLeave, op.stepdown); + this.clear(r, levels, { stepover: op.stepover, pattern: op.pattern, climb: op.direction !== 'conventional', entry: op.entry, rampAngle: op.rampAngle, tol: 0.005, materialTop: this.stockTop }); + } + } + + rough(op: RoughOp) { + const st = this.part.frame.stock; + const R = this.R; + const m = R + 2; + const cutter = cutterOf(this.tool, op.leave); + const flats = flatHeights(this.part.tris, this.partBottom, this.stockTop).map((h) => h + op.floorLeave); + const levels = stepLevels(this.stockTop, this.partBottom + op.floorLeave, op.stepdown, flats); + this.steps = levels.length + 1; + const r = this.region(st.min[0] - m, st.min[1] - m, st.max[0] + m, st.max[1] + m, cutter, op.floorLeave); + this.tick(); + if (st.min[2] >= this.partBottom - 1e-6) this.b.warnings.push('The roughing goes down to the bottom of the part, which is the bottom of the stock. Leave stock below the part (Setup: stock below) to keep it held.'); + // The tool stays within the stock (plus most of its radius, to cut its edges). + const gx = R * 0.9; + const lim = (x: number, y: number) => Math.min(x - (st.min[0] - gx), st.max[0] + gx - x, y - (st.min[1] - gx), st.max[1] + gx - y); + const g = r.grid; + r.limit = new Float64Array(g.nx * g.ny); + for (let j = 0; j < g.ny; j++) for (let i = 0; i < g.nx; i++) r.limit[j * g.nx + i] = lim(g.x0 + i * g.c, g.y0 + j * g.c); + r.limitAt = lim; + this.clear(r, levels, { stepover: op.stepover, pattern: op.pattern, climb: op.direction !== 'conventional', entry: op.entry, rampAngle: op.rampAngle, tol: 0.01, materialTop: this.stockTop }); + } + + /** Holes that open toward the tool, from the cylinders. */ + private holes(picked: boolean, diameter: number | null) { + const cyl = (this.input.cylinders ?? []).filter((c) => Math.abs(Math.abs(c.d[2]) - 1) < 1e-3 && (!picked || c.picked)); + // Merge faces of the same hole (split cylinders). + const holes: { x: number; y: number; r: number; top: number; bottom: number }[] = []; + for (const c of cyl) { + let top = -Infinity, bottom = Infinity; + for (let i = 2; i < c.tris.length; i += 3) { top = Math.max(top, c.tris[i]); bottom = Math.min(bottom, c.tris[i]); } + if (!Number.isFinite(top)) continue; + const h = holes.find((o) => Math.hypot(o.x - c.p[0], o.y - c.p[1]) < 1e-3 && Math.abs(o.r - c.radius) < 1e-3); + if (h) { h.top = Math.max(h.top, top); h.bottom = Math.min(h.bottom, bottom); } else holes.push({ x: c.p[0], y: c.p[1], r: c.radius, top, bottom }); + } + const pin = new DropCutter(this.part.index, makeCutter('flat', 1e-3, 0, 0)); + const out: { x: number; y: number; r: number; top: number; bottom: number; through: boolean }[] = []; + for (const h of holes) { + if (diameter != null && Math.abs(2 * h.r - diameter) > Math.max(0.05, diameter * 0.01)) continue; + // A hole, not a boss: nothing at its centre down to its bottom. + const centre = pin.drop(h.x, h.y); + if (centre > h.bottom + 1e-3) continue; + // Reachable from above: a cutter nearly as wide goes down to the bottom. + const wide = new DropCutter(this.part.index, makeCutter('flat', h.r * 0.95, 0, 0)).drop(h.x, h.y); + if (wide > h.bottom + 1e-3) continue; + const point = h.r / Math.tan((59 * Math.PI) / 180); + out.push({ ...h, through: centre < h.bottom - point - 1e-2 }); + } + return nearestOrder(out); + } + + drill(op: DrillOp) { + const b = this.b; + const anyPicked = (this.input.cylinders ?? []).some((c) => c.picked); + const holes = this.holes(anyPicked, anyPicked ? null : this.tool.diameter); + if (!holes.length) { + b.warnings.push(anyPicked ? 'None of the picked faces is a hole that opens toward the tool.' : `No hole of the tool's diameter (${this.tool.diameter} mm) opens toward the tool. Pick the holes to drill.`); + return; + } + const tip = this.tool.type === 'drill' || this.tool.type === 'chamfer' ? this.R / Math.tan(((this.tool.tipAngle ?? 118) / 2) * Math.PI / 180) : 0; + this.steps = holes.length; + for (const h of holes) { + this.tick(); + if (Math.abs(2 * h.r - this.tool.diameter) > Math.max(0.05, h.r * 0.02)) b.warnings.push(`A hole of ${(2 * h.r).toFixed(3)} mm is drilled with a ${this.tool.diameter} mm tool.`); + const z = h.through ? h.bottom - Math.max(0, op.breakthrough) - (op.tipThrough ? tip : 0) : h.bottom; + b.cycle(h.x, h.y, { cycle: op.cycle, r: h.top + this.input.setup.retract, z, peck: op.cycle === 'drill' ? 0 : Math.max(0.05, op.peck), dwell: Math.max(0, op.dwell) }); + } + } + + bore(op: BoreOp) { + const b = this.b; + const anyPicked = (this.input.cylinders ?? []).some((c) => c.picked); + const holes = this.holes(anyPicked, null).filter((h) => h.r - op.leave > this.R * 1.05); + if (!holes.length) { b.warnings.push(anyPicked ? 'No picked hole is larger than the tool.' : 'Pick the holes to bore; they must be larger than the tool.'); return; } + if (!anyPicked) b.warnings.push('No holes picked: every hole larger than the tool is bored.'); + this.steps = holes.length; + const climb = op.direction !== 'conventional'; + for (const h of holes) { + this.tick(); + const rh = h.r - op.leave - this.R; + const z = h.through ? h.bottom - Math.max(0, op.breakthrough) : h.bottom; + const zFrom = h.top + 0.5; + b.rapidTo(h.x + rh, h.y, h.top + this.input.setup.retract); + b.rapid(h.x + rh, h.y, zFrom + 0.5); + this.helix(h.x, h.y, rh, zFrom, z, Math.max(0.05, op.pitch), climb); + // Away from the wall and out through the middle. + b.feed(h.x, h.y, z); + b.rapid(h.x, h.y, h.top + this.input.setup.retract); + } + } + + parallel(op: ParallelOp) { + const R = this.R; + const cutter = cutterOf(this.tool, op.leave); + const dc = new DropCutter(this.part.index, cutter); + const pb = this.part.frame.part; + const st = this.part.frame.stock; + const box = op.boundary === 'stock' ? { x0: st.min[0], y0: st.min[1], x1: st.max[0], y1: st.max[1] } : { x0: pb.min[0] - R, y0: pb.min[1] - R, x1: pb.max[0] + R, y1: pb.max[1] + R }; + const floor = this.partBottom; + const a = (op.angle * Math.PI) / 180, ca = Math.cos(a), sa = Math.sin(a); + const cs = [[box.x0, box.y0], [box.x1, box.y0], [box.x1, box.y1], [box.x0, box.y1]]; + const us = cs.map(([x, y]) => x * ca + y * sa), vs = cs.map(([x, y]) => -x * sa + y * ca); + const u0 = Math.min(...us), u1 = Math.max(...us), v0 = Math.min(...vs), v1 = Math.max(...vs); + const xy = (u: number, v: number): [number, number] => [u * ca - v * sa, u * sa + v * ca]; + const inBox = (x: number, y: number) => x >= box.x0 - 1e-9 && x <= box.x1 + 1e-9 && y >= box.y0 - 1e-9 && y <= box.y1 + 1e-9; + const ds = clamp(Math.min(op.stepover, R / 4), 0.05, 0.25); + const step = Math.max(op.stepover, 0.01); + const nLines = Math.max(1, Math.floor((v1 - v0) / step) + 1); + const vStart = v0 + ((v1 - v0) - (nLines - 1) * step) / 2; + this.steps = nLines; + const zAt = (x: number, y: number) => { + const z = dc.drop(x, y); + if (z <= NO_CONTACT / 2) return op.boundary === 'stock' ? floor + op.leave : null; + return z + op.leave; + }; + const runs: number[][] = []; + for (let li = 0; li < nLines; li++) { + this.tick(); + const v = vStart + li * step; + const nu = Math.max(1, Math.ceil((u1 - u0) / ds)); + let cur: number[] = []; + const lineRuns: number[][] = []; + for (let k = 0; k <= nu; k++) { + const u = u0 + ((u1 - u0) * k) / nu; + const [x, y] = xy(u, v); + const z = inBox(x, y) ? zAt(x, y) : null; + if (z === null) { if (cur.length >= 6) lineRuns.push(cur); cur = []; continue; } + cur.push(x, y, z); + } + if (cur.length >= 6) lineRuns.push(cur); + if (li % 2) { lineRuns.reverse(); for (const r of lineRuns) reverse3(r); } + for (const r of lineRuns) runs.push(simplify(r, Math.max(op.tolerance, 1e-4), 3)); + } + this.linkRuns(runs, dc, op.leave, op.stepover, ds); + } + + /** Cuts 3D runs in order, staying down over short gaps (following the surface) and lifting over long ones. */ + private linkRuns(runs: number[][], dc: DropCutter, lift: number, stepover: number, ds: number) { + const b = this.b; + for (const r of runs) { + const x = r[0], y = r[1], z = r[2]; + const gap = Number.isNaN(b.x) ? Infinity : Math.hypot(x - b.x, y - b.y); + if (gap <= stepover * 2 + ds && b.z < b.retract) { + // Follow the surface across. + const n = Math.max(1, Math.ceil(gap / ds)); + const px = b.x, py = b.y; + for (let k = 1; k < n; k++) { + const qx = px + ((x - px) * k) / n, qy = py + ((y - py) * k) / n; + const qz = dc.drop(qx, qy); + b.feed(qx, qy, Math.max(qz + lift, Math.min(b.z, z))); + } + b.feed(x, y, z); + } else { + b.rapidTo(x, y, b.retract); + b.hop(b.retract, x, y, Math.min(b.retract, z + 1)); + b.plunge(x, y, z); + } + for (let i = 3; i < r.length; i += 3) b.feed(r[i], r[i + 1], r[i + 2]); + } + } + + waterline(op: WaterlineOp) { + const b = this.b; + const R = this.R; + const pb = this.part.frame.part; + const m = R + op.leave + 3; + const cutter = cutterOf(this.tool, op.leave); + const topZ = this.partTop + op.leave; + const levels = stepLevels(topZ, this.partBottom + op.leave + 1e-3, op.stepdown); + this.steps = levels.length + 1; + const r = this.region(pb.min[0] - m, pb.min[1] - m, pb.max[0] + m, pb.max[1] + m, cutter, op.leave, clamp(R / 6, 0.05, 0.4)); + this.tick(); + const climb = op.direction !== 'conventional'; + for (const z of levels) { + this.tick(); + const loops = this.boundary(r, z, Math.max(op.tolerance, 1e-4)).filter((l) => l.closed); + const pending = loops.map((l) => (climb ? l.pts : reverse2(l.pts.slice()))); + while (pending.length) { + let bi = 0, bd = Infinity; + pending.forEach((p, i) => { for (let k = 0; k < p.length; k += 2) { const d = Number.isNaN(b.x) ? 0 : (p[k] - b.x) ** 2 + (p[k + 1] - b.y) ** 2; if (d < bd) { bd = d; bi = i; } } }); + const raw = pending.splice(bi, 1)[0]; + const pts = Number.isNaN(b.x) ? raw : this.startNear(raw, b.x, b.y); + b.rapidTo(pts[0], pts[1], b.retract); + b.hop(b.retract, pts[0], pts[1], Math.min(b.retract, z + 1)); + b.plunge(pts[0], pts[1], z); + this.loop(pts, z); + b.rapid(b.x, b.y, Math.min(b.retract, z + 1)); + } + } + } +} + +/** Reverses a 2D point list in place (keeping its first point first). */ +function reverse2(pts: number[]): number[] { + const n = pts.length / 2; + const out: number[] = [pts[0], pts[1]]; + for (let i = n - 1; i >= 1; i--) out.push(pts[i * 2], pts[i * 2 + 1]); + for (let i = 0; i < pts.length; i++) pts[i] = out[i]; + return pts; +} + +function reverse3(pts: number[]) { + const n = pts.length / 3; + for (let i = 0, j = n - 1; i < j; i++, j--) for (let k = 0; k < 3; k++) { const t = pts[i * 3 + k]; pts[i * 3 + k] = pts[j * 3 + k]; pts[j * 3 + k] = t; } +} + +/** Starts a closed loop in the middle of its longest segment (leads and tabs sit better there than on a corner). */ +function startOnStraight(pts: number[]): number[] { + const n = pts.length / 2; + let best = 0, bl = -1; + for (let i = 0; i < n; i++) { + const j = (i + 1) % n; + const l = Math.hypot(pts[j * 2] - pts[i * 2], pts[j * 2 + 1] - pts[i * 2 + 1]); + if (l > bl) { bl = l; best = i; } + } + const j = (best + 1) % n; + const mx = (pts[best * 2] + pts[j * 2]) / 2, my = (pts[best * 2 + 1] + pts[j * 2 + 1]) / 2; + const out = [mx, my]; + for (let k = 1; k <= n; k++) { const q = (best + k) % n; out.push(pts[q * 2], pts[q * 2 + 1]); } + return out; +} + +/** 4-connected components of a node mask (labels from 1; 0 outside). */ +function components(g: GridSpec, m: Uint8Array): Int32Array { + const label = new Int32Array(m.length); + let next = 0; + const stack: number[] = []; + for (let k = 0; k < m.length; k++) { + if (!m[k] || label[k]) continue; + next++; + label[k] = next; + stack.push(k); + while (stack.length) { + const p = stack.pop()!; + const i = p % g.nx, j = (p - i) / g.nx; + const nb = [i > 0 ? p - 1 : -1, i < g.nx - 1 ? p + 1 : -1, j > 0 ? p - g.nx : -1, j < g.ny - 1 ? p + g.nx : -1]; + for (const q of nb) if (q >= 0 && m[q] && !label[q]) { label[q] = next; stack.push(q); } + } + } + return label; +} + +/** Sets the nodes covered by the triangles (projected on XY). */ +function rasterTriangles(g: GridSpec, t: Float64Array, out: Uint8Array) { + for (let o = 0; o + 8 < t.length; o += 9) { + const ax = t[o], ay = t[o + 1], bx = t[o + 3], by = t[o + 4], cx = t[o + 6], cy = t[o + 7]; + const i0 = Math.max(0, Math.ceil((Math.min(ax, bx, cx) - g.x0) / g.c)), i1 = Math.min(g.nx - 1, Math.floor((Math.max(ax, bx, cx) - g.x0) / g.c)); + const j0 = Math.max(0, Math.ceil((Math.min(ay, by, cy) - g.y0) / g.c)), j1 = Math.min(g.ny - 1, Math.floor((Math.max(ay, by, cy) - g.y0) / g.c)); + const d = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay); + if (Math.abs(d) < 1e-14) continue; + for (let j = j0; j <= j1; j++) { + const y = g.y0 + j * g.c; + for (let i = i0; i <= i1; i++) { + const x = g.x0 + i * g.c; + const w1 = ((bx - x) * (cy - y) - (cx - x) * (by - y)) / d; + const w2 = ((cx - x) * (ay - y) - (ax - x) * (cy - y)) / d; + const w3 = 1 - w1 - w2; + if (w1 >= -1e-9 && w2 >= -1e-9 && w3 >= -1e-9) out[j * g.nx + i] = 1; + } + } + } +} + +/** Heights of the part's flat areas facing the tool, between two heights. */ +export function flatHeights(tris: Float64Array, lo: number, hi: number): number[] { + const out: number[] = []; + for (let o = 0; o + 8 < tris.length; o += 9) { + const ux = tris[o + 3] - tris[o], uy = tris[o + 4] - tris[o + 1], uz = tris[o + 5] - tris[o + 2]; + const vx = tris[o + 6] - tris[o], vy = tris[o + 7] - tris[o + 1], vz = tris[o + 8] - tris[o + 2]; + const nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx; + const l = Math.hypot(nx, ny, nz); + if (l < 1e-12 || Math.abs(nz) / l < 0.99999) continue; + const z = (tris[o + 2] + tris[o + 5] + tris[o + 8]) / 3; + if (z <= lo + 1e-6 || z >= hi - 1e-6) continue; + if (out.every((h) => Math.abs(h - z) > 0.005)) out.push(z); + } + return out; +} + +function nearestOrder(items: T[]): T[] { + const left = items.slice(); + const out: T[] = []; + let x = 0, y = 0; + while (left.length) { + let bi = 0, bd = Infinity; + left.forEach((h, i) => { const d = (h.x - x) ** 2 + (h.y - y) ** 2; if (d < bd) { bd = d; bi = i; } }); + const h = left.splice(bi, 1)[0]; + out.push(h); + x = h.x; y = h.y; + } + return out; +} + +/** Was generation stopped (a newer request replaced it)? */ +export const isCancelled = (e: unknown) => e instanceof Cancelled; diff --git a/src/parametric/src/cam/post.ts b/src/parametric/src/cam/post.ts new file mode 100644 index 000000000..de54559c4 --- /dev/null +++ b/src/parametric/src/cam/post.ts @@ -0,0 +1,301 @@ +// Post processing: toolpaths to G-code for a controller. Straight feeds that +// follow circles are written as arcs (G2/G3, helical when the height changes +// steadily), drilling as canned cycles where the controller has them. + +import type { CamController, CamPost, CamTool } from '../model/cam'; +import { CYCLE, PLUNGE, RAPID, type CycleInfo, type Toolpath, expandMoves } from './toolpath'; + +export interface PostOperation { + name: string; + tool: CamTool; + rpm: number; + feed: number; + plunge: number; + toolpath: Toolpath; +} + +export interface PostSetup { + name: string; + workOffset: number; + ops: PostOperation[]; +} + +export interface PostJob { + /** Program name (the part's). */ + name: string; + post: CamPost; + units: 'mm' | 'in'; + setups: PostSetup[]; + /** Comment lines for the header (date, generator...). */ + notes?: string[]; +} + +interface Dialect { + percent: boolean; + oNumber: boolean; + toolChange: 'm6' | 'pause'; + lengthComp: boolean; + home: boolean; + canned: boolean; + /** G82 dwell word: milliseconds (Fanuc, Haas) or seconds. */ + dwellMs: boolean; + end: string; +} + +const DIALECTS: Record = { + fanuc: { percent: true, oNumber: true, toolChange: 'm6', lengthComp: true, home: true, canned: true, dwellMs: true, end: 'M30' }, + haas: { percent: true, oNumber: true, toolChange: 'm6', lengthComp: true, home: true, canned: true, dwellMs: true, end: 'M30' }, + mach3: { percent: false, oNumber: false, toolChange: 'm6', lengthComp: true, home: false, canned: true, dwellMs: false, end: 'M30' }, + linuxcnc: { percent: true, oNumber: false, toolChange: 'm6', lengthComp: true, home: false, canned: true, dwellMs: false, end: 'M2' }, + // Grbl has no tool changer, no tool length offsets and no canned cycles. + grbl: { percent: false, oNumber: false, toolChange: 'pause', lengthComp: false, home: false, canned: false, dwellMs: false, end: 'M30' }, +}; + +/** Comment text safe inside parentheses. */ +const comment = (s: string) => `(${s.replace(/[()]/g, '').replace(/[^\x20-\x7e]/g, '?').trim().slice(0, 120)})`; + +export function postProcess(job: PostJob): string { + const d = DIALECTS[job.post.controller]; + const inch = job.units === 'in'; + const k = inch ? 1 / 25.4 : 1; + const dec = inch ? 4 : 3; + const num = (v: number) => { + let s = (v * k).toFixed(dec); + if (s.includes('.')) s = s.replace(/0+$/, ''); + if (s === '-0.' || s === '-0') s = '0.'; + return s; + }; + const feedNum = (v: number) => { + const f = v * k; + let s = f.toFixed(inch ? 2 : 1); + s = s.replace(/0+$/, ''); + return s; + }; + const lines: string[] = []; + let n = 0; + const out = (s: string) => { + if (job.post.lineNumbers && s && !s.startsWith('%') && !s.startsWith('O')) { n += 10; lines.push(`N${n} ${s}`); } + else lines.push(s); + }; + if (d.percent) lines.push('%'); + if (d.oNumber) lines.push(`O${String(job.post.program).padStart(4, '0')} ${comment(job.name)}`); + else out(comment(job.name)); + for (const note of job.notes ?? []) out(comment(note)); + // Tool list. + const tools = new Map(); + for (const s of job.setups) for (const o of s.ops) tools.set(o.tool.number, o.tool); + for (const t of [...tools.values()].sort((a, b) => a.number - b.number)) out(comment(`T${t.number} D=${num(t.diameter)} ${t.name}`)); + out(job.post.controller === 'grbl' ? 'G90 G94 G17' : 'G90 G94 G17 G40 G49 G80'); + out(inch ? 'G20' : 'G21'); + if (d.home) { out('G28 G91 Z0.'); out('G90'); } + + // Modal state. + let x = NaN, y = NaN, z = NaN, f = NaN, motion = ''; + let tool: number | null = null; + let lengthDone = false; + const words = (nx: number, ny: number, nz: number) => { + let s = ''; + if (num(nx) !== num(x)) s += ` X${num(nx)}`; + if (num(ny) !== num(y)) s += ` Y${num(ny)}`; + if (num(nz) !== num(z)) s += ` Z${num(nz)}`; + return s; + }; + const rapid = (nx: number, ny: number, nz: number) => { + const w = words(nx, ny, nz); + if (!w) return; + out(`${motion === 'G0' ? '' : 'G0'}${w}`.trim()); + motion = 'G0'; + x = nx; y = ny; z = nz; + }; + const linear = (nx: number, ny: number, nz: number, feed: number) => { + const w = words(nx, ny, nz); + if (!w) return; + const fw = feedNum(feed) !== feedNum(f) ? ` F${feedNum(feed)}` : ''; + out(`${motion === 'G1' ? '' : 'G1'}${w}${fw}`.trim()); + motion = 'G1'; + x = nx; y = ny; z = nz; f = feed; + }; + const arc = (cw: boolean, nx: number, ny: number, nz: number, cx: number, cy: number, feed: number) => { + const g = cw ? 'G2' : 'G3'; + let w = ` X${num(nx)} Y${num(ny)}`; + if (num(nz) !== num(z)) w += ` Z${num(nz)}`; + w += ` I${num(cx - x)} J${num(cy - y)}`; + const fw = feedNum(feed) !== feedNum(f) ? ` F${feedNum(feed)}` : ''; + out(`${g}${w}${fw}`); + motion = g; + x = nx; y = ny; z = nz; f = feed; + }; + const dwell = (sec: number) => { + if (sec <= 0) return; + out(job.post.controller === 'fanuc' || job.post.controller === 'haas' ? `G4 X${sec.toFixed(2)}` : `G4 P${sec.toFixed(2)}`); + }; + + for (const setup of job.setups) { + out(comment(setup.name)); + for (const op of setup.ops) { + out(comment(op.name)); + const t = op.tool; + if (tool !== t.number) { + if (tool !== null) { + out('M9'); + out('M5'); + if (d.home) { out('G28 G91 Z0.'); out('G90'); } + } + if (d.toolChange === 'm6') out(`T${t.number} M6`); + else { out(comment(`Change to T${t.number} ${t.name}`)); if (tool !== null) out('M0'); } + tool = t.number; + lengthDone = false; + x = y = z = f = NaN; + motion = ''; + } + out(`S${Math.round(op.rpm)} M3`); + out(`G${setup.workOffset}`); + if (t.coolant) out('M8'); + const moves = op.toolpath.moves; + // The first move: across at the clearance height, then down with the length offset. + const clear = op.toolpath.clearance; + if (!lengthDone) { + if (moves.length >= 4) { + // Up first, where the tool is, then across. + if (!d.lengthComp && num(z) !== num(clear)) { out(`G0 Z${num(clear)}`); z = clear; motion = 'G0'; } + const fx = moves[1], fy = moves[2]; + if (d.lengthComp) { + out(`G0 X${num(fx)} Y${num(fy)}`); + out(`G43 Z${num(clear)} H${t.number}`); + x = fx; y = fy; z = clear; motion = 'G0'; + } else rapid(fx, fy, clear); + } + lengthDone = true; + } + // Moves, with arcs fitted over runs of feeds. + const feedOf = (kind: number) => (kind === PLUNGE ? op.plunge : op.feed); + const flushRun = (run: number[], kind: number) => { + if (!run.length) return; + const pts = [x, y, z, ...run]; + if (job.post.arcs) { + writeArcs(pts, 0.005, (px, py, pz) => linear(px, py, pz, feedOf(kind)), (cw, px, py, pz, cx, cy) => arc(cw, px, py, pz, cx, cy, feedOf(kind))); + } else for (let i = 3; i < pts.length; i += 3) linear(pts[i], pts[i + 1], pts[i + 2], feedOf(kind)); + }; + let run: number[] = []; + let runKind = -1; + const cycles: CycleInfo[] = op.toolpath.cycles; + const canned = d.canned && job.post.cannedCycles; + let inCycle = ''; + const endCycle = () => { if (inCycle) { out('G80'); inCycle = ''; motion = ''; } }; + for (let i = 0; i < moves.length; i += 4) { + const kind = moves[i], mx = moves[i + 1], my = moves[i + 2], mz = moves[i + 3]; + if (kind !== runKind || kind === RAPID || kind === CYCLE) { flushRun(run, runKind); run = []; runKind = kind; } + if (kind === RAPID) { endCycle(); rapid(mx, my, mz); continue; } + if (kind === CYCLE) { + const c = cycles[mz]; + const peck = c.cycle !== 'drill' && c.peck > 0; + const dwellCanned = c.dwell > 0 && !peck && (job.post.controller === 'fanuc' || job.post.controller === 'haas' || job.post.controller === 'linuxcnc'); + if (canned && (c.dwell <= 0 || dwellCanned)) { + if (num(z) !== num(c.r) && !inCycle) rapid(x, y, c.r); + const code = peck ? (c.cycle === 'peck' ? 'G83' : 'G73') : c.dwell > 0 ? 'G82' : 'G81'; + if (inCycle !== code) { + const extra = peck ? ` Q${num(c.peck)}` : c.dwell > 0 ? ` P${d.dwellMs ? Math.round(c.dwell * 1000) : c.dwell.toFixed(2)}` : ''; + out(`G98 ${code} X${num(mx)} Y${num(my)} Z${num(c.z)} R${num(c.r)}${extra} F${feedNum(op.plunge)}`); + inCycle = code; + f = op.plunge; + } else out(`X${num(mx)} Y${num(my)}`); + x = mx; y = my; z = c.r; + } else { + endCycle(); + expandMoves({ moves: Float64Array.of(CYCLE, mx, my, mz), cycles, clearance: clear, warnings: [] }, (kk, ex, ey, ez, dw) => { + if (kk === RAPID) rapid(ex, ey, ez); + else { linear(ex, ey, ez, op.plunge); dwell(dw); } + }); + } + continue; + } + endCycle(); + run.push(mx, my, mz); + } + flushRun(run, runKind); + endCycle(); + } + } + out('M9'); + out('M5'); + if (d.home) { out('G28 G91 Z0.'); out('G90'); } + out(d.end); + if (d.percent) lines.push('%'); + return lines.join('\n') + '\n'; +} + +/** + * Writes a polyline (x, y, z triples; the first point is where the tool is) + * as lines and arcs: runs of at least four short segments whose points stay + * within `tol` of a circle in XY (their chords' middles within 4 × tol), that + * turn one way less than half a turn and descend evenly become one arc. + */ +export function writeArcs(pts: number[], tol: number, line: (x: number, y: number, z: number) => void, arc: (cw: boolean, x: number, y: number, z: number, cx: number, cy: number) => void) { + const n = pts.length / 3; + let i = 0; + const P = (k: number) => [pts[k * 3], pts[k * 3 + 1], pts[k * 3 + 2]]; + while (i < n - 1) { + let best = -1; + let bestFit: { cx: number; cy: number; cw: boolean } | null = null; + for (let j = i + 4; j < n && j - i <= 400; j++) { + const fit = fitArc(pts, i, j, tol); + if (!fit) break; + best = j; + bestFit = fit; + } + if (best > 0 && bestFit) { + const [ex, ey, ez] = P(best); + arc(bestFit.cw, ex, ey, ez, bestFit.cx, bestFit.cy); + i = best; + } else { + const [ex, ey, ez] = P(i + 1); + line(ex, ey, ez); + i++; + } + } +} + +function fitArc(pts: number[], i: number, j: number, tol: number): { cx: number; cy: number; cw: boolean } | null { + const m = (i + j) >> 1; + const ax = pts[i * 3], ay = pts[i * 3 + 1], bx = pts[m * 3], by = pts[m * 3 + 1], cx = pts[j * 3], cy = pts[j * 3 + 1]; + const d = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by)); + if (Math.abs(d) < 1e-12) return null; + const a2 = ax * ax + ay * ay, b2 = bx * bx + by * by, c2 = cx * cx + cy * cy; + const ox = (a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by)) / d; + const oy = (a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax)) / d; + const r = Math.hypot(ax - ox, ay - oy); + if (r < 0.05 || r > 5000) return null; + // One direction, under half a turn, every point and chord middle on the circle. + let sweep = 0, dir = 0; + const z0 = pts[i * 3 + 2], z1 = pts[j * 3 + 2]; + for (let k = i; k < j; k++) { + const px = pts[k * 3], py = pts[k * 3 + 1], qx = pts[(k + 1) * 3], qy = pts[(k + 1) * 3 + 1]; + const a0 = Math.atan2(py - oy, px - ox), a1 = Math.atan2(qy - oy, qx - ox); + let da = a1 - a0; + while (da > Math.PI) da -= 2 * Math.PI; + while (da < -Math.PI) da += 2 * Math.PI; + // Short steps only: a polygon's corners also lie on a circle. + if (Math.abs(da) < 1e-12 || Math.abs(da) > Math.PI / 12) return null; + const s = Math.sign(da); + if (dir === 0) dir = s; else if (s !== dir) return null; + sweep += da; + if (Math.abs(Math.hypot(qx - ox, qy - oy) - r) > tol) return null; + const mx = (px + qx) / 2, my = (py + qy) / 2; + // The arc bulges from the chords the points were sampled on; a little more is allowed there. + if (Math.abs(Math.hypot(mx - ox, my - oy) - r) > tol * 4) return null; + } + if (Math.abs(sweep) >= Math.PI * 0.999) return null; + // Height changes evenly with the angle (a helix) or not at all. + let acc = 0; + for (let k = i + 1; k <= j; k++) { + const px = pts[(k - 1) * 3], py = pts[(k - 1) * 3 + 1], qx = pts[k * 3], qy = pts[k * 3 + 1]; + let da = Math.atan2(qy - oy, qx - ox) - Math.atan2(py - oy, px - ox); + while (da > Math.PI) da -= 2 * Math.PI; + while (da < -Math.PI) da += 2 * Math.PI; + acc += da; + const zk = z0 + ((z1 - z0) * acc) / sweep; + if (Math.abs(zk - pts[k * 3 + 2]) > tol) return null; + } + return { cx: ox, cy: oy, cw: dir < 0 }; +} + diff --git a/src/parametric/src/cam/simulate.ts b/src/parametric/src/cam/simulate.ts new file mode 100644 index 000000000..af71682fc --- /dev/null +++ b/src/parametric/src/cam/simulate.ts @@ -0,0 +1,214 @@ +// Material removal simulation on a height map of the stock (a z-map): each +// move of each toolpath lowers the stock under the tool to the tool's +// surface. Records snapshots for playback, rapid moves that cut, material +// reaching above the flutes, and compares the result with the part (gouges +// and what is left to cut). + +import type { CamTool } from '../model/cam'; +import { cutterOf, DropCutter, NO_CONTACT, makeCutter, type TriIndex } from './dropcutter'; +import type { Box3 } from './frame'; +import { type GridSpec, gridOver } from './grid'; +import { PLUNGE, RAPID, type Toolpath, expandMoves } from './toolpath'; + +export interface SimStep { + toolpath: Toolpath; + tool: CamTool; + feed: number; + plunge: number; +} + +export interface SimInput { + stock: Box3; + part: TriIndex; + steps: SimStep[]; + rapidFeed: number; + /** Stock cell size (absent: chosen from the stock's size). */ + cell?: number; + /** Number of playback snapshots. */ + snapshots?: number; + /** Largest display grid side. */ + displaySide?: number; + cancelled?: () => boolean; + progress?: (f: number) => void; +} + +export interface SimSnapshot { + /** Seconds into the program. */ + time: number; + /** Stock heights on the display grid. */ + z: Float32Array; +} + +export interface SimResult { + /** Display grid (stock heights of snapshots and the part's top use it). */ + grid: GridSpec; + bottom: number; + top: number; + snapshots: SimSnapshot[]; + /** Height of the part's top surface on the display grid (NO_CONTACT where there is none). */ + partTop: Float32Array; + /** + * Tool positions for playback: x, y, z, seconds, step index, move kind per + * point (6 numbers each). + */ + timeline: Float32Array; + /** Total program time (seconds). */ + time: number; + /** Cells cut deeper than the part, and the deepest gouge. */ + gouges: number; + maxGouge: number; + /** Rapid moves that cut stock, per step. */ + rapidCuts: number[]; + /** Feed moves where the stock reached above the flutes, per step. */ + shankHits: number[]; + /** Thickest material left over the part, and the area left thicker than 0.1 mm (mm²). */ + maxRemaining: number; + remainingArea: number; + /** Removed volume (mm³). */ + removed: number; +} + +/** Simulates the steps in order on fresh stock. */ +export function simulate(input: SimInput): SimResult { + const st = input.stock; + const w = st.max[0] - st.min[0], d = st.max[1] - st.min[1]; + const cell = input.cell ?? Math.max(0.05, Math.sqrt((w * d) / 250_000)); + // Nodes at cell centres. + const g = gridOver(st.min[0] + cell / 2, st.min[1] + cell / 2, st.max[0] - cell / 2, st.max[1] - cell / 2, cell, 600_000); + const top = st.max[2], bottom = st.min[2]; + const z = new Float32Array(g.nx * g.ny).fill(top); + const startVolume = z.length * g.c * g.c * (top - bottom); + + // Display grid. + const side = input.displaySide ?? 220; + const fx = Math.max(1, Math.ceil(g.nx / side)), fy = Math.max(1, Math.ceil(g.ny / side)); + const dg: GridSpec = { x0: g.x0 + ((fx - 1) * g.c) / 2, y0: g.y0 + ((fy - 1) * g.c) / 2, c: g.c * fx, nx: Math.ceil(g.nx / fx), ny: Math.ceil(g.ny / fy) }; + // A display cell shows the lowest stock under it (cuts stay visible). + const down = (src: Float32Array): Float32Array => { + const out = new Float32Array(dg.nx * dg.ny).fill(Infinity); + for (let j = 0; j < g.ny; j++) { + const dj = Math.min(dg.ny - 1, Math.floor(j / fy)); + for (let i = 0; i < g.nx; i++) { + const k = dj * dg.nx + Math.min(dg.nx - 1, Math.floor(i / fx)); + const v = src[j * g.nx + i]; + if (v < out[k]) out[k] = v; + } + } + return out; + }; + + // Total time, for evenly spaced snapshots. + const times: number[] = []; + let total = 0; + for (const s of input.steps) { + let t = 0, px = NaN, py = NaN, pz = NaN; + expandMoves(s.toolpath, (k, x, y, zz, dwell) => { + if (!Number.isNaN(px)) { + const l = Math.hypot(x - px, y - py, zz - pz); + t += (l / Math.max(1e-6, k === RAPID ? input.rapidFeed : k === PLUNGE ? s.plunge : s.feed)) * 60; + } + t += dwell; + px = x; py = y; pz = zz; + }); + times.push(t); + total += t; + } + const nSnap = Math.max(2, input.snapshots ?? 90); + const snapshots: SimSnapshot[] = [{ time: 0, z: down(z) }]; + let nextSnap = total / nSnap; + const timeline: number[] = []; + const rapidCuts: number[] = [], shankHits: number[] = []; + let now = 0; + + input.steps.forEach((s, si) => { + const cutter = cutterOf(s.tool); + const R = cutter.r; + const flute = Math.max(s.tool.fluteLength, 0.1); + let rapid = 0, shank = 0; + let px = NaN, py = NaN, pz = NaN; + const stampAt = (x: number, y: number, tz: number, kind: number): boolean => { + const i0 = Math.max(0, Math.ceil((x - R - g.x0) / g.c)), i1 = Math.min(g.nx - 1, Math.floor((x + R - g.x0) / g.c)); + const j0 = Math.max(0, Math.ceil((y - R - g.y0) / g.c)), j1 = Math.min(g.ny - 1, Math.floor((y + R - g.y0) / g.c)); + let cut = false, hit = false; + for (let j = j0; j <= j1; j++) { + const cy = g.y0 + j * g.c - y; + for (let i = i0; i <= i1; i++) { + const cx = g.x0 + i * g.c - x; + const dd = cx * cx + cy * cy; + if (dd > R * R) continue; + const k = j * g.nx + i; + const zc = tz + cutter.h(Math.sqrt(dd)); + if (zc < z[k] - 1e-4) { + if (z[k] > tz + flute + 0.01) hit = true; + z[k] = zc; + cut = true; + } + } + } + if (cut && kind === RAPID) rapid++; + if (hit && kind !== RAPID) shank++; + return cut; + }; + const move = (kind: number, x: number, y: number, zz: number, dwell: number) => { + if (Number.isNaN(px)) { px = x; py = y; pz = zz; stampAt(x, y, zz, kind); return; } + const lxy = Math.hypot(x - px, y - py); + const l = Math.hypot(lxy, zz - pz); + const dt = (l / Math.max(1e-6, kind === RAPID ? input.rapidFeed : kind === PLUNGE ? s.plunge : s.feed)) * 60 + dwell; + // Only moves that may reach the stock need stamping. + if (Math.min(pz, zz) < top + 1e-6) { + const n = Math.max(1, Math.ceil(lxy / (g.c * 0.5))); + for (let k = 1; k <= n; k++) { + const t = k / n; + stampAt(px + (x - px) * t, py + (y - py) * t, pz + (zz - pz) * t, kind); + } + } + now += dt; + timeline.push(x, y, zz, now, si, kind); + while (now >= nextSnap && snapshots.length < nSnap) { + snapshots.push({ time: now, z: down(z) }); + nextSnap += total / nSnap; + } + px = x; py = y; pz = zz; + if ((timeline.length / 6) % 2048 === 0) { + if (input.cancelled?.()) throw new Error('cancelled'); + input.progress?.(total ? now / total : 0); + } + }; + expandMoves(s.toolpath, move); + rapidCuts.push(rapid); + shankHits.push(shank); + }); + snapshots.push({ time: total, z: down(z) }); + + // Compare with the part: its top surface under each display cell, and on the stock grid + // (eroded by a cell so cells on a wall's edge do not read as gouges). + const pin = new DropCutter(input.part, makeCutter('flat', 1e-4, 0, 0)); + const fine = new Float32Array(g.nx * g.ny); + for (let j = 0; j < g.ny; j++) for (let i = 0; i < g.nx; i++) fine[j * g.nx + i] = pin.drop(g.x0 + i * g.c, g.y0 + j * g.c); + const eroded = new Float32Array(fine.length); + for (let j = 0; j < g.ny; j++) { + for (let i = 0; i < g.nx; i++) { + let m = Infinity; + for (let dj = -1; dj <= 1; dj++) for (let di = -1; di <= 1; di++) { + const ii = Math.min(g.nx - 1, Math.max(0, i + di)), jj = Math.min(g.ny - 1, Math.max(0, j + dj)); + m = Math.min(m, fine[jj * g.nx + ii]); + } + eroded[j * g.nx + i] = m; + } + } + let gouges = 0, maxGouge = 0, maxRemaining = 0, remainingCells = 0, volume = 0; + for (let k = 0; k < z.length; k++) { + volume += (z[k] - bottom) * g.c * g.c; + const p = eroded[k]; + if (p <= NO_CONTACT / 2) continue; + const diff = z[k] - p; + if (diff < -0.02) { gouges++; maxGouge = Math.max(maxGouge, -diff); } + if (fine[k] > NO_CONTACT / 2 && z[k] - fine[k] > 0.1) { remainingCells++; maxRemaining = Math.max(maxRemaining, z[k] - fine[k]); } + } + const partTop = new Float32Array(dg.nx * dg.ny); + for (let j = 0; j < dg.ny; j++) for (let i = 0; i < dg.nx; i++) partTop[j * dg.nx + i] = pin.drop(dg.x0 + i * dg.c, dg.y0 + j * dg.c); + return { + grid: dg, bottom, top, snapshots, partTop, timeline: Float32Array.from(timeline), time: total, + gouges, maxGouge, rapidCuts, shankHits, maxRemaining, remainingArea: remainingCells * g.c * g.c, removed: Math.max(0, startVolume - volume), + }; +} diff --git a/src/parametric/src/cam/toolpath.ts b/src/parametric/src/cam/toolpath.ts new file mode 100644 index 000000000..7a66c8773 --- /dev/null +++ b/src/parametric/src/cam/toolpath.ts @@ -0,0 +1,155 @@ +// Toolpaths: the moves of an operation in work coordinates, packed in a +// typed array (kind, x, y, z per move) so large finishing paths stay cheap to +// keep, transfer from the worker and draw. Drilling cycles are kept as cycles +// so the post processor can write them as canned cycles. + +import type { DrillCycle } from '../model/cam'; + +export const RAPID = 0; +export const FEED = 1; +/** Plunges, ramps and helical entries (at the plunge feed). */ +export const PLUNGE = 2; +/** A drilling cycle at (x, y) down to z; its details are in `cycles`. */ +export const CYCLE = 3; + +export interface CycleInfo { + cycle: DrillCycle; + /** Height the cycle starts and retracts to (R plane). */ + r: number; + /** Bottom of the hole. */ + z: number; + peck: number; + dwell: number; +} + +export interface Toolpath { + /** kind, x, y, z per move. */ + moves: Float64Array; + cycles: CycleInfo[]; + /** Height rapids between features use (work coordinates). */ + clearance: number; + /** Notes about the operation (what was left uncut...). */ + warnings: string[]; +} + +export class PathBuilder { + private data: number[] = []; + readonly cycles: CycleInfo[] = []; + warnings: string[] = []; + x = NaN; + y = NaN; + z = NaN; + + constructor(readonly clearance: number, readonly retract: number) {} + + get length() { return this.data.length / 4; } + + private push(kind: number, x: number, y: number, z: number) { + // Repeats add nothing. + if (x === this.x && y === this.y && z === this.z && kind !== CYCLE) return; + this.data.push(kind, x, y, z); + this.x = x; this.y = y; this.z = z; + } + + rapid(x: number, y: number, z: number) { this.push(RAPID, x, y, z); } + feed(x: number, y: number, z: number) { this.push(FEED, x, y, z); } + plunge(x: number, y: number, z: number) { this.push(PLUNGE, x, y, z); } + + /** Up to the clearance height (if not there), across, and down to `z` at rapid. */ + rapidTo(x: number, y: number, z: number) { + if (Number.isNaN(this.z)) { + this.push(RAPID, x, y, this.clearance); + } else { + if (this.z < this.clearance) this.push(RAPID, this.x, this.y, this.clearance); + this.push(RAPID, x, y, this.clearance); + } + if (z < this.clearance) this.push(RAPID, x, y, z); + } + + /** Lifts to `z` at rapid, moves across and goes down to `down` at rapid (within the operation). */ + hop(z: number, x: number, y: number, down: number) { + if (this.z < z) this.push(RAPID, this.x, this.y, z); + this.push(RAPID, x, y, Math.max(z, this.z)); + if (down < this.z) this.push(RAPID, x, y, down); + } + + cycle(x: number, y: number, info: CycleInfo) { + this.rapidTo(x, y, info.r); + this.data.push(CYCLE, x, y, this.cycles.length); + this.cycles.push(info); + this.x = x; this.y = y; this.z = info.r; + } + + /** Back up to the clearance height. */ + finish() { + if (!Number.isNaN(this.z) && this.z < this.clearance) this.push(RAPID, this.x, this.y, this.clearance); + } + + build(): Toolpath { + this.finish(); + return { moves: Float64Array.from(this.data), cycles: this.cycles, clearance: this.clearance, warnings: this.warnings }; + } +} + +export interface ExpandedMove { kind: number; x: number; y: number; z: number; dwell?: number } + +/** + * The moves of a toolpath with drilling cycles written out as the moves the + * machine makes (for drawing, simulating and machines without canned cycles). + */ +export function expandMoves(tp: Toolpath, visit: (kind: number, x: number, y: number, z: number, dwell: number) => void) { + const m = tp.moves; + let cx = NaN, cy = NaN; + for (let i = 0; i < m.length; i += 4) { + const k = m[i]; + if (k !== CYCLE) { visit(k, m[i + 1], m[i + 2], m[i + 3], 0); cx = m[i + 1]; cy = m[i + 2]; continue; } + const c = tp.cycles[m[i + 3]]; + const x = m[i + 1], y = m[i + 2]; + if (x !== cx || y !== cy) visit(RAPID, x, y, c.r, 0); + cx = x; cy = y; + if (c.cycle === 'drill' || c.peck <= 0) { + visit(PLUNGE, x, y, c.z, c.dwell); + } else { + // Pecks: down a peck at a time; a full retract (peck) or a short one (chip break) between. + let depth = c.r; + const clear = Math.min(0.5, c.peck / 4); + while (depth > c.z + 1e-9) { + const next = Math.max(c.z, depth - c.peck); + visit(PLUNGE, x, y, next, next <= c.z + 1e-9 ? c.dwell : 0); + depth = next; + if (depth > c.z + 1e-9) { + if (c.cycle === 'peck') { visit(RAPID, x, y, c.r, 0); visit(RAPID, x, y, depth + clear, 0); } + else visit(RAPID, x, y, depth + clear, 0); + } + } + } + visit(RAPID, x, y, c.r, 0); + } +} + +export interface PathStats { + cutLength: number; + rapidLength: number; + /** Seconds. */ + time: number; + zMin: number; + zMax: number; + moves: number; +} + +export function pathStats(tp: Toolpath, feed: number, plunge: number, rapidFeed: number): PathStats { + let cut = 0, rapid = 0, time = 0, zMin = Infinity, zMax = -Infinity, n = 0; + let px = NaN, py = NaN, pz = NaN; + expandMoves(tp, (k, x, y, z, dwell) => { + n++; + if (!Number.isNaN(px)) { + const l = Math.hypot(x - px, y - py, z - pz); + if (k === RAPID) { rapid += l; time += (l / rapidFeed) * 60; } + else { cut += l; time += (l / Math.max(1e-6, k === PLUNGE ? plunge : feed)) * 60; } + } + time += dwell; + if (k !== RAPID) { zMin = Math.min(zMin, z); zMax = Math.max(zMax, z); } + px = x; py = y; pz = z; + }); + return { cutLength: cut, rapidLength: rapid, time, zMin, zMax, moves: n }; +} diff --git a/src/parametric/src/model/cam.ts b/src/parametric/src/model/cam.ts new file mode 100644 index 000000000..a71cf2d97 --- /dev/null +++ b/src/parametric/src/model/cam.ts @@ -0,0 +1,427 @@ +// CAM (computer-aided manufacturing) data kept with the part: the cutting +// tools, the setups (how the part sits on the machine, its stock and work +// origin) and each setup's machining operations. Plain JSON like the rest of +// the part, in millimetres, degrees, millimetres per minute and revolutions +// per minute. Toolpaths are not stored: they are generated from the part. + +import type { FaceRef, Id, PartDocument } from './types'; + +/** Direction from the part toward the spindle, in model coordinates. */ +export type CamAxis = '+X' | '-X' | '+Y' | '-Y' | '+Z' | '-Z'; + +/** Where the work coordinate system (G54) is, on the stock. */ +export type CamOrigin = 'topCenter' | 'topFrontLeft' | 'topBackLeft' | 'bottomFrontLeft' | 'modelOrigin'; + +export type CamToolType = 'flat' | 'ball' | 'bull' | 'drill' | 'chamfer'; + +export interface CamTool { + id: Id; + /** Tool number in the machine's tool changer (T1...). */ + number: number; + name: string; + type: CamToolType; + diameter: number; + /** Bull nose end mills: radius of the rounded corners. */ + cornerRadius?: number; + /** Drills and chamfer mills: included angle of the point (118 for a drill, 90 for a chamfer mill). */ + tipAngle?: number; + /** Length of the cutting part. */ + fluteLength: number; + flutes: number; + /** Spindle speed (rpm). */ + rpm: number; + /** Cutting feed (mm/min). */ + feed: number; + /** Plunge and ramp feed (mm/min). */ + plunge: number; + coolant: boolean; +} + +export interface CamStock { + /** 'offset': the part's bounding box grown by the offsets; 'fixed': a box of this size around the part. */ + mode: 'offset' | 'fixed'; + /** Offset mode: added around the sides, above and below the part. */ + side: number; + top: number; + bottom: number; + /** Fixed mode: width (X), depth (Y) and height (Z) on the machine. */ + size: [number, number, number]; +} + +export type CamOpType = 'face' | 'contour' | 'pocket' | 'drill' | 'bore' | 'rough' | 'parallel' | 'waterline'; + +export interface CamOpBase { + id: Id; + name: string; + type: CamOpType; + tool: Id; + suppressed?: boolean; + /** Feeds and speeds overriding the tool's (absent: the tool's). */ + rpm?: number; + feed?: number; + plunge?: number; +} + +/** Faces the top of the stock down to the top of the part. */ +export interface FaceOp extends CamOpBase { + type: 'face'; + stepover: number; + stepdown: number; + /** Left on top of the part (absent: 0). */ + leave: number; + /** Angle of the passes from the machine's X axis (degrees). */ + angle: number; +} + +/** Cuts around the outside of the part, through its full height. */ +export interface ContourOp extends CamOpBase { + type: 'contour'; + stepdown: number; + /** Stock to leave on the walls. */ + leave: number; + /** How far below the bottom of the part to cut. */ + breakthrough: number; + direction: 'climb' | 'conventional'; + /** Holding tabs left in the last passes (count 0: none). */ + tabs: { count: number; width: number; height: number }; + /** Radius of the arcs leading on and off the wall (0: straight on). */ + lead: number; + /** Angle the passes ramp down at along the contour (degrees from horizontal). */ + rampAngle: number; +} + +export type ClearingPattern = 'offset' | 'zigzag'; +export type EntryKind = 'helix' | 'ramp' | 'plunge'; + +/** Clears pockets down to picked flat floors. */ +export interface PocketOp extends CamOpBase { + type: 'pocket'; + /** Floors of the pockets (planar faces facing the tool). */ + faces: FaceRef[]; + stepover: number; + stepdown: number; + /** Stock to leave on the walls and floor. */ + leave: number; + floorLeave: number; + pattern: ClearingPattern; + direction: 'climb' | 'conventional'; + entry: EntryKind; + /** Ramp and helix angle (degrees from horizontal). */ + rampAngle: number; +} + +export interface HoleRef { + /** One of the hole's cylindrical faces. */ + face: FaceRef; +} + +export type DrillCycle = 'drill' | 'peck' | 'chipBreak'; + +/** Drills holes with a drill (canned cycles). */ +export interface DrillOp extends CamOpBase { + type: 'drill'; + /** Holes to drill; empty: every hole of the tool's diameter that opens toward the tool. */ + holes: HoleRef[]; + cycle: DrillCycle; + /** Peck depth (peck and chip break cycles). */ + peck: number; + /** Dwell at the bottom (seconds). */ + dwell: number; + /** Extra depth through holes that go through the part. */ + breakthrough: number; + /** Through holes: the drill point goes all the way through (adds the point's length). */ + tipThrough: boolean; +} + +/** Mills holes larger than the tool along a helix. */ +export interface BoreOp extends CamOpBase { + type: 'bore'; + holes: HoleRef[]; + /** Depth per turn of the helix. */ + pitch: number; + leave: number; + breakthrough: number; + direction: 'climb' | 'conventional'; +} + +/** Removes the bulk of the stock around the part in levels (3D). */ +export interface RoughOp extends CamOpBase { + type: 'rough'; + stepover: number; + stepdown: number; + leave: number; + floorLeave: number; + pattern: ClearingPattern; + direction: 'climb' | 'conventional'; + entry: EntryKind; + rampAngle: number; +} + +/** Finishes the surfaces with parallel passes (3D). */ +export interface ParallelOp extends CamOpBase { + type: 'parallel'; + stepover: number; + /** Angle of the passes from the machine's X axis (degrees). */ + angle: number; + leave: number; + /** Chord tolerance of the passes. */ + tolerance: number; + /** Area machined: the stock, or the part's outline (plus the tool radius). */ + boundary: 'stock' | 'silhouette'; + /** Only surfaces flatter than this (degrees from horizontal); 90: all. */ + maxSlope: number; +} + +/** Finishes steep walls with constant-height passes (3D). */ +export interface WaterlineOp extends CamOpBase { + type: 'waterline'; + stepdown: number; + leave: number; + tolerance: number; + direction: 'climb' | 'conventional'; +} + +export type CamOperation = FaceOp | ContourOp | PocketOp | DrillOp | BoreOp | RoughOp | ParallelOp | WaterlineOp; + +export interface CamSetup { + id: Id; + name: string; + axis: CamAxis; + /** Turn of the part about the tool axis (degrees, a multiple of 90). */ + rotation: number; + origin: CamOrigin; + stock: CamStock; + /** Heights above the top of the stock: rapid moves above clearance, feeds start from retract. */ + clearance: number; + retract: number; + /** Work offset (54 for G54 ... 59). */ + workOffset: number; + ops: CamOperation[]; +} + +export type CamController = 'fanuc' | 'haas' | 'linuxcnc' | 'mach3' | 'grbl'; + +export interface CamPost { + controller: CamController; + /** Program number (O-number for Fanuc and Haas). */ + program: number; + /** Output inch (G20) or millimetre (G21) values; absent: the part's units. */ + units?: 'mm' | 'in'; + /** Write arcs as G2/G3 (else as short lines). */ + arcs: boolean; + /** Write line numbers (N10, N20...). */ + lineNumbers: boolean; + /** Write drilling as canned cycles (G81/G83/G73); else as moves. */ + cannedCycles: boolean; + /** Rapid feed of the machine, for the cycle time estimate (mm/min). */ + rapidFeed: number; +} + +export interface CamDoc { + tools: CamTool[]; + setups: CamSetup[]; + post: CamPost; +} + +export const CAM_OP_LABELS: Record = { + face: 'Face', + contour: '2D Contour', + pocket: '2D Pocket', + drill: 'Drill', + bore: 'Bore', + rough: '3D Rough', + parallel: 'Parallel', + waterline: 'Waterline', +}; + +export const CAM_OP_ICONS: Record = { + face: 'camFace', + contour: 'camContour', + pocket: 'camPocket', + drill: 'camDrill', + bore: 'camBore', + rough: 'camRough', + parallel: 'camParallel', + waterline: 'camWaterline', +}; + +export const TOOL_TYPE_LABELS: Record = { + flat: 'Flat end mill', + ball: 'Ball end mill', + bull: 'Bull nose end mill', + drill: 'Drill', + chamfer: 'Chamfer mill', +}; + +export const CONTROLLER_LABELS: Record = { + fanuc: 'Fanuc (generic)', + haas: 'Haas', + linuxcnc: 'LinuxCNC', + mach3: 'Mach3 / Mach4', + grbl: 'Grbl', +}; + +/** The tool types an operation can use. */ +export function opToolTypes(type: CamOpType): CamToolType[] { + switch (type) { + case 'drill': return ['drill', 'flat']; + case 'face': case 'contour': case 'pocket': case 'bore': case 'rough': return ['flat', 'bull']; + case 'parallel': return ['ball', 'bull', 'flat', 'chamfer']; + case 'waterline': return ['ball', 'bull', 'flat']; + } +} + +/** New CAM data; `id` gives ids from the part's counter (so they never meet a feature's). */ +export function newCamDoc(id: (prefix: string) => Id, inch = false): CamDoc { + return { + tools: defaultTools(id, inch), + setups: [], + post: { controller: 'fanuc', program: 1001, arcs: true, lineNumbers: false, cannedCycles: true, rapidFeed: 5000 }, + }; +} + +/** A starting tool library: common end mills and drills. */ +export function defaultTools(id: (prefix: string) => Id, inch = false): CamTool[] { + const mm = (v: number, i: number) => (inch ? i * 25.4 : v); + const t = (number: number, name: string, type: CamToolType, d: number, extra: Partial = {}): CamTool => ({ + id: id('t'), number, name, type, diameter: d, fluteLength: Math.max(3 * d, 6), flutes: type === 'drill' ? 2 : 3, + rpm: Math.round(Math.min(18000, 80000 / Math.max(1, d))), feed: Math.round(Math.max(150, Math.min(2500, 120 * d))), plunge: Math.round(Math.max(80, Math.min(800, 40 * d))), coolant: true, + ...extra, + }); + return [ + t(1, inch ? '1/2" flat end mill' : '12 mm flat end mill', 'flat', mm(12, 0.5)), + t(2, inch ? '1/4" flat end mill' : '6 mm flat end mill', 'flat', mm(6, 0.25)), + t(3, inch ? '1/8" flat end mill' : '3 mm flat end mill', 'flat', mm(3, 0.125)), + t(4, inch ? '1/4" ball end mill' : '6 mm ball end mill', 'ball', mm(6, 0.25)), + t(5, inch ? '1/8" ball end mill' : '3 mm ball end mill', 'ball', mm(3, 0.125)), + t(6, inch ? '#7 drill (M5 tap)' : '4.2 mm drill (M5 tap)', 'drill', inch ? 0.201 * 25.4 : 4.2, { tipAngle: 118, feed: 200, plunge: 200, rpm: 2500 }), + t(7, inch ? '1/4" drill' : '5 mm drill', 'drill', mm(5, 0.25), { tipAngle: 118, feed: 220, plunge: 220, rpm: 2200 }), + t(8, inch ? '1/2" chamfer mill 90°' : '10 mm chamfer mill 90°', 'chamfer', mm(10, 0.5), { tipAngle: 90 }), + ]; +} + +const finite = (v: unknown, lo = -Infinity, hi = Infinity): v is number => typeof v === 'number' && Number.isFinite(v) && v >= lo && v <= hi; +const isObj = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const oneOf = (v: unknown, all: readonly T[]): v is T => typeof v === 'string' && (all as readonly string[]).includes(v); + +const AXES: CamAxis[] = ['+X', '-X', '+Y', '-Y', '+Z', '-Z']; +const ORIGINS: CamOrigin[] = ['topCenter', 'topFrontLeft', 'topBackLeft', 'bottomFrontLeft', 'modelOrigin']; +const TOOL_TYPES: CamToolType[] = ['flat', 'ball', 'bull', 'drill', 'chamfer']; +const OP_TYPES: CamOpType[] = ['face', 'contour', 'pocket', 'drill', 'bore', 'rough', 'parallel', 'waterline']; +const CONTROLLERS: CamController[] = ['fanuc', 'haas', 'linuxcnc', 'mach3', 'grbl']; + +function validFaceRef(v: unknown): boolean { + return isObj(v) && typeof v.name === 'string' && isObj(v.sig) && typeof v.sig.type === 'string' && Array.isArray(v.sig.c); +} + +function validTool(t: unknown): t is CamTool { + return isObj(t) && typeof t.id === 'string' && typeof t.name === 'string' && oneOf(t.type, TOOL_TYPES) && finite(t.diameter, 1e-3, 1e4) + && finite(t.number, 0, 1e6) && finite(t.rpm, 0) && finite(t.feed, 0) && finite(t.plunge, 0); +} + +function validOp(o: unknown): o is CamOperation { + if (!isObj(o) || typeof o.id !== 'string' || typeof o.name !== 'string' || !oneOf(o.type, OP_TYPES) || typeof o.tool !== 'string') return false; + if ((o.type === 'pocket') && !(Array.isArray(o.faces) && o.faces.every(validFaceRef))) return false; + if ((o.type === 'drill' || o.type === 'bore') && !(Array.isArray(o.holes) && o.holes.every((x) => isObj(x) && validFaceRef(x.face)))) return false; + return true; +} + +/** + * Checks and completes CAM data read from a file. Returns null for data that + * is not CAM data at all; drops tools and operations that are damaged, and + * fills in values added since the file was written from the defaults. + */ +export function normalizeCam(raw: unknown): CamDoc | null { + if (!isObj(raw)) return null; + const base = newCamDoc(() => ''); + const tools = (Array.isArray(raw.tools) ? raw.tools : []).filter(validTool).map((t) => ({ + ...t, fluteLength: finite(t.fluteLength, 0) ? t.fluteLength : t.diameter * 3, flutes: finite(t.flutes, 1, 20) ? Math.round(t.flutes) : 2, coolant: t.coolant !== false, + })); + const ids = new Set(); + const uniqueTools = tools.filter((t) => !ids.has(t.id) && ids.add(t.id)); + const setups: CamSetup[] = []; + for (const s of Array.isArray(raw.setups) ? raw.setups : []) { + if (!isObj(s) || typeof s.id !== 'string' || ids.has(s.id)) continue; + ids.add(s.id); + const st = isObj(s.stock) ? s.stock : {}; + const size = Array.isArray(st.size) && st.size.length === 3 && st.size.every((v) => finite(v, 0)) ? st.size as [number, number, number] : [100, 100, 25] as [number, number, number]; + const ops = (Array.isArray(s.ops) ? s.ops : []).filter(validOp).filter((o) => !ids.has(o.id) && ids.add(o.id)).map((o) => withOpDefaults(o)); + setups.push({ + id: s.id, + name: typeof s.name === 'string' ? s.name : 'Setup', + axis: oneOf(s.axis, AXES) ? s.axis : '+Y', + rotation: finite(s.rotation) ? (((Math.round(s.rotation / 90) * 90) % 360) + 360) % 360 : 0, + origin: oneOf(s.origin, ORIGINS) ? s.origin : 'topFrontLeft', + stock: { + mode: st.mode === 'fixed' ? 'fixed' : 'offset', + side: finite(st.side, 0) ? st.side : 2, top: finite(st.top, 0) ? st.top : 1, bottom: finite(st.bottom, 0) ? st.bottom : 0, size, + }, + clearance: finite(s.clearance, 0) ? s.clearance : 10, + retract: finite(s.retract, 0) ? s.retract : 3, + workOffset: finite(s.workOffset, 54, 59) ? Math.round(s.workOffset) : 54, + ops, + }); + } + const p = isObj(raw.post) ? raw.post : {}; + const post: CamPost = { + controller: oneOf(p.controller, CONTROLLERS) ? p.controller : base.post.controller, + program: finite(p.program, 1, 99999) ? Math.round(p.program) : base.post.program, + ...(p.units === 'mm' || p.units === 'in' ? { units: p.units } : {}), + arcs: p.arcs !== false, + lineNumbers: p.lineNumbers === true, + cannedCycles: p.cannedCycles !== false, + rapidFeed: finite(p.rapidFeed, 1) ? p.rapidFeed : base.post.rapidFeed, + }; + return { tools: uniqueTools, setups, post }; +} + +/** Defaults of an operation's values (by type), for a tool of this diameter. */ +export function opDefaults(type: CamOpType, d: number): Record { + const r = d / 2; + switch (type) { + case 'face': return { stepover: d * 0.7, stepdown: 1, leave: 0, angle: 0 }; + case 'contour': return { stepdown: Math.max(0.5, Math.min(d, 3)), leave: 0, breakthrough: 0.5, direction: 'climb', tabs: { count: 0, width: Math.max(3, d), height: 1.5 }, lead: Math.max(0.5, r * 0.5), rampAngle: 3 }; + case 'pocket': return { faces: [], stepover: d * 0.45, stepdown: Math.max(0.5, Math.min(d / 2, 3)), leave: 0, floorLeave: 0, pattern: 'offset', direction: 'climb', entry: 'helix', rampAngle: 3 }; + case 'drill': return { holes: [], cycle: 'peck', peck: Math.max(1, d), dwell: 0, breakthrough: 1, tipThrough: true }; + case 'bore': return { holes: [], pitch: Math.max(0.3, d / 6), leave: 0, breakthrough: 0.5, direction: 'climb' }; + case 'rough': return { stepover: d * 0.4, stepdown: Math.max(0.5, Math.min(d / 2, 3)), leave: 0.3, floorLeave: 0.2, pattern: 'offset', direction: 'climb', entry: 'helix', rampAngle: 3 }; + case 'parallel': return { stepover: Math.max(0.05, d * 0.1), angle: 45, leave: 0, tolerance: 0.01, boundary: 'stock', maxSlope: 90 }; + case 'waterline': return { stepdown: Math.max(0.05, d * 0.08), leave: 0, tolerance: 0.01, direction: 'climb' }; + } +} + +function withOpDefaults(o: CamOperation): CamOperation { + const defs = opDefaults(o.type, 6); + const out = { ...defs, ...o } as Record; + for (const [k, v] of Object.entries(defs)) if (typeof v === 'number' && !finite(out[k])) out[k] = v; + return out as unknown as CamOperation; +} + +/** The ids CAM data uses (they share the part's id counter). */ +export function camIds(cam: CamDoc | null | undefined): string[] { + if (!cam) return []; + return [...cam.tools.map((t) => t.id), ...cam.setups.flatMap((s) => [s.id, ...s.ops.map((o) => o.id)])]; +} + +export function camOf(doc: PartDocument): CamDoc | null { + return doc.cam ?? null; +} + +/** Name for a new item: the label followed by the first number not taken. */ +export function nextCamName(taken: string[], label: string): string { + const used = new Set(taken.map((n) => n.toLowerCase())); + for (let i = 1; ; i++) if (!used.has(`${label}${i}`.toLowerCase())) return `${label}${i}`; +} + +export function findOp(cam: CamDoc, id: Id): { setup: CamSetup; op: CamOperation } | null { + for (const setup of cam.setups) { + const op = setup.ops.find((o) => o.id === id); + if (op) return { setup, op }; + } + return null; +} + +/** Feeds and speeds an operation runs at. */ +export function opFeeds(op: CamOperation, tool: CamTool): { rpm: number; feed: number; plunge: number } { + return { rpm: op.rpm ?? tool.rpm, feed: op.feed ?? tool.feed, plunge: op.plunge ?? tool.plunge }; +} diff --git a/src/parametric/src/model/document.ts b/src/parametric/src/model/document.ts index f27804e10..a1df14d3b 100644 --- a/src/parametric/src/model/document.ts +++ b/src/parametric/src/model/document.ts @@ -11,6 +11,7 @@ import { uniqueId } from './ids'; import { validFeature } from './validate-feature'; import { validSketch } from './validate-sketch'; import { validDrawing } from './validate-drawing'; +import { camIds, normalizeCam } from './cam'; import { solveSketch } from '../sketch/solver'; import { hasExternal } from '../sketch/external'; @@ -81,11 +82,13 @@ export function parseDocument(text: string): PartDocument { for (const k of ['created', 'modified'] as const) if (!Number.isFinite(doc[k]) || Math.abs(doc[k]) > 8.64e15) doc[k] = base[k]; if (doc.material != null && !(isObj(doc.material) && typeof doc.material.name === 'string' && Number.isFinite(doc.material.density) && doc.material.density > 0)) doc.material = null; if (doc.drawing != null && !validDrawing(doc.drawing)) throw new Error('The part file is damaged (invalid drawing).'); + // Machining data that cannot be read is dropped rather than refusing the part. + if (doc.cam != null) doc.cam = normalizeCam(doc.cam); for (const f of doc.features) if (typeof f.name !== 'string' || !f.name) f.name = f.id; // New feature ids must not collide with existing ones, even when the file's // counter is missing or stale. let maxId = 0; - for (const f of [...doc.features, ...doc.variables]) { + for (const f of [...doc.features, ...doc.variables, ...camIds(doc.cam).map((id) => ({ id }))]) { const m = /^[a-z]+(\d+)$/i.exec(String(f?.id ?? '')); const suffix = m ? Number(m[1]) : NaN; // Unsafe suffixes cannot be emitted by the numeric allocator. diff --git a/src/parametric/src/model/types.ts b/src/parametric/src/model/types.ts index 7bdcf1647..ce29b8a86 100644 --- a/src/parametric/src/model/types.ts +++ b/src/parametric/src/model/types.ts @@ -5,6 +5,7 @@ import type { Vec2, Vec3, Frame } from '../math/vec'; import type { BaseFlangeFeature, EdgeFlangeFeature, HemFeature, SketchedBendFeature } from './sheetmetal'; +import type { CamDoc } from './cam'; export type Id = string; @@ -617,6 +618,8 @@ export interface PartDocument { blobs: Record; /** 2D drawing of the part (sheet with projected views), if created. */ drawing?: DrawingDoc | null; + /** Machining: tools, setups and operations (see model/cam.ts), if any. */ + cam?: CamDoc | null; nextId: number; created: number; modified: number; diff --git a/src/parametric/tests/cam-engine.test.ts b/src/parametric/tests/cam-engine.test.ts new file mode 100644 index 000000000..432f67c64 --- /dev/null +++ b/src/parametric/tests/cam-engine.test.ts @@ -0,0 +1,358 @@ +// The CAM engine on meshes built by hand: drop-cutter heights against exact +// answers, toolpaths that stay clear of the part, simulation and G-code. +import { describe, expect, it } from 'vitest'; +import { DropCutter, NO_CONTACT, TriIndex, cutterOf, makeCutter } from '../src/cam/dropcutter'; +import { machineFrame, setupAxes, toModel, pointToWork } from '../src/cam/frame'; +import { contours, gridOver, simplify } from '../src/cam/grid'; +import { placePart, generateFor } from '../src/cam/engine'; +import { stepLevels } from '../src/cam/ops'; +import { simulate } from '../src/cam/simulate'; +import { postProcess, writeArcs } from '../src/cam/post'; +import { CYCLE, FEED, PLUNGE, RAPID, type Toolpath, expandMoves, pathStats } from '../src/cam/toolpath'; +import { type CamOperation, type CamSetup, type CamTool, newCamDoc, normalizeCam, opDefaults } from '../src/model/cam'; +import type { Vec3 } from '../src/math/vec'; + +type Tri = number[]; + +function box(x0: number, y0: number, z0: number, x1: number, y1: number, z1: number): Tri { + const p = (x: number, y: number, z: number) => [x, y, z]; + const q = (a: number[], b: number[], c: number[], d: number[]) => [...a, ...b, ...c, ...a, ...c, ...d]; + return [ + ...q(p(x0, y0, z1), p(x1, y0, z1), p(x1, y1, z1), p(x0, y1, z1)), + ...q(p(x0, y0, z0), p(x0, y1, z0), p(x1, y1, z0), p(x1, y0, z0)), + ...q(p(x0, y0, z0), p(x1, y0, z0), p(x1, y0, z1), p(x0, y0, z1)), + ...q(p(x0, y1, z0), p(x0, y1, z1), p(x1, y1, z1), p(x1, y1, z0)), + ...q(p(x0, y0, z0), p(x0, y0, z1), p(x0, y1, z1), p(x0, y1, z0)), + ...q(p(x1, y0, z0), p(x1, y1, z0), p(x1, y1, z1), p(x1, y0, z1)), + ]; +} + +const mesh = (...parts: Tri[]) => Float32Array.from(parts.flat()); + +const tool = (type: CamTool['type'], diameter: number, extra: Partial = {}): CamTool => ({ + id: 'tt', number: 1, name: 'tool', type, diameter, fluteLength: 30, flutes: 2, rpm: 10000, feed: 1000, plunge: 300, coolant: true, ...extra, +}); + +const setup = (extra: Partial = {}): CamSetup => ({ + id: 's', name: 'Setup1', axis: '+Z', rotation: 0, origin: 'modelOrigin', + stock: { mode: 'offset', side: 5, top: 2, bottom: 3, size: [0, 0, 0] }, clearance: 10, retract: 3, workOffset: 54, ops: [], ...extra, +}); + +const op = (type: T, t: CamTool, extra: Record = {}) => + ({ id: 'o', name: type, type, tool: t.id, ...opDefaults(type, t.diameter), ...extra }) as Extract; + +/** Every move with its kind, cycles written out. */ +function moves(tp: Toolpath) { + const out: { k: number; x: number; y: number; z: number }[] = []; + expandMoves(tp, (k, x, y, z) => out.push({ k, x, y, z })); + return out; +} + +/** Distance from a point to an axis-aligned rectangle (0 inside). */ +const rectDist = (x: number, y: number, x0: number, y0: number, x1: number, y1: number) => + Math.hypot(Math.max(x0 - x, 0, x - x1), Math.max(y0 - y, 0, y - y1)); + +describe('drop-cutter', () => { + const idx = new TriIndex(Float64Array.from(box(0, 0, 0, 20, 20, 10))); + + it('rests a flat end mill on a box top until its edge leaves the box', () => { + const dc = new DropCutter(idx, makeCutter('flat', 3, 0, 0)); + expect(dc.drop(10, 10)).toBeCloseTo(10, 9); + expect(dc.drop(22.9, 10)).toBeCloseTo(10, 9); + expect(dc.drop(23.1, 10)).toBe(NO_CONTACT); + // Off the corner diagonally: touches only within the radius of the corner. + expect(dc.drop(22, 22)).toBeCloseTo(10, 9); + expect(dc.drop(22.2, 22.2)).toBe(NO_CONTACT); + }); + + it('drops a ball onto the edge of a box at the exact height', () => { + const dc = new DropCutter(idx, makeCutter('ball', 3, 3, 0)); + // 2 mm beyond the edge: the ball touches the edge; the centre is sqrt(9-4) above it. + expect(dc.drop(22, 10)).toBeCloseTo(10 + Math.sqrt(5) - 3, 9); + expect(dc.drop(10, 10)).toBeCloseTo(10, 9); + }); + + it('drops a ball on a sloped plane at the offset surface height', () => { + const s = 0.5; + // A large plane z = s * x. + const tris = Float64Array.from([-100, -100, -50, 100, -100, 50, 100, 100, 50, -100, -100, -50, 100, 100, 50, -100, 100, -50]); + const dc = new DropCutter(new TriIndex(tris), makeCutter('ball', 4, 4, 0)); + expect(dc.drop(10, 0)).toBeCloseTo(s * 10 + 4 * Math.sqrt(1 + s * s) - 4, 9); + const flat = new DropCutter(new TriIndex(tris), makeCutter('flat', 4, 0, 0)); + expect(flat.drop(10, 0)).toBeCloseTo(s * 14, 9); + }); + + it('drops a cone onto an edge and a bull nose between flat and ball', () => { + const cone = new DropCutter(idx, cutterOf({ type: 'chamfer', diameter: 10, tipAngle: 90 })); + // 45° half angle: 2 mm beyond the edge the tip is 2 mm below it. + expect(cone.drop(22, 10)).toBeCloseTo(8, 6); + const bull = new DropCutter(idx, cutterOf({ type: 'bull', diameter: 6, cornerRadius: 1 })); + // Flat part (radius 2) reaches 1 mm beyond the edge; the corner beyond that. + expect(bull.drop(21.5, 10)).toBeCloseTo(10, 6); + expect(bull.drop(22.5, 10)).toBeCloseTo(10 - (1 - Math.sqrt(1 - 0.25)), 5); + }); +}); + +describe('machine frame', () => { + it('gives right-handed axes for every tool direction and turn', () => { + for (const axis of ['+X', '-X', '+Y', '-Y', '+Z', '-Z'] as const) { + for (const rot of [0, 90, 180, 270]) { + const { x, y, z } = setupAxes(axis, rot); + const c: Vec3 = [x[1] * y[2] - x[2] * y[1], x[2] * y[0] - x[0] * y[2], x[0] * y[1] - x[1] * y[0]]; + for (let k = 0; k < 3; k++) expect(c[k]).toBeCloseTo(z[k], 9); + } + } + }); + + it('puts the work origin on the stock and maps points back', () => { + const tris = mesh(box(0, 0, 0, 40, 20, 10)); + // Top view: the tool comes down along -Y of the model (its axis is +Y). + const f = machineFrame({ axis: '+Y', rotation: 0, origin: 'topFrontLeft', stock: { mode: 'offset', side: 2, top: 1, bottom: 0, size: [0, 0, 0] } }, tris)!; + expect(f.stock.max[2]).toBeCloseTo(0, 9); + expect(f.stock.min[0]).toBeCloseTo(0, 9); + expect(f.stock.min[1]).toBeCloseTo(0, 9); + expect(f.part.max[2]).toBeCloseTo(-1, 9); + const p: Vec3 = [5, 7, 3]; + const w = pointToWork(f, p); + const back = toModel(f, w[0], w[1], w[2]); + for (let k = 0; k < 3; k++) expect(back[k]).toBeCloseTo(p[k], 9); + }); +}); + +describe('contours and levels', () => { + it('traces a disc counter-clockwise with the inside on the left', () => { + const g = gridOver(-10, -10, 10, 10, 0.25); + const v = new Float64Array(g.nx * g.ny); + for (let j = 0; j < g.ny; j++) for (let i = 0; i < g.nx; i++) v[j * g.nx + i] = 5 - Math.hypot(g.x0 + i * g.c, g.y0 + j * g.c); + const ls = contours(g, v, 0); + expect(ls).toHaveLength(1); + expect(ls[0].closed).toBe(true); + let a = 0; + const p = ls[0].pts; + for (let i = 0; i < p.length; i += 2) { + expect(Math.hypot(p[i], p[i + 1])).toBeCloseTo(5, 1); + const j = (i + 2) % p.length; + a += p[i] * p[j + 1] - p[j] * p[i + 1]; + } + expect(a).toBeGreaterThan(0); + expect(simplify(p, 0.01, 2, true).length).toBeLessThan(p.length); + }); + + it('steps down to the bottom with extra levels', () => { + expect(stepLevels(10, 0, 3)).toEqual([7, 4, 1, 0]); + expect(stepLevels(10, 0, 3, [5])).toEqual([7, 5, 4, 1, 0]); + }); +}); + +// A 100 x 60 x 20 plate with a 40 x 20 pocket 10 deep. +const floorTris = Float32Array.from(box(30, 20, 9, 70, 40, 10).slice(0, 18)); +const pocketPlate = mesh(box(0, 0, 0, 100, 60, 10), box(0, 0, 10, 30, 60, 20), box(70, 0, 10, 100, 60, 20), box(30, 0, 10, 70, 20, 20), box(30, 40, 10, 70, 60, 20)); + +describe('operations', () => { + it('faces the stock down to the top of the part', () => { + const t = tool('flat', 12); + const s = setup(); + const part = placePart(s, pocketPlate)!; + const tp = generateFor(part, { setup: s, op: op('face', t, { stepdown: 1 }), tool: t }); + const ms = moves(tp).filter((m) => m.k !== RAPID); + expect(ms.length).toBeGreaterThan(0); + expect(Math.min(...ms.map((m) => m.z))).toBeCloseTo(20, 9); + expect(new Set(ms.map((m) => m.z.toFixed(3)))).toEqual(new Set(['21.000', '20.000'])); + // Passes start and end off the stock. + const xs = ms.map((m) => m.x); + expect(Math.min(...xs)).toBeLessThan(-5 - 6); + expect(Math.max(...xs)).toBeGreaterThan(105 + 6); + }); + + it('cuts a contour round a box at the tool radius, with lead arcs outside', () => { + const t = tool('flat', 6); + const s = setup(); + const part = placePart(s, mesh(box(0, 0, 0, 40, 30, 10)))!; + const tp = generateFor(part, { setup: s, op: op('contour', t, { stepdown: 4, lead: 1.5 }), tool: t }); + const ms = moves(tp).filter((m) => m.k !== RAPID && m.z < 10); + expect(ms.length).toBeGreaterThan(10); + // Never closer than the tool radius; the wall pass right at it. + const d = ms.map((m) => rectDist(m.x, m.y, 0, 0, 40, 30)); + expect(Math.min(...d)).toBeGreaterThan(3 - 0.01); + expect(d.filter((v) => Math.abs(v - 3) < 0.01).length).toBeGreaterThan(8); + // Down to the breakthrough below the part. + expect(Math.min(...ms.map((m) => m.z))).toBeCloseTo(-0.5, 6); + // Climb milling: clockwise round the part (negative signed area of the wall pass). + const wall = ms.filter((m) => Math.abs(m.z + 0.5) < 1e-6 && Math.abs(rectDist(m.x, m.y, 0, 0, 40, 30) - 3) < 0.01); + let a = 0; + for (let i = 0; i + 1 < wall.length; i++) a += wall[i].x * wall[i + 1].y - wall[i + 1].x * wall[i].y; + expect(a).toBeLessThan(0); + }); + + it('leaves holding tabs in the last passes', () => { + const t = tool('flat', 6); + const s = setup({ stock: { mode: 'offset', side: 5, top: 0, bottom: 0, size: [0, 0, 0] } }); + const part = placePart(s, mesh(box(0, 0, 0, 40, 30, 10)))!; + const tp = generateFor(part, { setup: s, op: op('contour', t, { stepdown: 5, breakthrough: 0, tabs: { count: 4, width: 4, height: 2 } }), tool: t }); + const low = moves(tp).filter((m) => m.k !== RAPID && Math.abs(m.z - 2) < 1e-6); + expect(low.length).toBeGreaterThan(4); + }); + + it('clears a pocket to its floor without touching the walls', () => { + const t = tool('flat', 6); + const s = setup(); + const part = placePart(s, pocketPlate)!; + for (const pattern of ['offset', 'zigzag'] as const) { + const tp = generateFor(part, { setup: s, op: op('pocket', t, { stepdown: 4, pattern }), tool: t, floors: [floorTris] }); + const cut = moves(tp).filter((m) => m.k !== RAPID && m.z < 20); + expect(cut.length).toBeGreaterThan(20); + for (const m of cut) { + expect(m.x).toBeGreaterThan(33 - 0.01); + expect(m.x).toBeLessThan(67 + 0.01); + expect(m.y).toBeGreaterThan(23 - 0.01); + expect(m.y).toBeLessThan(37 + 0.01); + } + expect(Math.min(...cut.map((m) => m.z))).toBeCloseTo(10, 6); + const sim = simulate({ stock: part.frame.stock, part: part.index, steps: [{ toolpath: tp, tool: t, feed: 1000, plunge: 300 }], rapidFeed: 5000, cell: 0.25 }); + expect(sim.gouges).toBe(0); + expect(sim.rapidCuts[0]).toBe(0); + // The pocket is cleared to its floor. + const g = sim.grid; + const last = sim.snapshots[sim.snapshots.length - 1].z; + const at = (x: number, y: number) => last[Math.round((y - g.y0) / g.c) * g.nx + Math.round((x - g.x0) / g.c)]; + expect(at(50, 30)).toBeCloseTo(10, 1); + expect(at(36, 26)).toBeCloseTo(10, 1); + } + }, 60_000); + + it('roughs round the part leaving the allowance, without gouging', () => { + const t = tool('flat', 6); + const s = setup(); + const part = placePart(s, mesh(box(0, 0, 0, 30, 20, 8), box(10, 5, 8, 20, 15, 14)))!; + const tp = generateFor(part, { setup: s, op: op('rough', t, { stepdown: 2, leave: 0.3, floorLeave: 0.2 }), tool: t }); + const sim = simulate({ stock: part.frame.stock, part: part.index, steps: [{ toolpath: tp, tool: t, feed: 1000, plunge: 300 }], rapidFeed: 5000, cell: 0.25 }); + expect(sim.gouges).toBe(0); + expect(sim.rapidCuts[0]).toBe(0); + expect(sim.removed).toBeGreaterThan(0); + // The step at z = 8 is left with the floor allowance. + const g = sim.grid; + const last = sim.snapshots[sim.snapshots.length - 1].z; + const at = (x: number, y: number) => last[Math.round((y - g.y0) / g.c) * g.nx + Math.round((x - g.x0) / g.c)]; + expect(at(5, 10)).toBeCloseTo(8.2, 1); + expect(at(15, 10)).toBeCloseTo(14.2, 1); + }, 60_000); + + it('finishes with parallel passes and waterlines that stay on the surface', () => { + const ball = tool('ball', 4); + const s = setup({ stock: { mode: 'offset', side: 2, top: 0.5, bottom: 0, size: [0, 0, 0] } }); + // A ridge: two sloped planes. + const ridge = Float32Array.from([0, 0, 0, 20, 0, 10, 20, 30, 10, 0, 0, 0, 20, 30, 10, 0, 30, 0, 20, 0, 10, 40, 0, 0, 40, 30, 0, 20, 0, 10, 40, 30, 0, 20, 30, 10]); + const part = placePart(s, ridge)!; + const par = generateFor(part, { setup: s, op: op('parallel', ball, { stepover: 0.5, angle: 0, boundary: 'silhouette' }), tool: ball }); + const dc = new DropCutter(part.index, cutterOf(ball)); + for (const m of moves(par)) if (m.k !== RAPID) expect(m.z).toBeGreaterThan(dc.drop(m.x, m.y) - 0.02); + const wl = generateFor(part, { setup: s, op: op('waterline', ball, { stepdown: 1 }), tool: ball }); + const w = moves(wl).filter((m) => m.k === FEED); + expect(w.length).toBeGreaterThan(10); + for (const m of w) expect(m.z).toBeGreaterThan(dc.drop(m.x, m.y) - 0.02); + }, 60_000); + + it('drills and bores the holes picked, by their cylinders', () => { + const drill = tool('drill', 5, { tipAngle: 118 }); + const s = setup(); + const part = placePart(s, mesh(box(0, 0, 0, 40, 40, 10)))!; + // A through hole's wall as a cylinder of triangles (the plate itself has no hole: the + // check that its centre is empty is answered by the hole's own triangles only). + const wall: number[] = []; + for (let i = 0; i < 16; i++) { + const a = (i / 16) * Math.PI * 2, b = ((i + 1) / 16) * Math.PI * 2; + const p = (t: number, z: number) => [20 + 2.5 * Math.cos(t), 20 + 2.5 * Math.sin(t), z]; + wall.push(...p(a, 0), ...p(b, 0), ...p(b, 10), ...p(a, 0), ...p(b, 10), ...p(a, 10)); + } + const holed = placePart(s, mesh(box(0, 0, 0, 40, 17.5, 10), box(0, 22.5, 0, 40, 40, 10), box(0, 17.5, 0, 17.5, 22.5, 10), box(22.5, 17.5, 0, 40, 22.5, 10)))!; + const cyl = [{ name: 'F1', p: [20, 20, 0] as Vec3, d: [0, 0, 1] as Vec3, radius: 2.5, tris: Float32Array.from(wall) }]; + const tp = generateFor(holed, { setup: s, op: op('drill', drill, { cycle: 'peck', peck: 2 }), tool: drill, cylinders: cyl }); + const cycle = [...tp.moves].findIndex((v, i) => i % 4 === 0 && v === CYCLE); + expect(cycle).toBeGreaterThanOrEqual(0); + expect(tp.moves[cycle + 1]).toBeCloseTo(20, 6); + expect(tp.cycles[0].z).toBeLessThan(-1); + expect(tp.cycles[0].r).toBeCloseTo(13, 6); + // Bore it with a 3 mm end mill. + const em = tool('flat', 3); + const big = [{ ...cyl[0], radius: 2.5 }]; + const bore = generateFor(holed, { setup: s, op: op('bore', em, { pitch: 1 }), tool: em, cylinders: big, picked: ['F1'] }); + const helix = moves(bore).filter((m) => m.k === PLUNGE); + expect(helix.length).toBeGreaterThan(20); + for (const m of helix) expect(Math.hypot(m.x - 20, m.y - 20)).toBeCloseTo(1, 6); + void part; + }); +}); + +describe('simulation and G-code', () => { + it('reports a rapid move into the stock', () => { + const t = tool('flat', 6); + const s = setup(); + const part = placePart(s, mesh(box(0, 0, 0, 20, 20, 10)))!; + const tp: Toolpath = { moves: Float64Array.from([RAPID, -10, 10, 30, RAPID, -10, 10, 11, RAPID, 30, 10, 11]), cycles: [], clearance: 22, warnings: [] }; + const sim = simulate({ stock: part.frame.stock, part: part.index, steps: [{ toolpath: tp, tool: t, feed: 1000, plunge: 300 }], rapidFeed: 5000 }); + expect(sim.rapidCuts[0]).toBeGreaterThan(0); + expect(sim.time).toBeGreaterThan(0); + }); + + it('writes arcs for points on a circle', () => { + const pts: number[] = []; + for (let i = 0; i <= 20; i++) { const a = (i / 20) * Math.PI * 0.8; pts.push(10 * Math.cos(a), 10 * Math.sin(a), -i * 0.05); } + const arcs: unknown[] = []; + let lines = 0; + writeArcs(pts, 0.005, () => lines++, (...a) => arcs.push(a)); + expect(arcs).toHaveLength(1); + expect(lines).toBe(0); + expect((arcs[0] as [boolean])[0]).toBe(false); + }); + + it('posts G-code with tool changes, arcs and canned cycles, per controller', () => { + const t = tool('flat', 6); + const d = tool('drill', 5, { number: 2, name: '5 mm drill' }); + const s = setup(); + const part = placePart(s, pocketPlate)!; + const pocket = generateFor(part, { setup: s, op: op('pocket', t, { stepdown: 5 }), tool: t, floors: [floorTris] }); + const drill: Toolpath = { moves: Float64Array.from([RAPID, 10, 10, 32, CYCLE, 10, 10, 0, CYCLE, 20, 10, 1]), cycles: [{ cycle: 'peck', r: 23, z: 0, peck: 2, dwell: 0 }, { cycle: 'peck', r: 23, z: 0, peck: 2, dwell: 0 }], clearance: 32, warnings: [] }; + const job = (controller: 'fanuc' | 'grbl' | 'linuxcnc') => ({ + name: 'Plate (test)', units: 'mm' as const, + post: { ...newCamDoc(() => 'x').post, controller }, + setups: [{ name: 'Setup1', workOffset: 54, ops: [ + { name: 'Pocket1', tool: t, rpm: 9000, feed: 800, plunge: 200, toolpath: pocket }, + { name: 'Drill1', tool: d, rpm: 2000, feed: 200, plunge: 150, toolpath: drill }, + ] }], + }); + const fanuc = postProcess(job('fanuc')); + expect(fanuc.startsWith('%\nO1001 (Plate test)')).toBe(true); + expect(fanuc).toContain('G21'); + expect(fanuc).toContain('T1 M6'); + expect(fanuc).toContain('T2 M6'); + expect(fanuc).toMatch(/G43 Z\S+ H1/); + expect(fanuc).toMatch(/\nG[23] X/); + expect(fanuc).toMatch(/G98 G83 X10\. Y10\. Z0\. R23\. Q2\. F150/); + expect(fanuc).toContain('\nX20. Y10.\n'); + expect(fanuc.trimEnd().endsWith('M30\n%')).toBe(true); + const grbl = postProcess(job('grbl')); + expect(grbl).not.toMatch(/M6|G43|G83|^%/m); + expect(grbl).toContain('M0'); + const linux = postProcess(job('linuxcnc')); + expect(linux).not.toMatch(/^O\d/m); + expect(linux).toContain('M2'); + // Inches: values divided by 25.4. + const inch = postProcess({ ...job('fanuc'), units: 'in' }); + expect(inch).toContain('G20'); + expect(inch).toContain('R0.9055'); + const st = pathStats(pocket, 800, 200, 5000); + expect(st.time).toBeGreaterThan(0); + expect(st.zMin).toBeCloseTo(10, 6); + }, 60_000); + + it('reads CAM data back and drops what is damaged', () => { + const doc = newCamDoc((p) => `${p}9`); + const raw = JSON.parse(JSON.stringify({ ...doc, tools: [...doc.tools.slice(0, 1), { id: 'bad', type: 'laser' }], setups: [{ id: 's1', name: 'S', axis: '+Q', ops: [{ id: 'o1', name: 'P', type: 'pocket', tool: doc.tools[0].id, faces: 'nope' }, { id: 'o2', name: 'F', type: 'face', tool: doc.tools[0].id }] }] })); + const n = normalizeCam(raw)!; + expect(n.tools).toHaveLength(1); + expect(n.setups[0].axis).toBe('+Y'); + expect(n.setups[0].ops.map((o) => o.id)).toEqual(['o2']); + expect((n.setups[0].ops[0] as { stepover: number }).stepover).toBeGreaterThan(0); + expect(normalizeCam('x')).toBeNull(); + }); +}); From 4a7c8bfd30484f3f0389cc9070a5b7383eb47fac Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:13:42 -0700 Subject: [PATCH 02/34] Parametric: CAM tab, setups, operations, simulation and post processing in the interface --- src/parametric/src/app/app.ts | 17 + src/parametric/src/app/cam/dialogs.ts | 216 ++++++++ src/parametric/src/app/cam/index.ts | 315 +++++++++++ src/parametric/src/app/cam/panels.ts | 522 +++++++++++++++++++ src/parametric/src/app/cam/simulate-panel.ts | 344 ++++++++++++ src/parametric/src/app/cam/workspace.ts | 383 ++++++++++++++ src/parametric/src/app/tree.ts | 27 +- src/parametric/src/cam/client.ts | 110 ++++ src/parametric/src/cam/engine.ts | 14 + src/parametric/src/cam/ops.ts | 87 +++- src/parametric/src/cam/simulate.ts | 5 +- src/parametric/src/cam/worker.ts | 62 +++ src/parametric/src/main.ts | 2 + src/parametric/src/render/renderer.ts | 107 ++++ src/parametric/src/styles/app.css | 31 ++ src/parametric/tests/cam-kernel.test.ts | 118 +++++ 16 files changed, 2333 insertions(+), 27 deletions(-) create mode 100644 src/parametric/src/app/cam/dialogs.ts create mode 100644 src/parametric/src/app/cam/index.ts create mode 100644 src/parametric/src/app/cam/panels.ts create mode 100644 src/parametric/src/app/cam/simulate-panel.ts create mode 100644 src/parametric/src/app/cam/workspace.ts create mode 100644 src/parametric/src/cam/client.ts create mode 100644 src/parametric/src/cam/worker.ts create mode 100644 src/parametric/tests/cam-kernel.test.ts diff --git a/src/parametric/src/app/app.ts b/src/parametric/src/app/app.ts index 1d0e8cb0c..abe5aa6bd 100644 --- a/src/parametric/src/app/app.ts +++ b/src/parametric/src/app/app.ts @@ -137,6 +137,8 @@ export class App { onDocumentChanged: (reason: string) => void = () => {}; /** Renames the part and its saved file, as Rename Part does (set by the file operations). */ renamePart: ((name: string) => Promise) | null = null; + /** CAM of the part: toolpaths and their display (set up by the CAM module). */ + cam: import('./cam/workspace').CamWorkspace | null = null; /** The open assembly's interface and geometry; null while a part is open (set up by the assembly module). */ assembly: AssemblyMode | null = null; /** Called when a document is loaded, to switch between part and assembly mode (set by the assembly module). */ @@ -387,7 +389,16 @@ export class App { this.setRibbonTab(this.ribbonTab); } + /** The CommandManager tab shown. */ + get ribbonTabId(): string { + return this.ribbonTab; + } + + /** Called when another CommandManager tab is shown. */ + readonly ribbonTabListeners: ((id: string) => void)[] = []; + setRibbonTab(id: string) { + const changed = id !== this.ribbonTab; this.ribbonTab = id; for (const b of this.shell.cmTabs.querySelectorAll('[role="tab"]')) { b.setAttribute('aria-selected', String(b.dataset.tab === id)); @@ -409,6 +420,7 @@ export class App { } const tab = this.hooks.ribbonTabs.find((t) => t.id === id)!; renderRibbon(this.shell.cmTools, tab, this.commands); + if (changed) for (const fn of this.ribbonTabListeners) fn(id); } private buildHud() { @@ -1101,6 +1113,11 @@ export class App { if (this.inDrawing) void this.drawing.refresh(); } + /** The part's body mesh as the last rebuild made it (null without one). */ + get modelMesh(): MeshData | null { + return this.shownMesh; + } + /** Shows the part's body again after a mode showed another mesh in its place (the flat pattern). */ showModelMesh() { this.renderer.setModel(this.shownMesh, this.faces.length, this.edges.length); diff --git a/src/parametric/src/app/cam/dialogs.ts b/src/parametric/src/app/cam/dialogs.ts new file mode 100644 index 000000000..c4453ee9d --- /dev/null +++ b/src/parametric/src/app/cam/dialogs.ts @@ -0,0 +1,216 @@ +// CAM dialogs: the tool library and post processing to G-code. + +import { CamCancelled } from '../../cam/client'; +import { postProcess, type PostOperation } from '../../cam/post'; +import { type CamController, type CamTool, type CamToolType, CONTROLLER_LABELS, TOOL_TYPE_LABELS, opFeeds } from '../../model/cam'; +import { allocateId } from '../../model/document'; +import { UNIT_SYSTEMS } from '../../model/units'; +import { download, safeName } from '../../platform/files'; +import { h, nextDomId } from '../../ui/dom'; +import { icon } from '../../ui/icons'; +import { showDialog, toast } from '../../ui/overlay'; +import type { App } from '../app'; +import { checkbox, numberField, selectField } from '../pm'; +import { rateField } from './panels'; +import type { CamWorkspace } from './workspace'; + +const TYPES = Object.entries(TOOL_TYPE_LABELS).map(([value, label]) => ({ value: value as CamToolType, label })); + +/** The tool library: add, change and remove the part's cutting tools (one undo step). */ +export async function toolLibraryDialog(app: App, ws: CamWorkspace, select?: string) { + ws.ensureCam(); + const cam = app.store.doc.cam!; + const tools: CamTool[] = structuredClone(cam.tools); + const used = (id: string) => cam.setups.flatMap((s) => s.ops).filter((o) => o.tool === id).length; + let current = tools.find((t) => t.id === select) ?? tools[0] ?? null; + const ctx = app.unitContext(); + const u = UNIT_SYSTEMS[ctx.units]; + const fs = ctx.units === 'IPS' ? 25.4 : 1, fu = ctx.units === 'IPS' ? 'in/min' : 'mm/min'; + const list = h('div', { class: 'cam-tool-list', role: 'listbox', 'aria-label': 'Tools', tabindex: '0' }); + const form = h('div', { class: 'cam-tool-form' }); + const msg = h('p', { class: 'pm-msg', role: 'status', hidden: true }); + let nextLocal = 0; + const newId = () => { + // Ids from the part's counter (taken on OK); until then a placeholder. + nextLocal++; + return `__new${nextLocal}`; + }; + const drawList = () => { + list.textContent = ''; + for (const t of [...tools].sort((a, b) => a.number - b.number)) { + const opt = h('div', { role: 'option', class: 'cam-tool', 'aria-selected': String(t === current), tabindex: '-1' }, + h('span', { class: 'num' }, `T${t.number}`), h('span', { class: 'grow' }, t.name), h('span', { class: 'muted' }, `${TOOL_TYPE_LABELS[t.type]} · ${formatLen(t.diameter)}`)); + opt.addEventListener('click', () => { current = t; drawList(); drawForm(); }); + list.append(opt); + } + }; + const formatLen = (mm: number) => `${Number((mm / u.scale).toPrecision(6))} ${u.length}`; + list.addEventListener('keydown', (e) => { + const sorted = [...tools].sort((a, b) => a.number - b.number); + const i = current ? sorted.indexOf(current) : -1; + if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { + e.preventDefault(); + current = sorted[Math.max(0, Math.min(sorted.length - 1, i + (e.key === 'ArrowDown' ? 1 : -1)))] ?? null; + drawList(); drawForm(); + } + }); + const drawForm = () => { + form.textContent = ''; + msg.hidden = true; + const t = current; + if (!t) { form.append(h('p', { class: 'field-label' }, 'No tools. Add one.')); return; } + const nameId = nextDomId('tn'); + const name = h('input', { class: 'input', id: nameId, value: t.name }) as HTMLInputElement; + name.addEventListener('input', () => { t.name = name.value; drawList(); }); + const corner = numberField({ label: 'Corner radius', value: t.cornerRadius ?? 0, kind: 'length', ctx, min: 0, allowExpr: false, onChange: (v) => { t.cornerRadius = Number(v); } }); + const tip = numberField({ label: 'Point angle', value: t.tipAngle ?? (t.type === 'drill' ? 118 : 90), kind: 'angle', ctx, min: 10, max: 179, allowExpr: false, onChange: (v) => { t.tipAngle = Number(v); } }); + corner.hidden = t.type !== 'bull'; + tip.hidden = t.type !== 'drill' && t.type !== 'chamfer'; + form.append( + h('div', {}, h('label', { class: 'field-label', for: nameId }, 'Name'), name), + selectField('Type', t.type, TYPES, (v) => { + t.type = v; + if (v === 'drill' || v === 'chamfer') t.tipAngle ??= v === 'drill' ? 118 : 90; + if (v === 'bull') t.cornerRadius ??= Math.min(1, t.diameter / 4); + drawList(); drawForm(); + }), + numberField({ label: 'Tool number', value: t.number, kind: 'count', ctx, min: 0, max: 9999, allowExpr: false, onChange: (v) => { t.number = Number(v); drawList(); } }), + numberField({ label: 'Diameter', value: t.diameter, kind: 'length', ctx, min: 0.01, allowExpr: false, onChange: (v) => { t.diameter = Number(v); drawList(); } }), + corner, tip, + numberField({ label: 'Flute length', value: t.fluteLength, kind: 'length', ctx, min: 0.01, allowExpr: false, onChange: (v) => { t.fluteLength = Number(v); } }), + numberField({ label: 'Flutes', value: t.flutes, kind: 'count', ctx, min: 1, max: 20, allowExpr: false, onChange: (v) => { t.flutes = Number(v); } }), + rateField('Spindle speed', t.rpm, 'rpm', 1, (v) => { t.rpm = v ?? t.rpm; }, { whole: true }), + rateField('Cutting feed', t.feed, fu, fs, (v) => { t.feed = v ?? t.feed; }, { min: 0.001 }), + rateField('Plunge feed', t.plunge, fu, fs, (v) => { t.plunge = v ?? t.plunge; }, { min: 0.001 }), + checkbox('Coolant (M8)', t.coolant, (v) => { t.coolant = v; }), + ); + }; + const addBtn = h('button', { class: 'btn small', type: 'button' }, icon('plus', 14), 'Add'); + addBtn.addEventListener('click', () => { + const n = Math.max(0, ...tools.map((t) => t.number)) + 1; + const d = ctx.units === 'IPS' ? 6.35 : 6; + const t: CamTool = { id: newId(), number: n, name: `${formatLen(d)} flat end mill`, type: 'flat', diameter: d, fluteLength: d * 3, flutes: 3, rpm: 12000, feed: 700, plunge: 240, coolant: true }; + tools.push(t); + current = t; + drawList(); drawForm(); + }); + const dupBtn = h('button', { class: 'btn small', type: 'button' }, icon('copy', 14), 'Duplicate'); + dupBtn.addEventListener('click', () => { + if (!current) return; + const t = { ...structuredClone(current), id: newId(), number: Math.max(0, ...tools.map((x) => x.number)) + 1, name: `${current.name} (copy)` }; + tools.push(t); + current = t; + drawList(); drawForm(); + }); + const delBtn = h('button', { class: 'btn small', type: 'button' }, icon('trash', 14), 'Delete'); + delBtn.addEventListener('click', () => { + if (!current) return; + const n = used(current.id); + if (n) { msg.hidden = false; msg.className = 'pm-msg warn'; msg.textContent = `${current.name} is used by ${n} operation${n === 1 ? '' : 's'}. Choose another tool for ${n === 1 ? 'it' : 'them'} first.`; return; } + tools.splice(tools.indexOf(current), 1); + current = tools[0] ?? null; + drawList(); drawForm(); + }); + drawList(); + drawForm(); + const body = h('div', { class: 'cam-tools' }, + h('div', { class: 'cam-tools-side' }, list, h('div', { class: 'row' }, addBtn, dupBtn, delBtn), msg), + form); + const v = await showDialog({ + title: 'Tool Library', body, wide: true, signal: app.documentSignal, + buttons: [{ label: 'Cancel', value: 'cancel' }, { label: 'OK', primary: true, value: 'ok' }], + onAction: (val) => { + if (val !== 'ok') return; + const numbers = tools.map((t) => t.number); + if (new Set(numbers).size !== numbers.length) { msg.hidden = false; msg.className = 'pm-msg error'; msg.textContent = 'Two tools have the same number. Give each tool its own number.'; return false; } + if (tools.some((t) => !t.name.trim())) { msg.hidden = false; msg.className = 'pm-msg error'; msg.textContent = 'Every tool needs a name.'; return false; } + return true; + }, + }); + if (v !== 'ok') return; + app.store.change('Edit tool library', (d) => { + for (const t of tools) if (t.id.startsWith('__new')) t.id = allocateId(d, 't'); + d.cam!.tools = tools; + }); + ws.changed(); +} + +const EXTENSIONS: Record = { fanuc: 'nc', haas: 'nc', mach3: 'tap', linuxcnc: 'ngc', grbl: 'gcode' }; + +/** Writes the G-code of the setups for a controller and downloads it. */ +export async function postDialog(app: App, ws: CamWorkspace) { + const cam = ws.cam; + if (!cam?.setups.some((s) => s.ops.some((o) => !o.suppressed))) { toast({ kind: 'info', message: 'Add a setup with operations first (CAM tab).' }); return; } + const why = ws.ready(); + if (why) { toast({ kind: 'warning', message: why }); return; } + const post = structuredClone(cam.post); + const units = post.units ?? (app.store.doc.units === 'IPS' ? 'in' : 'mm'); + let unitsSel: 'mm' | 'in' = units; + const chosen = new Set(cam.setups.map((s) => s.id)); + const preview = h('pre', { class: 'cam-gcode', tabindex: '0', 'aria-label': 'G-code preview' }, 'Generating toolpaths...'); + const status = h('p', { class: 'pm-msg', role: 'status', hidden: true }); + let code = ''; + const make = async () => { + status.hidden = true; + try { + await ws.generate(cam.setups.filter((s) => chosen.has(s.id)).map((s) => s.id)); + } catch (e) { + if (e instanceof CamCancelled) return; + } + const now = ws.cam!; + const setups = now.setups.filter((s) => chosen.has(s.id)).map((s) => { + const ops: PostOperation[] = []; + for (const o of s.ops) { + if (o.suppressed) continue; + const r = ws.result(o.id), tool = ws.toolOf(o); + if (!tool || !r?.toolpath || ws.state(s, o) !== 'ok') { status.hidden = false; status.className = 'pm-msg error'; status.textContent = `${o.name} has no toolpath${r?.error ? `: ${r.error}` : ''}. It is left out.`; continue; } + const f = opFeeds(o, tool); + ops.push({ name: o.name, tool, rpm: f.rpm, feed: f.feed, plunge: f.plunge, toolpath: r.toolpath }); + } + return { name: s.name, workOffset: s.workOffset, ops }; + }).filter((s) => s.ops.length); + const date = new Date().toISOString().slice(0, 10); + code = setups.length ? postProcess({ name: app.store.doc.name, post: { ...post, units: unitsSel }, units: unitsSel, setups, notes: [`Parametric CAM, ${date}`, `Post: ${CONTROLLER_LABELS[post.controller]}`] }) : ''; + const lines = code.split('\n'); + preview.textContent = code ? `${lines.slice(0, 400).join('\n')}${lines.length > 400 ? `\n... ${lines.length - 400} more lines` : ''}` : 'Nothing to post.'; + count.textContent = code ? `${lines.length - 1} lines` : ''; + }; + const count = h('span', { class: 'field-label' }); + const refresh = () => { preview.textContent = 'Writing...'; void make(); }; + const setupChecks = cam.setups.map((s) => checkbox(s.name, true, (v) => { if (v) chosen.add(s.id); else chosen.delete(s.id); refresh(); })); + const progNum = h('input', { class: 'input', id: nextDomId('prog'), inputmode: 'numeric', value: String(post.program) }) as HTMLInputElement; + progNum.addEventListener('change', () => { const n = Math.round(Number(progNum.value)); if (n >= 1 && n <= 99999) { post.program = n; refresh(); } }); + const body = h('div', { class: 'cam-post' }, + h('div', { class: 'cam-post-side' }, + selectField('Machine controller', post.controller, Object.entries(CONTROLLER_LABELS).map(([value, label]) => ({ value: value as CamController, label })), (v) => { post.controller = v; refresh(); }), + selectField<'mm' | 'in'>('Units', unitsSel, [{ value: 'mm', label: 'Millimetres (G21)' }, { value: 'in', label: 'Inches (G20)' }], (v) => { unitsSel = v; refresh(); }), + h('div', {}, h('label', { class: 'field-label', for: progNum.id }, 'Program number'), progNum), + checkbox('Arcs (G2/G3)', post.arcs, (v) => { post.arcs = v; refresh(); }), + checkbox('Drilling cycles (G81/G83)', post.cannedCycles, (v) => { post.cannedCycles = v; refresh(); }), + checkbox('Line numbers', post.lineNumbers, (v) => { post.lineNumbers = v; refresh(); }), + h('div', { class: 'field-label' }, 'Setups'), ...setupChecks, + status), + h('div', { class: 'cam-post-main' }, preview, count)); + void make(); + const v = await showDialog({ + title: 'Post Process', body, wide: true, signal: app.documentSignal, + buttons: [{ label: 'Cancel', value: 'cancel' }, { label: 'Copy', value: 'copy' }, { label: 'Download G-code', primary: true, value: 'ok' }], + onAction: async (val) => { + if (val === 'cancel') return; + if (!code) await make(); + if (!code) { status.hidden = false; status.className = 'pm-msg error'; status.textContent = 'There is no G-code to write.'; return false; } + if (val === 'copy') { + try { await navigator.clipboard.writeText(code); toast({ kind: 'success', message: 'G-code copied' }); } catch { toast({ kind: 'error', message: 'Could not copy to the clipboard' }); } + return false; + } + return true; + }, + }); + if (v !== 'ok' || !code) return; + // Keep the post settings with the part. + if (JSON.stringify({ ...cam.post }) !== JSON.stringify({ ...post, units: unitsSel === (app.store.doc.units === 'IPS' ? 'in' : 'mm') ? post.units : unitsSel })) { + app.store.change('Post settings', (d) => { if (d.cam) d.cam.post = { ...post, ...(unitsSel !== (d.units === 'IPS' ? 'in' : 'mm') ? { units: unitsSel } : {}) }; }); + } + download(code, `${safeName(app.store.doc.name)}.${EXTENSIONS[post.controller]}`, 'text/plain'); + toast({ kind: 'success', message: `G-code written for ${CONTROLLER_LABELS[post.controller]}` }); +} diff --git a/src/parametric/src/app/cam/index.ts b/src/parametric/src/app/cam/index.ts new file mode 100644 index 000000000..201548d77 --- /dev/null +++ b/src/parametric/src/app/cam/index.ts @@ -0,0 +1,315 @@ +// CAM in the interface: the CAM tab of the CommandManager, its commands, +// the CAM rows of the design tree and their menus. + +import type { CamOperation, CamSetup, CamOpType } from '../../model/cam'; +import { CAM_OP_ICONS, CAM_OP_LABELS, findOp, nextCamName } from '../../model/cam'; +import { allocateId } from '../../model/document'; +import type { Id } from '../../model/types'; +import { addIcons } from '../../ui/icons'; +import { type MenuItem, openMenu as showMenu } from '../../ui/menu'; +import { confirmDialog, promptDialog, toast } from '../../ui/overlay'; +import type { App, AppHooks } from '../app'; +import type { Command } from '../commands'; +import type { RibbonTab } from '../shell'; +import { postDialog, toolLibraryDialog } from './dialogs'; +import { CamPanel, OperationPanel, SetupPanel, defaultTool, newOperation } from './panels'; +import { SimulationPanel } from './simulate-panel'; +import { CamWorkspace } from './workspace'; + +const P = (d: string, cls?: string): [string, Record] => (cls ? ['path', { d, class: cls }] : ['path', { d }]); +const C = (cx: number, cy: number, r: number, cls?: string): [string, Record] => (cls ? ['circle', { cx, cy, r, class: cls }] : ['circle', { cx, cy, r }]); +const DASH = (d: string, dash = '2.5 2'): [string, Record] => ['path', { d, 'stroke-dasharray': dash }]; + +addIcons({ + // An end mill over a block. + cam: [P('M3 16l9-4 9 4-9 4z', 's'), P('M3 16v3l9 4 9-4v-3'), P('M10 2h4v4h-4z'), P('M10.5 6v5l1.5 1 1.5-1V6', 'a')], + camSetup: [P('M3 15l9-4 9 4-9 4z', 's'), P('M3 15v3l9 4 9-4v-3'), P('M12 14V3'), P('M10 5l2-2 2 2'), C(12, 15, 1.2, 'f')], + camStock: [P('M3 8l9-4 9 4-9 4z', 's'), P('M3 8v8l9 4 9-4V8'), P('M12 12v8')], + camTool: [P('M9 2h6v6H9z'), P('M10 8v9l2 3 2-3V8', 'a'), P('M10 11l4-2M10 14l4-2', 'thin')], + camTools: [P('M4 3h4v4H4zM10 3h4v4h-4zM16 3h4v4h-4z'), P('M5 7v9l1 2 1-2V7M11 7v11l1 2 1-2V7M17 7v7l1 2 1-2V7', 'a')], + camFace: [P('M3 13l9-4 9 4-9 4z', 'a'), P('M3 13v4l9 4 9-4v-4'), P('M10 2h4v3h-4zM10.5 5v4h3V5'), DASH('M5 12l8 3.5M8 10.5l8 3.5')], + camContour: [P('M5 9l7-3 7 3v7l-7 3-7-3z', 's'), P('M3 9.5l9-4.5 9 4.5v7.5l-9 4.5-9-4.5z'), P('M12 1v4', 'thin'), C(3, 10, 1.3, 'f')], + camPocket: [P('M3 10l9-4 9 4v6l-9 4-9-4z', 's'), P('M7 11l5-2 5 2-5 2z', 'a'), P('M7 11v2l5 2 5-2v-2'), DASH('M9 11.2l3 1.2 3-1.2')], + camDrill: [P('M3 15l9-4 9 4-9 4z', 's'), P('M3 15v3l9 4 9-4v-3'), P('M10.5 2h3v8l-1.5 3-1.5-3z', 'a'), P('M10.5 5l3-1.5M10.5 8l3-1.5', 'thin')], + camBore: [P('M3 15l9-4 9 4-9 4z', 's'), P('M3 15v3l9 4 9-4v-3'), ['ellipse', { cx: 12, cy: 15, rx: 4, ry: 1.8 }], P('M14 3v7a2 2 0 0 1-2 2'), DASH('M8 6c0 2 8 2 8 0M8 9c0 2 8 2 8 0')], + camRough: [P('M3 17l9-4 9 4-9 4z', 's'), P('M6 13l6-3 6 3M8 9l4-2 4 2', 'a'), P('M3 17v1l9 4 9-4v-1')], + camParallel: [P('M3 18c4-9 14-9 18 0', 's'), P('M5 17c3-6 11-6 14 0'), DASH('M7 12l10 0M5.5 15h13M9 9.5h6')], + camWaterline: [P('M5 20c0-8 3-16 7-16s7 8 7 16', 's'), P('M6.3 16h11.4M7.5 12h9M9.4 8h5.2', 'a')], + camGenerate: [P('M4 18c3-8 6-8 8-4s5 4 8-6'), P('M16 8l4 0 0 4'), C(4, 18, 1.4, 'f')], + camSimulate: [P('M3 15l9-4 9 4-9 4z', 's'), P('M3 15v3l9 4 9-4v-3'), P('M15 2v7l-1.5 2.5L12 9V2', 'a'), P('M7 13.5l3 1.5', 'thick-a')], + camPost: [P('M6 2h9l4 4v16H6z'), P('M15 2v4h4'), P('M9 10h7M9 13h5M9 16h7', 'thin'), P('M2 13h3M4 11l2 2-2 2')], + play: [P('M7 4l13 8-13 8z', 'a')], + pause: [P('M7 4h3v16H7zM14 4h3v16h-3z', 'a')], +}); + +/** The setup new operations go in: the one focused, else the last one. */ +function currentSetup(ws: CamWorkspace): CamSetup | null { + const cam = ws.cam; + if (!cam?.setups.length) return null; + if (ws.focus) { + const s = cam.setups.find((x) => x.id === ws.focus || x.ops.some((o) => o.id === ws.focus)); + if (s) return s; + } + return cam.setups[cam.setups.length - 1]; +} + +function newSetup(app: App, ws: CamWorkspace): CamSetup { + const cam = ws.cam; + const inch = app.store.doc.units === 'IPS'; + // A second setup usually machines the other side. + const prev = cam?.setups[cam.setups.length - 1]; + const flip: Record = { '+X': '-X', '-X': '+X', '+Y': '-Y', '-Y': '+Y', '+Z': '-Z', '-Z': '+Z' }; + return { + id: '', name: nextCamName(cam?.setups.map((s) => s.name) ?? [], 'Setup'), + axis: prev ? flip[prev.axis] : '+Y', rotation: 0, origin: 'topFrontLeft', + stock: prev ? structuredClone(prev.stock) : { mode: 'offset', side: inch ? 2.54 : 2, top: inch ? 1.27 : 1, bottom: 0, size: [0, 0, 0] }, + clearance: inch ? 12.7 : 10, retract: inch ? 2.54 : 3, workOffset: prev ? Math.min(59, prev.workOffset + 1) : 54, ops: [], + }; +} + +export function installCam(app: App, hooks: AppHooks): CamWorkspace { + const ws = new CamWorkspace(app); + app.cam = ws; + const c = app.commands; + const partOnly = () => !app.assembly && !app.inDrawing; + const hasOps = () => partOnly() && !!ws.cam?.setups.some((s) => s.ops.length); + + const startSetup = () => { + if (!partOnly()) return; + const why = ws.ready(); + if (why) { toast({ kind: 'info', message: why }); return; } + void ws.mesh().then(() => { + const s = newSetup(app, ws); + ws.ensureCam(); + s.id = allocateId(app.store.doc, 's'); + app.exitModes(); + void app.openPanel(new SetupPanel(app, ws, s, true)); + }); + }; + + const startOp = (type: CamOpType) => { + if (!partOnly()) return; + const why = ws.ready(); + if (why) { toast({ kind: 'info', message: why }); return; } + const cam = ws.ensureCam(); + let setup = currentSetup(ws); + if (!setup) { + // A first operation comes with a setup from the top. + const s = newSetup(app, ws); + app.store.change('New setup', (d) => { s.id = allocateId(d, 's'); d.cam!.setups.push(s); }); + setup = ws.cam!.setups[0]; + } + const tool = defaultTool(cam.tools, type, cam.setups); + if (!tool) { toast({ kind: 'warning', message: 'Add a tool to the tool library first.' }); void toolLibraryDialog(app, ws); return; } + const op = newOperation(type, allocateId(app.store.doc, 'op'), nextCamName(cam.setups.flatMap((s) => s.ops.map((o) => o.name)), CAM_OP_LABELS[type].replace(/^\d+D /, '').replace(/\s+/g, '')), tool); + // Pocket floors and holes picked beforehand go in. + const faces = app.selection.ofKind('face').map((it) => app.faces[it.index]).filter(Boolean); + if (op.type === 'pocket') op.faces = faces.filter((f) => f.type === 'plane').map((f) => ({ name: f.name, sig: { type: f.type, c: f.center, n: f.normal, area: f.area } })); + if (op.type === 'drill' || op.type === 'bore') op.holes = faces.filter((f) => f.type === 'cylinder').map((f) => ({ face: { name: f.name, sig: { type: f.type, c: f.center, n: f.normal, area: f.area } } })); + app.exitModes(); + void ws.mesh().then(() => app.openPanel(new OperationPanel(app, ws, setup.id, op, true))); + }; + + const opCommand = (type: CamOpType, desc: string, keywords: string): Command => ({ + id: `cam:${type}`, label: CAM_OP_LABELS[type], icon: CAM_OP_ICONS[type], description: desc, keywords: `cam machining cnc toolpath ${keywords}`, + enabled: partOnly, run: () => startOp(type), + }); + + const commands: Command[] = [ + { id: 'cam:setup', label: 'Setup', icon: 'camSetup', keywords: 'cam machining cnc stock work origin wcs g54 fixture', description: 'Set how the part sits on the machine: the tool direction, the stock and the work origin.', enabled: partOnly, run: startSetup }, + { id: 'cam:tools', label: 'Tool Library', icon: 'camTools', keywords: 'cam end mill drill cutter feeds speeds', description: 'The cutting tools: end mills, ball and bull nose mills, drills and chamfer mills, with their feeds and speeds.', enabled: partOnly, run: () => void toolLibraryDialog(app, ws) }, + opCommand('face', 'Face the top of the stock down to the top of the part.', 'facing'), + opCommand('contour', 'Cut round the outside of the part, with tabs to hold it.', 'profile 2d outside cutout'), + opCommand('pocket', 'Clear pockets down to picked floors.', '2d pocketing clear'), + opCommand('drill', 'Drill holes with a drilling cycle.', 'holes peck g81 g83'), + opCommand('bore', 'Mill holes larger than the tool along a helix.', 'helical boring circular'), + opCommand('rough', 'Remove the stock around the part in levels (3D roughing).', '3d adaptive clearing roughing'), + opCommand('parallel', 'Finish surfaces with parallel passes (3D).', '3d finishing raster scallop'), + opCommand('waterline', 'Finish walls with constant-height passes (3D).', '3d finishing contour z-level'), + { + id: 'cam:generate', label: 'Generate', icon: 'camGenerate', keywords: 'cam toolpath calculate regenerate', description: 'Generate the toolpaths that are not up to date.', + enabled: hasOps, run: () => void ws.generate(), + }, + { + id: 'cam:simulate', label: 'Simulate', icon: 'camSimulate', keywords: 'cam simulation stock material removal verify collision gouge', description: 'Watch the stock being cut by the setup\'s operations, and check for gouges and collisions.', + enabled: hasOps, checked: () => app.panel instanceof SimulationPanel, + run: () => { + if (app.panel instanceof SimulationPanel) { void app.closePanel(false); return; } + const s = currentSetup(ws); + if (!s) return; + const why = ws.ready(); + if (why) { toast({ kind: 'info', message: why }); return; } + app.exitModes(); + void app.openPanel(new SimulationPanel(app, ws, s.id)); + }, + }, + { id: 'cam:post', label: 'Post Process', icon: 'camPost', keywords: 'cam gcode g-code nc export cnc program fanuc haas grbl linuxcnc mach3', description: 'Write the toolpaths as G-code for a machine.', enabled: hasOps, run: () => void postDialog(app, ws) }, + ]; + c.register(...commands); + + const tab: RibbonTab = { + id: 'cam', label: 'CAM', + groups: [ + [{ cmd: 'cam:setup' }, { cmd: 'cam:tools' }], + [{ cmd: 'cam:face' }, { stack: [{ cmd: 'cam:contour' }, { cmd: 'cam:pocket' }] }, { stack: [{ cmd: 'cam:drill' }, { cmd: 'cam:bore' }] }], + [{ cmd: 'cam:rough' }, { stack: [{ cmd: 'cam:parallel' }, { cmd: 'cam:waterline' }] }], + [{ cmd: 'cam:generate' }, { cmd: 'cam:simulate' }, { cmd: 'cam:post' }], + ], + labels: ['Setup', '2D', '3D', 'Program'], + }; + // After Weldments, before Drafting. + const at = hooks.ribbonTabs.findIndex((t) => t.id === 'drawing'); + hooks.ribbonTabs.splice(at < 0 ? hooks.ribbonTabs.length : at, 0, tab); + + // Undo, redo and edits may remove operations: their toolpaths go. + app.store.on(() => { + const cam = ws.cam; + const ids = new Set(cam?.setups.flatMap((s) => s.ops.map((o) => o.id)) ?? []); + ws.prune(ids); + if (ws.focus && !ids.has(ws.focus) && !cam?.setups.some((s) => s.id === ws.focus)) ws.focus = null; + }); + ws.listeners.add(() => app.renderTrees()); + return ws; +} + +// ---------- design tree ---------- + +export interface CamRow { + key: string; + label: string; + icon: string; + depth: number; + children?: boolean; + expanded?: boolean; + muted?: string; + badge?: { kind: 'error' | 'warn'; text: string }; + selected?: boolean; + suppressed?: boolean; + action: () => void; + open: () => void; + menu: (x: number, y: number) => void; +} + +export function camTreeRows(app: App, expanded: (key: string) => boolean): CamRow[] { + const ws = app.cam; + const cam = ws?.cam; + if (!ws || !cam || !cam.setups.length || app.assembly) return []; + const rows: CamRow[] = []; + const show = (id: Id | null) => { + ws.focus = id; + if (app.ribbonTabId !== 'cam') app.setRibbonTab('cam'); + ws.changed(); + }; + const camOpen = expanded('cam'); + rows.push({ + key: 'cam', label: 'CAM', icon: 'cam', depth: 1, children: true, expanded: camOpen, selected: false, + action: () => show(null), open: () => app.setRibbonTab('cam'), + menu: (x, y) => app.openCommandMenu(['cam:setup', 'cam:tools', 'cam:generate', 'cam:post'], x, y, 'CAM menu'), + }); + if (!camOpen) return rows; + for (const s of cam.setups) { + const key = `cam:${s.id}`; + const open = expanded(key); + rows.push({ + key, label: s.name, icon: 'camSetup', depth: 2, children: s.ops.length > 0, expanded: open, selected: ws.focus === s.id, + action: () => show(s.id), open: () => editSetup(app, ws, s.id), menu: (x, y) => setupMenu(app, ws, s.id, x, y), + }); + if (!open) continue; + for (const o of s.ops) { + const st = ws.state(s, o); + const r = ws.result(o.id); + const busy = ws.busy?.id === o.id ? ` ${Math.round(ws.busy.progress * 100)}%` : ''; + rows.push({ + key: `cam:${o.id}`, label: o.name, icon: CAM_OP_ICONS[o.type], depth: 3, selected: ws.focus === o.id, suppressed: !!o.suppressed, + muted: st === 'busy' ? ` generating${busy}` : st === 'none' ? ' (not generated)' : '', + badge: st === 'error' ? { kind: 'error', text: r?.error ?? 'Error' } : st === 'stale' ? { kind: 'warn', text: 'Out of date: generate it again' } : r?.toolpath?.warnings.length && st === 'ok' ? { kind: 'warn', text: r.toolpath.warnings.join(' ') } : undefined, + action: () => show(o.id), open: () => editOp(app, ws, o.id), menu: (x, y) => opMenu(app, ws, o.id, x, y), + }); + } + } + return rows; +} + +function editSetup(app: App, ws: CamWorkspace, id: Id) { + const s = ws.cam?.setups.find((x) => x.id === id); + if (!s) return; + app.exitModes(); + void ws.mesh().then(() => app.openPanel(new SetupPanel(app, ws, s, false))); +} + +function editOp(app: App, ws: CamWorkspace, id: Id) { + const f = ws.cam && findOp(ws.cam, id); + if (!f) return; + app.exitModes(); + void ws.mesh().then(() => app.openPanel(new OperationPanel(app, ws, f.setup.id, f.op, false))); +} + +function openMenu(_app: App, items: MenuItem[], x: number, y: number, label: string) { + showMenu(items, x, y, { label }); +} + +function setupMenu(app: App, ws: CamWorkspace, id: Id, x: number, y: number) { + const s = ws.cam?.setups.find((v) => v.id === id); + if (!s) return; + const add = (type: CamOpType): MenuItem => ({ label: CAM_OP_LABELS[type], icon: CAM_OP_ICONS[type], run: () => { ws.focus = id; app.commands.run(`cam:${type}`); } }); + openMenu(app, [ + { label: 'Edit Setup', icon: 'edit', run: () => editSetup(app, ws, id) }, + { label: 'New Operation', icon: 'plus', submenu: () => (['face', 'contour', 'pocket', 'drill', 'bore', 'rough', 'parallel', 'waterline'] as CamOpType[]).map(add) }, + { separator: true }, + { label: 'Generate', icon: 'camGenerate', disabled: !s.ops.length, run: () => void ws.generate([id]) }, + { label: 'Simulate', icon: 'camSimulate', disabled: !s.ops.length, run: () => { ws.focus = id; app.commands.run('cam:simulate'); } }, + { label: 'Post Process...', icon: 'camPost', disabled: !s.ops.length, run: () => app.commands.run('cam:post') }, + { separator: true }, + { label: 'Rename', icon: 'text', run: () => void rename(app, s.name, (name) => app.store.change('Rename setup', (d) => { const v = d.cam?.setups.find((q) => q.id === id); if (v) v.name = name; })) }, + { label: 'Delete', icon: 'trash', run: () => void deleteSetup(app, ws, id) }, + ], x, y, 'Setup menu'); +} + +function opMenu(app: App, ws: CamWorkspace, id: Id, x: number, y: number) { + const f = ws.cam && findOp(ws.cam, id); + if (!f) return; + const { setup, op } = f; + const i = setup.ops.indexOf(op); + const move = (d: number) => app.store.change(`Move ${op.name}`, (doc) => { + const s = doc.cam?.setups.find((v) => v.id === setup.id); + if (!s) return; + const k = s.ops.findIndex((v) => v.id === id); + const j = k + d; + if (k < 0 || j < 0 || j >= s.ops.length) return; + [s.ops[k], s.ops[j]] = [s.ops[j], s.ops[k]]; + }); + openMenu(app, [ + { label: 'Edit Operation', icon: 'edit', run: () => editOp(app, ws, id) }, + { label: 'Generate', icon: 'camGenerate', disabled: !!op.suppressed, run: () => { ws.forget([id]); void ws.generate([id]); } }, + { label: 'Tool Library...', icon: 'camTools', run: () => void toolLibraryDialog(app, ws, op.tool) }, + { separator: true }, + { label: 'Move Up', icon: 'chevronUp', disabled: i <= 0, run: () => move(-1) }, + { label: 'Move Down', icon: 'chevronDown', disabled: i >= setup.ops.length - 1, run: () => move(1) }, + { label: 'Duplicate', icon: 'copy', run: () => app.store.change(`Duplicate ${op.name}`, (d) => { + const s = d.cam?.setups.find((v) => v.id === setup.id); + if (!s) return; + const copy: CamOperation = { ...structuredClone(op), id: allocateId(d, 'op'), name: nextCamName(d.cam!.setups.flatMap((v) => v.ops.map((o) => o.name)), op.name.replace(/\d+$/, '')) }; + s.ops.splice(s.ops.findIndex((v) => v.id === id) + 1, 0, copy); + }) }, + { label: op.suppressed ? 'Unsuppress' : 'Suppress', icon: op.suppressed ? 'eye' : 'eyeOff', run: () => app.store.change(op.suppressed ? 'Unsuppress' : 'Suppress', (d) => { + const o = d.cam && findOp(d.cam, id)?.op; + if (o) o.suppressed = !o.suppressed || undefined; + }) }, + { label: 'Rename', icon: 'text', run: () => void rename(app, op.name, (name) => app.store.change('Rename operation', (d) => { const o = d.cam && findOp(d.cam, id)?.op; if (o) o.name = name; })) }, + { separator: true }, + { label: 'Delete', icon: 'trash', run: () => app.store.change(`Delete ${op.name}`, (d) => { const s = d.cam?.setups.find((v) => v.id === setup.id); if (s) s.ops = s.ops.filter((v) => v.id !== id); }) }, + ], x, y, 'Operation menu'); +} + +async function rename(app: App, current: string, apply: (name: string) => void) { + const name = await promptDialog('Rename', 'Name', current, (v) => (v.trim() ? null : 'Enter a name'), app.documentSignal); + if (name && name.trim() !== current) apply(name.trim()); +} + +async function deleteSetup(app: App, ws: CamWorkspace, id: Id) { + const s = ws.cam?.setups.find((v) => v.id === id); + if (!s) return; + if (s.ops.length && !(await confirmDialog('Delete setup', `Delete ${s.name} and its ${s.ops.length} operation${s.ops.length === 1 ? '' : 's'}?`, 'Delete', true, app.documentSignal))) return; + if (app.panel instanceof CamPanel) await app.closePanel(false); + app.store.change(`Delete ${s.name}`, (d) => { if (d.cam) d.cam.setups = d.cam.setups.filter((v) => v.id !== id); }); +} diff --git a/src/parametric/src/app/cam/panels.ts b/src/parametric/src/app/cam/panels.ts new file mode 100644 index 000000000..b465c6815 --- /dev/null +++ b/src/parametric/src/app/cam/panels.ts @@ -0,0 +1,522 @@ +// PropertyManager panels of CAM: a setup (tool direction, work origin, +// stock, heights) and each kind of operation (tool, passes, geometry, +// feeds), with the toolpath previewed while the values change. + +import type { CamAxis, CamOperation, CamOrigin, CamSetup, CamTool, ClearingPattern, DrillCycle, EntryKind } from '../../model/cam'; +import { CAM_OP_ICONS, CAM_OP_LABELS, TOOL_TYPE_LABELS, opDefaults, opToolTypes } from '../../model/cam'; +import { UNIT_SYSTEMS, formatNumber } from '../../model/units'; +import type { FaceRef, Id } from '../../model/types'; +import { pathStats, type Toolpath } from '../../cam/toolpath'; +import { h, nextDomId } from '../../ui/dom'; +import { icon } from '../../ui/icons'; +import type { App } from '../app'; +import { PropertyPanel, SelectionBox, type SelBoxItem, checkbox, fmt, numberField, section, segmented, selectField, type UnitContext } from '../pm'; +import { faceRef, type SelItem } from '../selection'; +import type { CamWorkspace } from './workspace'; + +/** Panels of CAM (the workspace shows its overlays while one is open). */ +export abstract class CamPanel extends PropertyPanel { + readonly camPanel = true; +} + +const AXES: { value: CamAxis; label: string }[] = [ + { value: '+Y', label: 'From the top (+Y)' }, + { value: '-Y', label: 'From the bottom (−Y)' }, + { value: '+Z', label: 'From the front (+Z)' }, + { value: '-Z', label: 'From the back (−Z)' }, + { value: '+X', label: 'From the right (+X)' }, + { value: '-X', label: 'From the left (−X)' }, +]; + +const ORIGINS: { value: CamOrigin; label: string }[] = [ + { value: 'topFrontLeft', label: 'Stock top, front left corner' }, + { value: 'topBackLeft', label: 'Stock top, back left corner' }, + { value: 'topCenter', label: 'Stock top, centre' }, + { value: 'bottomFrontLeft', label: 'Stock bottom, front left corner' }, + { value: 'modelOrigin', label: 'Part origin' }, +]; + +/** + * A plain number in a unit of its own (feeds, speeds): feeds are shown in + * the part's length unit per minute. + */ +export function rateField(label: string, value: number | undefined, unit: string, scale: number, onChange: (v: number | undefined) => void, opts: { placeholder?: number; min?: number; whole?: boolean } = {}): HTMLElement { + const id = nextDomId('rate'); + const show = (v: number) => formatNumber(v / scale, opts.whole ? 0 : 2).replace(/\.?0+$/, '') || '0'; + const input = h('input', { + class: 'input', id, inputmode: 'decimal', autocomplete: 'off', spellcheck: 'false', 'aria-label': `${label} (${unit})`, + value: value === undefined ? '' : show(value), placeholder: opts.placeholder === undefined ? '' : show(opts.placeholder), + }) as HTMLInputElement; + const commit = () => { + const t = input.value.trim(); + if (t === '' && opts.placeholder !== undefined) { input.classList.remove('invalid'); input.removeAttribute('aria-invalid'); input.title = ''; onChange(undefined); return; } + const v = Number(t); + const bad = !Number.isFinite(v) || t === '' ? 'Enter a number' : v < (opts.min ?? 0) ? `Must be at least ${opts.min ?? 0}` : ''; + input.classList.toggle('invalid', !!bad); + if (bad) { input.setAttribute('aria-invalid', 'true'); input.title = bad; return; } + input.removeAttribute('aria-invalid'); + input.title = ''; + onChange(opts.whole ? Math.round(v) * scale : v * scale); + }; + input.addEventListener('change', commit); + input.addEventListener('keydown', (e) => { if (e.key === 'Enter') commit(); }); + return h('div', {}, h('label', { class: 'field-label', for: id }, `${label} (${unit})`), h('div', { class: 'row' }, h('div', { class: 'spin grow' }, input))); +} + +const feedUnit = (ctx: UnitContext) => (ctx.units === 'IPS' ? 'in/min' : 'mm/min'); +const feedScale = (ctx: UnitContext) => (ctx.units === 'IPS' ? 25.4 : 1); + +/** A length with its name shown above it (CAM panels have many lengths side by side). */ +function len(label: string, value: number, ctx: UnitContext, onChange: (v: number) => void, min = 0): HTMLElement { + return numberField({ label, value, kind: 'length', ctx, min, allowExpr: false, onChange: (v) => onChange(Number(v)) }); +} + +// ---------- setup ---------- + +export class SetupPanel extends CamPanel { + title: string; + icon = 'camSetup'; + helpText = 'Where the part sits on the machine: the direction the tool comes from, the stock around the part and the work origin (G54).'; + private s: CamSetup; + private dirty = false; + + constructor(private app: App, private ws: CamWorkspace, setup: CamSetup, private readonly isNew: boolean) { + super(); + this.s = structuredClone(setup); + this.title = isNew ? 'New Setup' : setup.name; + this.editingId = null; + this.update(); + } + + get edited() { return this.dirty || this.isNew; } + + private update() { + this.ws.preview = { setup: this.s, op: null, toolpath: null }; + this.ws.redraw(); + } + + private changed() { + this.dirty = true; + this.update(); + } + + render(): HTMLElement[] { + const s = this.s; + const ctx = this.app.unitContext(); + const face = new SelectionBox(this, 'Top face (sets the direction)', { face: true, planarOnly: true }, (it) => this.toFace(it), (items) => { + const f = items[0]?.data as { axis: CamAxis } | undefined; + if (f) { s.axis = f.axis; this.changed(); this.app.refreshPanel(); } + }, { single: true, placeholder: 'Optional: a flat face facing the tool', icon: 'camSetup' }); + const stock = s.stock; + const offsets = h('div', {}, + len('Sides', stock.side, ctx, (v) => { stock.side = v; this.changed(); }), + len('Above the part', stock.top, ctx, (v) => { stock.top = v; this.changed(); }), + len('Below the part', stock.bottom, ctx, (v) => { stock.bottom = v; this.changed(); })); + const fixed = h('div', {}, + len('Width (X)', stock.size[0], ctx, (v) => { stock.size[0] = v; this.changed(); }), + len('Depth (Y)', stock.size[1], ctx, (v) => { stock.size[1] = v; this.changed(); }), + len('Height (Z)', stock.size[2], ctx, (v) => { stock.size[2] = v; this.changed(); }), + len('Above the part', stock.top, ctx, (v) => { stock.top = v; this.changed(); })); + offsets.hidden = stock.mode !== 'offset'; + fixed.hidden = stock.mode !== 'fixed'; + const frame = this.ws.frameOf(s); + const size = frame ? frame.stock : null; + const u = UNIT_SYSTEMS[ctx.units]; + return [ + section('Setup', [ + nameField('Name', s.name, (v) => { s.name = v; this.dirty = true; }), + selectField('Tool direction', s.axis, AXES, (v) => { s.axis = v; this.changed(); }, 'camSetup'), + face.el, + h('div', { class: 'field-label' }, 'Turn about the tool'), + segmented('Turn about the tool', String(s.rotation) as '0', [0, 90, 180, 270].map((a) => ({ value: String(a) as '0', label: `${a}°` })), (v) => { s.rotation = Number(v); this.changed(); }), + selectField('Work origin (G54)', s.origin, ORIGINS, (v) => { s.origin = v; this.changed(); }, 'origin'), + selectField('Work offset', String(s.workOffset), [54, 55, 56, 57, 58, 59].map((n) => ({ value: String(n), label: `G${n}` })), (v) => { s.workOffset = Number(v); this.dirty = true; }), + ], { icon: 'camSetup' }), + section('Stock', [ + segmented('Stock size', stock.mode, [{ value: 'offset', label: 'Around the part' }, { value: 'fixed', label: 'Fixed size' }], (v) => { + stock.mode = v; + if (v === 'fixed' && frame && stock.size.every((x) => !x)) stock.size = [0, 1, 2].map((k) => Math.ceil(frame.stock.max[k] - frame.stock.min[k])) as [number, number, number]; + offsets.hidden = v !== 'offset'; + fixed.hidden = v !== 'fixed'; + this.changed(); + this.app.refreshPanel(); + }), + offsets, fixed, + size ? h('p', { class: 'field-label', role: 'note' }, `Stock: ${formatNumber((size.max[0] - size.min[0]) / u.scale, ctx.decimals)} × ${formatNumber((size.max[1] - size.min[1]) / u.scale, ctx.decimals)} × ${formatNumber((size.max[2] - size.min[2]) / u.scale, ctx.decimals)} ${u.length}`) : null, + ], { icon: 'camStock' }), + section('Heights', [ + h('p', { class: 'field-label' }, 'Above the top of the stock: rapid moves between features go at the clearance height, feeds start from the retract height.'), + len('Clearance', s.clearance, ctx, (v) => { s.clearance = v; this.changed(); }), + len('Retract', s.retract, ctx, (v) => { s.retract = v; this.changed(); }), + ]), + ]; + } + + private toFace(it: SelItem): SelBoxItem | null { + if (it.kind !== 'face') return null; + const f = this.app.faces[it.index]; + if (!f?.normal) return null; + const n = f.normal; + const k = [0, 1, 2].reduce((a, b) => (Math.abs(n[b]) > Math.abs(n[a]) ? b : a), 0); + if (Math.abs(n[k]) < 0.999) { this.setMessage('warn', 'Pick a face square to the model\'s X, Y or Z axis.'); return null; } + const axis = `${n[k] > 0 ? '+' : '-'}${'XYZ'[k]}` as CamAxis; + return { item: it, data: { axis }, label: this.app.describe(it) }; + } + + ok(): boolean { + const s = this.s; + if (!s.name.trim()) { this.setMessage('error', 'Enter a name'); return false; } + const app = this.app; + this.ws.ensureCam(); + app.store.change(this.isNew ? 'New setup' : 'Edit setup', (d) => { + const cam = d.cam!; + const i = cam.setups.findIndex((x) => x.id === s.id); + if (i >= 0) cam.setups[i] = { ...structuredClone(s), ops: cam.setups[i].ops }; + else cam.setups.push(structuredClone(s)); + }); + this.ws.focus = s.id; + return true; + } + + dispose() { + this.ws.preview = null; + this.ws.changed(); + } +} + +function nameField(label: string, value: string, onChange: (v: string) => void): HTMLElement { + const id = nextDomId('name'); + const input = h('input', { class: 'input', id, value, autocomplete: 'off', spellcheck: 'false' }) as HTMLInputElement; + input.addEventListener('input', () => onChange(input.value)); + return h('div', {}, h('label', { class: 'field-label', for: id }, label), h('div', { class: 'row' }, h('div', { class: 'grow' }, input))); +} + +// ---------- operations ---------- + +/** A new operation of a type with defaults for its tool. */ +export function newOperation(type: CamOperation['type'], id: Id, name: string, tool: CamTool): CamOperation { + return { id, name, type, tool: tool.id, ...opDefaults(type, tool.diameter) } as unknown as CamOperation; +} + +/** The tool an operation of this type starts with: the last one used for it, else the first that fits. */ +export function defaultTool(tools: CamTool[], type: CamOperation['type'], setups: CamSetup[]): CamTool | null { + const fits = opToolTypes(type); + const used = setups.flatMap((s) => s.ops).filter((o) => o.type === type).map((o) => tools.find((t) => t.id === o.tool)).filter((t): t is CamTool => !!t); + if (used.length) return used[used.length - 1]; + for (const kind of fits) { + const t = tools.filter((x) => x.type === kind); + // Roughing and 2D work: the largest; finishing: the smallest. + if (t.length) return (type === 'parallel' || type === 'waterline' ? t.sort((a, b) => a.diameter - b.diameter) : t.sort((a, b) => b.diameter - a.diameter))[0]; + } + return tools[0] ?? null; +} + +export class OperationPanel extends CamPanel { + title: string; + icon: string; + helpText: string; + private o: CamOperation; + private dirty = false; + private timer = 0; + private seq = 0; + private toolpath: Toolpath | null = null; + private error: string | null = null; + private busy = false; + private info: HTMLElement = h('div'); + + constructor(private app: App, private ws: CamWorkspace, private setupId: Id, op: CamOperation, private readonly isNew: boolean) { + super(); + this.o = structuredClone(op); + this.title = isNew ? `New ${CAM_OP_LABELS[op.type]}` : op.name; + this.icon = CAM_OP_ICONS[op.type]; + this.helpText = HELP[op.type]; + // An operation already generated shows its toolpath at once. + const r = isNew ? null : ws.result(op.id); + if (r?.toolpath && ws.state(this.setup()!, op) === 'ok') this.toolpath = r.toolpath; + this.schedule(0); + } + + get edited() { return this.dirty || this.isNew; } + + private setup(): CamSetup | null { + return this.ws.cam?.setups.find((s) => s.id === this.setupId) ?? null; + } + + private tools(): CamTool[] { + return this.ws.cam?.tools ?? []; + } + + private changed() { + this.dirty = true; + this.schedule(450); + } + + /** Generates the preview after a pause in the changes. */ + private schedule(ms: number) { + clearTimeout(this.timer); + const setup = this.setup(); + if (!setup) return; + this.ws.preview = { setup, op: this.o, toolpath: this.toolpath }; + this.ws.redraw(); + this.timer = window.setTimeout(() => void this.run(), ms); + } + + private async run() { + const setup = this.setup(); + if (!setup || this.disposed) return; + const why = this.ws.ready(); + if (why) { this.error = why; this.renderInfo(); return; } + if (this.o.type === 'pocket' && !this.o.faces.length) { this.toolpath = null; this.error = 'Pick the floor faces of the pockets.'; this.showPreview(); return; } + const seq = ++this.seq; + this.busy = true; + this.renderInfo(); + try { + const tp = await this.ws.previewOf(setup, structuredClone(this.o)); + if (seq !== this.seq || this.disposed) return; + this.toolpath = tp; + this.error = null; + } catch (e) { + if (seq !== this.seq || this.disposed) return; + if ((e as Error).message === 'Cancelled') return; + this.toolpath = null; + this.error = (e as Error).message; + } + this.busy = false; + this.showPreview(); + } + + private disposed = false; + + private showPreview() { + const setup = this.setup(); + if (setup) this.ws.preview = { setup, op: this.o, toolpath: this.toolpath }; + this.ws.redraw(); + this.renderInfo(); + } + + private renderInfo() { + const ctx = this.app.unitContext(); + const el = this.info; + el.textContent = ''; + if (this.busy) { el.append(h('p', { class: 'field-label', role: 'status' }, 'Generating the toolpath...')); return; } + if (this.error) { el.append(h('p', { class: 'pm-msg error', role: 'alert' }, this.error)); return; } + const tp = this.toolpath; + const tool = this.tools().find((t) => t.id === this.o.tool); + if (!tp || !tool) return; + const feed = this.o.feed ?? tool.feed, plunge = this.o.plunge ?? tool.plunge; + const st = pathStats(tp, feed, plunge, this.ws.cam?.post.rapidFeed ?? 5000); + el.append(h('table', { class: 'table cam-stats' }, h('tbody', {}, + h('tr', {}, h('th', {}, 'Machining time'), h('td', { class: 'num' }, formatTime(st.time))), + h('tr', {}, h('th', {}, 'Cutting length'), h('td', { class: 'num' }, fmt(st.cutLength, 'length', ctx))), + h('tr', {}, h('th', {}, 'Lowest point'), h('td', { class: 'num' }, Number.isFinite(st.zMin) ? fmt(st.zMin, 'length', ctx) : '–'))))); + for (const w of tp.warnings) el.append(h('p', { class: 'pm-msg warn', role: 'note' }, w)); + } + + render(): HTMLElement[] { + const o = this.o; + const ctx = this.app.unitContext(); + const tools = this.tools(); + const tool = tools.find((t) => t.id === o.tool); + const fits = opToolTypes(o.type); + const toolOptions = tools.filter((t) => fits.includes(t.type) || t.id === o.tool).map((t) => ({ value: t.id, label: `T${t.number} ${t.name}` })); + if (!tool) toolOptions.unshift({ value: o.tool, label: 'Choose a tool' }); + const fs = feedScale(ctx), fu = feedUnit(ctx); + const geometry = this.geometry(ctx); + const out = [ + section('Operation', [ + nameField('Name', o.name, (v) => { o.name = v; this.dirty = true; }), + selectField('Tool', o.tool, toolOptions, (v) => { + const t = tools.find((x) => x.id === v); + if (!t) return; + // Values made for the old tool follow the new one's size. + const before = tool ? opDefaults(o.type, tool.diameter) : null; + const after = opDefaults(o.type, t.diameter); + const rec = o as unknown as Record; + if (before) for (const [k, dv] of Object.entries(before)) if (typeof dv === 'number' && rec[k] === dv) rec[k] = after[k]; + o.tool = v; + this.changed(); + this.app.refreshPanel(); + }, 'camTool'), + h('button', { class: 'btn small', type: 'button', onclick: () => this.app.commands.run('cam:tools') }, 'Tool Library...'), + tool ? h('p', { class: 'field-label' }, `${TOOL_TYPE_LABELS[tool.type]}, ${fmt(tool.diameter, 'length', ctx)}`) : h('p', { class: 'pm-msg warn' }, 'The tool is not in the tool library.'), + ], { icon: this.icon }), + ...geometry, + ...this.passes(ctx), + section('Feeds and Speeds', [ + h('p', { class: 'field-label' }, 'Empty: the tool\'s values.'), + rateField('Spindle speed', o.rpm, 'rpm', 1, (v) => { o.rpm = v; this.dirty = true; this.renderInfo(); }, { placeholder: tool?.rpm, whole: true }), + rateField('Cutting feed', o.feed, fu, fs, (v) => { o.feed = v; this.dirty = true; this.renderInfo(); }, { placeholder: tool?.feed, min: 0.001 }), + rateField('Plunge feed', o.plunge, fu, fs, (v) => { o.plunge = v; this.dirty = true; this.renderInfo(); }, { placeholder: tool?.plunge, min: 0.001 }), + ], { collapsed: o.rpm === undefined && o.feed === undefined && o.plunge === undefined }), + section('Toolpath', [this.info]), + ]; + this.renderInfo(); + return out; + } + + /** Faces the operation works on (pocket floors, holes). */ + private geometry(_ctx: UnitContext): HTMLElement[] { + const o = this.o; + if (o.type === 'pocket') { + const box = new SelectionBox(this, 'Pocket floors', { face: true, planarOnly: true }, (it) => this.toFace(it, 'plane'), (items) => { + o.faces = items.map((i) => i.data as FaceRef); + this.changed(); + }, { placeholder: 'Pick the flat floors of the pockets', icon: 'camPocket' }); + box.setItems(this.itemsOf(o.faces)); + return [section('Geometry', [box.el])]; + } + if (o.type === 'drill' || o.type === 'bore') { + const box = new SelectionBox(this, 'Holes', { face: true }, (it) => this.toFace(it, 'cylinder'), (items) => { + o.holes = items.map((i) => ({ face: i.data as FaceRef })); + this.changed(); + }, { placeholder: o.type === 'drill' ? 'All holes of the drill\'s size, or pick holes' : 'Pick the holes to bore', icon: 'camDrill' }); + box.setItems(this.itemsOf(o.holes.map((x) => x.face))); + return [section('Geometry', [box.el])]; + } + return []; + } + + private itemsOf(refs: FaceRef[]): SelBoxItem[] { + return refs.map((r) => { + const i = this.ws.faceIndex(r); + const item: SelItem | null = i >= 0 ? { kind: 'face', index: i, name: this.app.faces[i].name } : null; + return { item, data: r, label: item ? this.app.describe(item) : `${r.name} (missing)` }; + }); + } + + private toFace(it: SelItem, type: 'plane' | 'cylinder'): SelBoxItem | null { + if (it.kind !== 'face') return null; + const f = this.app.faces[it.index]; + if (!f || f.type !== type) { + this.setMessage('warn', type === 'plane' ? 'Pick flat faces.' : 'Pick the cylindrical wall of a hole.'); + return null; + } + this.setMessage(null); + return { item: it, data: faceRef(f), label: this.app.describe(it) }; + } + + private passes(ctx: UnitContext): HTMLElement[] { + const o = this.o; + const set = (k: K) => (v: number) => { (o as unknown as Record)[k] = v; this.changed(); }; + const dir = (value: 'climb' | 'conventional', on: (v: 'climb' | 'conventional') => void) => segmented('Direction', value, [{ value: 'climb', label: 'Climb' }, { value: 'conventional', label: 'Conventional' }], (v) => { on(v); this.changed(); }); + const angle = (label: string, value: number, on: (v: number) => void, min = 0, max = 180) => numberField({ label, value, kind: 'angle', ctx, min, max, allowExpr: false, onChange: (v) => { on(Number(v)); this.changed(); } }); + const pattern = (value: ClearingPattern, on: (v: ClearingPattern) => void) => selectField('Pattern', value, [{ value: 'offset', label: 'Offset (follows the walls)' }, { value: 'zigzag', label: 'Zigzag (parallel lines)' }], (v) => { on(v); this.changed(); }); + const entry = (value: EntryKind, on: (v: EntryKind) => void) => selectField('Entry', value, [{ value: 'helix', label: 'Helix' }, { value: 'ramp', label: 'Ramp' }, { value: 'plunge', label: 'Plunge' }], (v) => { on(v); this.changed(); }); + switch (o.type) { + case 'face': return [section('Passes', [ + len('Stepover', o.stepover, ctx, set('stepover'), 0.01), + len('Stepdown', o.stepdown, ctx, set('stepdown'), 0.01), + len('Stock to leave', o.leave, ctx, set('leave')), + angle('Pass angle', o.angle, (v) => { o.angle = v; }, -360, 360), + ])]; + case 'contour': return [section('Passes', [ + len('Stepdown', o.stepdown, ctx, set('stepdown'), 0.01), + len('Stock to leave', o.leave, ctx, set('leave')), + len('Below the part', o.breakthrough, ctx, set('breakthrough')), + dir(o.direction, (v) => { o.direction = v; }), + len('Lead-in radius', o.lead, ctx, set('lead')), + angle('Ramp angle', o.rampAngle, (v) => { o.rampAngle = v; }, 0.5, 45), + ]), section('Tabs', [ + h('p', { class: 'field-label' }, 'Bridges left on the last passes to hold the part.'), + numberField({ label: 'Number of tabs', value: o.tabs.count, kind: 'count', ctx, min: 0, max: 64, allowExpr: false, onChange: (v) => { o.tabs.count = Number(v); this.changed(); } }), + len('Tab width', o.tabs.width, ctx, (v) => { o.tabs.width = v; this.changed(); }), + len('Tab height', o.tabs.height, ctx, (v) => { o.tabs.height = v; this.changed(); }), + ], { collapsed: !o.tabs.count })]; + case 'pocket': return [section('Passes', [ + pattern(o.pattern, (v) => { o.pattern = v; }), + len('Stepover', o.stepover, ctx, set('stepover'), 0.01), + len('Stepdown', o.stepdown, ctx, set('stepdown'), 0.01), + len('Stock to leave (walls)', o.leave, ctx, set('leave')), + len('Stock to leave (floor)', o.floorLeave, ctx, set('floorLeave')), + dir(o.direction, (v) => { o.direction = v; }), + entry(o.entry, (v) => { o.entry = v; }), + angle('Ramp angle', o.rampAngle, (v) => { o.rampAngle = v; }, 0.5, 45), + ])]; + case 'rough': return [section('Passes', [ + pattern(o.pattern, (v) => { o.pattern = v; }), + len('Stepover', o.stepover, ctx, set('stepover'), 0.01), + len('Stepdown', o.stepdown, ctx, set('stepdown'), 0.01), + len('Stock to leave (walls)', o.leave, ctx, set('leave')), + len('Stock to leave (floors)', o.floorLeave, ctx, set('floorLeave')), + dir(o.direction, (v) => { o.direction = v; }), + entry(o.entry, (v) => { o.entry = v; }), + angle('Ramp angle', o.rampAngle, (v) => { o.rampAngle = v; }, 0.5, 45), + ])]; + case 'drill': return [section('Cycle', [ + selectField('Cycle', o.cycle, [{ value: 'drill', label: 'Drill (G81)' }, { value: 'peck', label: 'Deep peck (G83)' }, { value: 'chipBreak', label: 'Chip breaking (G73)' }], (v) => { o.cycle = v; this.changed(); this.app.refreshPanel(); }), + o.cycle === 'drill' ? null : len('Peck depth', o.peck, ctx, set('peck'), 0.01), + rateField('Dwell at the bottom', o.dwell, 's', 1, (v) => { o.dwell = v ?? 0; this.changed(); }), + len('Through holes: below the part', o.breakthrough, ctx, set('breakthrough')), + checkbox('Through holes: drill point through', o.tipThrough, (v) => { o.tipThrough = v; this.changed(); }), + ])]; + case 'bore': return [section('Passes', [ + len('Depth per turn', o.pitch, ctx, set('pitch'), 0.01), + len('Stock to leave', o.leave, ctx, set('leave')), + len('Through holes: below the part', o.breakthrough, ctx, set('breakthrough')), + dir(o.direction, (v) => { o.direction = v; }), + ])]; + case 'parallel': return [section('Passes', [ + len('Stepover', o.stepover, ctx, set('stepover'), 0.01), + angle('Pass angle', o.angle, (v) => { o.angle = v; }, -360, 360), + len('Stock to leave', o.leave, ctx, set('leave')), + len('Tolerance', o.tolerance, ctx, set('tolerance'), 0.0001), + selectField<'stock' | 'silhouette'>('Area', o.boundary, [{ value: 'silhouette', label: 'Over the part' }, { value: 'stock', label: 'Whole stock' }], (v) => { o.boundary = v; this.changed(); }), + ])]; + case 'waterline': return [section('Passes', [ + len('Stepdown', o.stepdown, ctx, set('stepdown'), 0.01), + len('Stock to leave', o.leave, ctx, set('leave')), + len('Tolerance', o.tolerance, ctx, set('tolerance'), 0.0001), + dir(o.direction, (v) => { o.direction = v; }), + ])]; + } + } + + ok(): boolean { + const o = this.o; + if (!o.name.trim()) { this.setMessage('error', 'Enter a name'); return false; } + if (!this.tools().some((t) => t.id === o.tool)) { this.setMessage('error', 'Choose a tool'); return false; } + if (o.type === 'pocket' && !o.faces.length) { this.setMessage('error', 'Pick the floor faces of the pockets'); return false; } + if (o.type === 'bore' && !o.holes.length) { this.setMessage('error', 'Pick the holes to bore'); return false; } + const setupId = this.setupId; + this.app.store.change(this.isNew ? `New ${CAM_OP_LABELS[o.type]}` : `Edit ${o.name}`, (d) => { + const s = d.cam?.setups.find((x) => x.id === setupId); + if (!s) return; + const i = s.ops.findIndex((x) => x.id === o.id); + if (i >= 0) s.ops[i] = structuredClone(o); + else s.ops.push(structuredClone(o)); + }); + this.ws.focus = o.id; + void this.ws.generate([o.id]); + return true; + } + + dispose() { + this.disposed = true; + clearTimeout(this.timer); + this.ws.previewClientCancel(); + this.ws.preview = null; + this.ws.changed(); + } +} + +export function formatTime(sec: number): string { + if (!Number.isFinite(sec)) return '–'; + const s = Math.round(sec); + const hh = Math.floor(s / 3600), mm = Math.floor((s % 3600) / 60), ss = s % 60; + return hh ? `${hh}:${String(mm).padStart(2, '0')}:${String(ss).padStart(2, '0')}` : `${mm}:${String(ss).padStart(2, '0')}`; +} + +const HELP: Record = { + face: 'Cuts the top of the stock flat, down to the top of the part, in passes across it.', + contour: 'Cuts round the outside of the part through its full height, with a lead-in arc, ramping down along the wall; tabs can hold the part on the last passes.', + pocket: 'Clears pockets down to the flat floors picked, from the inside out, entering with a helix or a ramp.', + drill: 'Drills the holes of the drill\'s size (or those picked) with a drilling cycle.', + bore: 'Mills holes larger than the tool along a helix, finishing with a full circle at the bottom.', + rough: 'Removes the stock around the whole part in levels, leaving an allowance for finishing.', + parallel: 'Finishes the surfaces with passes side by side that follow the part; best on shallow areas, with a ball end mill.', + waterline: 'Finishes the walls with passes at constant heights round the part; best on steep areas.', +}; + +export function opIcon(type: CamOperation['type']) { + return icon(CAM_OP_ICONS[type], 16); +} diff --git a/src/parametric/src/app/cam/simulate-panel.ts b/src/parametric/src/app/cam/simulate-panel.ts new file mode 100644 index 000000000..68fa1acc4 --- /dev/null +++ b/src/parametric/src/app/cam/simulate-panel.ts @@ -0,0 +1,344 @@ +// Simulation of a setup: the stock cut by each operation in turn, played +// back with the tool, coloured by what is left over the part, with the +// machining time and what went wrong (gouges, rapid moves through stock, +// material above the flutes). + +import type { SimResult } from '../../cam/simulate'; +import { type MachineFrame, toModel } from '../../cam/frame'; +import { NO_CONTACT } from '../../cam/dropcutter'; +import { cutterOf } from '../../cam/dropcutter'; +import { CamCancelled } from '../../cam/client'; +import type { Vec3 } from '../../math/vec'; +import { type CamSetup, type CamTool, opFeeds } from '../../model/cam'; +import type { Id } from '../../model/types'; +import type { SolidBatch } from '../../render/renderer'; +import { h } from '../../ui/dom'; +import { icon } from '../../ui/icons'; +import type { App } from '../app'; +import { checkbox, fmt, section } from '../pm'; +import { CamPanel, formatTime } from './panels'; +import type { CamWorkspace } from './workspace'; + +const STOCK: number[] = [176, 184, 196]; +const DONE: number[] = [104, 172, 116]; +const LEFT: number[] = [232, 170, 66]; +const GOUGE: number[] = [222, 58, 48]; + +/** Colour of stock left `r` mm over the part. */ +function shade(r: number): number[] { + if (r < -0.05) return GOUGE; + if (r <= 0.05) return DONE; + const t = Math.min(1, (r - 0.05) / 2); + return LEFT.map((c, k) => Math.round(c + (STOCK[k] - c) * t)); +} + +/** The stock height map as a closed mesh (top, sides and bottom) in model coordinates. */ +export function stockMesh(res: SimResult, z: Float32Array, f: MachineFrame): SolidBatch { + const g = res.grid; + const nx = g.nx, ny = g.ny; + const pos: number[] = [], nor: number[] = [], col: number[] = [], idx: number[] = []; + const dirModel = (d: Vec3): Vec3 => [f.x[0] * d[0] + f.y[0] * d[1] + f.z[0] * d[2], f.x[1] * d[0] + f.y[1] * d[1] + f.z[1] * d[2], f.x[2] * d[0] + f.y[2] * d[1] + f.z[2] * d[2]]; + const zAt = (i: number, j: number) => z[Math.max(0, Math.min(ny - 1, j)) * nx + Math.max(0, Math.min(nx - 1, i))]; + // The cells span half a cell beyond the outer nodes: the stock's edges. + const xs = (i: number) => (i <= 0 ? g.x0 - g.c / 2 : i >= nx - 1 ? g.x0 + (nx - 1) * g.c + g.c / 2 : g.x0 + i * g.c); + const ys = (j: number) => (j <= 0 ? g.y0 - g.c / 2 : j >= ny - 1 ? g.y0 + (ny - 1) * g.c + g.c / 2 : g.y0 + j * g.c); + for (let j = 0; j < ny; j++) { + for (let i = 0; i < nx; i++) { + const zz = zAt(i, j); + pos.push(...toModel(f, xs(i), ys(j), zz)); + const dx = (zAt(i + 1, j) - zAt(i - 1, j)) / (2 * g.c), dy = (zAt(i, j + 1) - zAt(i, j - 1)) / (2 * g.c); + const l = Math.hypot(dx, dy, 1); + nor.push(...dirModel([-dx / l, -dy / l, 1 / l])); + // Where the part has no material (beside it, in its holes) all the stock is to go. + const p = res.partTop[j * nx + i]; + col.push(...shade(p <= NO_CONTACT / 2 ? Math.max(0, zz - res.bottom) : zz - p), 255); + } + } + for (let j = 0; j + 1 < ny; j++) { + for (let i = 0; i + 1 < nx; i++) { + const a = j * nx + i, b = a + 1, c = a + nx, d = c + 1; + idx.push(a, b, d, a, d, c); + } + } + // Sides and bottom. + const wall = (pts: [number, number, number][], n: Vec3) => { + const base = pos.length / 3; + const nm = dirModel(n); + for (const [x, y, zz] of pts) { + pos.push(...toModel(f, x, y, zz), ...toModel(f, x, y, res.bottom)); + nor.push(...nm, ...nm); + col.push(...STOCK, 255, ...STOCK, 255); + } + for (let k = 0; k + 1 < pts.length; k++) { + const a = base + k * 2; + idx.push(a, a + 1, a + 3, a, a + 3, a + 2); + } + }; + const row = (j: number) => Array.from({ length: nx }, (_, i) => [xs(i), ys(j), zAt(i, j)] as [number, number, number]); + const colm = (i: number) => Array.from({ length: ny }, (_, j) => [xs(i), ys(j), zAt(i, j)] as [number, number, number]); + wall(row(0), [0, -1, 0]); + wall(row(ny - 1), [0, 1, 0]); + wall(colm(0), [-1, 0, 0]); + wall(colm(nx - 1), [1, 0, 0]); + const b0 = pos.length / 3; + for (const [x, y] of [[xs(0), ys(0)], [xs(nx - 1), ys(0)], [xs(nx - 1), ys(ny - 1)], [xs(0), ys(ny - 1)]]) { + pos.push(...toModel(f, x, y, res.bottom)); + nor.push(...dirModel([0, 0, -1])); + col.push(...STOCK, 255); + } + idx.push(b0, b0 + 2, b0 + 1, b0, b0 + 3, b0 + 2); + return { positions: Float32Array.from(pos), normals: Float32Array.from(nor), colors: Uint8Array.from(col), indices: Uint32Array.from(idx) }; +} + +/** The tool at (x, y, z) (its tip, work coordinates): the cutting part and the shank above it. */ +export function toolMesh(tool: CamTool, f: MachineFrame, x: number, y: number, z: number): SolidBatch { + const c = cutterOf(tool); + const R = c.r; + const seg = 28; + // Profile from the tip up: radius and height pairs. + const prof: [number, number][] = []; + const steps = 8; + for (let k = 0; k <= steps; k++) { const r = (R * k) / steps; prof.push([r, c.h(r)]); } + const flute = Math.max(tool.fluteLength, c.h(R) + 0.1); + prof.push([R, flute], [R * 0.95, flute], [R * 0.95, flute * 2 + R]); + const pos: number[] = [], nor: number[] = [], col: number[] = [], idx: number[] = []; + const dirModel = (d: Vec3): Vec3 => [f.x[0] * d[0] + f.y[0] * d[1] + f.z[0] * d[2], f.x[1] * d[0] + f.y[1] * d[1] + f.z[1] * d[2], f.x[2] * d[0] + f.y[2] * d[1] + f.z[2] * d[2]]; + for (let p = 0; p < prof.length; p++) { + const [r, hh] = prof[p]; + const [r0, h0] = prof[Math.max(0, p - 1)], [r1, h1] = prof[Math.min(prof.length - 1, p + 1)]; + // Normal of the profile in (r, h): perpendicular to its tangent. + let tr = r1 - r0, th = h1 - h0; + const tl = Math.hypot(tr, th) || 1; + tr /= tl; th /= tl; + const nr = th, nh = -tr; + const fluteCol = hh <= flute ? [214, 176, 72] : [150, 154, 164]; + for (let s = 0; s <= seg; s++) { + const a = (s / seg) * Math.PI * 2; + const ca = Math.cos(a), sa = Math.sin(a); + pos.push(...toModel(f, x + r * ca, y + r * sa, z + hh)); + nor.push(...dirModel([nr * ca, nr * sa, nh])); + col.push(...fluteCol, 255); + } + } + const w = seg + 1; + for (let p = 0; p + 1 < prof.length; p++) for (let s = 0; s < seg; s++) { + const a = p * w + s, b = a + 1, cc = a + w, d = cc + 1; + idx.push(a, cc, d, a, d, b); + } + return { positions: Float32Array.from(pos), normals: Float32Array.from(nor), colors: Uint8Array.from(col), indices: Uint32Array.from(idx) }; +} + +export class SimulationPanel extends CamPanel { + title = 'Simulation'; + icon = 'camSimulate'; + confirm = false; + closeLabel = 'Exit Simulation'; + helpText = 'The stock cut by each operation of the setup in turn. Green is finished, amber still has material over the part, red is cut into the part.'; + private res: SimResult | null = null; + private error: string | null = null; + private progress = 0; + private phase = 'Generating toolpaths...'; + private t = 0; + private playing = false; + private speed = 0; + private raf = 0; + private lastFrame = 0; + private shownSnap = -1; + private disposed = false; + private showPart = false; + private tools: CamTool[] = []; + private names: string[] = []; + private frame: MachineFrame | null = null; + private slider: HTMLInputElement | null = null; + private clock: HTMLElement | null = null; + private playBtn: HTMLButtonElement | null = null; + + constructor(private app: App, private ws: CamWorkspace, private setupId: Id) { + super(); + app.selection.clear(); + ws.hidePaths = true; + ws.focus = setupId; + ws.redraw(); + void this.start(); + } + + private setup(): CamSetup | null { + return this.ws.cam?.setups.find((s) => s.id === this.setupId) ?? null; + } + + private async start() { + const ws = this.ws; + await ws.generate([this.setupId]); + if (this.disposed) return; + const setup = this.setup(); + const cam = ws.cam; + if (!setup || !cam) return; + const steps = []; + const skipped: string[] = []; + for (const o of setup.ops) { + if (o.suppressed) continue; + const r = ws.result(o.id); + const tool = ws.toolOf(o); + if (!r?.toolpath || !tool || ws.state(setup, o) !== 'ok') { skipped.push(o.name); continue; } + const f = opFeeds(o, tool); + steps.push({ toolpath: r.toolpath, tool, feed: f.feed, plunge: f.plunge }); + this.tools.push(tool); + this.names.push(o.name); + } + if (!steps.length) { this.error = setup.ops.length ? 'No operation of the setup has a toolpath to simulate.' : 'The setup has no operations yet.'; this.app.refreshPanel(); return; } + if (skipped.length) this.setMessage('warn', `Not simulated (no toolpath): ${skipped.join(', ')}`); + this.phase = 'Simulating...'; + this.app.refreshPanel(); + try { + const res = await ws.client.simulate(setup, { steps, rapidFeed: cam.post.rapidFeed }, (v) => { + this.progress = v; + const bar = this.el.querySelector('progress'); + if (bar) bar.value = v; + }); + if (this.disposed) return; + this.res = res; + this.frame = ws.frameOf(setup); + this.t = res.time; + this.speed = Math.max(1, res.time / 20); + this.showAt(this.t); + this.app.refreshPanel(); + } catch (e) { + if (this.disposed || e instanceof CamCancelled) return; + this.error = (e as Error).message; + this.app.refreshPanel(); + } + } + + private modelHidden = false; + + private hideModel(hide: boolean) { + if (hide === this.modelHidden) return; + this.modelHidden = hide; + if (hide) this.app.renderer.setModel(null, 1, 1); + else this.app.showModelMesh(); + } + + /** Shows the stock and the tool at time t. */ + private showAt(t: number) { + const res = this.res, f = this.frame; + if (!res || !f) return; + this.hideModel(!this.showPart); + // The last snapshot at or before t. + let lo = 0, hi = res.snapshots.length - 1; + while (lo < hi) { const m = (lo + hi + 1) >> 1; if (res.snapshots[m].time <= t + 1e-9) lo = m; else hi = m - 1; } + if (lo !== this.shownSnap) { + this.shownSnap = lo; + this.app.renderer.setSolid('camStock', stockMesh(res, res.snapshots[lo].z, f)); + } + // The tool: between the timeline points around t. + const tl = res.timeline; + const n = tl.length / 6; + if (!n) return; + let a = 0, b = n - 1; + while (a < b) { const m = (a + b) >> 1; if (tl[m * 6 + 3] < t) a = m + 1; else b = m; } + const i = a; + const t1 = tl[i * 6 + 3], t0 = i > 0 ? tl[(i - 1) * 6 + 3] : 0; + const k = t1 > t0 ? Math.max(0, Math.min(1, (t - t0) / (t1 - t0))) : 1; + const p0 = i > 0 ? [tl[(i - 1) * 6], tl[(i - 1) * 6 + 1], tl[(i - 1) * 6 + 2]] : [tl[0], tl[1], tl[2]]; + const p1 = [tl[i * 6], tl[i * 6 + 1], tl[i * 6 + 2]]; + const step = tl[i * 6 + 4]; + const tool = this.tools[step]; + if (tool && t < res.time) this.app.renderer.setSolid('camTool', toolMesh(tool, f, p0[0] + (p1[0] - p0[0]) * k, p0[1] + (p1[1] - p0[1]) * k, p0[2] + (p1[2] - p0[2]) * k)); + else this.app.renderer.setSolid('camTool', null); + if (this.slider) this.slider.value = String(Math.round((t / Math.max(res.time, 1e-9)) * 1000)); + if (this.clock) this.clock.textContent = `${formatTime(t)} / ${formatTime(res.time)}${tool && t < res.time ? ` · ${this.names[step]}` : ''}`; + } + + private play(on: boolean) { + if (!this.res) return; + this.playing = on; + if (on && this.t >= this.res.time - 1e-9) this.t = 0; + if (this.playBtn) { + this.playBtn.replaceChildren(icon(on ? 'pause' : 'play', 16), on ? 'Pause' : 'Play'); + this.playBtn.setAttribute('aria-pressed', String(on)); + } + cancelAnimationFrame(this.raf); + if (!on) return; + this.lastFrame = performance.now(); + const tick = (now: number) => { + if (!this.playing || this.disposed || !this.res) return; + const dt = (now - this.lastFrame) / 1000; + this.lastFrame = now; + this.t = Math.min(this.res.time, this.t + dt * this.speed); + this.showAt(this.t); + if (this.t >= this.res.time) { this.play(false); return; } + this.raf = requestAnimationFrame(tick); + }; + this.raf = requestAnimationFrame(tick); + } + + render(): HTMLElement[] { + const res = this.res; + const ctx = this.app.unitContext(); + if (this.error) return [section('Simulation', [h('p', { class: 'pm-msg error', role: 'alert' }, this.error)])]; + if (!res) { + const bar = h('progress', { max: '1', value: String(this.progress), 'aria-label': 'Simulation progress' }); + return [section('Simulation', [h('p', { class: 'field-label', role: 'status' }, this.phase), bar])]; + } + const slider = h('input', { type: 'range', min: '0', max: '1000', step: '1', value: String(Math.round((this.t / Math.max(res.time, 1e-9)) * 1000)), 'aria-label': 'Program position', class: 'cam-slider' }) as HTMLInputElement; + slider.addEventListener('input', () => { this.play(false); this.t = (Number(slider.value) / 1000) * res.time; this.showAt(this.t); }); + this.slider = slider; + this.clock = h('div', { class: 'field-label cam-clock', 'aria-live': 'off' }); + const play = h('button', { class: 'btn small', type: 'button', 'aria-pressed': String(this.playing) }, icon(this.playing ? 'pause' : 'play', 16), this.playing ? 'Pause' : 'Play') as HTMLButtonElement; + play.addEventListener('click', () => this.play(!this.playing)); + this.playBtn = play; + const speeds = [1, 5, 20, 100, 500].map((x) => ({ value: String(x), label: `${x}×` })); + const auto = String(Math.max(1, Math.round(res.time / 20))); + const speed = h('select', { class: 'input', 'aria-label': 'Playback speed' }) as HTMLSelectElement; + for (const o of [{ value: auto, label: 'Whole program in 20 s' }, ...speeds]) speed.append(h('option', { value: o.value, selected: Number(o.value) === Math.round(this.speed) }, o.label)); + speed.addEventListener('change', () => { this.speed = Number(speed.value); }); + const toStart = h('button', { class: 'icon-btn', type: 'button', 'aria-label': 'To the start', onclick: () => { this.play(false); this.t = 0; this.showAt(0); } }, icon('upToLine', 16)); + const toEnd = h('button', { class: 'icon-btn', type: 'button', 'aria-label': 'To the end', onclick: () => { this.play(false); this.t = res.time; this.showAt(res.time); } }, icon('downToLine', 16)); + const rapid = res.rapidCuts.reduce((a, b) => a + b, 0), shank = res.shankHits.reduce((a, b) => a + b, 0); + const problems: HTMLElement[] = []; + if (res.gouges) problems.push(h('p', { class: 'pm-msg error', role: 'alert' }, `The tool cuts into the part (up to ${fmt(res.maxGouge, 'length', ctx)} deep). Shown in red.`)); + res.rapidCuts.forEach((n, i) => { if (n) problems.push(h('p', { class: 'pm-msg error', role: 'alert' }, `${this.names[i]}: ${n} rapid move${n === 1 ? '' : 's'} through the stock.`)); }); + res.shankHits.forEach((n, i) => { if (n) problems.push(h('p', { class: 'pm-msg warn', role: 'note' }, `${this.names[i]}: material reaches above the flutes (${n} move${n === 1 ? '' : 's'}). Use a tool with longer flutes or cut in more steps.`)); }); + if (!res.gouges && !rapid && !shank) problems.push(h('p', { class: 'pm-msg info', role: 'status' }, 'No collisions: no gouges, no rapid moves through the stock.')); + const u = ctx; + const legend = h('div', { class: 'cam-legend' }, + ...[[DONE, 'Finished'], [LEFT, 'Material left'], [STOCK, 'Stock'], [GOUGE, 'Gouge']].map(([c, l]) => h('span', {}, h('i', { style: { background: `rgb(${(c as number[]).join(',')})` } }), l as string))); + queueMicrotask(() => this.showAt(this.t)); + return [ + section('Playback', [ + h('div', { class: 'row cam-play' }, toStart, play, toEnd), + slider, this.clock, + h('label', { class: 'field-label' }, 'Speed'), speed, + checkbox('Show the part', this.showPart, (v) => { this.showPart = v; this.hideModel(!v); }), + checkbox('Show the toolpaths', !this.ws.hidePaths, (v) => { this.ws.hidePaths = !v; this.ws.redraw(); }), + legend, + ], { icon: 'camSimulate' }), + section('Results', [ + ...problems, + h('table', { class: 'table cam-stats' }, h('tbody', {}, + h('tr', {}, h('th', {}, 'Machining time'), h('td', { class: 'num' }, formatTime(res.time))), + h('tr', {}, h('th', {}, 'Material removed'), h('td', { class: 'num' }, `${formatVolume(res.removed, u.units)}`)), + h('tr', {}, h('th', {}, 'Most left over the part'), h('td', { class: 'num' }, res.maxRemaining > 0 ? fmt(res.maxRemaining, 'length', ctx) : '–')))), + ]), + ]; + } + + ok() { return true; } + + dispose() { + this.disposed = true; + this.playing = false; + cancelAnimationFrame(this.raf); + this.ws.client.cancel(); + this.app.renderer.setSolid('camStock', null); + this.app.renderer.setSolid('camTool', null); + this.app.showModelMesh(); + this.ws.hidePaths = false; + this.ws.changed(); + } +} + +function formatVolume(mm3: number, units: string): string { + if (units === 'IPS') return `${(mm3 / 16387.064).toFixed(3)} in³`; + return mm3 > 1e5 ? `${(mm3 / 1000).toFixed(1)} cm³` : `${Math.round(mm3)} mm³`; +} diff --git a/src/parametric/src/app/cam/workspace.ts b/src/parametric/src/app/cam/workspace.ts new file mode 100644 index 000000000..18d7bf2c8 --- /dev/null +++ b/src/parametric/src/app/cam/workspace.ts @@ -0,0 +1,383 @@ +// The CAM state of the open part: the mesh the CAM engine works on, the +// toolpath generated for each operation (kept until the part, the operation, +// its tool or its setup changes), generation in the CAM worker, and the +// toolpaths, stock and work origin drawn in the graphics area. + +import { CamCancelled, CamClient } from '../../cam/client'; +import { type GenerateJob, type ModelCylinder, stlTriangles } from '../../cam/engine'; +import { type MachineFrame, machineFrame, toModel } from '../../cam/frame'; +import { PLUNGE, RAPID, type PathStats, type Toolpath, expandMoves, pathStats } from '../../cam/toolpath'; +import type { Vec3 } from '../../math/vec'; +import { type CamDoc, type CamOperation, type CamSetup, type CamTool, findOp, newCamDoc, opFeeds } from '../../model/cam'; +import { allocateId } from '../../model/document'; +import type { FaceRef, Id } from '../../model/types'; +import type { App } from '../app'; + +export type OpState = 'none' | 'busy' | 'ok' | 'stale' | 'error' | 'suppressed'; + +interface OpResult { + key: string; + toolpath?: Toolpath; + stats?: PathStats; + error?: string; +} + +const placementKey = (s: CamSetup) => JSON.stringify([s.axis, s.rotation, s.origin, s.stock]); + +/** Colours of the toolpath moves (RGBA). */ +const COLORS: Record = { + [RAPID]: [225, 150, 30, 235], + 1: [40, 110, 230, 255], + [PLUNGE]: [30, 160, 90, 255], +}; + +export class CamWorkspace { + readonly client = new CamClient(); + /** A second worker for the preview of the operation being edited, so it never waits for (or stops) generation. */ + private readonly previewClient = new CamClient(); + private results = new Map(); + private meshVersion = -1; + private tris: Float32Array | null = null; + private loading: Promise | null = null; + private frames = new Map(); + private queue: Promise = Promise.resolve(); + /** The operation being generated, with its progress. */ + busy: { id: Id; progress: number } | null = null; + /** The operation or setup whose toolpaths show (null: all). */ + focus: Id | null = null; + /** Toolpath shown in place of an operation's while its panel is open. */ + preview: { setup: CamSetup; op: CamOperation | null; toolpath: Toolpath | null } | null = null; + /** Hides the toolpaths (the simulation shows its own). */ + hidePaths = false; + /** Called when results change (the design tree and panels redraw). */ + readonly listeners = new Set<() => void>(); + private generation = 0; + + constructor(private readonly app: App) { + app.ribbonTabListeners.push(() => this.redraw()); + app.store.on((reason) => { + if (reason === 'load') this.reset(); + this.redraw(); + }); + app.commands.onChange(() => { + if (app.geometryVersion !== this.meshVersion && this.tris) { + // The part changed: its toolpaths are out of date (kept, marked, until generated again). + this.tris = null; + this.frames.clear(); + this.changed(); + } + }); + } + + private reset() { + this.client.cancel(); + this.previewClient.cancel(); + this.results.clear(); + this.tris = null; + this.meshVersion = -1; + this.frames.clear(); + this.focus = null; + this.preview = null; + this.busy = null; + this.generation++; + } + + get cam(): CamDoc | null { + return this.app.store.doc.cam ?? null; + } + + /** The part's CAM data, created (as an undo step) the first time it is needed. */ + ensureCam(): CamDoc { + const doc = this.app.store.doc; + if (!doc.cam) this.app.store.change('Start CAM', (d) => { d.cam = newCamDoc((p) => allocateId(d, p), d.units === 'IPS'); }); + return this.app.store.doc.cam!; + } + + changed() { + this.redraw(); + for (const fn of this.listeners) fn(); + } + + // ---------- geometry ---------- + + /** Can CAM work on the part now (a body, not rolled back to a feature being edited)? */ + ready(): string | null { + const app = this.app; + if (app.assembly) return 'CAM works on parts. Open the part to machine it.'; + if (!app.bbox) return 'The part has no solid body to machine yet.'; + if (app.panel?.editingId || app.sketchEditor) return 'Finish the feature or sketch being edited first.'; + return null; + } + + /** The part's triangles in model coordinates (a fine mesh from the kernel), current with the model. */ + async mesh(): Promise { + const app = this.app; + await app.whenBuilt(); + const version = app.geometryVersion; + if (this.tris && this.meshVersion === version) return this.tris; + if (this.loading) return this.loading; + this.loading = (async () => { + try { + const data = await app.kernel.exportFile('stl', 2); + const tris = stlTriangles(data); + if (app.geometryVersion !== version) return this.mesh(); + this.tris = tris.length ? tris : null; + this.meshVersion = version; + this.frames.clear(); + if (this.tris) for (const c of [this.client, this.previewClient]) c.setMesh(`g${version}`, this.tris); + return this.tris; + } catch { + return null; + } finally { + this.loading = null; + } + })(); + return this.loading; + } + + /** Where a setup puts the part (its machine frame), from the current mesh. */ + frameOf(setup: CamSetup): MachineFrame | null { + if (!this.tris) return null; + const key = placementKey(setup); + if (!this.frames.has(key)) this.frames.set(key, machineFrame(setup, this.tris)); + return this.frames.get(key) ?? null; + } + + // ---------- operations ---------- + + toolOf(op: CamOperation): CamTool | null { + return this.cam?.tools.find((t) => t.id === op.tool) ?? null; + } + + faceIndex(ref: FaceRef): number { + const faces = this.app.faces; + const i = faces.findIndex((f) => f.name === ref.name); + if (i >= 0) return i; + // A face renamed by a change: the nearest of the same kind and size. + let best = -1, bd = Infinity; + faces.forEach((f, k) => { + if (f.type !== ref.sig.type) return; + const d = Math.hypot(f.center[0] - ref.sig.c[0], f.center[1] - ref.sig.c[1], f.center[2] - ref.sig.c[2]) + Math.abs(f.area - ref.sig.area) * 1e-3; + if (d < bd) { bd = d; best = k; } + }); + return bd < 1e-3 ? best : -1; + } + + /** The triangles of a face of the shown model. */ + faceTriangles(index: number): Float32Array { + const m = this.app.modelMesh; + if (!m) return new Float32Array(0); + const out: number[] = []; + const idx = m.indices, P = m.positions, vf = m.vertexFace; + for (let t = 0; t < idx.length; t += 3) { + const a = idx[t]; + if (Math.round(vf[a]) !== index) continue; + for (let k = 0; k < 3; k++) { const v = idx[t + k] * 3; out.push(P[v], P[v + 1], P[v + 2]); } + } + return Float32Array.from(out); + } + + /** Cylindrical faces of the part (hole candidates). */ + cylinders(): ModelCylinder[] { + return this.app.faces.flatMap((f, i) => (f.type === 'cylinder' && f.axis && f.radius && !f.body + ? [{ name: f.name, p: f.axis.p, d: f.axis.d, radius: f.radius, tris: this.faceTriangles(i) }] + : [])); + } + + jobFor(setup: CamSetup, op: CamOperation): GenerateJob { + const tool = this.toolOf(op); + if (!tool) throw new Error('The operation\'s tool is no longer in the tool library. Choose another tool.'); + const job: GenerateJob = { setup, op, tool }; + if (op.type === 'pocket') { + job.floors = op.faces.map((f) => this.faceIndex(f)).filter((i) => i >= 0).map((i) => this.faceTriangles(i)).filter((t) => t.length); + if (op.faces.length && job.floors.length < op.faces.length) throw new Error('A picked floor is no longer in the part. Pick the floors again.'); + } + if (op.type === 'drill' || op.type === 'bore') { + job.cylinders = this.cylinders(); + const names = op.holes.map((h) => this.faceIndex(h.face)).filter((i) => i >= 0).map((i) => this.app.faces[i].name); + if (op.holes.length && !names.length) throw new Error('The picked holes are no longer in the part. Pick them again.'); + job.picked = names; + } + return job; + } + + private keyOf(setup: CamSetup, op: CamOperation): string { + const { name: _n, suppressed: _s, rpm: _r, feed: _f, plunge: _p, ...shape } = op; + void _n; void _s; void _r; void _f; void _p; + const tool = this.toolOf(op); + const t = tool ? { ...tool, name: '', number: 0, rpm: 0, feed: 0, plunge: 0, coolant: false } : null; + return JSON.stringify([this.meshVersion, placementKey(setup), setup.clearance, setup.retract, shape, t]); + } + + result(id: Id): OpResult | null { + return this.results.get(id) ?? null; + } + + state(setup: CamSetup, op: CamOperation): OpState { + if (op.suppressed) return 'suppressed'; + if (this.busy?.id === op.id) return 'busy'; + const r = this.results.get(op.id); + if (!r) return 'none'; + if (!this.tris || r.key !== this.keyOf(setup, op)) return 'stale'; + return r.error ? 'error' : 'ok'; + } + + /** Statistics of an operation's toolpath at its feeds. */ + statsOf(op: CamOperation): PathStats | null { + const r = this.results.get(op.id); + const tool = this.toolOf(op); + if (!r?.toolpath || !tool) return null; + const f = opFeeds(op, tool); + return pathStats(r.toolpath, f.feed, f.plunge, this.cam?.post.rapidFeed ?? 5000); + } + + /** + * Generates the toolpaths of operations that are not up to date (all, or + * those given). Runs one operation at a time; resolves when they are done. + */ + generate(ids?: Id[]): Promise { + const gen = this.generation; + const run = async () => { + if (gen !== this.generation) return; + const why = this.ready(); + if (why) { this.app.setStatus(why, true); return; } + const tris = await this.mesh(); + if (gen !== this.generation) return; + if (!tris) { this.app.setStatus('The part has no solid body to machine.', true); return; } + const cam = this.cam; + if (!cam) return; + const list = cam.setups.flatMap((s) => s.ops.filter((o) => !o.suppressed && (!ids || ids.includes(o.id) || ids.includes(s.id))).map((o) => ({ s, o }))); + let failed = 0; + for (const { o } of list) { + if (gen !== this.generation) return; + // Read again: an edit while an earlier one ran may have changed it. + const now = this.cam && findOp(this.cam, o.id); + if (!now || now.op.suppressed) continue; + const key = this.keyOf(now.setup, now.op); + if (this.results.get(o.id)?.key === key) continue; + let job: GenerateJob; + try { job = this.jobFor(now.setup, now.op); } catch (e) { this.results.set(o.id, { key, error: (e as Error).message }); failed++; this.changed(); continue; } + this.busy = { id: o.id, progress: 0 }; + this.changed(); + this.app.setStatus(`Generating ${now.op.name}...`); + try { + const tp = await this.client.generate(job, (v) => { + if (this.busy?.id === o.id) { this.busy.progress = v; this.app.setStatus(`Generating ${now.op.name}... ${Math.round(v * 100)}%`); for (const fn of this.listeners) fn(); } + }); + if (gen !== this.generation) return; + this.results.set(o.id, { key, toolpath: tp }); + } catch (e) { + if (e instanceof CamCancelled) { this.busy = null; this.changed(); return; } + this.results.set(o.id, { key, error: (e as Error).message }); + failed++; + } + this.busy = null; + this.changed(); + } + this.app.setStatus(failed ? `${failed} operation${failed === 1 ? '' : 's'} could not be generated` : 'Toolpaths are up to date', !!failed); + }; + const p = this.queue.then(run, run); + this.queue = p.catch(() => {}); + return p; + } + + /** Generates a toolpath for an operation being edited (not stored), for its panel's preview. */ + async previewOf(setup: CamSetup, op: CamOperation): Promise { + const tris = await this.mesh(); + if (!tris) throw new Error('The part has no solid body to machine.'); + // Only the newest preview matters. + this.previewClient.cancel(); + return this.previewClient.generate(this.jobFor(setup, op)); + } + + previewClientCancel() { + this.previewClient.cancel(); + } + + /** Stops generation in progress. */ + cancel() { + this.client.cancel(); + this.busy = null; + this.changed(); + } + + /** Drops the toolpaths of operations that are gone. */ + prune(keep: Set) { + const gone = [...this.results.keys()].filter((id) => !keep.has(id)); + if (gone.length) this.forget(gone); + } + + forget(ids: Id[]) { + for (const id of ids) this.results.delete(id); + this.changed(); + } + + // ---------- display ---------- + + /** Are CAM overlays wanted now (the CAM tab or a CAM panel)? */ + private shown(): boolean { + const app = this.app; + if (app.inDrawing || app.assembly || app.sketchEditor) return false; + return app.ribbonTabId === 'cam' || !!this.preview || !!(app.panel as { camPanel?: boolean } | null)?.camPanel; + } + + redraw() { + const r = this.app.renderer; + if (!r) return; + const cam = this.cam; + if (!cam || !this.shown() || !this.tris) { + for (const k of ['camRapid', 'camCut', 'camStock', 'camWcs']) r.setLines(k, null); + if (cam && this.shown() && !this.tris && !this.loading && !this.ready()) void this.mesh().then((t) => { if (t) this.redraw(); }); + return; + } + const rapid: number[] = [], rc: number[] = [], cut: number[] = [], cc: number[] = []; + const focusSetup = this.focus ? cam.setups.find((s) => s.id === this.focus || s.ops.some((o) => o.id === this.focus)) : null; + const add = (setup: CamSetup, tp: Toolpath) => { + const f = this.frameOf(setup); + if (!f) return; + let prev: Vec3 | null = null; + expandMoves(tp, (k, x, y, z) => { + const p = toModel(f, x, y, z); + if (prev) { + const into = k === RAPID ? rapid : cut; + const col = k === RAPID ? rc : cc; + into.push(...prev, ...p); + col.push(...(COLORS[k] ?? COLORS[1])); + } + prev = p; + }); + }; + if (!this.hidePaths) { + if (this.preview) { + if (this.preview.toolpath) add(this.preview.setup, this.preview.toolpath); + } else { + for (const s of cam.setups) { + if (focusSetup && s !== focusSetup) continue; + for (const o of s.ops) { + if (o.suppressed) continue; + if (this.focus && this.focus !== s.id && this.focus !== o.id) continue; + const res = this.results.get(o.id); + if (res?.toolpath) add(s, res.toolpath); + } + } + } + } + r.setLines('camRapid', rapid.length ? { positions: new Float32Array(rapid), colors: new Uint8Array(rc), width: 1, depth: 'test', dash: 5, order: 7, clip: false } : null); + r.setLines('camCut', cut.length ? { positions: new Float32Array(cut), colors: new Uint8Array(cc), width: 1.4, depth: 'test', order: 7, clip: false } : null); + // The stock and work origin of the setup shown (or the first). + const setup = this.preview?.setup ?? focusSetup ?? cam.setups[0]; + const f = setup ? this.frameOf(setup) : null; + if (!f) { r.setLines('camStock', null); r.setLines('camWcs', null); return; } + const { min, max } = f.stock; + const c = (i: number): Vec3 => toModel(f, i & 1 ? max[0] : min[0], i & 2 ? max[1] : min[1], i & 4 ? max[2] : min[2]); + const edges = [[0, 1], [2, 3], [4, 5], [6, 7], [0, 2], [1, 3], [4, 6], [5, 7], [0, 4], [1, 5], [2, 6], [3, 7]]; + const sp: number[] = [], scol: number[] = []; + for (const [a, b] of edges) { sp.push(...c(a), ...c(b)); scol.push(120, 130, 145, 200); } + r.setLines('camStock', { positions: new Float32Array(sp), colors: new Uint8Array(scol), width: 1, depth: 'test', dash: 3, order: 6, clip: false }); + const size = Math.max(5, Math.min(30, Math.hypot(max[0] - min[0], max[1] - min[1]) * 0.15)); + const o = toModel(f, 0, 0, 0); + const wp: number[] = [...o, ...toModel(f, size, 0, 0), ...o, ...toModel(f, 0, size, 0), ...o, ...toModel(f, 0, 0, size)]; + r.setLines('camWcs', { positions: new Float32Array(wp), colors: new Uint8Array([220, 50, 50, 255, 40, 170, 60, 255, 50, 90, 220, 255]), width: 2.5, depth: 'always', order: 8 }); + } +} + diff --git a/src/parametric/src/app/tree.ts b/src/parametric/src/app/tree.ts index ffcc11ef6..53528cddc 100644 --- a/src/parametric/src/app/tree.ts +++ b/src/parametric/src/app/tree.ts @@ -11,6 +11,7 @@ import { icon } from '../ui/icons'; import type { App } from './app'; import type { SelItem } from './selection'; import { sheetMetalTreeRows } from './sheetmetal-panels'; +import { camTreeRows } from './cam'; interface Row { key: string; @@ -23,6 +24,12 @@ interface Row { expanded?: boolean; muted?: string; action?: () => void; + /** Rows that are not features (CAM): double click or Enter, the context menu, a badge, selection and suppression. */ + open?: () => void; + menu?: (x: number, y: number) => void; + badge?: { kind: 'error' | 'warn'; text: string }; + selected?: boolean; + suppressed?: boolean; } export class FeatureTree { @@ -89,6 +96,8 @@ export class FeatureTree { // A filter also searches the sketches nested under collapsed features. if (expanded || this.filter) for (const k of kids) rows.push({ key: k.id, item: { kind: 'feature', id: k.id }, label: k.name, icon: featureIcon(k), depth: 2, feature: k }); } + // CAM: setups and their operations, open unless closed (the set holds the closed ones). + rows.push(...camTreeRows(app, (k) => !this.expanded.has(k) || !!this.filter).map((r) => ({ ...r, item: null }))); if (!this.filter) return rows; return rows.filter((r) => r.depth === 0 || r.label.toLowerCase().includes(this.filter)); } @@ -114,17 +123,17 @@ export class FeatureTree { const f = r.feature; const index = f ? doc.features.indexOf(f) : -1; // Rollback bar sits after the last built top-level feature. - if (f && r.depth === 1 && !rollbackPlaced && index >= built) { + if (!rollbackPlaced && ((f && r.depth === 1 && index >= built) || r.key === 'cam')) { this.list.append(this.rollbackBar()); rollbackPlaced = true; } const status = f ? app.featureStatus(f.id) : null; const selected = r.item ? sel.has(r.item) : false; const el = h('div', { - class: `ti${f?.suppressed || status?.suppressed ? ' suppressed' : ''}${f && index >= built ? ' rolled' : ''}${status && !status.ok ? ' error' : ''}${editingId === f?.id ? ' editing' : ''}`, + class: `ti${f?.suppressed || status?.suppressed || r.suppressed ? ' suppressed' : ''}${f && index >= built ? ' rolled' : ''}${status && !status.ok ? ' error' : ''}${editingId === f?.id ? ' editing' : ''}`, role: 'treeitem', tabindex: r.key === tabKey ? '0' : '-1', - 'aria-selected': r.item ? String(selected) : null, + 'aria-selected': r.item ? String(selected) : r.selected !== undefined ? String(r.selected) : null, 'aria-level': String(r.depth + 1), 'aria-expanded': r.children ? String(!!r.expanded) : null, 'data-key': r.key, @@ -142,12 +151,15 @@ export class FeatureTree { } // What grey text and badges show is told to screen readers too. const states: string[] = []; - if (f?.suppressed || status?.suppressed) states.push('Suppressed'); + if (f?.suppressed || status?.suppressed || r.suppressed) states.push('Suppressed'); if (f && index >= built) states.push('Rolled back'); if (status && !status.ok) { const b = h('span', { class: 'badge', title: status.error ?? 'Error' }, icon('error', 14)); el.append(b); states.push(`Error: ${status.error ?? ''}`); + } else if (r.badge) { + el.append(h('span', { class: `badge${r.badge.kind === 'warn' ? ' warn' : ''}`, title: r.badge.text }, icon(r.badge.kind === 'warn' ? 'warning' : 'error', 14))); + states.push(`${r.badge.kind === 'warn' ? 'Warning' : 'Error'}: ${r.badge.text}`); } else if (f && app.featureWarning(f.id)) { el.append(h('span', { class: 'badge warn', title: app.featureWarning(f.id)! }, icon('warning', 14))); states.push(`Warning: ${app.featureWarning(f.id)}`); @@ -158,7 +170,8 @@ export class FeatureTree { el.addEventListener('contextmenu', (e) => { e.preventDefault(); if (r.item && !sel.has(r.item)) sel.set([r.item]); - if (f) app.openFeatureMenu(f.id, e.clientX, e.clientY); + if (r.menu) r.menu(e.clientX, e.clientY); + else if (f) app.openFeatureMenu(f.id, e.clientX, e.clientY); else if (r.item) app.openReferenceMenu(r.item, e.clientX, e.clientY); // The part and Material rows have menus too (Shift+F10 on them did nothing). else if (r.key === 'part') app.openCommandMenu(['properties', 'rename', 'equations', 'appearance'], e.clientX, e.clientY, 'Part menu'); @@ -323,7 +336,8 @@ export class FeatureTree { } private onDouble(r: Row) { - if (r.feature) this.app.editFeature(r.feature.id); + if (r.open) r.open(); + else if (r.feature) this.app.editFeature(r.feature.id); else if (r.key === 'part') this.app.commands.run('properties'); } @@ -400,6 +414,7 @@ export class FeatureTree { e.preventDefault(); e.stopPropagation(); if (this.app.store.feature(key)) this.app.editFeature(key); + else if (this.shown.find((r) => r.key === key)?.open) this.shown.find((r) => r.key === key)!.open!(); // As a click on Material or a double click on the part does. else if (key === 'material') this.app.commands.run('material'); else if (key === 'cutlist') this.app.commands.run('cutList'); diff --git a/src/parametric/src/cam/client.ts b/src/parametric/src/cam/client.ts new file mode 100644 index 000000000..4d60691ca --- /dev/null +++ b/src/parametric/src/cam/client.ts @@ -0,0 +1,110 @@ +// The interface side of the CAM worker. Requests run one at a time in +// order; cancelling stops the worker (a computation in progress cannot be +// interrupted otherwise) and starts a new one, which is given the mesh again. + +import type { CamSetup } from '../model/cam'; +import type { GenerateJob, SimulateJob } from './engine'; +import type { SimResult } from './simulate'; +import type { Toolpath } from './toolpath'; +import type { CamWorkerRequest, CamWorkerResponse } from './worker'; + +type Payload = { type: 'mesh'; key: string; tris: Float32Array } | { type: 'generate'; job: GenerateJob } | { type: 'simulate'; setup: CamSetup; job: SimulateJob }; + +interface Pending { + resolve: (v: unknown) => void; + reject: (e: Error) => void; + progress?: (v: number) => void; +} + +export class CamCancelled extends Error { + constructor() { super('Cancelled'); } +} + +export class CamClient { + private worker: Worker | null = null; + private nextId = 1; + private pending = new Map(); + private mesh: { key: string; tris: Float32Array } | null = null; + private sentKey: string | null = null; + + constructor(private readonly create: () => Worker = () => new Worker(new URL('./worker.ts', import.meta.url), { type: 'module', name: 'cam' })) {} + + /** The part's triangles (model coordinates); sent to the worker before the next request. */ + setMesh(key: string, tris: Float32Array) { + this.mesh = { key, tris }; + } + + get meshKey(): string | null { + return this.mesh?.key ?? null; + } + + private ensure(): Worker { + if (this.worker) return this.worker; + const w = this.create(); + w.onmessage = (ev: MessageEvent) => { + const r = ev.data; + const p = this.pending.get(r.id); + if (!p) return; + if (r.type === 'progress') { p.progress?.(r.value); return; } + this.pending.delete(r.id); + if (r.type === 'done') p.resolve(r.result); + else p.reject(new Error(r.error)); + }; + w.onerror = (ev) => { + ev.preventDefault?.(); + this.fail(new Error(`The CAM engine stopped${ev.message ? ` (${ev.message})` : ''}`)); + }; + this.worker = w; + this.sentKey = null; + return w; + } + + private send(payload: Payload, progress?: (v: number) => void, transfer: Transferable[] = []): Promise { + const w = this.ensure(); + if (payload.type !== 'mesh' && this.mesh && this.sentKey !== this.mesh.key) { + // A copy: the client keeps the mesh for a replacing worker. + const id = this.nextId++; + this.pending.set(id, { resolve: () => {}, reject: () => {} }); + w.postMessage({ id, type: 'mesh', key: this.mesh.key, tris: this.mesh.tris.slice() } satisfies CamWorkerRequest); + this.sentKey = this.mesh.key; + } + const id = this.nextId++; + return new Promise((resolve, reject) => { + this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, progress }); + w.postMessage({ id, ...payload } as CamWorkerRequest, transfer); + }); + } + + generate(job: GenerateJob, progress?: (v: number) => void): Promise { + return this.send({ type: 'generate', job }, progress); + } + + simulate(setup: CamSetup, job: SimulateJob, progress?: (v: number) => void): Promise { + return this.send({ type: 'simulate', setup, job }, progress); + } + + /** Stops whatever is running or queued (their promises reject with CamCancelled). */ + cancel() { + if (!this.pending.size) return; + this.fail(new CamCancelled()); + } + + private fail(e: Error) { + this.worker?.terminate(); + this.worker = null; + this.sentKey = null; + const all = [...this.pending.values()]; + this.pending.clear(); + for (const p of all) p.reject(e); + } + + get busy(): boolean { + return this.pending.size > 0; + } + + dispose() { + this.worker?.terminate(); + this.worker = null; + this.pending.clear(); + } +} diff --git a/src/parametric/src/cam/engine.ts b/src/parametric/src/cam/engine.ts index 592b64626..d5e13851f 100644 --- a/src/parametric/src/cam/engine.ts +++ b/src/parametric/src/cam/engine.ts @@ -18,6 +18,20 @@ export interface ModelCylinder { tris: Float32Array; } +/** Binary STL to triangles (9 numbers each). */ +export function stlTriangles(data: Uint8Array): Float32Array { + const dv = new DataView(data.buffer, data.byteOffset, data.byteLength); + if (data.byteLength < 84) return new Float32Array(0); + const n = dv.getUint32(80, true); + const count = Math.min(n, Math.floor((data.byteLength - 84) / 50)); + const out = new Float32Array(count * 9); + for (let t = 0; t < count; t++) { + const o = 84 + t * 50 + 12; + for (let k = 0; k < 9; k++) out[t * 9 + k] = dv.getFloat32(o + k * 4, true); + } + return out; +} + export function placePart(setup: Pick, tris: Float32Array): CamPart | null { const frame = machineFrame(setup, tris); if (!frame) return null; diff --git a/src/parametric/src/cam/ops.ts b/src/parametric/src/cam/ops.ts index ff038c3c1..02e77c39a 100644 --- a/src/parametric/src/cam/ops.ts +++ b/src/parametric/src/cam/ops.ts @@ -13,7 +13,7 @@ import type { Vec3 } from '../math/vec'; import { type Cutter, cutterOf, DropCutter, NO_CONTACT, TriIndex, makeCutter } from './dropcutter'; import type { MachineFrame } from './frame'; import { type GridSpec, type Polyline, area, contours, edt, gridOver, pointInPolygon, polyLength, sample, signedDistance, simplify } from './grid'; -import { PathBuilder, type Toolpath } from './toolpath'; +import { CYCLE, PathBuilder, type Toolpath } from './toolpath'; export interface CamPart { frame: MachineFrame; @@ -68,7 +68,44 @@ export function generate(input: OpInput): Toolpath { case 'waterline': g.waterline(op); break; } if (b.length === 0 && !b.warnings.length) b.warnings.push('The operation has nothing to cut.'); - return b.build(); + const tp = b.build(); + const v = verifyToolpath(part, input.tool, tp, input.cancelled); + if (v.count) tp.warnings.push(`The toolpath cuts into the part (${v.count} place${v.count === 1 ? '' : 's'}, up to ${v.depth.toFixed(3)} mm deep). Check it in the simulation.`); + return tp; +} + +/** + * Checks every move against the part with the drop-cutter. The cutter is + * taken `tol` smaller and may dip `tol` below the part: passes along a + * vertical wall are chords within the path tolerance of it, and a tool a + * hair closer to a wall would otherwise read as cutting the whole wall's + * height into it. Returns how many moves cut deeper, and the deepest. + */ +export function verifyToolpath(part: CamPart, tool: CamTool, tp: Toolpath, cancelled?: () => boolean, tol = 0.02): { count: number; depth: number } { + const dc = new DropCutter(part.index, cutterOf(tool, -tol)); + const m = tp.moves; + let count = 0, depth = 0; + let px = NaN, py = NaN, pz = NaN; + const top = part.index.zMax; + for (let i = 0; i < m.length; i += 4) { + const k = m[i]; + if (k === CYCLE) { px = NaN; continue; } + const x = m[i + 1], y = m[i + 2], z = m[i + 3]; + if (!Number.isNaN(px) && Math.min(pz, z) < top + tol) { + const n = Math.max(1, Math.ceil(Math.hypot(x - px, y - py) / 0.4)); + let worst = 0; + for (let s = n === 1 ? 1 : 0; s <= n; s++) { + const t = s / n; + const zz = pz + (z - pz) * t; + const d = dc.drop(px + (x - px) * t, py + (y - py) * t) - zz; + if (d > worst) worst = d; + } + if (worst > tol) { count++; depth = Math.max(depth, worst); } + } + px = x; py = y; pz = z; + if ((i & 0xffff) === 0 && cancelled?.()) break; + } + return { count, depth }; } const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v)); @@ -380,21 +417,31 @@ class Gen { this.loop(pts, z); return; } - if (o.entry === 'helix') { - // The deepest point of the region. + if (o.entry === 'helix' && area(pts) * (o.climb ? 1 : -1) > 0) { + // The deepest point of the region inside this pass (a region can have several + // innermost passes, one in each of its wider parts). let best = -1, bv = -Infinity; - for (let k = 0; k < s.length; k++) if (label[k] === comp && s[k] > bv) { bv = s[k]; best = k; } + let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity; + for (let k = 0; k < pts.length; k += 2) { x0 = Math.min(x0, pts[k]); x1 = Math.max(x1, pts[k]); y0 = Math.min(y0, pts[k + 1]); y1 = Math.max(y1, pts[k + 1]); } + const i0 = Math.max(0, Math.ceil((x0 - g.x0) / g.c)), i1 = Math.min(g.nx - 1, Math.floor((x1 - g.x0) / g.c)); + const j0 = Math.max(0, Math.ceil((y0 - g.y0) / g.c)), j1 = Math.min(g.ny - 1, Math.floor((y1 - g.y0) / g.c)); + for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) { + const k = j * g.nx + i; + if (label[k] === comp && s[k] > bv && pointInPolygon(pts, g.x0 + i * g.c, g.y0 + j * g.c)) { bv = s[k]; best = k; } + } const rh = Math.min(bv * 0.9, this.R * 0.9); if (best >= 0 && rh >= this.R * 0.15) { const cx = g.x0 + (best % g.nx) * g.c, cy = g.y0 + Math.floor(best / g.nx) * g.c; - const pitch = 2 * Math.PI * rh * Math.tan((clamp(o.rampAngle, 0.5, 45) * Math.PI) / 180); - b.rapidTo(cx + rh, cy, b.retract); - b.hop(b.retract, cx + rh, cy, Math.max(zFrom, z)); - this.helix(cx, cy, rh, Math.max(zFrom, z), z, pitch, o.climb); - const start = this.startNear(pts, b.x, b.y); - b.feed(start[0], start[1], z); - this.loop(start, z); - return; + const start = this.startNear(pts, cx + rh, cy); + if (this.insideAlong(g, s, cx + rh, cy, start[0], start[1], g.c * 0.25)) { + const pitch = 2 * Math.PI * rh * Math.tan((clamp(o.rampAngle, 0.5, 45) * Math.PI) / 180); + b.rapidTo(cx + rh, cy, b.retract); + b.hop(b.retract, cx + rh, cy, Math.max(zFrom, z)); + this.helix(cx, cy, rh, Math.max(zFrom, z), z, pitch, o.climb); + b.feed(start[0], start[1], z); + this.loop(start, z); + return; + } } } if (o.entry !== 'plunge' && polyLength(pts, 2, true) > this.R) { @@ -555,8 +602,9 @@ class Gen { const cx = x0 + N[0] * lead, cy = y0 + N[1] * lead; const aStart = Math.atan2(-T[1], -T[0]); const sx = cx + lead * Math.cos(aStart), sy = cy + lead * Math.sin(aStart); + // The lead starts beside the slot the passes above cut, where the tool's edge may + // still be in stock: down from the retract height at the plunge feed. b.rapidTo(sx, sy, b.retract); - b.hop(b.retract, sx, sy, zStart); b.plunge(sx, sy, zStart); const aEnd = Math.atan2(-N[1], -N[0]); let sweep = aEnd - aStart; @@ -565,7 +613,7 @@ class Gen { arc(cx, cy, aStart, sweep, zStart, 'feed'); } else { b.rapidTo(x0, y0, b.retract); - b.hop(b.retract, x0, y0, zStart); + b.plunge(x0, y0, zStart); } // Ramp down along the loop, then once round at depth. if (!tabs) this.rampLoop(pts, zStart, z, rampAngle); @@ -699,8 +747,10 @@ class Gen { // Reachable from above: a cutter nearly as wide goes down to the bottom. const wide = new DropCutter(this.part.index, makeCutter('flat', h.r * 0.95, 0, 0)).drop(h.x, h.y); if (wide > h.bottom + 1e-3) continue; + // Through when that cutter goes on past the bottom (a drill point's depth): not a + // counterbore, whose floor stops it though its centre is open (the smaller hole). const point = h.r / Math.tan((59 * Math.PI) / 180); - out.push({ ...h, through: centre < h.bottom - point - 1e-2 }); + out.push({ ...h, through: wide < h.bottom - point - 1e-2 }); } return nearestOrder(out); } @@ -807,8 +857,8 @@ class Gen { } b.feed(x, y, z); } else { + // Finishing follows roughing that leaves stock: down from the retract height at the plunge feed. b.rapidTo(x, y, b.retract); - b.hop(b.retract, x, y, Math.min(b.retract, z + 1)); b.plunge(x, y, z); } for (let i = 3; i < r.length; i += 3) b.feed(r[i], r[i + 1], r[i + 2]); @@ -837,10 +887,9 @@ class Gen { const raw = pending.splice(bi, 1)[0]; const pts = Number.isNaN(b.x) ? raw : this.startNear(raw, b.x, b.y); b.rapidTo(pts[0], pts[1], b.retract); - b.hop(b.retract, pts[0], pts[1], Math.min(b.retract, z + 1)); b.plunge(pts[0], pts[1], z); this.loop(pts, z); - b.rapid(b.x, b.y, Math.min(b.retract, z + 1)); + b.rapid(b.x, b.y, b.retract); } } } diff --git a/src/parametric/src/cam/simulate.ts b/src/parametric/src/cam/simulate.ts index af71682fc..0883fa3a7 100644 --- a/src/parametric/src/cam/simulate.ts +++ b/src/parametric/src/cam/simulate.ts @@ -205,8 +205,9 @@ export function simulate(input: SimInput): SimResult { if (diff < -0.02) { gouges++; maxGouge = Math.max(maxGouge, -diff); } if (fine[k] > NO_CONTACT / 2 && z[k] - fine[k] > 0.1) { remainingCells++; maxRemaining = Math.max(maxRemaining, z[k] - fine[k]); } } - const partTop = new Float32Array(dg.nx * dg.ny); - for (let j = 0; j < dg.ny; j++) for (let i = 0; i < dg.nx; i++) partTop[j * dg.nx + i] = pin.drop(dg.x0 + i * dg.c, dg.y0 + j * dg.c); + // The part under a display cell, the lowest of its cells as its stock is (a cell on a wall's + // edge then reads as finished, not as cut into the wall). + const partTop = down(fine); return { grid: dg, bottom, top, snapshots, partTop, timeline: Float32Array.from(timeline), time: total, gouges, maxGouge, rapidCuts, shankHits, maxRemaining, remainingArea: remainingCells * g.c * g.c, removed: Math.max(0, startVolume - volume), diff --git a/src/parametric/src/cam/worker.ts b/src/parametric/src/cam/worker.ts new file mode 100644 index 000000000..ca886ba43 --- /dev/null +++ b/src/parametric/src/cam/worker.ts @@ -0,0 +1,62 @@ +/// +// CAM worker: generates toolpaths and simulates setups away from the +// interface. It keeps the part's mesh and its placement in each setup. + +import { type GenerateJob, type SimulateJob, generateFor, placePart, simulateFor } from './engine'; +import { CamError } from './ops'; +import type { CamPart } from './ops'; +import type { CamSetup } from '../model/cam'; +import type { SimResult } from './simulate'; +import type { Toolpath } from './toolpath'; + +declare const self: DedicatedWorkerGlobalScope; + +export type CamWorkerRequest = + | { id: number; type: 'mesh'; key: string; tris: Float32Array } + | { id: number; type: 'generate'; job: GenerateJob } + | { id: number; type: 'simulate'; setup: CamSetup; job: SimulateJob }; + +export type CamWorkerResponse = + | { id: number; type: 'progress'; value: number } + | { id: number; type: 'done'; result: unknown } + | { id: number; type: 'error'; error: string; user: boolean }; + +let tris: Float32Array | null = null; +const parts = new Map(); + +const placementKey = (s: CamSetup) => JSON.stringify([s.axis, s.rotation, s.origin, s.stock]); + +function partFor(setup: CamSetup): CamPart { + if (!tris) throw new CamError('The part has no geometry to machine.'); + const key = placementKey(setup); + if (!parts.has(key)) { + if (parts.size > 8) parts.clear(); + parts.set(key, placePart(setup, tris)); + } + const p = parts.get(key); + if (!p) throw new CamError('The part has no geometry to machine.'); + return p; +} + +self.onmessage = (ev: MessageEvent) => { + const msg = ev.data; + const progress = (value: number) => self.postMessage({ id: msg.id, type: 'progress', value } satisfies CamWorkerResponse); + try { + if (msg.type === 'mesh') { + tris = msg.tris; + parts.clear(); + self.postMessage({ id: msg.id, type: 'done', result: null } satisfies CamWorkerResponse); + return; + } + if (msg.type === 'generate') { + const tp: Toolpath = generateFor(partFor(msg.job.setup), msg.job, progress); + self.postMessage({ id: msg.id, type: 'done', result: tp } satisfies CamWorkerResponse, [tp.moves.buffer]); + return; + } + const res: SimResult = simulateFor(partFor(msg.setup), msg.job, progress); + const transfer: Transferable[] = [res.partTop.buffer, res.timeline.buffer, ...res.snapshots.map((s) => s.z.buffer)]; + self.postMessage({ id: msg.id, type: 'done', result: res } satisfies CamWorkerResponse, transfer); + } catch (e) { + self.postMessage({ id: msg.id, type: 'error', error: (e as Error).message ?? String(e), user: e instanceof CamError } satisfies CamWorkerResponse); + } +}; diff --git a/src/parametric/src/main.ts b/src/parametric/src/main.ts index c94155ee6..ca0356de1 100644 --- a/src/parametric/src/main.ts +++ b/src/parametric/src/main.ts @@ -2,6 +2,7 @@ import './styles/app.css'; import { App } from './app/app'; import { makeHooks, registerCommands } from './app/actions'; import { installAssembly } from './app/assembly'; +import { installCam } from './app/cam'; import { FileOps } from './app/fileops'; import { StartScreen, bindAccountMenu, bindUserMenu, refreshAccount } from './app/start'; import { TaskPane, recentItems } from './app/taskpane'; @@ -32,6 +33,7 @@ async function boot() { registerCommands(app, files); const hooks = makeHooks(app); installAssembly(app, files, hooks); + installCam(app, hooks); let start: StartScreen | null = null; hooks.recent = () => recentItems(app, files); hooks.gettingStarted = () => app.openTaskPane('help'); diff --git a/src/parametric/src/render/renderer.ts b/src/parametric/src/render/renderer.ts index e9d2fba3f..eaf956364 100644 --- a/src/parametric/src/render/renderer.ts +++ b/src/parametric/src/render/renderer.ts @@ -223,6 +223,52 @@ in vec4 vColor; out vec4 outColor; void main() { outColor = vColor; }`; +// Opaque shaded meshes with a colour per vertex (the simulated stock, the tool). +const SOLID_VS = `#version 300 es +layout(location=0) in vec3 aPos; +layout(location=1) in vec3 aNormal; +layout(location=2) in vec4 aColor; +uniform mat4 uViewProj; +uniform mat4 uView; +out vec3 vN; +out vec3 vPosV; +out vec4 vColor; +out vec3 vWorld; +void main() { + vec4 w = vec4(aPos, 1.0); + gl_Position = uViewProj * w; + vN = mat3(uView) * aNormal; + vPosV = (uView * w).xyz; + vColor = aColor; + vWorld = aPos; +}`; + +const SOLID_FS = `#version 300 es +precision highp float; +in vec3 vN; +in vec3 vPosV; +in vec4 vColor; +in vec3 vWorld; +uniform int uOrtho; +uniform vec4 uClip; +uniform int uClipOn; +out vec4 outColor; +void main() { + if (uClipOn == 1 && dot(vec4(vWorld, 1.0), uClip) > 0.0) discard; + vec3 n = normalize(vN); + if (!gl_FrontFacing) n = -n; + vec3 v = uOrtho == 1 ? vec3(0.0, 0.0, 1.0) : normalize(-vPosV); + vec3 l1 = normalize(vec3(0.35, 0.55, 1.0)); + vec3 l2 = normalize(vec3(-0.6, -0.25, 0.55)); + float d1 = max(dot(n, l1), 0.0); + float d2 = max(dot(n, l2), 0.0); + vec3 h = normalize(l1 + v); + float sp = pow(max(dot(n, h), 0.0), 40.0); + float hemi = 0.5 + 0.5 * n.y; + vec3 base = vColor.rgb; + outColor = vec4(base * (0.34 + 0.16 * hemi + 0.5 * d1 + 0.12 * d2) + vec3(0.16) * sp, 1.0); +}`; + // Picking: id in an R32UI target and eye distance in an R32F target. const PICK_MESH_FS = `#version 300 es precision highp float; @@ -399,6 +445,15 @@ export interface PointBatch { order?: number; } +/** An opaque, shaded mesh with a colour per vertex. */ +export interface SolidBatch { + positions: Float32Array; + normals: Float32Array; + /** RGBA per vertex (0..255). */ + colors: Uint8Array; + indices: Uint32Array; +} + export interface TriBatch { positions: Float32Array; colors: Uint8Array; @@ -465,6 +520,7 @@ export class Renderer { private lines = new Map(); private points = new Map(); private tris = new Map(); + private solids = new Map(); private pickFbo: WebGLFramebuffer | null = null; private pickTex: WebGLTexture | null = null; private pickDepthTex: WebGLTexture | null = null; @@ -507,6 +563,7 @@ export class Renderer { this.progs.seg = this.program(SEG_VS, SEG_FS); this.progs.pt = this.program(PT_VS, PT_FS); this.progs.tri = this.program(TRI_VS, TRI_FS); + this.progs.solid = this.program(SOLID_VS, SOLID_FS); this.progs.pickMesh = this.program(MESH_VS, PICK_MESH_FS); this.progs.pickSeg = this.program(SEG_VS, PICK_SEG_FS); this.progs.pickPt = this.program(PICK_PT_VS, PICK_PT_FS); @@ -540,6 +597,7 @@ export class Renderer { for (const [k, b] of [...this.lines]) { b.gpu = undefined; this.setLines(k, b); } for (const [k, b] of [...this.points]) { b.gpu = undefined; this.setPoints(k, b); } for (const [k, b] of [...this.tris]) { b.gpu = undefined; this.setTris(k, b); } + for (const [k, b] of [...this.solids]) { b.gpu = undefined; this.setSolid(k, b); } this.requestRender(); } @@ -811,6 +869,36 @@ export class Renderer { this.requestRender(); } + /** Shows (or with null removes) an opaque shaded mesh, drawn with the model. */ + setSolid(key: string, batch: SolidBatch | null) { + const gl = this.gl; + const old = this.solids.get(key); + if (old?.gpu) { gl.deleteVertexArray(old.gpu.vao); old.gpu.bufs.forEach((b) => gl.deleteBuffer(b)); } + this.setBox(`solid:${key}`, batch?.positions ?? null); + if (!batch || !batch.indices.length) { this.solids.delete(key); this.requestRender(); return; } + const vao = gl.createVertexArray()!; + gl.bindVertexArray(vao); + const bufs: WebGLBuffer[] = []; + const attr = (data: ArrayBufferView, loc: number, size: number, type: number, norm: boolean) => { + const b = gl.createBuffer()!; + gl.bindBuffer(gl.ARRAY_BUFFER, b); + gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW); + gl.enableVertexAttribArray(loc); + gl.vertexAttribPointer(loc, size, type, norm, 0, 0); + bufs.push(b); + }; + attr(batch.positions, 0, 3, gl.FLOAT, false); + attr(batch.normals, 1, 3, gl.FLOAT, false); + attr(batch.colors, 2, 4, gl.UNSIGNED_BYTE, true); + const ib = gl.createBuffer()!; + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ib); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, batch.indices, gl.STATIC_DRAW); + bufs.push(ib); + gl.bindVertexArray(null); + this.solids.set(key, { ...batch, gpu: { vao, bufs, count: batch.indices.length } }); + this.requestRender(); + } + // ---- frame ---- resize(cssW: number, cssH: number, dpr: number) { @@ -956,6 +1044,25 @@ export class Renderer { if (!showBody && this.model) this.drawModelStates(this.model, vp, view, viewport, clip, style === 'wireframe'); } + if (this.solids.size) { + const { p, u } = this.progs.solid; + gl.useProgram(p); + gl.uniformMatrix4fv(u.uViewProj, false, vp); + gl.uniformMatrix4fv(u.uView, false, view); + gl.uniform1i(u.uOrtho, cam.ortho ? 1 : 0); + gl.uniform1i(u.uClipOn, clip ? 1 : 0); + if (clip) gl.uniform4fv(u.uClip, clip); + gl.enable(gl.POLYGON_OFFSET_FILL); + gl.polygonOffset(1, 1); + for (const s of this.solids.values()) { + if (!s.gpu) continue; + gl.bindVertexArray(s.gpu.vao); + gl.drawElements(gl.TRIANGLES, s.gpu.count, gl.UNSIGNED_INT, 0); + } + gl.bindVertexArray(null); + gl.disable(gl.POLYGON_OFFSET_FILL); + } + for (const b of ordered(this.lines, 'test')) this.drawLineBatch(b, vp, viewport, b.clip === false ? null : clip); for (const b of ordered(this.points, 'test')) this.drawPointBatch(b, vp, viewport, clip); diff --git a/src/parametric/src/styles/app.css b/src/parametric/src/styles/app.css index 426078cd4..0f324e181 100644 --- a/src/parametric/src/styles/app.css +++ b/src/parametric/src/styles/app.css @@ -710,3 +710,34 @@ a.icon-btn { text-decoration: none; } .weld-cutlist th, .weld-cutlist td { white-space: nowrap; } .weld-cutlist th.num, .weld-cutlist td.num { text-align: right; } .weld-cutlist tfoot th, .weld-cutlist tfoot td { font-weight: 600; border-bottom: none; } + +/* ---------- CAM ---------- */ +.cam-stats td.num { text-align: right; } +.cam-play { gap: 6px; align-items: center; } +.cam-slider { width: 100%; accent-color: var(--accent); } +.cam-clock { font-family: var(--font-mono); } +.cam-legend { display: flex; flex-wrap: wrap; gap: 4px 12px; font-size: var(--fs-sm); color: var(--text-2); } +.cam-legend span { display: inline-flex; align-items: center; gap: 5px; } +.cam-legend i { width: 12px; height: 12px; border-radius: 3px; border: 1px solid var(--border-strong); } +.pm-content progress { width: 100%; accent-color: var(--accent); } +.cam-tools { display: grid; grid-template-columns: minmax(0, 1.1fr) minmax(0, 1fr); gap: 16px; align-items: start; } +.cam-tools-side { display: flex; flex-direction: column; gap: 8px; min-width: 0; } +.cam-tools-side .row { gap: 6px; flex-wrap: wrap; } +.cam-tool-list { border: 1px solid var(--border); border-radius: var(--radius); max-height: 340px; overflow: auto; background: var(--panel); } +.cam-tool-list:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; } +.cam-tool { display: flex; gap: 8px; align-items: baseline; padding: 6px 8px; cursor: pointer; border-bottom: 1px solid var(--border); font-size: var(--fs-sm); } +.cam-tool:last-child { border-bottom: 0; } +.cam-tool .num { font-family: var(--font-mono); color: var(--text-2); flex: none; width: 34px; } +.cam-tool .grow { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.cam-tool .muted { color: var(--text-3); flex: none; } +.cam-tool[aria-selected='true'] { background: var(--accent-weak, var(--panel-2)); } +.cam-tool:hover { background: var(--panel-2); } +.cam-tool-form { display: flex; flex-direction: column; gap: 6px; min-width: 0; } +.cam-post { display: grid; grid-template-columns: 230px minmax(0, 1fr); gap: 16px; align-items: start; } +.cam-post-side { display: flex; flex-direction: column; gap: 8px; } +.cam-post-main { display: flex; flex-direction: column; gap: 4px; min-width: 0; } +.cam-gcode { margin: 0; height: 360px; overflow: auto; padding: 8px 10px; font: 12px/1.45 var(--font-mono); background: var(--panel-2); border: 1px solid var(--border); border-radius: var(--radius); white-space: pre; user-select: text; -webkit-user-select: text; } +@media (max-width: 760px) { + .cam-tools, .cam-post { grid-template-columns: minmax(0, 1fr); } + .cam-gcode { height: 220px; } +} diff --git a/src/parametric/tests/cam-kernel.test.ts b/src/parametric/tests/cam-kernel.test.ts new file mode 100644 index 000000000..19da4ebf0 --- /dev/null +++ b/src/parametric/tests/cam-kernel.test.ts @@ -0,0 +1,118 @@ +// CAM on parts built by the real OpenCascade kernel: every kind of operation +// on the example parts, simulated together, without gouges or rapid moves +// through the stock, and the holes found and drilled. +import { beforeAll, describe, expect, it } from 'vitest'; +import init from 'replicad-opencascadejs'; +import { ModelBuilder } from '../src/kernel/build'; +import { setOc } from '../src/kernel/occ'; +import { bracketExample, flangeExample } from '../src/app/examples'; +import { type ModelCylinder, generateFor, placePart, stlTriangles } from '../src/cam/engine'; +import { simulate } from '../src/cam/simulate'; +import { CYCLE } from '../src/cam/toolpath'; +import { postProcess } from '../src/cam/post'; +import { type CamOperation, type CamSetup, type CamTool, newCamDoc, opDefaults } from '../src/model/cam'; +import type { PartDocument } from '../src/model/types'; +import { req } from './helpers'; + +beforeAll(async () => { + setOc(await init()); +}); + +async function build(doc: PartDocument) { + const b = new ModelBuilder(); + const res = await b.build(req(doc.features, { quality: 1 })); + expect(res.status.every((s) => s.ok)).toBe(true); + const tris = stlTriangles(b.exportStl(2)); + // The hole candidates, as the interface collects them from the shown mesh. + const m = res.mesh!; + const cylinders: ModelCylinder[] = res.faces.flatMap((f, i) => { + if (f.type !== 'cylinder' || !f.axis || !f.radius) return []; + const t: number[] = []; + for (let k = 0; k < m.indices.length; k += 3) { + if (Math.round(m.vertexFace[m.indices[k]]) !== i) continue; + for (let q = 0; q < 3; q++) { const v = m.indices[k + q] * 3; t.push(m.positions[v], m.positions[v + 1], m.positions[v + 2]); } + } + return [{ name: f.name, p: f.axis.p, d: f.axis.d, radius: f.radius, tris: Float32Array.from(t) }]; + }); + return { tris, cylinders, faces: res.faces }; +} + +const setup = (extra: Partial = {}): CamSetup => ({ + id: 's', name: 'Setup1', axis: '+Y', rotation: 0, origin: 'topCenter', + stock: { mode: 'offset', side: 2, top: 1, bottom: 2, size: [0, 0, 0] }, clearance: 10, retract: 3, workOffset: 54, ops: [], ...extra, +}); + +const opOf = (type: CamOperation['type'], tool: CamTool, extra: Record = {}) => + ({ id: type, name: type, type, tool: tool.id, ...opDefaults(type, tool.diameter), ...extra }) as CamOperation; + +describe('CAM on kernel parts', () => { + it('machines the flange: face, rough, finish, drill and contour without gouges', async () => { + const { tris, cylinders } = await build(flangeExample()); + const s = setup(); + const part = placePart(s, tris)!; + const cam = newCamDoc((p) => `${p}x`); + const em12 = cam.tools[0], em6 = cam.tools[1], ball6 = cam.tools[3]; + const drill7: CamTool = { ...cam.tools[6], diameter: 7, name: '7 mm drill' }; + const steps = []; + for (const [type, tool, extra] of [ + ['face', em12, {}], ['rough', em6, {}], ['waterline', ball6, { stepdown: 1 }], ['parallel', ball6, { stepover: 1 }], + ['drill', drill7, {}], ['contour', em6, {}], + ] as const) { + const tp = generateFor(part, { setup: s, op: opOf(type, tool, extra), tool, cylinders }); + expect(tp.warnings.filter((w) => /cuts into/.test(w)), type).toEqual([]); + expect(tp.moves.length, type).toBeGreaterThan(0); + steps.push({ toolpath: tp, tool, feed: tool.feed, plunge: tool.plunge }); + } + // The six bolt holes, drilled through. + const drill = steps[4].toolpath; + expect(drill.cycles).toHaveLength(6); + expect([...drill.moves].filter((v, i) => i % 4 === 0 && v === CYCLE)).toHaveLength(6); + for (const c of drill.cycles) expect(c.z).toBeLessThan(part.frame.part.min[2]); + const sim = simulate({ stock: part.frame.stock, part: part.index, steps, rapidFeed: 5000 }); + expect(sim.gouges).toBe(0); + expect(sim.rapidCuts).toEqual([0, 0, 0, 0, 0, 0]); + expect(sim.removed).toBeGreaterThan(0); + // G-code for the whole program. + const code = postProcess({ + name: 'Pipe Flange', units: 'mm', post: cam.post, + setups: [{ name: 'Setup1', workOffset: 54, ops: steps.map((st, i) => ({ name: `Op${i + 1}`, tool: st.tool, rpm: st.tool.rpm, feed: st.feed, plunge: st.plunge, toolpath: st.toolpath })) }], + }); + expect(code).toContain('G83'); + expect(code).toMatch(/\nG[23] /); + expect(code.split('\n').length).toBeGreaterThan(1000); + }, 240_000); + + it('machines the bracket from the top, then its other side in a second setup', async () => { + const { tris, cylinders } = await build(bracketExample()); + const cam = newCamDoc((p) => `${p}x`); + const em6 = cam.tools[1]; + for (const s of [setup(), setup({ axis: '-Y', origin: 'topFrontLeft' }), setup({ axis: '+Z', rotation: 90 })]) { + const part = placePart(s, tris)!; + const steps = []; + for (const type of ['rough', 'contour'] as const) { + const tp = generateFor(part, { setup: s, op: opOf(type, em6), tool: em6, cylinders }); + expect(tp.warnings.filter((w) => /cuts into/.test(w)), `${s.axis} ${type}`).toEqual([]); + steps.push({ toolpath: tp, tool: em6, feed: em6.feed, plunge: em6.plunge }); + } + const sim = simulate({ stock: part.frame.stock, part: part.index, steps, rapidFeed: 5000 }); + expect(sim.gouges, s.axis).toBe(0); + expect(sim.rapidCuts, s.axis).toEqual([0, 0]); + } + }, 240_000); + + it('pockets a picked floor and bores the counterbores of the bracket', async () => { + const { tris, cylinders, faces } = await build(bracketExample()); + const s = setup({ origin: 'topFrontLeft' }); + const part = placePart(s, tris)!; + const cam = newCamDoc((p) => `${p}x`); + const em3 = cam.tools[2]; + // The counterbores (11 mm) are larger than a 3 mm end mill; the 6 mm holes too. + const cb = faces.filter((f) => f.type === 'cylinder' && Math.abs((f.radius ?? 0) - 5.5) < 1e-6).map((f) => f.name); + expect(cb.length).toBeGreaterThanOrEqual(2); + const bore = generateFor(part, { setup: s, op: opOf('bore', em3, { holes: cb.map((name) => ({ face: { name, sig: { type: 'cylinder', c: [0, 0, 0], area: 0 } } })) }), tool: em3, cylinders, picked: cb }); + expect(bore.warnings.filter((w) => /cuts into/.test(w))).toEqual([]); + const sim = simulate({ stock: part.frame.stock, part: part.index, steps: [{ toolpath: bore, tool: em3, feed: em3.feed, plunge: em3.plunge }], rapidFeed: 5000 }); + expect(sim.gouges).toBe(0); + expect(sim.removed).toBeGreaterThan(2 * Math.PI * 5.5 * 5.5 * 3 * 0.8); + }, 240_000); +}); From 2616f6ac280ca859fa892ce8e194bb1ff19fa061 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:32:25 -0700 Subject: [PATCH 03/34] Parametric: CAM safety fixes, browser test and docs Drills, bores, contour leads and finishing passes feed down from the retract height (the stock over them may be uncut); helix entries go inside the pass they enter; counterbores are no longer taken for through holes. Every toolpath is checked against the part. Toolpath lines are cached, the first setup or operation is one undo step and the tool library no longer creates CAM data until OK. --- src/parametric/README.md | 12 +++- src/parametric/package.json | 2 +- src/parametric/src/app/cam/dialogs.ts | 28 +++++---- src/parametric/src/app/cam/index.ts | 15 +++-- src/parametric/src/app/cam/panels.ts | 10 +-- src/parametric/src/app/cam/workspace.ts | 63 ++++++++++++------- src/parametric/src/cam/ops.ts | 12 ++-- src/parametric/tests/cam-engine.test.ts | 14 ++++- src/parametric/tests/e2e/cam.spec.ts | 83 +++++++++++++++++++++++++ 9 files changed, 185 insertions(+), 54 deletions(-) create mode 100644 src/parametric/tests/e2e/cam.spec.ts diff --git a/src/parametric/README.md b/src/parametric/README.md index 6a24f30b3..7521feb18 100644 --- a/src/parametric/README.md +++ b/src/parametric/README.md @@ -4,7 +4,7 @@

Live app: parametric.puter.com

-

Feature-based parametric 3D CAD in the browser. An open-source alternative to SolidWorks, Autodesk Fusion and Autodesk Inventor.

+

Feature-based parametric 3D CAD and CAM in the browser. An open-source alternative to SolidWorks, Autodesk Fusion and Autodesk Inventor.

> **Early alpha.** Features may change and work could be lost. Please do not rely on Parametric for production designs yet, and keep a downloaded copy of anything important. @@ -74,6 +74,15 @@ It runs entirely in the browser. The geometry kernel is OpenCascade compiled to - Sheet metal drawings: a Flat Pattern view (Drafting tab, or Add view) shows the flat outline and cuts, the bend lines (dashed up, chain lines down) with their notes ("UP 90° R 1") and the overall size; it can be dimensioned and detailed like any view. - Weldment drawings: a Cut List table (Annotation tab) with item, quantity, description, length and end angles, which follows the part, and balloons on members numbered from it. +**CAM (machining)** +- A CAM tab turns the part into CNC programs. A setup says where the part sits on the machine: the direction the tool comes from (any side of the part, picked from a list or from a flat face), a turn about it, the stock (a margin around the part or a fixed block), the work origin (a corner or the centre of the stock's top, or the part's origin), the work offset (G54 to G59) and the clearance and retract heights. A second setup usually machines the other side. +- A tool library of flat, ball and bull nose end mills, drills and chamfer mills with their flutes, speeds and feeds, kept with the part. +- 2D operations: Face (the top of the stock down to the part), 2D Contour (round the outside through the full height, with lead-in arcs, a ramp down along the wall and holding tabs), 2D Pocket (down to picked floors, offset or zigzag passes, entering by a helix, a ramp or a plunge), Drill (drilling, deep peck and chip breaking cycles on every hole of the drill's size or those picked; through holes found by themselves) and Bore (helical milling of holes larger than the tool). +- 3D operations: 3D Rough (the stock around the whole part in levels, with stock to leave and extra levels at its flat areas), Parallel finishing and Waterline finishing, with ball, bull nose or flat end mills. +- Climb or conventional milling, stock to leave on walls and floors, feeds and speeds per operation. The toolpath shows while an operation is edited, with its machining time; operations are listed under CAM in the design tree, marked when the part changed since they were generated. +- Every toolpath is checked against the part; Simulate cuts the stock operation by operation and plays it back with the tool, coloured by what is finished, what is left and where the part would be cut, and reports rapid moves through the stock and material above the flutes. +- Post Process writes G-code for Fanuc, Haas, LinuxCNC, Mach3/Mach4 or Grbl, in millimetres or inches, with arcs (G2/G3, helical) and drilling cycles (G81, G82, G83, G73) where the controller has them; preview it, copy it or download it. + **Working with parts** - Design tree with rollback bar, suppress, rename, hide/show, edit and delete with dependency warnings. - Global variables and equations: type `=Width/2` in any dimension or feature value. @@ -116,6 +125,7 @@ npm run build # type check, license check, production build in dist/ | Renderer | `src/render` | WebGL2: shaded meshes with per-face state in a data texture, screen-space thick edges, GPU picking with depth (asynchronous readback for hover), section clipping, render on demand. | | Interface | `src/app`, `src/ui` | No framework. CommandManager, design tree, PropertyManager panels, sketch editor, dialogs. | | SolidWorks import | `src/formats/sldprt` | Reads the SolidWorks container (2015+ chunk format and the older OLE2), decodes the embedded Parasolid transmit and writes it as exact STEP for the kernel. Runs in the geometry worker. | +| CAM | `src/model/cam.ts`, `src/cam`, `src/app/cam` | Toolpaths are generated in a worker of their own from a fine mesh of the part, in the setup's work coordinates. Drop-cutter (`src/cam/dropcutter.ts`) gives the lowest height a flat, ball, bull nose or conical cutter can reach at a point (face, edge and corner contacts, exact where a closed form exists). Where the tool can be at a height is where that is lower: its boundary is traced by marching squares with each crossing refined by bisection on the drop-cutter, and the passes inside it are offsets of a distance transform, cut from the innermost out. Parallel finishing follows drop-cutter heights along lines. The simulation lowers a height map of the stock along every move. Post processors write the moves with arcs fitted to them. | | Assistant | `src/assistant` | Tool-calling agent on Puter AI. Tools work on the document through a host interface (the app, or the kernel in Node for tests); each change rebuilds and is checked, failing steps are reverted, and a message's changes are squashed into one undo step. | | Platform | `src/platform` | Puter.js access, files (Puter or browser storage), theme. | diff --git a/src/parametric/package.json b/src/parametric/package.json index 1754e25d7..4449d345a 100644 --- a/src/parametric/package.json +++ b/src/parametric/package.json @@ -1,7 +1,7 @@ { "name": "parametric", "version": "0.1.0", - "description": "Parametric: feature-based 3D part modeling in the browser. Sketch with constraints, extrude, revolve, fillet, shell and pattern on a real B-rep kernel, then export STEP and STL, stored in your own Puter cloud.", + "description": "Parametric: feature-based 3D part modeling in the browser. Sketch with constraints, extrude, revolve, fillet, shell and pattern on a real B-rep kernel, then export STEP and STL or machine it with CAM toolpaths and G-code, stored in your own Puter cloud.", "type": "module", "private": true, "license": "AGPL-3.0-only", diff --git a/src/parametric/src/app/cam/dialogs.ts b/src/parametric/src/app/cam/dialogs.ts index c4453ee9d..0e789880d 100644 --- a/src/parametric/src/app/cam/dialogs.ts +++ b/src/parametric/src/app/cam/dialogs.ts @@ -2,7 +2,7 @@ import { CamCancelled } from '../../cam/client'; import { postProcess, type PostOperation } from '../../cam/post'; -import { type CamController, type CamTool, type CamToolType, CONTROLLER_LABELS, TOOL_TYPE_LABELS, opFeeds } from '../../model/cam'; +import { type CamController, type CamTool, type CamToolType, CONTROLLER_LABELS, TOOL_TYPE_LABELS, newCamDoc, opFeeds } from '../../model/cam'; import { allocateId } from '../../model/document'; import { UNIT_SYSTEMS } from '../../model/units'; import { download, safeName } from '../../platform/files'; @@ -11,15 +11,16 @@ import { icon } from '../../ui/icons'; import { showDialog, toast } from '../../ui/overlay'; import type { App } from '../app'; import { checkbox, numberField, selectField } from '../pm'; -import { rateField } from './panels'; +import { CamPanel, rateField } from './panels'; import type { CamWorkspace } from './workspace'; const TYPES = Object.entries(TOOL_TYPE_LABELS).map(([value, label]) => ({ value: value as CamToolType, label })); /** The tool library: add, change and remove the part's cutting tools (one undo step). */ export async function toolLibraryDialog(app: App, ws: CamWorkspace, select?: string) { - ws.ensureCam(); - const cam = app.store.doc.cam!; + // Without CAM data yet, the starting library (kept only if OK is pressed). + let fresh = 0; + const cam = app.store.doc.cam ?? newCamDoc(() => `__new${++fresh}`, app.store.doc.units === 'IPS'); const tools: CamTool[] = structuredClone(cam.tools); const used = (id: string) => cam.setups.flatMap((s) => s.ops).filter((o) => o.tool === id).length; let current = tools.find((t) => t.id === select) ?? tools[0] ?? null; @@ -33,7 +34,7 @@ export async function toolLibraryDialog(app: App, ws: CamWorkspace, select?: str const newId = () => { // Ids from the part's counter (taken on OK); until then a placeholder. nextLocal++; - return `__new${nextLocal}`; + return `__add${nextLocal}`; }; const drawList = () => { list.textContent = ''; @@ -128,11 +129,13 @@ export async function toolLibraryDialog(app: App, ws: CamWorkspace, select?: str }, }); if (v !== 'ok') return; - app.store.change('Edit tool library', (d) => { - for (const t of tools) if (t.id.startsWith('__new')) t.id = allocateId(d, 't'); - d.cam!.tools = tools; + app.store.change(app.store.doc.cam ? 'Edit tool library' : 'Start CAM', (d) => { + for (const t of tools) if (t.id.startsWith('__')) t.id = allocateId(d, 't'); + d.cam ??= { ...newCamDoc(() => ''), tools: [] }; + d.cam.tools = tools; }); ws.changed(); + if (app.panel instanceof CamPanel) app.refreshPanel(); } const EXTENSIONS: Record = { fanuc: 'nc', haas: 'nc', mach3: 'tap', linuxcnc: 'ngc', grbl: 'gcode' }; @@ -207,10 +210,11 @@ export async function postDialog(app: App, ws: CamWorkspace) { }, }); if (v !== 'ok' || !code) return; - // Keep the post settings with the part. - if (JSON.stringify({ ...cam.post }) !== JSON.stringify({ ...post, units: unitsSel === (app.store.doc.units === 'IPS' ? 'in' : 'mm') ? post.units : unitsSel })) { - app.store.change('Post settings', (d) => { if (d.cam) d.cam.post = { ...post, ...(unitsSel !== (d.units === 'IPS' ? 'in' : 'mm') ? { units: unitsSel } : {}) }; }); - } + // Keep the post settings with the part (units only when they differ from the part's). + const next = { ...post }; + delete next.units; + if (unitsSel !== (app.store.doc.units === 'IPS' ? 'in' : 'mm')) next.units = unitsSel; + if (JSON.stringify(next) !== JSON.stringify(cam.post)) app.store.change('Post settings', (d) => { if (d.cam) d.cam.post = next; }); download(code, `${safeName(app.store.doc.name)}.${EXTENSIONS[post.controller]}`, 'text/plain'); toast({ kind: 'success', message: `G-code written for ${CONTROLLER_LABELS[post.controller]}` }); } diff --git a/src/parametric/src/app/cam/index.ts b/src/parametric/src/app/cam/index.ts index 201548d77..4062e9869 100644 --- a/src/parametric/src/app/cam/index.ts +++ b/src/parametric/src/app/cam/index.ts @@ -2,7 +2,7 @@ // the CAM rows of the design tree and their menus. import type { CamOperation, CamSetup, CamOpType } from '../../model/cam'; -import { CAM_OP_ICONS, CAM_OP_LABELS, findOp, nextCamName } from '../../model/cam'; +import { CAM_OP_ICONS, CAM_OP_LABELS, findOp, newCamDoc, nextCamName } from '../../model/cam'; import { allocateId } from '../../model/document'; import type { Id } from '../../model/types'; import { addIcons } from '../../ui/icons'; @@ -80,7 +80,6 @@ export function installCam(app: App, hooks: AppHooks): CamWorkspace { if (why) { toast({ kind: 'info', message: why }); return; } void ws.mesh().then(() => { const s = newSetup(app, ws); - ws.ensureCam(); s.id = allocateId(app.store.doc, 's'); app.exitModes(); void app.openPanel(new SetupPanel(app, ws, s, true)); @@ -91,14 +90,18 @@ export function installCam(app: App, hooks: AppHooks): CamWorkspace { if (!partOnly()) return; const why = ws.ready(); if (why) { toast({ kind: 'info', message: why }); return; } - const cam = ws.ensureCam(); let setup = currentSetup(ws); if (!setup) { - // A first operation comes with a setup from the top. + // A first operation comes with the tool library and a setup from the top (one undo step). const s = newSetup(app, ws); - app.store.change('New setup', (d) => { s.id = allocateId(d, 's'); d.cam!.setups.push(s); }); - setup = ws.cam!.setups[0]; + app.store.change(ws.cam ? 'New setup' : 'Start CAM', (d) => { + d.cam ??= newCamDoc((p) => allocateId(d, p), d.units === 'IPS'); + s.id = allocateId(d, 's'); + d.cam.setups.push(s); + }); + setup = ws.cam!.setups[ws.cam!.setups.length - 1]; } + const cam = ws.cam!; const tool = defaultTool(cam.tools, type, cam.setups); if (!tool) { toast({ kind: 'warning', message: 'Add a tool to the tool library first.' }); void toolLibraryDialog(app, ws); return; } const op = newOperation(type, allocateId(app.store.doc, 'op'), nextCamName(cam.setups.flatMap((s) => s.ops.map((o) => o.name)), CAM_OP_LABELS[type].replace(/^\d+D /, '').replace(/\s+/g, '')), tool); diff --git a/src/parametric/src/app/cam/panels.ts b/src/parametric/src/app/cam/panels.ts index b465c6815..a2cd7f300 100644 --- a/src/parametric/src/app/cam/panels.ts +++ b/src/parametric/src/app/cam/panels.ts @@ -3,7 +3,8 @@ // feeds), with the toolpath previewed while the values change. import type { CamAxis, CamOperation, CamOrigin, CamSetup, CamTool, ClearingPattern, DrillCycle, EntryKind } from '../../model/cam'; -import { CAM_OP_ICONS, CAM_OP_LABELS, TOOL_TYPE_LABELS, opDefaults, opToolTypes } from '../../model/cam'; +import { CAM_OP_ICONS, CAM_OP_LABELS, TOOL_TYPE_LABELS, newCamDoc, opDefaults, opToolTypes } from '../../model/cam'; +import { allocateId } from '../../model/document'; import { UNIT_SYSTEMS, formatNumber } from '../../model/units'; import type { FaceRef, Id } from '../../model/types'; import { pathStats, type Toolpath } from '../../cam/toolpath'; @@ -167,9 +168,10 @@ export class SetupPanel extends CamPanel { const s = this.s; if (!s.name.trim()) { this.setMessage('error', 'Enter a name'); return false; } const app = this.app; - this.ws.ensureCam(); - app.store.change(this.isNew ? 'New setup' : 'Edit setup', (d) => { - const cam = d.cam!; + app.store.change(this.isNew ? (app.store.doc.cam ? 'New setup' : 'Start CAM') : 'Edit setup', (d) => { + // The first setup brings the tool library with it (one undo step). + d.cam ??= newCamDoc((p) => allocateId(d, p), d.units === 'IPS'); + const cam = d.cam; const i = cam.setups.findIndex((x) => x.id === s.id); if (i >= 0) cam.setups[i] = { ...structuredClone(s), ops: cam.setups[i].ops }; else cam.setups.push(structuredClone(s)); diff --git a/src/parametric/src/app/cam/workspace.ts b/src/parametric/src/app/cam/workspace.ts index 18d7bf2c8..42cb0b8a7 100644 --- a/src/parametric/src/app/cam/workspace.ts +++ b/src/parametric/src/app/cam/workspace.ts @@ -8,8 +8,7 @@ import { type GenerateJob, type ModelCylinder, stlTriangles } from '../../cam/en import { type MachineFrame, machineFrame, toModel } from '../../cam/frame'; import { PLUNGE, RAPID, type PathStats, type Toolpath, expandMoves, pathStats } from '../../cam/toolpath'; import type { Vec3 } from '../../math/vec'; -import { type CamDoc, type CamOperation, type CamSetup, type CamTool, findOp, newCamDoc, opFeeds } from '../../model/cam'; -import { allocateId } from '../../model/document'; +import { type CamDoc, type CamOperation, type CamSetup, type CamTool, findOp, opFeeds } from '../../model/cam'; import type { FaceRef, Id } from '../../model/types'; import type { App } from '../app'; @@ -31,7 +30,38 @@ const COLORS: Record = { [PLUNGE]: [30, 160, 90, 255], }; +/** A toolpath's moves as line segments in model coordinates (rapids and cuts apart). */ +interface PathLines { rapid: Float32Array; rapidColors: Uint8Array; cut: Float32Array; cutColors: Uint8Array } + +function pathLines(tp: Toolpath, f: MachineFrame): PathLines { + let nr = 0, nc = 0, first = true; + expandMoves(tp, (k) => { if (!first) { if (k === RAPID) nr++; else nc++; } first = false; }); + const rapid = new Float32Array(nr * 6), cut = new Float32Array(nc * 6); + const rapidColors = new Uint8Array(nr * 4), cutColors = new Uint8Array(nc * 4); + let ir = 0, ic = 0; + let px = NaN, py = NaN, pz = NaN; + expandMoves(tp, (k, x, y, z) => { + const p = toModel(f, x, y, z); + if (!Number.isNaN(px)) { + const col = COLORS[k] ?? COLORS[1]; + if (k === RAPID) { rapid.set([px, py, pz, p[0], p[1], p[2]], ir * 6); rapidColors.set(col, ir * 4); ir++; } + else { cut.set([px, py, pz, p[0], p[1], p[2]], ic * 6); cutColors.set(col, ic * 4); ic++; } + } + [px, py, pz] = p; + }); + return { rapid, rapidColors, cut, cutColors }; +} + +const concat = (parts: T[], make: (n: number) => T): T => { + const out = make(parts.reduce((n, p) => n + p.length, 0)); + let o = 0; + for (const p of parts) { out.set(p, o); o += p.length; } + return out; +}; + export class CamWorkspace { + /** Line geometry of toolpaths, by the frame it was placed with. */ + private lineCache = new WeakMap(); readonly client = new CamClient(); /** A second worker for the preview of the operation being edited, so it never waits for (or stops) generation. */ private readonly previewClient = new CamClient(); @@ -86,13 +116,6 @@ export class CamWorkspace { return this.app.store.doc.cam ?? null; } - /** The part's CAM data, created (as an undo step) the first time it is needed. */ - ensureCam(): CamDoc { - const doc = this.app.store.doc; - if (!doc.cam) this.app.store.change('Start CAM', (d) => { d.cam = newCamDoc((p) => allocateId(d, p), d.units === 'IPS'); }); - return this.app.store.doc.cam!; - } - changed() { this.redraw(); for (const fn of this.listeners) fn(); @@ -330,22 +353,14 @@ export class CamWorkspace { if (cam && this.shown() && !this.tris && !this.loading && !this.ready()) void this.mesh().then((t) => { if (t) this.redraw(); }); return; } - const rapid: number[] = [], rc: number[] = [], cut: number[] = [], cc: number[] = []; + const shown: PathLines[] = []; const focusSetup = this.focus ? cam.setups.find((s) => s.id === this.focus || s.ops.some((o) => o.id === this.focus)) : null; const add = (setup: CamSetup, tp: Toolpath) => { const f = this.frameOf(setup); if (!f) return; - let prev: Vec3 | null = null; - expandMoves(tp, (k, x, y, z) => { - const p = toModel(f, x, y, z); - if (prev) { - const into = k === RAPID ? rapid : cut; - const col = k === RAPID ? rc : cc; - into.push(...prev, ...p); - col.push(...(COLORS[k] ?? COLORS[1])); - } - prev = p; - }); + let c = this.lineCache.get(tp); + if (!c || c.frame !== f) { c = { frame: f, lines: pathLines(tp, f) }; this.lineCache.set(tp, c); } + shown.push(c.lines); }; if (!this.hidePaths) { if (this.preview) { @@ -362,8 +377,10 @@ export class CamWorkspace { } } } - r.setLines('camRapid', rapid.length ? { positions: new Float32Array(rapid), colors: new Uint8Array(rc), width: 1, depth: 'test', dash: 5, order: 7, clip: false } : null); - r.setLines('camCut', cut.length ? { positions: new Float32Array(cut), colors: new Uint8Array(cc), width: 1.4, depth: 'test', order: 7, clip: false } : null); + const rapid = concat(shown.map((l) => l.rapid), (n) => new Float32Array(n)); + const cut = concat(shown.map((l) => l.cut), (n) => new Float32Array(n)); + r.setLines('camRapid', rapid.length ? { positions: rapid, colors: concat(shown.map((l) => l.rapidColors), (n) => new Uint8Array(n)), width: 1, depth: 'test', dash: 5, order: 7, clip: false } : null); + r.setLines('camCut', cut.length ? { positions: cut, colors: concat(shown.map((l) => l.cutColors), (n) => new Uint8Array(n)), width: 1.4, depth: 'test', order: 7, clip: false } : null); // The stock and work origin of the setup shown (or the first). const setup = this.preview?.setup ?? focusSetup ?? cam.setups[0]; const f = setup ? this.frameOf(setup) : null; diff --git a/src/parametric/src/cam/ops.ts b/src/parametric/src/cam/ops.ts index 02e77c39a..242efa845 100644 --- a/src/parametric/src/cam/ops.ts +++ b/src/parametric/src/cam/ops.ts @@ -714,7 +714,6 @@ class Gen { this.steps = levels.length + 1; const r = this.region(st.min[0] - m, st.min[1] - m, st.max[0] + m, st.max[1] + m, cutter, op.floorLeave); this.tick(); - if (st.min[2] >= this.partBottom - 1e-6) this.b.warnings.push('The roughing goes down to the bottom of the part, which is the bottom of the stock. Leave stock below the part (Setup: stock below) to keep it held.'); // The tool stays within the stock (plus most of its radius, to cut its edges). const gx = R * 0.9; const lim = (x: number, y: number) => Math.min(x - (st.min[0] - gx), st.max[0] + gx - x, y - (st.min[1] - gx), st.max[1] + gx - y); @@ -769,7 +768,8 @@ class Gen { this.tick(); if (Math.abs(2 * h.r - this.tool.diameter) > Math.max(0.05, h.r * 0.02)) b.warnings.push(`A hole of ${(2 * h.r).toFixed(3)} mm is drilled with a ${this.tool.diameter} mm tool.`); const z = h.through ? h.bottom - Math.max(0, op.breakthrough) - (op.tipThrough ? tip : 0) : h.bottom; - b.cycle(h.x, h.y, { cycle: op.cycle, r: h.top + this.input.setup.retract, z, peck: op.cycle === 'drill' ? 0 : Math.max(0.05, op.peck), dwell: Math.max(0, op.dwell) }); + // From the retract height over the stock: the stock over the hole may not be cut yet. + b.cycle(h.x, h.y, { cycle: op.cycle, r: b.retract, z, peck: op.cycle === 'drill' ? 0 : Math.max(0.05, op.peck), dwell: Math.max(0, op.dwell) }); } } @@ -785,13 +785,13 @@ class Gen { this.tick(); const rh = h.r - op.leave - this.R; const z = h.through ? h.bottom - Math.max(0, op.breakthrough) : h.bottom; - const zFrom = h.top + 0.5; - b.rapidTo(h.x + rh, h.y, h.top + this.input.setup.retract); - b.rapid(h.x + rh, h.y, zFrom + 0.5); + // Down from over the stock (it may not be cut over the hole yet). + const zFrom = this.stockTop + 0.5; + b.rapidTo(h.x + rh, h.y, b.retract); this.helix(h.x, h.y, rh, zFrom, z, Math.max(0.05, op.pitch), climb); // Away from the wall and out through the middle. b.feed(h.x, h.y, z); - b.rapid(h.x, h.y, h.top + this.input.setup.retract); + b.rapid(h.x, h.y, b.retract); } } diff --git a/src/parametric/tests/cam-engine.test.ts b/src/parametric/tests/cam-engine.test.ts index 432f67c64..dfe69b613 100644 --- a/src/parametric/tests/cam-engine.test.ts +++ b/src/parametric/tests/cam-engine.test.ts @@ -11,6 +11,7 @@ import { postProcess, writeArcs } from '../src/cam/post'; import { CYCLE, FEED, PLUNGE, RAPID, type Toolpath, expandMoves, pathStats } from '../src/cam/toolpath'; import { type CamOperation, type CamSetup, type CamTool, newCamDoc, normalizeCam, opDefaults } from '../src/model/cam'; import type { Vec3 } from '../src/math/vec'; +import { allocateId, newDocument, parseDocument, serializeDocument } from '../src/model/document'; type Tri = number[]; @@ -271,7 +272,7 @@ describe('operations', () => { expect(cycle).toBeGreaterThanOrEqual(0); expect(tp.moves[cycle + 1]).toBeCloseTo(20, 6); expect(tp.cycles[0].z).toBeLessThan(-1); - expect(tp.cycles[0].r).toBeCloseTo(13, 6); + expect(tp.cycles[0].r).toBeCloseTo(15, 6); // Bore it with a 3 mm end mill. const em = tool('flat', 3); const big = [{ ...cyl[0], radius: 2.5 }]; @@ -345,6 +346,17 @@ describe('simulation and G-code', () => { expect(st.zMin).toBeCloseTo(10, 6); }, 60_000); + it('saves CAM data with the part and opens it again, without id clashes', () => { + const doc = newDocument('Plate'); + doc.cam = newCamDoc((p) => allocateId(doc, p)); + doc.cam.setups.push({ ...setup({ id: allocateId(doc, 's') }), ops: [{ ...op('face', doc.cam.tools[0]), id: allocateId(doc, 'op') }] }); + const back = parseDocument(serializeDocument({ ...doc, nextId: 1 })); + expect(back.cam).toEqual(doc.cam); + // A stale counter is moved past the CAM ids. + const used = new Set([...back.cam!.tools.map((t) => t.id), back.cam!.setups[0].id, back.cam!.setups[0].ops[0].id]); + for (let i = 0; i < 5; i++) expect(used.has(allocateId(back, 't'))).toBe(false); + }); + it('reads CAM data back and drops what is damaged', () => { const doc = newCamDoc((p) => `${p}9`); const raw = JSON.parse(JSON.stringify({ ...doc, tools: [...doc.tools.slice(0, 1), { id: 'bad', type: 'laser' }], setups: [{ id: 's1', name: 'S', axis: '+Q', ops: [{ id: 'o1', name: 'P', type: 'pocket', tool: doc.tools[0].id, faces: 'nope' }, { id: 'o2', name: 'F', type: 'face', tool: doc.tools[0].id }] }] })); diff --git a/src/parametric/tests/e2e/cam.spec.ts b/src/parametric/tests/e2e/cam.spec.ts new file mode 100644 index 000000000..605d6a062 --- /dev/null +++ b/src/parametric/tests/e2e/cam.spec.ts @@ -0,0 +1,83 @@ +import { expect, test } from '@playwright/test'; +import { openApp } from './helpers'; + +type W = { __parametric: import('../../src/app/app').App }; + +test('machines a part from the CAM tab: setup, tools, operations, simulation and G-code', async ({ page }) => { + test.setTimeout(240_000); + const errors = await openApp(page); + await page.getByRole('button', { name: /Pipe Flange/ }).click(); + await page.waitForFunction(() => !!(window as unknown as W).__parametric.bbox); + await page.getByRole('tab', { name: 'CAM' }).click(); + + // A setup from the top. + await page.locator('[data-cmd="cam:setup"]').click(); + await expect(page.getByRole('heading', { name: 'New Setup' })).toBeVisible(); + await expect(page.getByLabel('Tool direction')).toHaveValue('+Y'); + await page.locator('.confirm-corner .ok').click(); + await expect(page.getByRole('treeitem', { name: 'Setup1' })).toBeVisible(); + + // A 7 mm drill for the bolt holes, added in the tool library. + await page.locator('[data-cmd="cam:tools"]').click(); + const dialog = page.getByRole('dialog', { name: 'Tool Library' }); + await dialog.getByRole('button', { name: 'Add' }).click(); + await dialog.getByLabel('Type').selectOption('drill'); + const dia = dialog.getByRole('textbox', { name: 'Diameter' }); + await dia.fill('7'); + await dia.press('Tab'); + await dialog.getByRole('textbox', { name: 'Name' }).fill('7 mm drill'); + await dialog.getByRole('button', { name: 'OK' }).click(); + await expect(dialog).toBeHidden(); + expect(await page.evaluate(() => (window as unknown as W).__parametric.store.doc.cam!.tools.some((t) => t.type === 'drill' && t.diameter === 7))).toBe(true); + + // Drill: every hole of the drill's size. + await page.locator('[data-cmd="cam:drill"]').click(); + await expect(page.getByLabel('Tool', { exact: true })).toContainText('7 mm drill'); + await expect(page.locator('.cam-stats')).toBeVisible({ timeout: 60_000 }); + await page.locator('.confirm-corner .ok').click(); + await expect(page.getByRole('treeitem', { name: /^Drill1/ })).toBeVisible(); + await page.waitForFunction(() => { + const app = (window as unknown as W).__parametric; + const s = app.store.doc.cam!.setups[0]; + return s.ops.every((o) => app.cam!.state(s, o) === 'ok'); + }, null, { timeout: 60_000 }); + expect(await page.evaluate(() => { + const app = (window as unknown as W).__parametric; + return app.cam!.result(app.store.doc.cam!.setups[0].ops[0].id)!.toolpath!.cycles.length; + })).toBe(6); + + // A contour round the outside. + await page.locator('[data-cmd="cam:contour"]').click(); + await expect(page.locator('.cam-stats')).toBeVisible({ timeout: 60_000 }); + await page.locator('.confirm-corner .ok').click(); + await page.waitForFunction(() => { + const app = (window as unknown as W).__parametric; + const s = app.store.doc.cam!.setups[0]; + return s.ops.length === 2 && s.ops.every((o) => app.cam!.state(s, o) === 'ok'); + }, null, { timeout: 90_000 }); + + // The simulation finds no collisions. + await page.locator('[data-cmd="cam:simulate"]').click(); + await expect(page.getByText('No collisions')).toBeVisible({ timeout: 90_000 }); + await expect(page.getByLabel('Program position')).toBeVisible(); + await page.getByRole('button', { name: 'Exit Simulation' }).click(); + + // G-code with peck drilling cycles, downloaded. + await page.locator('[data-cmd="cam:post"]').click(); + const post = page.getByRole('dialog', { name: 'Post Process' }); + await expect(post.getByLabel('G-code preview')).toContainText('G83', { timeout: 60_000 }); + await expect(post.getByLabel('G-code preview')).toContainText('T9 M6'); + const download = page.waitForEvent('download'); + await post.getByRole('button', { name: 'Download G-code' }).click(); + const file = await download; + expect(file.suggestedFilename()).toMatch(/\.nc$/); + const fs = await import('node:fs'); + const text = new TextDecoder().decode(fs.readFileSync((await file.path())!)); + expect(text).toMatch(/^%\nO1001 \(Pipe Flange\)/); + expect(text).toContain('G21'); + + // Undo takes the contour away, with its row. + await page.keyboard.press('ControlOrMeta+z'); + await expect(page.getByRole('treeitem', { name: /^Contour1/ })).toHaveCount(0); + expect(errors).toEqual([]); +}); From 8de548a828f128345b3557a412586ee4e8e7ed96 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:41:30 -0700 Subject: [PATCH 04/34] Parametric CAM: position the tool again when a new setup keeps it A later setup that used the same tool skipped the move to its start (the modal X, Y and Z were those of the previous setup's work offset) and ran straight on in the same work offset without a stop to turn the part. --- src/parametric/src/cam/post.ts | 17 ++++- src/parametric/tests/cam-post-sim.test.ts | 89 +++++++++++++++++++++++ 2 files changed, 103 insertions(+), 3 deletions(-) create mode 100644 src/parametric/tests/cam-post-sim.test.ts diff --git a/src/parametric/src/cam/post.ts b/src/parametric/src/cam/post.ts index de54559c4..24d61cdb7 100644 --- a/src/parametric/src/cam/post.ts +++ b/src/parametric/src/cam/post.ts @@ -130,19 +130,30 @@ export function postProcess(job: PostJob): string { out(job.post.controller === 'fanuc' || job.post.controller === 'haas' ? `G4 X${sec.toFixed(2)}` : `G4 P${sec.toFixed(2)}`); }; + let offset: number | null = null; for (const setup of job.setups) { out(comment(setup.name)); + // A later setup: the tool is positioned again in its work offset, and the program stops for + // the part to be turned when the setup uses the same offset as the one before. + let newSetup = tool !== null; + const refixture = newSetup && setup.workOffset === offset; + offset = setup.workOffset; for (const op of setup.ops) { out(comment(op.name)); const t = op.tool; - if (tool !== t.number) { + if (tool !== t.number || newSetup) { + let stopped = false; if (tool !== null) { out('M9'); out('M5'); if (d.home) { out('G28 G91 Z0.'); out('G90'); } } - if (d.toolChange === 'm6') out(`T${t.number} M6`); - else { out(comment(`Change to T${t.number} ${t.name}`)); if (tool !== null) out('M0'); } + if (newSetup && refixture) { out(comment(`Set up the part for ${setup.name}`)); out('M0'); stopped = true; } + if (tool !== t.number) { + if (d.toolChange === 'm6') out(`T${t.number} M6`); + else { out(comment(`Change to T${t.number} ${t.name}`)); if (tool !== null && !stopped) out('M0'); } + } + newSetup = false; tool = t.number; lengthDone = false; x = y = z = f = NaN; diff --git a/src/parametric/tests/cam-post-sim.test.ts b/src/parametric/tests/cam-post-sim.test.ts new file mode 100644 index 000000000..429dce0d7 --- /dev/null +++ b/src/parametric/tests/cam-post-sim.test.ts @@ -0,0 +1,89 @@ +// Post processor, simulation and CAM data edge cases. +import { describe, expect, it } from 'vitest'; +import { simulate } from '../src/cam/simulate'; +import { postProcess, type PostJob } from '../src/cam/post'; +import { TriIndex } from '../src/cam/dropcutter'; +import { FEED, PLUNGE, RAPID, type Toolpath } from '../src/cam/toolpath'; +import { type CamTool, newCamDoc, normalizeCam } from '../src/model/cam'; + +const tool = (extra: Partial = {}): CamTool => ({ + id: 'tt', number: 1, name: 'tool', type: 'flat', diameter: 6, fluteLength: 30, flutes: 2, rpm: 10000, feed: 1000, plunge: 300, coolant: true, ...extra, +}); +const path = (m: number[], clearance = 20): Toolpath => ({ moves: Float64Array.from(m), cycles: [], clearance, warnings: [] }); +const job = (setups: PostJob['setups'], extra: Partial = {}, units: 'mm' | 'in' = 'mm'): PostJob => ({ + name: 'Part', units, post: { ...newCamDoc(() => 'x').post, ...extra }, setups, +}); +const emptyPart = new TriIndex(new Float64Array(0)); + +describe('post processor', () => { + it('positions the tool again in a new setup that keeps the tool', () => { + const t = tool(); + const tp = path([RAPID, 10, 10, 20, RAPID, 10, 10, 2, FEED, 10, 10, -1, RAPID, 10, 10, 20]); + const code = postProcess(job([ + { name: 'Setup1', workOffset: 54, ops: [{ name: 'A', tool: t, rpm: 1000, feed: 500, plunge: 100, toolpath: tp }] }, + { name: 'Setup2', workOffset: 55, ops: [{ name: 'B', tool: t, rpm: 1000, feed: 500, plunge: 100, toolpath: tp }] }, + ])); + const second = code.slice(code.indexOf('G55')); + expect(second).toMatch(/X10\. Y10\./); + expect(second).toMatch(/Z20\./); + expect(code).not.toContain('M0'); + // The same work offset: a stop to turn the part, then the tool comes back to it. + const same = postProcess(job([ + { name: 'Setup1', workOffset: 54, ops: [{ name: 'A', tool: t, rpm: 1000, feed: 500, plunge: 100, toolpath: tp }] }, + { name: 'Setup2', workOffset: 54, ops: [{ name: 'B', tool: t, rpm: 1000, feed: 500, plunge: 100, toolpath: tp }] }, + ])); + const after = same.slice(same.indexOf('(Setup2)')); + expect(after).toMatch(/^\(Setup2\)\n\(B\)\nM9\nM5\nG28 G91 Z0\.\nG90\n\(Set up the part for Setup2\)\nM0\nS1000 M3\nG54\nM8\nG0 X10\. Y10\.\nG43 Z20\. H1\n/); + const grbl = postProcess({ ...job([ + { name: 'Setup1', workOffset: 54, ops: [{ name: 'A', tool: t, rpm: 1000, feed: 500, plunge: 100, toolpath: tp }] }, + { name: 'Setup2', workOffset: 54, ops: [{ name: 'B', tool: tool({ number: 2 }), rpm: 1000, feed: 500, plunge: 100, toolpath: tp }] }, + ]), post: { ...newCamDoc(() => 'x').post, controller: 'grbl' } }); + // One stop for both the part and the tool. + expect(grbl.match(/^M0$/gm)).toHaveLength(1); + }); + + it('keeps line numbers within five digits', () => { + const m: number[] = [RAPID, 0, 0, 20]; + for (let i = 0; i < 12000; i++) m.push(FEED, i % 2 ? 10 : 0, i * 0.01, -1); + const code = postProcess(job([{ name: 'S', workOffset: 54, ops: [{ name: 'A', tool: tool(), rpm: 1000, feed: 500, plunge: 100, toolpath: path(m) }] }], { lineNumbers: true, arcs: false })); + const ns = [...code.matchAll(/^N(\d+) /gm)].map((x) => Number(x[1])); + expect(ns.length).toBeGreaterThan(12000); + expect(Math.max(...ns)).toBeLessThanOrEqual(99999); + }); +}); + +describe('simulation', () => { + const stock = { min: [0, 0, 0] as [number, number, number], max: [40, 40, 10] as [number, number, number] }; + + it('counts a rapid move through the stock once', () => { + const sim = simulate({ stock, part: emptyPart, rapidFeed: 5000, steps: [{ tool: tool(), feed: 1000, plunge: 300, toolpath: path([RAPID, -10, 20, 5, RAPID, 50, 20, 5]) }] }); + expect(sim.rapidCuts[0]).toBe(1); + }); + + it('does not count material removed below the bottom of the stock', () => { + const sim = simulate({ stock, part: emptyPart, rapidFeed: 5000, cell: 0.5, steps: [{ tool: tool(), feed: 1000, plunge: 300, toolpath: path([RAPID, 20, 20, 20, PLUNGE, 20, 20, -5]) }] }); + // A 6 mm hole through 10 mm of stock. + expect(sim.removed).toBeLessThan(Math.PI * 9 * 10 * 1.2); + expect(Math.min(...sim.snapshots[sim.snapshots.length - 1].z)).toBeGreaterThanOrEqual(0); + }); + + it('starts each step on the timeline where its tool starts', () => { + const a = path([RAPID, 0, 0, 20, RAPID, 0, 0, 12]); + const b = path([RAPID, 30, 30, 20, RAPID, 30, 30, 12]); + const sim = simulate({ stock, part: emptyPart, rapidFeed: 5000, steps: [{ tool: tool(), feed: 1000, plunge: 300, toolpath: a }, { tool: tool({ number: 2 }), feed: 1000, plunge: 300, toolpath: b }] }); + const tl = sim.timeline; + const firstOfB = [...Array(tl.length / 6).keys()].find((i) => tl[i * 6 + 4] === 1)!; + expect([tl[firstOfB * 6], tl[firstOfB * 6 + 1], tl[firstOfB * 6 + 2]]).toEqual([30, 30, 20]); + }); +}); + +describe('CAM data from files', () => { + it('drops feeds and speeds that are not numbers', () => { + const doc = newCamDoc((p) => `${p}9`); + const raw = JSON.parse(JSON.stringify({ ...doc, setups: [{ id: 's1', ops: [{ id: 'o1', name: 'F', type: 'face', tool: doc.tools[0].id, feed: 'fast', rpm: -5, pattern: 'x' }] }] })); + const n = normalizeCam(raw)!; + const o = n.setups[0].ops[0]; + expect(o.feed).toBeUndefined(); + expect(o.rpm).toBeUndefined(); + }); +}); From e0cb715994eaa94d0eef8f5b4da25fe74a18f45a Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:41:41 -0700 Subject: [PATCH 05/34] Parametric CAM: keep G-code line numbers within N99999 Long programs with line numbers went past N99999, which most controllers reject; the numbers now start again at N10. --- src/parametric/src/cam/post.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/cam/post.ts b/src/parametric/src/cam/post.ts index 24d61cdb7..1beaa2ad5 100644 --- a/src/parametric/src/cam/post.ts +++ b/src/parametric/src/cam/post.ts @@ -74,7 +74,8 @@ export function postProcess(job: PostJob): string { const lines: string[] = []; let n = 0; const out = (s: string) => { - if (job.post.lineNumbers && s && !s.startsWith('%') && !s.startsWith('O')) { n += 10; lines.push(`N${n} ${s}`); } + // Sequence numbers start again after N99999 (five digits on most controllers). + if (job.post.lineNumbers && s && !s.startsWith('%') && !s.startsWith('O')) { n = n >= 99990 ? 10 : n + 10; lines.push(`N${n} ${s}`); } else lines.push(s); }; if (d.percent) lines.push('%'); From fc9ac07253a0e8ea66c176edd372c5393651f586 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:42:34 -0700 Subject: [PATCH 06/34] Parametric CAM: count rapid cuts and shank hits per move in the simulation They were counted per sample of a move (every half cell), so one rapid move through the stock was reported as hundreds of moves. --- src/parametric/src/cam/simulate.ts | 22 +++++++++++++++------- src/parametric/tests/cam-post-sim.test.ts | 4 ++++ 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/parametric/src/cam/simulate.ts b/src/parametric/src/cam/simulate.ts index 0883fa3a7..bd15013e9 100644 --- a/src/parametric/src/cam/simulate.ts +++ b/src/parametric/src/cam/simulate.ts @@ -126,10 +126,12 @@ export function simulate(input: SimInput): SimResult { const flute = Math.max(s.tool.fluteLength, 0.1); let rapid = 0, shank = 0; let px = NaN, py = NaN, pz = NaN; - const stampAt = (x: number, y: number, tz: number, kind: number): boolean => { + // Whether the move being stamped cut stock, and met stock above the flutes. + let cut = false, hit = false; + const stampAt = (x: number, y: number, tz: number) => { const i0 = Math.max(0, Math.ceil((x - R - g.x0) / g.c)), i1 = Math.min(g.nx - 1, Math.floor((x + R - g.x0) / g.c)); const j0 = Math.max(0, Math.ceil((y - R - g.y0) / g.c)), j1 = Math.min(g.ny - 1, Math.floor((y + R - g.y0) / g.c)); - let cut = false, hit = false; + let c = false, over = false; for (let j = j0; j <= j1; j++) { const cy = g.y0 + j * g.c - y; for (let i = i0; i <= i1; i++) { @@ -139,18 +141,23 @@ export function simulate(input: SimInput): SimResult { const k = j * g.nx + i; const zc = tz + cutter.h(Math.sqrt(dd)); if (zc < z[k] - 1e-4) { - if (z[k] > tz + flute + 0.01) hit = true; + if (z[k] > tz + flute + 0.01) over = true; z[k] = zc; - cut = true; + c = true; } } } + if (c) cut = true; + if (over) hit = true; + }; + // Problems are counted per move, however many samples of it cut. + const count = (kind: number) => { if (cut && kind === RAPID) rapid++; if (hit && kind !== RAPID) shank++; - return cut; }; const move = (kind: number, x: number, y: number, zz: number, dwell: number) => { - if (Number.isNaN(px)) { px = x; py = y; pz = zz; stampAt(x, y, zz, kind); return; } + cut = hit = false; + if (Number.isNaN(px)) { px = x; py = y; pz = zz; stampAt(x, y, zz); count(kind); return; } const lxy = Math.hypot(x - px, y - py); const l = Math.hypot(lxy, zz - pz); const dt = (l / Math.max(1e-6, kind === RAPID ? input.rapidFeed : kind === PLUNGE ? s.plunge : s.feed)) * 60 + dwell; @@ -159,8 +166,9 @@ export function simulate(input: SimInput): SimResult { const n = Math.max(1, Math.ceil(lxy / (g.c * 0.5))); for (let k = 1; k <= n; k++) { const t = k / n; - stampAt(px + (x - px) * t, py + (y - py) * t, pz + (zz - pz) * t, kind); + stampAt(px + (x - px) * t, py + (y - py) * t, pz + (zz - pz) * t); } + count(kind); } now += dt; timeline.push(x, y, zz, now, si, kind); diff --git a/src/parametric/tests/cam-post-sim.test.ts b/src/parametric/tests/cam-post-sim.test.ts index 429dce0d7..e21af9883 100644 --- a/src/parametric/tests/cam-post-sim.test.ts +++ b/src/parametric/tests/cam-post-sim.test.ts @@ -58,6 +58,10 @@ describe('simulation', () => { it('counts a rapid move through the stock once', () => { const sim = simulate({ stock, part: emptyPart, rapidFeed: 5000, steps: [{ tool: tool(), feed: 1000, plunge: 300, toolpath: path([RAPID, -10, 20, 5, RAPID, 50, 20, 5]) }] }); expect(sim.rapidCuts[0]).toBe(1); + // A slot 8 mm deep with 3 mm flutes: one feed move, one warning. + const deep = simulate({ stock, part: emptyPart, rapidFeed: 5000, steps: [{ tool: tool({ fluteLength: 3 }), feed: 1000, plunge: 300, toolpath: path([RAPID, -10, 20, 20, RAPID, -10, 20, 2, FEED, 50, 20, 2]) }] }); + expect(deep.shankHits[0]).toBe(1); + expect(deep.rapidCuts[0]).toBe(0); }); it('does not count material removed below the bottom of the stock', () => { From 4ddb2ed284a6f9485acf62e3a08d2e77d8d338a2 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:42:53 -0700 Subject: [PATCH 07/34] Parametric CAM: stop simulated cuts at the bottom of the stock Cuts through the stock (contour breakthrough, drilling) lowered the height map below the stock, which counted air as removed material and drew the stock surface below its own bottom. --- src/parametric/src/cam/simulate.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/cam/simulate.ts b/src/parametric/src/cam/simulate.ts index bd15013e9..43cc8d5cb 100644 --- a/src/parametric/src/cam/simulate.ts +++ b/src/parametric/src/cam/simulate.ts @@ -139,7 +139,8 @@ export function simulate(input: SimInput): SimResult { const dd = cx * cx + cy * cy; if (dd > R * R) continue; const k = j * g.nx + i; - const zc = tz + cutter.h(Math.sqrt(dd)); + // Nothing is left below the bottom of the stock (cuts through it stop there). + const zc = Math.max(bottom, tz + cutter.h(Math.sqrt(dd))); if (zc < z[k] - 1e-4) { if (z[k] > tz + flute + 0.01) over = true; z[k] = zc; From 02b882baa1a96df63a49bd095c311663c495c5c3 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:43:06 -0700 Subject: [PATCH 08/34] Parametric CAM: start each simulated step on the timeline where its tool starts The first move of every operation was left off the playback timeline, so the tool was drawn sliding from the previous operation's last point (through the stock) to the second move. --- src/parametric/src/cam/simulate.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/cam/simulate.ts b/src/parametric/src/cam/simulate.ts index 43cc8d5cb..2588fb888 100644 --- a/src/parametric/src/cam/simulate.ts +++ b/src/parametric/src/cam/simulate.ts @@ -158,7 +158,12 @@ export function simulate(input: SimInput): SimResult { }; const move = (kind: number, x: number, y: number, zz: number, dwell: number) => { cut = hit = false; - if (Number.isNaN(px)) { px = x; py = y; pz = zz; stampAt(x, y, zz); count(kind); return; } + if (Number.isNaN(px)) { + // Where the step's tool starts (playback moves it from there, not from the last tool's end). + px = x; py = y; pz = zz; stampAt(x, y, zz); count(kind); + timeline.push(x, y, zz, now, si, kind); + return; + } const lxy = Math.hypot(x - px, y - py); const l = Math.hypot(lxy, zz - pz); const dt = (l / Math.max(1e-6, kind === RAPID ? input.rapidFeed : kind === PLUNGE ? s.plunge : s.feed)) * 60 + dwell; From f0e42911fda5bac9aece0c36670a5fb2bd281ced Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:43:55 -0700 Subject: [PATCH 09/34] Parametric CAM: repair damaged operation and tool settings read from a file Only numeric settings were checked: overriding feeds that were not numbers reached the G-code as FNaN, a zero stepover or stepdown could keep the toolpath engine going forever, unknown choices (pattern, cycle, direction...) and missing tabs went through as they were, and tool numbers and shape values were not checked. --- src/parametric/src/model/cam.ts | 37 ++++++++++++++++++++--- src/parametric/tests/cam-post-sim.test.ts | 23 ++++++++++++++ 2 files changed, 56 insertions(+), 4 deletions(-) diff --git a/src/parametric/src/model/cam.ts b/src/parametric/src/model/cam.ts index a71cf2d97..7382fa34e 100644 --- a/src/parametric/src/model/cam.ts +++ b/src/parametric/src/model/cam.ts @@ -334,9 +334,15 @@ function validOp(o: unknown): o is CamOperation { export function normalizeCam(raw: unknown): CamDoc | null { if (!isObj(raw)) return null; const base = newCamDoc(() => ''); - const tools = (Array.isArray(raw.tools) ? raw.tools : []).filter(validTool).map((t) => ({ - ...t, fluteLength: finite(t.fluteLength, 0) ? t.fluteLength : t.diameter * 3, flutes: finite(t.flutes, 1, 20) ? Math.round(t.flutes) : 2, coolant: t.coolant !== false, - })); + const tools = (Array.isArray(raw.tools) ? raw.tools : []).filter(validTool).map((t) => { + const tool: CamTool = { + ...t, number: Math.round(t.number), fluteLength: finite(t.fluteLength, 0) ? t.fluteLength : t.diameter * 3, flutes: finite(t.flutes, 1, 20) ? Math.round(t.flutes) : 2, coolant: t.coolant !== false, + }; + // Optional shape values that are not numbers are left to the defaults. + if ('cornerRadius' in tool && !finite(tool.cornerRadius, 0)) delete tool.cornerRadius; + if ('tipAngle' in tool && !finite(tool.tipAngle, 1, 179)) delete tool.tipAngle; + return tool; + }); const ids = new Set(); const uniqueTools = tools.filter((t) => !ids.has(t.id) && ids.add(t.id)); const setups: CamSetup[] = []; @@ -390,10 +396,33 @@ export function opDefaults(type: CamOpType, d: number): Record } } +/** The values an operation's text settings may take. */ +const OP_CHOICES: Record = { + direction: ['climb', 'conventional'], + pattern: ['offset', 'zigzag'], + entry: ['helix', 'ramp', 'plunge'], + cycle: ['drill', 'peck', 'chipBreak'], + boundary: ['stock', 'silhouette'], +}; +/** Settings that must be above zero (a zero step never finishes). */ +const OP_POSITIVE = new Set(['stepover', 'stepdown', 'pitch', 'tolerance']); + function withOpDefaults(o: CamOperation): CamOperation { const defs = opDefaults(o.type, 6); const out = { ...defs, ...o } as Record; - for (const [k, v] of Object.entries(defs)) if (typeof v === 'number' && !finite(out[k])) out[k] = v; + for (const [k, v] of Object.entries(defs)) { + const cur = out[k]; + if (typeof v === 'number') { if (!finite(cur, OP_POSITIVE.has(k) ? 1e-3 : -Infinity)) out[k] = v; } + else if (typeof v === 'string') { if (!oneOf(cur, OP_CHOICES[k] ?? [v])) out[k] = v; } + else if (typeof v === 'boolean') { if (typeof cur !== 'boolean') out[k] = v; } + else if (k === 'tabs') { + const t = isObj(cur) ? cur : {}, dt = v as ContourOp['tabs']; + out.tabs = { count: finite(t.count, 0, 64) ? Math.round(t.count) : 0, width: finite(t.width, 0) ? t.width : dt.width, height: finite(t.height, 0) ? t.height : dt.height }; + } + } + // Feeds and speeds overriding the tool's: numbers above zero, else the tool's. + for (const k of ['rpm', 'feed', 'plunge']) if (k in out && !finite(out[k], 1e-3)) delete out[k]; + if ('suppressed' in out && typeof out.suppressed !== 'boolean') out.suppressed = !!out.suppressed; return out as unknown as CamOperation; } diff --git a/src/parametric/tests/cam-post-sim.test.ts b/src/parametric/tests/cam-post-sim.test.ts index e21af9883..dbd874579 100644 --- a/src/parametric/tests/cam-post-sim.test.ts +++ b/src/parametric/tests/cam-post-sim.test.ts @@ -90,4 +90,27 @@ describe('CAM data from files', () => { expect(o.feed).toBeUndefined(); expect(o.rpm).toBeUndefined(); }); + + it('repairs settings of the wrong kind with the defaults', () => { + const doc = newCamDoc((p) => `${p}9`); + const t = doc.tools[0]; + const raw = JSON.parse(JSON.stringify({ ...doc, tools: [{ ...t, number: 2.6, cornerRadius: 'big', tipAngle: 0 }], setups: [{ id: 's1', ops: [ + { id: 'o1', name: 'C', type: 'contour', tool: t.id, tabs: null, direction: 'sideways', stepdown: 0 }, + { id: 'o2', name: 'P', type: 'pocket', tool: t.id, faces: [], pattern: 'spiral', entry: 7, stepover: -1, suppressed: 1 }, + { id: 'o3', name: 'D', type: 'drill', tool: t.id, holes: [], cycle: 'bore', tipThrough: 'yes' }, + ] }] })); + const n = normalizeCam(raw)!; + expect(n.tools[0].number).toBe(3); + expect(n.tools[0]).not.toHaveProperty('cornerRadius'); + expect(n.tools[0]).not.toHaveProperty('tipAngle'); + const [c, p, d] = n.setups[0].ops as unknown as Record[]; + expect(c.tabs).toEqual({ count: 0, width: 6, height: 1.5 }); + expect(c.direction).toBe('climb'); + expect(c.stepdown).toBeGreaterThan(0); + expect([p.pattern, p.entry, p.suppressed]).toEqual(['offset', 'helix', true]); + expect(p.stepover).toBeGreaterThan(0); + expect([d.cycle, d.tipThrough]).toEqual(['peck', true]); + // Good data is kept as it is. + expect(normalizeCam(JSON.parse(JSON.stringify(n)))).toEqual(n); + }); }); From bd0c4f5e35abf09876fd04210dddbceb787296fd Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:44:56 -0700 Subject: [PATCH 10/34] Parametric CAM: write arcs too short to show as lines, not full circles An arc fitted over a few points on a small radius could end, once rounded to the output's precision, where it started; controllers run such a G2/G3 as a full circle. --- src/parametric/src/cam/post.ts | 2 ++ src/parametric/tests/cam-post-sim.test.ts | 11 +++++++++++ 2 files changed, 13 insertions(+) diff --git a/src/parametric/src/cam/post.ts b/src/parametric/src/cam/post.ts index 1beaa2ad5..00009f618 100644 --- a/src/parametric/src/cam/post.ts +++ b/src/parametric/src/cam/post.ts @@ -117,6 +117,8 @@ export function postProcess(job: PostJob): string { x = nx; y = ny; z = nz; f = feed; }; const arc = (cw: boolean, nx: number, ny: number, nz: number, cx: number, cy: number, feed: number) => { + // An arc ending where it starts (as written) is a full circle to the controller. + if (num(nx) === num(x) && num(ny) === num(y)) { linear(nx, ny, nz, feed); return; } const g = cw ? 'G2' : 'G3'; let w = ` X${num(nx)} Y${num(ny)}`; if (num(nz) !== num(z)) w += ` Z${num(nz)}`; diff --git a/src/parametric/tests/cam-post-sim.test.ts b/src/parametric/tests/cam-post-sim.test.ts index dbd874579..0125eebab 100644 --- a/src/parametric/tests/cam-post-sim.test.ts +++ b/src/parametric/tests/cam-post-sim.test.ts @@ -42,6 +42,17 @@ describe('post processor', () => { expect(grbl.match(/^M0$/gm)).toHaveLength(1); }); + it('never writes an arc that ends where it starts (a full circle)', () => { + // A tiny arc on a 0.1 mm radius, shorter than the output resolution. + const m = [RAPID, 5.1, 5, 20, FEED, 5.1, 5, -1]; + for (let i = 1; i <= 4; i++) m.push(FEED, 5 + 0.1 * Math.cos(i * 1e-3), 5 + 0.1 * Math.sin(i * 1e-3), -1); + m.push(FEED, 0, 0, -1); + for (const units of ['mm', 'in'] as const) { + const code = postProcess(job([{ name: 'S', workOffset: 54, ops: [{ name: 'A', tool: tool(), rpm: 1000, feed: 500, plunge: 100, toolpath: path(m) }] }], {}, units)); + expect(code).not.toMatch(/G[23] /); + } + }); + it('keeps line numbers within five digits', () => { const m: number[] = [RAPID, 0, 0, 20]; for (let i = 0; i < 12000; i++) m.push(FEED, i % 2 ? 10 : 0, i * 0.01, -1); From 776cec735a2f70eb91b875839006b64897d73bdc Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:45:33 -0700 Subject: [PATCH 11/34] Parametric CAM: write Haas dwells as G4 P in milliseconds Haas mills take the G04 dwell in P (milliseconds without a decimal point); the post wrote the Fanuc G4 X form for them. --- src/parametric/src/cam/post.ts | 5 ++++- src/parametric/tests/cam-post-sim.test.ts | 13 +++++++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/parametric/src/cam/post.ts b/src/parametric/src/cam/post.ts index 00009f618..51d5b598b 100644 --- a/src/parametric/src/cam/post.ts +++ b/src/parametric/src/cam/post.ts @@ -130,7 +130,10 @@ export function postProcess(job: PostJob): string { }; const dwell = (sec: number) => { if (sec <= 0) return; - out(job.post.controller === 'fanuc' || job.post.controller === 'haas' ? `G4 X${sec.toFixed(2)}` : `G4 P${sec.toFixed(2)}`); + // Fanuc: X in seconds; Haas: P without a decimal point in milliseconds (its mills have no X + // dwell word); the others: P in seconds. + const c = job.post.controller; + out(c === 'fanuc' ? `G4 X${sec.toFixed(2)}` : c === 'haas' ? `G4 P${Math.round(sec * 1000)}` : `G4 P${sec.toFixed(2)}`); }; let offset: number | null = null; diff --git a/src/parametric/tests/cam-post-sim.test.ts b/src/parametric/tests/cam-post-sim.test.ts index 0125eebab..5cce9a6fa 100644 --- a/src/parametric/tests/cam-post-sim.test.ts +++ b/src/parametric/tests/cam-post-sim.test.ts @@ -3,8 +3,8 @@ import { describe, expect, it } from 'vitest'; import { simulate } from '../src/cam/simulate'; import { postProcess, type PostJob } from '../src/cam/post'; import { TriIndex } from '../src/cam/dropcutter'; -import { FEED, PLUNGE, RAPID, type Toolpath } from '../src/cam/toolpath'; -import { type CamTool, newCamDoc, normalizeCam } from '../src/model/cam'; +import { CYCLE, FEED, PLUNGE, RAPID, type Toolpath } from '../src/cam/toolpath'; +import { type CamController, type CamTool, newCamDoc, normalizeCam } from '../src/model/cam'; const tool = (extra: Partial = {}): CamTool => ({ id: 'tt', number: 1, name: 'tool', type: 'flat', diameter: 6, fluteLength: 30, flutes: 2, rpm: 10000, feed: 1000, plunge: 300, coolant: true, ...extra, @@ -53,6 +53,15 @@ describe('post processor', () => { } }); + it('writes dwells in the units of each controller', () => { + const tp: Toolpath = { moves: Float64Array.from([RAPID, 5, 5, 20, RAPID, 5, 5, 2, CYCLE, 5, 5, 0]), cycles: [{ cycle: 'peck', r: 2, z: -6, peck: 2, dwell: 0.5 }], clearance: 20, warnings: [] }; + const dwell = (controller: CamController) => postProcess(job([{ name: 'S', workOffset: 54, ops: [{ name: 'D', tool: tool(), rpm: 1000, feed: 500, plunge: 100, toolpath: tp }] }], { controller })).match(/G4 .*/)?.[0]; + expect(dwell('fanuc')).toBe('G4 X0.50'); + expect(dwell('haas')).toBe('G4 P500'); + expect(dwell('linuxcnc')).toBe('G4 P0.50'); + expect(dwell('grbl')).toBe('G4 P0.50'); + }); + it('keeps line numbers within five digits', () => { const m: number[] = [RAPID, 0, 0, 20]; for (let i = 0; i < 12000; i++) m.push(FEED, i % 2 ? 10 : 0, i * 0.01, -1); From 4b48fb19ac078a44e7322b55e749da58fd48cb89 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:48:06 -0700 Subject: [PATCH 12/34] Parametric CAM: apply the tool length offset after an operation with no moves An operation that generated no moves (a drill finding no holes) marked the tool's G43 as done, so the next operation with that tool moved without tool length compensation. Such operations are now left out of the G-code. --- src/parametric/src/cam/post.ts | 5 ++++- src/parametric/tests/cam-post-sim.test.ts | 12 ++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/cam/post.ts b/src/parametric/src/cam/post.ts index 51d5b598b..2c188d192 100644 --- a/src/parametric/src/cam/post.ts +++ b/src/parametric/src/cam/post.ts @@ -145,6 +145,9 @@ export function postProcess(job: PostJob): string { const refixture = newSetup && setup.workOffset === offset; offset = setup.workOffset; for (const op of setup.ops) { + // Nothing to cut (no holes found...): no tool change, and the next operation still gets the + // tool length offset. + if (op.toolpath.moves.length < 4) continue; out(comment(op.name)); const t = op.tool; if (tool !== t.number || newSetup) { @@ -181,8 +184,8 @@ export function postProcess(job: PostJob): string { out(`G43 Z${num(clear)} H${t.number}`); x = fx; y = fy; z = clear; motion = 'G0'; } else rapid(fx, fy, clear); + lengthDone = true; } - lengthDone = true; } // Moves, with arcs fitted over runs of feeds. const feedOf = (kind: number) => (kind === PLUNGE ? op.plunge : op.feed); diff --git a/src/parametric/tests/cam-post-sim.test.ts b/src/parametric/tests/cam-post-sim.test.ts index 5cce9a6fa..6e6d4ff67 100644 --- a/src/parametric/tests/cam-post-sim.test.ts +++ b/src/parametric/tests/cam-post-sim.test.ts @@ -42,6 +42,18 @@ describe('post processor', () => { expect(grbl.match(/^M0$/gm)).toHaveLength(1); }); + it('applies the tool length offset after an operation without moves', () => { + const t = tool(); + const empty = path([]); + const tp = path([RAPID, 10, 10, 20, RAPID, 10, 10, 2, FEED, 10, 10, -1, RAPID, 10, 10, 20]); + const code = postProcess(job([{ name: 'S', workOffset: 54, ops: [ + { name: 'A', tool: t, rpm: 1000, feed: 500, plunge: 100, toolpath: empty }, + { name: 'B', tool: t, rpm: 1000, feed: 500, plunge: 100, toolpath: tp }, + ] }])); + expect(code).toMatch(/\(B\)\nT1 M6\nS1000 M3\nG54\nM8\nG0 X10\. Y10\.\nG43 Z20\. H1\n/); + expect(code).not.toContain('(A)'); + }); + it('never writes an arc that ends where it starts (a full circle)', () => { // A tiny arc on a 0.1 mm radius, shorter than the output resolution. const m = [RAPID, 5.1, 5, 20, FEED, 5.1, 5, -1]; From ccb06d0e8d45fa06ef8833b49fd8f89976e731eb Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:51:20 -0700 Subject: [PATCH 13/34] Parametric CAM: tell internal engine failures from messages for the user The client dropped the worker's flag for errors written for the user, so a crash inside the engine ("Cannot read properties of undefined...") showed as the operation's error as if it were advice. Errors now carry the flag and internal ones say the CAM engine ran into a problem. --- src/parametric/src/cam/client.ts | 9 ++++- src/parametric/tests/cam-client.test.ts | 47 +++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 src/parametric/tests/cam-client.test.ts diff --git a/src/parametric/src/cam/client.ts b/src/parametric/src/cam/client.ts index 4d60691ca..34e82e5ed 100644 --- a/src/parametric/src/cam/client.ts +++ b/src/parametric/src/cam/client.ts @@ -20,6 +20,13 @@ export class CamCancelled extends Error { constructor() { super('Cancelled'); } } +/** An error from the worker; `user`: its message is written for the user (else an internal failure). */ +export class CamEngineError extends Error { + constructor(message: string, readonly user: boolean) { + super(user ? message : `The CAM engine ran into a problem (${message})`); + } +} + export class CamClient { private worker: Worker | null = null; private nextId = 1; @@ -48,7 +55,7 @@ export class CamClient { if (r.type === 'progress') { p.progress?.(r.value); return; } this.pending.delete(r.id); if (r.type === 'done') p.resolve(r.result); - else p.reject(new Error(r.error)); + else p.reject(new CamEngineError(r.error, r.user)); }; w.onerror = (ev) => { ev.preventDefault?.(); diff --git a/src/parametric/tests/cam-client.test.ts b/src/parametric/tests/cam-client.test.ts new file mode 100644 index 000000000..574be245d --- /dev/null +++ b/src/parametric/tests/cam-client.test.ts @@ -0,0 +1,47 @@ +// The CAM worker client with a stand-in worker: errors and shutting down. +import { describe, expect, it } from 'vitest'; +import { CamCancelled, CamClient, CamEngineError } from '../src/cam/client'; +import type { CamWorkerRequest, CamWorkerResponse } from '../src/cam/worker'; +import type { GenerateJob } from '../src/cam/engine'; + +/** A worker that answers each request with `reply` (or never, when it returns null). */ +function fakeWorker(reply: (msg: CamWorkerRequest) => CamWorkerResponse | null) { + const w = { + onmessage: null as ((ev: { data: CamWorkerResponse }) => void) | null, + onerror: null as ((ev: unknown) => void) | null, + terminated: false, + postMessage(msg: CamWorkerRequest) { + const r = reply(msg); + if (r) queueMicrotask(() => { if (!w.terminated) w.onmessage?.({ data: r }); }); + }, + terminate() { w.terminated = true; }, + }; + return w; +} + +const job = {} as GenerateJob; + +describe('CAM client', () => { + it('passes on messages written for the user and marks internal errors', async () => { + const answer = { error: '', user: true }; + const client = new CamClient(() => fakeWorker((m) => ({ id: m.id, type: 'error', ...answer })) as unknown as Worker); + answer.error = 'Pick the floor faces of the pockets.'; + await expect(client.generate(job)).rejects.toThrow(/^Pick the floor faces of the pockets\.$/); + Object.assign(answer, { error: "Cannot read properties of undefined (reading 'x')", user: false }); + const e = (await client.generate(job).catch((x: Error) => x)) as Error; + expect(e.message).toMatch(/^The CAM engine ran into a problem/); + expect(e.message).toContain("reading 'x'"); + expect(e).toBeInstanceOf(CamEngineError); + expect((e as CamEngineError).user).toBe(false); + }); + + it('rejects requests still waiting when it is disposed', async () => { + const worker = fakeWorker(() => null); + const client = new CamClient(() => worker as unknown as Worker); + const p = client.generate(job); + client.dispose(); + await expect(p).rejects.toBeInstanceOf(CamCancelled); + expect(worker.terminated).toBe(true); + expect(client.busy).toBe(false); + }); +}); From 79046d35c9baa76cb922c4464836b1a27b9b7cdd Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:51:27 -0700 Subject: [PATCH 14/34] Parametric CAM: reject waiting requests when the CAM client is disposed dispose() cleared its requests without settling them, leaving their callers waiting forever; they now reject with CamCancelled. --- src/parametric/src/cam/client.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/parametric/src/cam/client.ts b/src/parametric/src/cam/client.ts index 34e82e5ed..3dea4f503 100644 --- a/src/parametric/src/cam/client.ts +++ b/src/parametric/src/cam/client.ts @@ -109,9 +109,8 @@ export class CamClient { return this.pending.size > 0; } + /** Stops the worker; requests still waiting reject with CamCancelled. */ dispose() { - this.worker?.terminate(); - this.worker = null; - this.pending.clear(); + this.fail(new CamCancelled()); } } From 3992fb27d64e4e75e21800ff1c14a1a8dc371aa9 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:47:09 -0700 Subject: [PATCH 15/34] Parametric CAM: keep clearing stepovers within what the tool can cut A stepover wider than the tool left strips of stock standing between face, pocket and rough passes (offset passes leave posts in their corners from about 0.85 of the diameter), with no warning. Zero or a negative stepover never finished zigzag clearing and overflowed the stack in offset clearing. --- src/parametric/src/cam/ops.ts | 23 +++++++++++++++---- src/parametric/tests/cam-engine.test.ts | 30 +++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 4 deletions(-) diff --git a/src/parametric/src/cam/ops.ts b/src/parametric/src/cam/ops.ts index 242efa845..dc6cb1267 100644 --- a/src/parametric/src/cam/ops.ts +++ b/src/parametric/src/cam/ops.ts @@ -151,6 +151,20 @@ class Gen { private get partTop() { return this.part.frame.part.max[2]; } private get partBottom() { return this.part.frame.part.min[2]; } + /** + * A clearing stepover the tool can take. Wider than the tool, straight + * passes leave strips uncut between them, and offset passes leave posts in + * their corners from about 0.85 of it. Zero or less would never finish. + */ + private clearStep(v: number, pattern: 'offset' | 'zigzag'): number { + const max = Math.round(this.tool.diameter * (pattern === 'offset' ? 0.8 : 1) * 1000) / 1000; + if (v > max) { + this.b.warnings.push(`The stepover is too wide for the tool; ${max} mm is used.`); + return max; + } + return v >= 0.01 ? v : 0.01; + } + private tick() { this.done++; if (this.input.cancelled?.()) throw new Cancelled('cancelled'); @@ -375,7 +389,7 @@ class Gen { } left.delete(next); const rs = comps.get(next)!; - const maxLevel = Math.max(...rs.map((r) => r.level)); + const maxLevel = rs.reduce((m, r) => Math.max(m, r.level), 0); let first = true; for (let lv = maxLevel; lv >= 0; lv--) { const pending = rs.filter((r) => r.level === lv); @@ -521,7 +535,7 @@ class Gen { const u0 = Math.min(...us) - R - 2, u1 = Math.max(...us) + R + 2; const v0 = Math.min(...vs), v1 = Math.max(...vs); const lo = v0 + 0.4 * R, hi = v1 - 0.4 * R; - const n = hi > lo ? Math.ceil((hi - lo) / Math.max(op.stepover, 0.01)) + 1 : 1; + const n = hi > lo ? Math.ceil((hi - lo) / this.clearStep(op.stepover, 'zigzag')) + 1 : 1; const vAt = (i: number) => (n === 1 ? (v0 + v1) / 2 : lo + ((hi - lo) * i) / (n - 1)); const xy = (u: number, v: number): [number, number] => [u * ca - v * sa, u * sa + v * ca]; this.steps = levels.length; @@ -681,6 +695,7 @@ class Gen { groups.set(key, [...(groups.get(key) ?? []), t]); } const order = [...groups.keys()].sort((a, c) => c - a); + const stepover = this.clearStep(op.stepover, op.pattern); this.steps = order.reduce((s, z) => s + stepLevels(this.stockTop, z + op.floorLeave, op.stepdown).length + 1, 0); for (const zf of order) { const tris = groups.get(zf)!; @@ -700,7 +715,7 @@ class Gen { r.limit = dist.map((d) => reach - d); r.limitAt = (x, y) => reach - sample(g, dist, x, y); const levels = stepLevels(this.stockTop, zf + op.floorLeave, op.stepdown); - this.clear(r, levels, { stepover: op.stepover, pattern: op.pattern, climb: op.direction !== 'conventional', entry: op.entry, rampAngle: op.rampAngle, tol: 0.005, materialTop: this.stockTop }); + this.clear(r, levels, { stepover, pattern: op.pattern, climb: op.direction !== 'conventional', entry: op.entry, rampAngle: op.rampAngle, tol: 0.005, materialTop: this.stockTop }); } } @@ -721,7 +736,7 @@ class Gen { r.limit = new Float64Array(g.nx * g.ny); for (let j = 0; j < g.ny; j++) for (let i = 0; i < g.nx; i++) r.limit[j * g.nx + i] = lim(g.x0 + i * g.c, g.y0 + j * g.c); r.limitAt = lim; - this.clear(r, levels, { stepover: op.stepover, pattern: op.pattern, climb: op.direction !== 'conventional', entry: op.entry, rampAngle: op.rampAngle, tol: 0.01, materialTop: this.stockTop }); + this.clear(r, levels, { stepover: this.clearStep(op.stepover, op.pattern), pattern: op.pattern, climb: op.direction !== 'conventional', entry: op.entry, rampAngle: op.rampAngle, tol: 0.01, materialTop: this.stockTop }); } /** Holes that open toward the tool, from the cylinders. */ diff --git a/src/parametric/tests/cam-engine.test.ts b/src/parametric/tests/cam-engine.test.ts index dfe69b613..b5e3ad2f5 100644 --- a/src/parametric/tests/cam-engine.test.ts +++ b/src/parametric/tests/cam-engine.test.ts @@ -221,6 +221,36 @@ describe('operations', () => { } }, 60_000); + it('keeps clearing stepovers to what the tool can cut', () => { + const t = tool('flat', 6); + const s = setup(); + const part = placePart(s, pocketPlate)!; + const leftOver = (tp: Toolpath, x0: number, y0: number, x1: number, y1: number) => { + const sim = simulate({ stock: part.frame.stock, part: part.index, steps: [{ toolpath: tp, tool: t, feed: 1000, plunge: 300 }], rapidFeed: 5000, cell: 0.25 }); + expect(sim.gouges).toBe(0); + const g = sim.grid; + const last = sim.snapshots[sim.snapshots.length - 1].z; + let top = -Infinity; + for (let j = 0; j < g.ny; j++) for (let i = 0; i < g.nx; i++) { + const x = g.x0 + i * g.c, y = g.y0 + j * g.c; + if (x > x0 && x < x1 && y > y0 && y < y1) top = Math.max(top, last[j * g.nx + i]); + } + return top; + }; + // Wider than the tool: passes 15 mm apart would leave strips of stock standing. + const face = generateFor(part, { setup: s, op: op('face', t, { stepover: 15, stepdown: 2 }), tool: t }); + expect(face.warnings.some((w) => /stepover is too wide/.test(w))).toBe(true); + expect(leftOver(face, 2, 2, 28, 58)).toBeCloseTo(20, 6); + // Offset passes leave posts in their corners well before the tool's diameter. + const pocket = generateFor(part, { setup: s, op: op('pocket', t, { stepover: 5.9, stepdown: 5 }), tool: t, floors: [floorTris] }); + expect(leftOver(pocket, 31, 21, 69, 39)).toBeCloseTo(10, 6); + // None or less: finishes (zigzag passes never did). + for (const pattern of ['offset', 'zigzag'] as const) { + const rough = generateFor(placePart(s, mesh(box(0, 0, 0, 30, 20, 8)))!, { setup: s, op: op('rough', t, { stepover: 0, pattern }), tool: t }); + expect(rough.moves.length).toBeGreaterThan(0); + } + }, 60_000); + it('roughs round the part leaving the allowance, without gouging', () => { const t = tool('flat', 6); const s = setup(); From 49c6edb6991d9e3571da96e6f6358e4500c1a190 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:48:16 -0700 Subject: [PATCH 16/34] Parametric CAM: bore wide holes from the middle out instead of leaving a core A single helix at the wall of a hole wider than two tools left a core standing in it, and the move out through the middle then fed sideways into that core at full depth. Helices now run from the middle out, a tool radius apart. --- src/parametric/src/cam/ops.ts | 12 +++++++++-- src/parametric/tests/cam-engine.test.ts | 27 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/src/parametric/src/cam/ops.ts b/src/parametric/src/cam/ops.ts index dc6cb1267..4292e8bf6 100644 --- a/src/parametric/src/cam/ops.ts +++ b/src/parametric/src/cam/ops.ts @@ -802,8 +802,16 @@ class Gen { const z = h.through ? h.bottom - Math.max(0, op.breakthrough) : h.bottom; // Down from over the stock (it may not be cut over the hole yet). const zFrom = this.stockTop + 0.5; - b.rapidTo(h.x + rh, h.y, b.retract); - this.helix(h.x, h.y, rh, zFrom, z, Math.max(0.05, op.pitch), climb); + // A helix at the wall alone would leave a core standing in a hole wider than + // two tools: helices from the middle out, a tool radius apart, the wall's last. + const radii = [rh]; + const inner = this.R * 0.5, n = rh > this.R ? Math.ceil((rh - inner) / this.R) : 0; + for (let k = 1; k <= n; k++) radii.unshift(rh - ((rh - inner) * k) / n); + for (const [i, r] of radii.entries()) { + if (i === 0) b.rapidTo(h.x + r, h.y, b.retract); + else { b.rapid(b.x, b.y, zFrom); b.rapid(h.x + r, h.y, zFrom); } + this.helix(h.x, h.y, r, zFrom, z, Math.max(0.05, op.pitch), climb); + } // Away from the wall and out through the middle. b.feed(h.x, h.y, z); b.rapid(h.x, h.y, b.retract); diff --git a/src/parametric/tests/cam-engine.test.ts b/src/parametric/tests/cam-engine.test.ts index b5e3ad2f5..752367e14 100644 --- a/src/parametric/tests/cam-engine.test.ts +++ b/src/parametric/tests/cam-engine.test.ts @@ -312,6 +312,33 @@ describe('operations', () => { for (const m of helix) expect(Math.hypot(m.x - 20, m.y - 20)).toBeCloseTo(1, 6); void part; }); + + it('bores a blind hole wider than two tools without leaving a core in it', () => { + const em = tool('flat', 3); + const s = setup({ stock: { mode: 'offset', side: 5, top: 0, bottom: 0, size: [0, 0, 0] } }); + // A 12 mm hole 6 deep in a 40 x 40 x 10 plate (its wall a cylinder of triangles). + const wall: number[] = []; + for (let i = 0; i < 48; i++) { + const a = (i / 48) * Math.PI * 2, b = ((i + 1) / 48) * Math.PI * 2; + const p = (t: number, z: number) => [20 + 6 * Math.cos(t), 20 + 6 * Math.sin(t), z]; + wall.push(...p(a, 4), ...p(b, 4), ...p(b, 10), ...p(a, 4), ...p(b, 10), ...p(a, 10)); + } + const part = placePart(s, mesh(box(0, 0, 0, 40, 40, 4), box(0, 0, 4, 40, 14, 10), box(0, 26, 4, 40, 40, 10), box(0, 14, 4, 14, 26, 10), box(26, 14, 4, 40, 26, 10)))!; + const cyl = [{ name: 'F1', p: [20, 20, 0] as Vec3, d: [0, 0, 1] as Vec3, radius: 6, tris: Float32Array.from(wall) }]; + const tp = generateFor(part, { setup: s, op: op('bore', em, { pitch: 1 }), tool: em, cylinders: cyl, picked: ['F1'] }); + expect(tp.warnings.filter((w) => /cuts into/.test(w))).toEqual([]); + const sim = simulate({ stock: part.frame.stock, part: part.index, steps: [{ toolpath: tp, tool: em, feed: 1000, plunge: 300 }], rapidFeed: 5000, cell: 0.1 }); + expect(sim.gouges).toBe(0); + expect(sim.rapidCuts[0]).toBe(0); + // Down to the floor everywhere in the hole: a helix at the wall alone leaves a 6 mm core. + const g = sim.grid; + const last = sim.snapshots[sim.snapshots.length - 1].z; + let top = -Infinity; + for (let j = 0; j < g.ny; j++) for (let i = 0; i < g.nx; i++) { + if (Math.hypot(g.x0 + i * g.c - 20, g.y0 + j * g.c - 20) < 5.8) top = Math.max(top, last[j * g.nx + i]); + } + expect(top).toBeLessThan(4.05); + }); }); describe('simulation and G-code', () => { From f5e11a09fb3e09867bf010e940aed3759be450d8 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:50:00 -0700 Subject: [PATCH 17/34] Parametric CAM: stop through-hole drilling at the part below the hole The breakthrough and drill point were added below a through hole whatever was under it, so a drill could go on into another wall of the part, and the toolpath check skips drilling cycles so nothing warned. The point depth now also comes from the tool's own shape (a chamfer tool without an angle used 118 degrees). --- src/parametric/src/cam/ops.ts | 14 ++++++++++++-- src/parametric/tests/cam-engine.test.ts | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/parametric/src/cam/ops.ts b/src/parametric/src/cam/ops.ts index 4292e8bf6..17ae519ff 100644 --- a/src/parametric/src/cam/ops.ts +++ b/src/parametric/src/cam/ops.ts @@ -777,12 +777,22 @@ class Gen { b.warnings.push(anyPicked ? 'None of the picked faces is a hole that opens toward the tool.' : `No hole of the tool's diameter (${this.tool.diameter} mm) opens toward the tool. Pick the holes to drill.`); return; } - const tip = this.tool.type === 'drill' || this.tool.type === 'chamfer' ? this.R / Math.tan(((this.tool.tipAngle ?? 118) / 2) * Math.PI / 180) : 0; + const cutter = cutterOf(this.tool); + const tip = cutter.kind === 'cone' ? cutter.r * cutter.k : 0; this.steps = holes.length; for (const h of holes) { this.tick(); if (Math.abs(2 * h.r - this.tool.diameter) > Math.max(0.05, h.r * 0.02)) b.warnings.push(`A hole of ${(2 * h.r).toFixed(3)} mm is drilled with a ${this.tool.diameter} mm tool.`); - const z = h.through ? h.bottom - Math.max(0, op.breakthrough) - (op.tipThrough ? tip : 0) : h.bottom; + let z = h.through ? h.bottom - Math.max(0, op.breakthrough) - (op.tipThrough ? tip : 0) : h.bottom; + if (h.through) { + // Not on into the part below the hole (within the hole's width). + const tool = { ...this.tool, diameter: Math.min(this.tool.diameter, h.r * 1.9) }; + const below = new DropCutter(this.part.index, cutterOf(tool)).drop(h.x, h.y); + if (z < below) { + z = below; + b.warnings.push(`A hole of ${(2 * h.r).toFixed(3)} mm is drilled short of its breakthrough: the part is below it.`); + } + } // From the retract height over the stock: the stock over the hole may not be cut yet. b.cycle(h.x, h.y, { cycle: op.cycle, r: b.retract, z, peck: op.cycle === 'drill' ? 0 : Math.max(0.05, op.peck), dwell: Math.max(0, op.dwell) }); } diff --git a/src/parametric/tests/cam-engine.test.ts b/src/parametric/tests/cam-engine.test.ts index 752367e14..6487b179b 100644 --- a/src/parametric/tests/cam-engine.test.ts +++ b/src/parametric/tests/cam-engine.test.ts @@ -313,6 +313,24 @@ describe('operations', () => { void part; }); + it('drills a through hole no deeper than the part below it', () => { + const drill = tool('drill', 5, { tipAngle: 118 }); + const s = setup(); + const wall: number[] = []; + for (let i = 0; i < 16; i++) { + const a = (i / 16) * Math.PI * 2, b = ((i + 1) / 16) * Math.PI * 2; + const p = (t: number, z: number) => [20 + 2.5 * Math.cos(t), 20 + 2.5 * Math.sin(t), z]; + wall.push(...p(a, 0), ...p(b, 0), ...p(b, 10), ...p(a, 0), ...p(b, 10), ...p(a, 10)); + } + // A plate with the hole, and 2 mm under it a second plate (a channel's other wall). + const part = placePart(s, mesh(box(0, 0, 0, 40, 17.5, 10), box(0, 22.5, 0, 40, 40, 10), box(0, 17.5, 0, 17.5, 22.5, 10), box(22.5, 17.5, 0, 40, 22.5, 10), box(0, 0, -10, 40, 40, -2), box(0, 0, -2, 2, 40, 0)))!; + const cyl = [{ name: 'F1', p: [20, 20, 0] as Vec3, d: [0, 0, 1] as Vec3, radius: 2.5, tris: Float32Array.from(wall) }]; + const tp = generateFor(part, { setup: s, op: op('drill', drill, { breakthrough: 1 }), tool: drill, cylinders: cyl }); + // 1 mm and the drill's point (1.5 mm) through would reach 0.5 mm into the plate below. + expect(tp.cycles[0].z).toBeCloseTo(-2, 6); + expect(tp.warnings.some((w) => /short of its breakthrough/.test(w))).toBe(true); + }); + it('bores a blind hole wider than two tools without leaving a core in it', () => { const em = tool('flat', 3); const s = setup({ stock: { mode: 'offset', side: 5, top: 0, bottom: 0, size: [0, 0, 0] } }); From 7228a663c0f22f4287a04b3b03f91c18622aeb0e Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:50:43 -0700 Subject: [PATCH 18/34] Parametric CAM: step down by the clamped stepdown A stepdown of zero or a tiny one counted levels with the clamped value but placed them with the raw one: thousands of passes at the top, then the whole depth at once. A negative one put levels above the stock, and a damaged one gave no levels at all. --- src/parametric/src/cam/ops.ts | 6 ++++-- src/parametric/tests/cam-engine.test.ts | 8 ++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/parametric/src/cam/ops.ts b/src/parametric/src/cam/ops.ts index 17ae519ff..4b643710a 100644 --- a/src/parametric/src/cam/ops.ts +++ b/src/parametric/src/cam/ops.ts @@ -114,8 +114,10 @@ const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v export function stepLevels(top: number, bottom: number, step: number, extra: number[] = []): number[] { const out: number[] = []; if (!(top > bottom + 1e-9)) return [bottom]; - const n = Math.max(1, Math.ceil((top - bottom) / Math.max(step, 1e-3) - 1e-9)); - for (let i = 1; i <= n; i++) out.push(i === n ? bottom : top - i * step); + // At least 0.01 mm (as the interface allows): less, or none, would never get down. + const st = step >= 0.01 ? step : 0.01; + const n = Math.max(1, Math.ceil((top - bottom) / st - 1e-9)); + for (let i = 1; i <= n; i++) out.push(i === n ? bottom : top - i * st); for (const e of extra) if (e < top - 1e-6 && e > bottom + 1e-6 && out.every((z) => Math.abs(z - e) > 0.01)) out.push(e); return out.sort((a, c) => c - a); } diff --git a/src/parametric/tests/cam-engine.test.ts b/src/parametric/tests/cam-engine.test.ts index 6487b179b..906cf4229 100644 --- a/src/parametric/tests/cam-engine.test.ts +++ b/src/parametric/tests/cam-engine.test.ts @@ -142,6 +142,14 @@ describe('contours and levels', () => { it('steps down to the bottom with extra levels', () => { expect(stepLevels(10, 0, 3)).toEqual([7, 4, 1, 0]); expect(stepLevels(10, 0, 3, [5])).toEqual([7, 5, 4, 1, 0]); + // A stepdown of none, less or a damaged one still steps down (it stayed at the top + // for thousands of levels, or above it, and then went down all the way at once). + for (const step of [0, -1, NaN, 1e-6]) { + const l = stepLevels(10, 0, step); + expect(l).toHaveLength(1000); + expect(l[0]).toBeCloseTo(9.99, 9); + for (let i = 1; i < l.length; i++) expect(l[i - 1] - l[i]).toBeCloseTo(0.01, 6); + } }); }); From 6c3fadd423e4ce7f5f2cf6ca72e2dba09bb6400f Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:54:26 -0700 Subject: [PATCH 19/34] Parametric CAM: keep exact boundaries exact on a grid coarser than the tool On a large part the region grid is capped and its cells can be wider than a small tool. The chord between two refined crossings then cut across the part's corners: a 0.3 mm tool on a 300 mm plate contoured into all four corners, the full depth of the wall. Points along long chords where the tool may not be are now moved out onto the boundary. --- src/parametric/src/cam/ops.ts | 30 ++++++++++++++++++++++++- src/parametric/tests/cam-engine.test.ts | 19 ++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/cam/ops.ts b/src/parametric/src/cam/ops.ts index 4b643710a..ebd63a9a0 100644 --- a/src/parametric/src/cam/ops.ts +++ b/src/parametric/src/cam/ops.ts @@ -216,7 +216,35 @@ class Gen { } return lo; }); - return loops.filter((l) => polyLength(l.pts, 2, l.closed) > g.c * 1.5).map((l) => ({ pts: simplify(l.pts, tol, 2, l.closed), closed: l.closed })); + // On a grid coarse for the tool (a large part, a small tool) a chord between two + // crossings can cut across a corner of the part: points along it where the tool may + // not be are moved out onto the boundary, square to the chord (the inside is on the left). + const h = Math.max(r.dc.cutter.r * 0.5, 1e-3); + const fill = (pts: number[], closed: boolean) => { + const n = pts.length / 2, out: number[] = []; + for (let i = 0; i < n; i++) { + const ax = pts[i * 2], ay = pts[i * 2 + 1]; + out.push(ax, ay); + if (i === n - 1 && !closed) break; + const j = (i + 1) % n, bx = pts[j * 2], by = pts[j * 2 + 1]; + const L = Math.hypot(bx - ax, by - ay), k = Math.ceil(L / h); + if (k < 2) continue; + const nx = -(by - ay) / L, ny = (bx - ax) / L; + for (let s = 1; s < k; s++) { + const px = ax + ((bx - ax) * s) / k, py = ay + ((by - ay) * s) / k; + if (at(px, py) >= 0) continue; + let lo = 0, hi = 2 * g.c; + if (at(px + nx * hi, py + ny * hi) < 0) continue; + for (let it = 0; it < 24 && hi - lo > 1e-5; it++) { + const m = (lo + hi) / 2; + if (at(px + nx * m, py + ny * m) >= 0) hi = m; else lo = m; + } + out.push(px + nx * hi, py + ny * hi); + } + } + return out; + }; + return loops.filter((l) => polyLength(l.pts, 2, l.closed) > g.c * 1.5).map((l) => ({ pts: simplify(fill(l.pts, l.closed), tol, 2, l.closed), closed: l.closed })); } // ---------- path pieces ---------- diff --git a/src/parametric/tests/cam-engine.test.ts b/src/parametric/tests/cam-engine.test.ts index 906cf4229..a151461cc 100644 --- a/src/parametric/tests/cam-engine.test.ts +++ b/src/parametric/tests/cam-engine.test.ts @@ -193,6 +193,25 @@ describe('operations', () => { expect(a).toBeLessThan(0); }); + it('keeps a small tool off the corners of a large part (a grid coarser than the tool)', () => { + const t = tool('flat', 0.3); + const s = setup({ stock: { mode: 'offset', side: 2, top: 0, bottom: 0, size: [0, 0, 0] } }); + // 300 mm across: the grid's cells are wider than the tool, and its chords cut the corners. + const part = placePart(s, mesh(box(0, 0, 0, 300, 300, 2), box(300, 150, 0, 301.3, 150.2, 2)))!; + const tp = generateFor(part, { setup: s, op: op('contour', t, { stepdown: 2, lead: 0, breakthrough: 0 }), tool: t }); + expect(tp.warnings).toEqual([]); + const dc = new DropCutter(part.index, makeCutter('flat', 0.14, 0, 0)); + const ms = moves(tp); + for (let i = 1; i < ms.length; i++) { + const a = ms[i - 1], b = ms[i]; + const n = Math.ceil(Math.hypot(b.x - a.x, b.y - a.y) / 0.01) + 1; + for (let k = 0; k <= n; k++) { + const u = k / n; + expect(dc.drop(a.x + (b.x - a.x) * u, a.y + (b.y - a.y) * u)).toBeLessThanOrEqual(a.z + (b.z - a.z) * u + 1e-6); + } + } + }); + it('leaves holding tabs in the last passes', () => { const t = tool('flat', 6); const s = setup({ stock: { mode: 'offset', side: 5, top: 0, bottom: 0, size: [0, 0, 0] } }); From 35f14ef85a1b31e836fb7ed9b73ca6cef7c9b996 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:46:02 -0700 Subject: [PATCH 20/34] Parametric CAM: preview the open operation again after the tool library changes --- src/parametric/src/app/cam/dialogs.ts | 5 ++++- src/parametric/src/app/cam/panels.ts | 7 +++++++ src/parametric/tests/e2e/cam.spec.ts | 30 +++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/app/cam/dialogs.ts b/src/parametric/src/app/cam/dialogs.ts index 0e789880d..23a7e4907 100644 --- a/src/parametric/src/app/cam/dialogs.ts +++ b/src/parametric/src/app/cam/dialogs.ts @@ -135,7 +135,10 @@ export async function toolLibraryDialog(app: App, ws: CamWorkspace, select?: str d.cam.tools = tools; }); ws.changed(); - if (app.panel instanceof CamPanel) app.refreshPanel(); + if (app.panel instanceof CamPanel) { + app.panel.toolsChanged(); + app.refreshPanel(); + } } const EXTENSIONS: Record = { fanuc: 'nc', haas: 'nc', mach3: 'tap', linuxcnc: 'ngc', grbl: 'gcode' }; diff --git a/src/parametric/src/app/cam/panels.ts b/src/parametric/src/app/cam/panels.ts index a2cd7f300..3e8b9c241 100644 --- a/src/parametric/src/app/cam/panels.ts +++ b/src/parametric/src/app/cam/panels.ts @@ -18,6 +18,8 @@ import type { CamWorkspace } from './workspace'; /** Panels of CAM (the workspace shows its overlays while one is open). */ export abstract class CamPanel extends PropertyPanel { readonly camPanel = true; + /** The tool library changed (the dialog was confirmed while this panel is open). */ + toolsChanged() {} } const AXES: { value: CamAxis; label: string }[] = [ @@ -240,6 +242,11 @@ export class OperationPanel extends CamPanel { get edited() { return this.dirty || this.isNew; } + /** The tool's size or shape may have changed: the preview is made again. */ + toolsChanged() { + this.schedule(0); + } + private setup(): CamSetup | null { return this.ws.cam?.setups.find((s) => s.id === this.setupId) ?? null; } diff --git a/src/parametric/tests/e2e/cam.spec.ts b/src/parametric/tests/e2e/cam.spec.ts index 605d6a062..5932da7b4 100644 --- a/src/parametric/tests/e2e/cam.spec.ts +++ b/src/parametric/tests/e2e/cam.spec.ts @@ -81,3 +81,33 @@ test('machines a part from the CAM tab: setup, tools, operations, simulation and await expect(page.getByRole('treeitem', { name: /^Contour1/ })).toHaveCount(0); expect(errors).toEqual([]); }); + +test('CAM panels follow the tool library, deletions and the post settings', async ({ page }) => { + test.setTimeout(180_000); + const errors = await openApp(page); + await page.getByRole('button', { name: /Pipe Flange/ }).click(); + await page.waitForFunction(() => !!(window as unknown as W).__parametric.bbox); + await page.getByRole('tab', { name: 'CAM' }).click(); + await page.locator('[data-cmd="cam:setup"]').click(); + await page.locator('.confirm-corner .ok').click(); + + // A smaller tool chosen in the tool library while the operation is open previews again. + await page.locator('[data-cmd="cam:contour"]').click(); + const length = page.locator('.cam-stats tr', { hasText: 'Cutting length' }).locator('td'); + await expect(length).toBeVisible({ timeout: 60_000 }); + const before = await length.innerText(); + await page.getByRole('button', { name: 'Tool Library...' }).click(); + const tools = page.getByRole('dialog', { name: 'Tool Library' }); + const dia = tools.getByRole('textbox', { name: 'Diameter' }); + await dia.fill('3'); + await dia.press('Tab'); + await tools.getByRole('button', { name: 'OK' }).click(); + await expect(length).not.toHaveText(before, { timeout: 60_000 }); + await page.locator('.confirm-corner .ok').click(); + await page.waitForFunction(() => { + const app = (window as unknown as W).__parametric; + const s = app.store.doc.cam!.setups[0]; + return s.ops.length === 1 && app.cam!.state(s, s.ops[0]) === 'ok'; + }, null, { timeout: 90_000 }); + expect(errors).toEqual([]); +}); From ed364f91d03f50f41da6d0d65b73b61ab5664e28 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:47:18 -0700 Subject: [PATCH 21/34] Parametric CAM: close a setup or operation panel when its setup or operation is deleted OK re-added an operation deleted from the design tree while it was being edited. --- src/parametric/src/app/cam/index.ts | 3 +++ src/parametric/src/app/cam/panels.ts | 11 +++++++++++ src/parametric/tests/e2e/cam.spec.ts | 10 ++++++++++ 3 files changed, 24 insertions(+) diff --git a/src/parametric/src/app/cam/index.ts b/src/parametric/src/app/cam/index.ts index 4062e9869..6e6bb240d 100644 --- a/src/parametric/src/app/cam/index.ts +++ b/src/parametric/src/app/cam/index.ts @@ -170,6 +170,9 @@ export function installCam(app: App, hooks: AppHooks): CamWorkspace { const ids = new Set(cam?.setups.flatMap((s) => s.ops.map((o) => o.id)) ?? []); ws.prune(ids); if (ws.focus && !ids.has(ws.focus) && !cam?.setups.some((s) => s.id === ws.focus)) ws.focus = null; + // A setup or operation deleted while its panel is open: OK would bring it back. + const p = app.panel; + if ((p instanceof SetupPanel || p instanceof OperationPanel) && !p.present) void app.closePanel(false); }); ws.listeners.add(() => app.renderTrees()); return ws; diff --git a/src/parametric/src/app/cam/panels.ts b/src/parametric/src/app/cam/panels.ts index 3e8b9c241..3779f72e8 100644 --- a/src/parametric/src/app/cam/panels.ts +++ b/src/parametric/src/app/cam/panels.ts @@ -93,6 +93,11 @@ export class SetupPanel extends CamPanel { get edited() { return this.dirty || this.isNew; } + /** Is the setup being edited still in the part (not deleted meanwhile)? */ + get present(): boolean { + return this.isNew || !!this.ws.cam?.setups.some((x) => x.id === this.s.id); + } + private update() { this.ws.preview = { setup: this.s, op: null, toolpath: null }; this.ws.redraw(); @@ -242,6 +247,12 @@ export class OperationPanel extends CamPanel { get edited() { return this.dirty || this.isNew; } + /** Are the operation (unless new) and its setup still in the part (not deleted meanwhile)? */ + get present(): boolean { + const s = this.setup(); + return !!s && (this.isNew || s.ops.some((x) => x.id === this.o.id)); + } + /** The tool's size or shape may have changed: the preview is made again. */ toolsChanged() { this.schedule(0); diff --git a/src/parametric/tests/e2e/cam.spec.ts b/src/parametric/tests/e2e/cam.spec.ts index 5932da7b4..66e3b3747 100644 --- a/src/parametric/tests/e2e/cam.spec.ts +++ b/src/parametric/tests/e2e/cam.spec.ts @@ -109,5 +109,15 @@ test('CAM panels follow the tool library, deletions and the post settings', asyn const s = app.store.doc.cam!.setups[0]; return s.ops.length === 1 && app.cam!.state(s, s.ops[0]) === 'ok'; }, null, { timeout: 90_000 }); + + // An operation deleted from the tree while its panel is open is not brought back by OK. + await page.getByRole('treeitem', { name: /^Contour1/ }).dblclick(); + await expect(page.getByRole('heading', { name: 'Contour1' })).toBeVisible(); + await page.locator('#left-tab-tree').click(); + await page.getByRole('treeitem', { name: /^Contour1/ }).click({ button: 'right' }); + await page.getByRole('menuitem', { name: 'Delete' }).click(); + await expect(page.locator('.confirm-corner .ok')).toBeHidden(); + expect(await page.evaluate(() => (window as unknown as W).__parametric.panel)).toBeNull(); + await expect(page.getByRole('treeitem', { name: /^Contour1/ })).toHaveCount(0); expect(errors).toEqual([]); }); From fcce5a8957ee6e781cdd33dba944e6df1243602f Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:48:11 -0700 Subject: [PATCH 22/34] Parametric CAM: Download and Copy write the program for the post settings just chosen A change still being written was skipped: the previous controller's G-code was saved under the new controller's extension. --- src/parametric/src/app/cam/dialogs.ts | 12 +++++++++--- src/parametric/tests/e2e/cam.spec.ts | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/parametric/src/app/cam/dialogs.ts b/src/parametric/src/app/cam/dialogs.ts index 23a7e4907..e8c1f9893 100644 --- a/src/parametric/src/app/cam/dialogs.ts +++ b/src/parametric/src/app/cam/dialogs.ts @@ -156,13 +156,17 @@ export async function postDialog(app: App, ws: CamWorkspace) { const preview = h('pre', { class: 'cam-gcode', tabindex: '0', 'aria-label': 'G-code preview' }, 'Generating toolpaths...'); const status = h('p', { class: 'pm-msg', role: 'status', hidden: true }); let code = ''; + // Each change writes the program again; only the newest one is shown and written out. + let seq = 0; const make = async () => { + const mine = ++seq; status.hidden = true; try { await ws.generate(cam.setups.filter((s) => chosen.has(s.id)).map((s) => s.id)); } catch (e) { if (e instanceof CamCancelled) return; } + if (mine !== seq) return; const now = ws.cam!; const setups = now.setups.filter((s) => chosen.has(s.id)).map((s) => { const ops: PostOperation[] = []; @@ -182,7 +186,8 @@ export async function postDialog(app: App, ws: CamWorkspace) { count.textContent = code ? `${lines.length - 1} lines` : ''; }; const count = h('span', { class: 'field-label' }); - const refresh = () => { preview.textContent = 'Writing...'; void make(); }; + let pending = Promise.resolve(); + const refresh = () => { preview.textContent = 'Writing...'; pending = make(); }; const setupChecks = cam.setups.map((s) => checkbox(s.name, true, (v) => { if (v) chosen.add(s.id); else chosen.delete(s.id); refresh(); })); const progNum = h('input', { class: 'input', id: nextDomId('prog'), inputmode: 'numeric', value: String(post.program) }) as HTMLInputElement; progNum.addEventListener('change', () => { const n = Math.round(Number(progNum.value)); if (n >= 1 && n <= 99999) { post.program = n; refresh(); } }); @@ -197,13 +202,14 @@ export async function postDialog(app: App, ws: CamWorkspace) { h('div', { class: 'field-label' }, 'Setups'), ...setupChecks, status), h('div', { class: 'cam-post-main' }, preview, count)); - void make(); + pending = make(); const v = await showDialog({ title: 'Post Process', body, wide: true, signal: app.documentSignal, buttons: [{ label: 'Cancel', value: 'cancel' }, { label: 'Copy', value: 'copy' }, { label: 'Download G-code', primary: true, value: 'ok' }], onAction: async (val) => { if (val === 'cancel') return; - if (!code) await make(); + // Settings just changed: what is written is the program for them. + await pending; if (!code) { status.hidden = false; status.className = 'pm-msg error'; status.textContent = 'There is no G-code to write.'; return false; } if (val === 'copy') { try { await navigator.clipboard.writeText(code); toast({ kind: 'success', message: 'G-code copied' }); } catch { toast({ kind: 'error', message: 'Could not copy to the clipboard' }); } diff --git a/src/parametric/tests/e2e/cam.spec.ts b/src/parametric/tests/e2e/cam.spec.ts index 66e3b3747..b203e6a80 100644 --- a/src/parametric/tests/e2e/cam.spec.ts +++ b/src/parametric/tests/e2e/cam.spec.ts @@ -110,6 +110,22 @@ test('CAM panels follow the tool library, deletions and the post settings', asyn return s.ops.length === 1 && app.cam!.state(s, s.ops[0]) === 'ok'; }, null, { timeout: 90_000 }); + // Download pressed right after changing the controller writes that controller's program. + await page.locator('[data-cmd="cam:post"]').click(); + const post = page.getByRole('dialog', { name: 'Post Process' }); + await expect(post.getByLabel('G-code preview')).toContainText('O1001', { timeout: 60_000 }); + const download = page.waitForEvent('download'); + await post.evaluate((dialog) => { + const controller = dialog.querySelector('select')!; + controller.value = 'grbl'; + controller.dispatchEvent(new Event('change', { bubbles: true })); + [...dialog.querySelectorAll('button')].find((b) => b.textContent === 'Download G-code')!.click(); + }); + const file = await download; + expect(file.suggestedFilename()).toMatch(/\.gcode$/); + const fs = await import('node:fs'); + expect(new TextDecoder().decode(fs.readFileSync((await file.path())!))).not.toContain('O1001'); + // An operation deleted from the tree while its panel is open is not brought back by OK. await page.getByRole('treeitem', { name: /^Contour1/ }).dblclick(); await expect(page.getByRole('heading', { name: 'Contour1' })).toBeVisible(); From 579e751ce065769e050ab6b46152a16c82c48a0c Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:49:07 -0700 Subject: [PATCH 23/34] Parametric CAM: a preview made for earlier values is not shown after the last pocket floor is removed --- src/parametric/src/app/cam/panels.ts | 4 +++- src/parametric/tests/e2e/cam.spec.ts | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/app/cam/panels.ts b/src/parametric/src/app/cam/panels.ts index 3779f72e8..6d5d312e9 100644 --- a/src/parametric/src/app/cam/panels.ts +++ b/src/parametric/src/app/cam/panels.ts @@ -284,10 +284,12 @@ export class OperationPanel extends CamPanel { private async run() { const setup = this.setup(); if (!setup || this.disposed) return; + // A preview still being made is for values that no longer hold. + const seq = ++this.seq; + this.busy = false; const why = this.ws.ready(); if (why) { this.error = why; this.renderInfo(); return; } if (this.o.type === 'pocket' && !this.o.faces.length) { this.toolpath = null; this.error = 'Pick the floor faces of the pockets.'; this.showPreview(); return; } - const seq = ++this.seq; this.busy = true; this.renderInfo(); try { diff --git a/src/parametric/tests/e2e/cam.spec.ts b/src/parametric/tests/e2e/cam.spec.ts index b203e6a80..781744bcf 100644 --- a/src/parametric/tests/e2e/cam.spec.ts +++ b/src/parametric/tests/e2e/cam.spec.ts @@ -135,5 +135,21 @@ test('CAM panels follow the tool library, deletions and the post settings', asyn await expect(page.locator('.confirm-corner .ok')).toBeHidden(); expect(await page.evaluate(() => (window as unknown as W).__parametric.panel)).toBeNull(); await expect(page.getByRole('treeitem', { name: /^Contour1/ })).toHaveCount(0); + + // A pocket preview still being made when its last floor is removed is not shown. + await page.locator('[data-cmd="cam:pocket"]').click(); + await expect(page.getByRole('heading', { name: 'New 2D Pocket' })).toBeVisible(); + expect(await page.evaluate(async () => { + const app = (window as unknown as W).__parametric; + type Panel = { o: { faces: unknown[] }; run(): Promise; error: string | null; toolpath: unknown }; + const p = app.panel as unknown as Panel; + const f = app.faces.find((x) => x.type === 'plane' && Math.abs(x.normal![1]) > 0.99)!; + p.o.faces = [{ name: f.name, sig: { type: f.type, c: f.center, n: f.normal, area: f.area } }]; + const first = p.run(); + p.o.faces = []; + await p.run(); + await first; + return { error: p.error, toolpath: !!p.toolpath, shown: !!app.cam!.preview?.toolpath }; + })).toEqual({ error: 'Pick the floor faces of the pockets.', toolpath: false, shown: false }); expect(errors).toEqual([]); }); From 6d98b25f2a8bda9ba6c61492810d68c902045543 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:52:13 -0700 Subject: [PATCH 24/34] Parametric CAM: write G-code in a worker so Post Process stays responsive A 1.2 million move program blocked the dialog for about a second on every option change. A change made while a program is still being written stops that one. --- src/parametric/src/app/cam/dialogs.ts | 53 ++++++++++++++++++++--- src/parametric/src/app/cam/post-worker.ts | 28 ++++++++++++ 2 files changed, 76 insertions(+), 5 deletions(-) create mode 100644 src/parametric/src/app/cam/post-worker.ts diff --git a/src/parametric/src/app/cam/dialogs.ts b/src/parametric/src/app/cam/dialogs.ts index e8c1f9893..3f33995e3 100644 --- a/src/parametric/src/app/cam/dialogs.ts +++ b/src/parametric/src/app/cam/dialogs.ts @@ -1,7 +1,7 @@ // CAM dialogs: the tool library and post processing to G-code. import { CamCancelled } from '../../cam/client'; -import { postProcess, type PostOperation } from '../../cam/post'; +import type { PostJob, PostOperation } from '../../cam/post'; import { type CamController, type CamTool, type CamToolType, CONTROLLER_LABELS, TOOL_TYPE_LABELS, newCamDoc, opFeeds } from '../../model/cam'; import { allocateId } from '../../model/document'; import { UNIT_SYSTEMS } from '../../model/units'; @@ -12,6 +12,7 @@ import { showDialog, toast } from '../../ui/overlay'; import type { App } from '../app'; import { checkbox, numberField, selectField } from '../pm'; import { CamPanel, rateField } from './panels'; +import type { PostWorkerResponse } from './post-worker'; import type { CamWorkspace } from './workspace'; const TYPES = Object.entries(TOOL_TYPE_LABELS).map(([value, label]) => ({ value: value as CamToolType, label })); @@ -143,6 +144,36 @@ export async function toolLibraryDialog(app: App, ws: CamWorkspace, select?: str const EXTENSIONS: Record = { fanuc: 'nc', haas: 'nc', mach3: 'tap', linuxcnc: 'ngc', grbl: 'gcode' }; +/** G-code writing in a worker; a newer request stops the one still running. */ +class PostWriter { + private worker: Worker | null = null; + + write(job: PostJob): Promise<{ code: string; lines: number; head: string }> { + this.stop(); + const w = new Worker(new URL('./post-worker.ts', import.meta.url), { type: 'module', name: 'cam-post' }); + this.worker = w; + return new Promise((resolve, reject) => { + const done = () => { w.terminate(); if (this.worker === w) this.worker = null; }; + w.onmessage = (ev: MessageEvent) => { + done(); + if ('error' in ev.data) reject(new Error(ev.data.error)); + else resolve(ev.data); + }; + w.onerror = (ev) => { + ev.preventDefault(); + done(); + reject(new Error(ev.message || 'The G-code could not be written.')); + }; + w.postMessage(job); + }); + } + + stop() { + this.worker?.terminate(); + this.worker = null; + } +} + /** Writes the G-code of the setups for a controller and downloads it. */ export async function postDialog(app: App, ws: CamWorkspace) { const cam = ws.cam; @@ -180,11 +211,22 @@ export async function postDialog(app: App, ws: CamWorkspace) { return { name: s.name, workOffset: s.workOffset, ops }; }).filter((s) => s.ops.length); const date = new Date().toISOString().slice(0, 10); - code = setups.length ? postProcess({ name: app.store.doc.name, post: { ...post, units: unitsSel }, units: unitsSel, setups, notes: [`Parametric CAM, ${date}`, `Post: ${CONTROLLER_LABELS[post.controller]}`] }) : ''; - const lines = code.split('\n'); - preview.textContent = code ? `${lines.slice(0, 400).join('\n')}${lines.length > 400 ? `\n... ${lines.length - 400} more lines` : ''}` : 'Nothing to post.'; - count.textContent = code ? `${lines.length - 1} lines` : ''; + let out = { code: '', lines: 0, head: '' }; + if (setups.length) { + try { + out = await writer.write({ name: app.store.doc.name, post: { ...post, units: unitsSel }, units: unitsSel, setups, notes: [`Parametric CAM, ${date}`, `Post: ${CONTROLLER_LABELS[post.controller]}`] }); + } catch (e) { + if (mine !== seq) return; + status.hidden = false; status.className = 'pm-msg error'; status.textContent = (e as Error).message; + } + } + // Settings changed while it was written: the newer request shows its program. + if (mine !== seq) return; + code = out.code; + preview.textContent = code ? out.head : 'Nothing to post.'; + count.textContent = code ? `${out.lines} lines` : ''; }; + const writer = new PostWriter(); const count = h('span', { class: 'field-label' }); let pending = Promise.resolve(); const refresh = () => { preview.textContent = 'Writing...'; pending = make(); }; @@ -218,6 +260,7 @@ export async function postDialog(app: App, ws: CamWorkspace) { return true; }, }); + writer.stop(); if (v !== 'ok' || !code) return; // Keep the post settings with the part (units only when they differ from the part's). const next = { ...post }; diff --git a/src/parametric/src/app/cam/post-worker.ts b/src/parametric/src/app/cam/post-worker.ts new file mode 100644 index 000000000..fa73c9a3d --- /dev/null +++ b/src/parametric/src/app/cam/post-worker.ts @@ -0,0 +1,28 @@ +/// +// Writes G-code away from the interface: a long finishing program takes a +// second or more, which froze the Post Process dialog on every change. + +import { type PostJob, postProcess } from '../../cam/post'; + +declare const self: DedicatedWorkerGlobalScope; + +/** The program, its line count and its first lines (for the preview). */ +export type PostWorkerResponse = { code: string; lines: number; head: string } | { error: string }; + +const HEAD = 400; + +self.onmessage = (ev: MessageEvent) => { + try { + const code = postProcess(ev.data); + let lines = 0, end = -1; + for (let i = code.indexOf('\n'); i >= 0; i = code.indexOf('\n', i + 1)) { + lines++; + if (lines === HEAD) end = i; + } + const more = lines + 1 - HEAD; + const head = end < 0 ? code : `${code.slice(0, end)}\n... ${more} more lines`; + self.postMessage({ code, lines, head } satisfies PostWorkerResponse); + } catch (e) { + self.postMessage({ error: (e as Error).message } satisfies PostWorkerResponse); + } +}; From c9d31276850c990b7325e8c973a66d3fcdad415a Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:53:22 -0700 Subject: [PATCH 25/34] Parametric CAM: OK keeps the previewed toolpath instead of generating it again The operation's toolpath vanished from the graphics area while the same toolpath was made a second time. --- src/parametric/src/app/cam/panels.ts | 8 ++++++++ src/parametric/src/app/cam/workspace.ts | 9 ++++++++- src/parametric/tests/e2e/cam.spec.ts | 8 ++++++++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/app/cam/panels.ts b/src/parametric/src/app/cam/panels.ts index 6d5d312e9..fe65c5b3d 100644 --- a/src/parametric/src/app/cam/panels.ts +++ b/src/parametric/src/app/cam/panels.ts @@ -229,6 +229,8 @@ export class OperationPanel extends CamPanel { private timer = 0; private seq = 0; private toolpath: Toolpath | null = null; + /** The values `toolpath` was made for (null: not known). */ + private toolpathKey: string | null = null; private error: string | null = null; private busy = false; private info: HTMLElement = h('div'); @@ -292,15 +294,18 @@ export class OperationPanel extends CamPanel { if (this.o.type === 'pocket' && !this.o.faces.length) { this.toolpath = null; this.error = 'Pick the floor faces of the pockets.'; this.showPreview(); return; } this.busy = true; this.renderInfo(); + const key = this.ws.keyOf(setup, this.o); try { const tp = await this.ws.previewOf(setup, structuredClone(this.o)); if (seq !== this.seq || this.disposed) return; this.toolpath = tp; + this.toolpathKey = key; this.error = null; } catch (e) { if (seq !== this.seq || this.disposed) return; if ((e as Error).message === 'Cancelled') return; this.toolpath = null; + this.toolpathKey = null; this.error = (e as Error).message; } this.busy = false; @@ -508,6 +513,9 @@ export class OperationPanel extends CamPanel { else s.ops.push(structuredClone(o)); }); this.ws.focus = o.id; + // The preview is the toolpath when nothing changed since it was made (no second generation). + const s = this.setup(); + if (s && this.toolpath && this.toolpathKey && !this.busy && this.toolpathKey === this.ws.keyOf(s, o)) this.ws.adopt(o.id, this.toolpathKey, this.toolpath); void this.ws.generate([o.id]); return true; } diff --git a/src/parametric/src/app/cam/workspace.ts b/src/parametric/src/app/cam/workspace.ts index 42cb0b8a7..7507c86ba 100644 --- a/src/parametric/src/app/cam/workspace.ts +++ b/src/parametric/src/app/cam/workspace.ts @@ -224,7 +224,8 @@ export class CamWorkspace { return job; } - private keyOf(setup: CamSetup, op: CamOperation): string { + /** What an operation's toolpath depends on: equal keys, equal toolpaths. */ + keyOf(setup: CamSetup, op: CamOperation): string { const { name: _n, suppressed: _s, rpm: _r, feed: _f, plunge: _p, ...shape } = op; void _n; void _s; void _r; void _f; void _p; const tool = this.toolOf(op); @@ -304,6 +305,12 @@ export class CamWorkspace { return p; } + /** Keeps a toolpath made for an operation's preview as its result (the key it was made for). */ + adopt(id: Id, key: string, toolpath: Toolpath) { + this.results.set(id, { key, toolpath }); + this.changed(); + } + /** Generates a toolpath for an operation being edited (not stored), for its panel's preview. */ async previewOf(setup: CamSetup, op: CamOperation): Promise { const tris = await this.mesh(); diff --git a/src/parametric/tests/e2e/cam.spec.ts b/src/parametric/tests/e2e/cam.spec.ts index 781744bcf..547dbfa07 100644 --- a/src/parametric/tests/e2e/cam.spec.ts +++ b/src/parametric/tests/e2e/cam.spec.ts @@ -103,12 +103,20 @@ test('CAM panels follow the tool library, deletions and the post settings', asyn await dia.press('Tab'); await tools.getByRole('button', { name: 'OK' }).click(); await expect(length).not.toHaveText(before, { timeout: 60_000 }); + // OK keeps the toolpath previewed for these values instead of generating it again. + await page.evaluate(() => { + const c = (window as unknown as W).__parametric.cam!.client; + const generate = c.generate.bind(c); + (window as unknown as { generated: number }).generated = 0; + c.generate = (...a) => { (window as unknown as { generated: number }).generated++; return generate(...a); }; + }); await page.locator('.confirm-corner .ok').click(); await page.waitForFunction(() => { const app = (window as unknown as W).__parametric; const s = app.store.doc.cam!.setups[0]; return s.ops.length === 1 && app.cam!.state(s, s.ops[0]) === 'ok'; }, null, { timeout: 90_000 }); + expect(await page.evaluate(() => (window as unknown as { generated: number }).generated)).toBe(0); // Download pressed right after changing the controller writes that controller's program. await page.locator('[data-cmd="cam:post"]').click(); From 71ff6625eacb21eee31e2fb0526ac34e0437f372 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:53:52 -0700 Subject: [PATCH 26/34] Parametric CAM: simulation Play button names its action without a pressed state; one speed selected MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A pressed "Pause" toggle was announced as paused, and a short program had both "Whole program in 20 s" and "1×" selected, showing 1×. --- src/parametric/src/app/cam/simulate-panel.ts | 7 ++++--- src/parametric/tests/e2e/cam.spec.ts | 7 +++++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/parametric/src/app/cam/simulate-panel.ts b/src/parametric/src/app/cam/simulate-panel.ts index 68fa1acc4..a3d377b95 100644 --- a/src/parametric/src/app/cam/simulate-panel.ts +++ b/src/parametric/src/app/cam/simulate-panel.ts @@ -254,8 +254,8 @@ export class SimulationPanel extends CamPanel { this.playing = on; if (on && this.t >= this.res.time - 1e-9) this.t = 0; if (this.playBtn) { + // The label tells the state (a pressed "Pause" toggle read as paused). this.playBtn.replaceChildren(icon(on ? 'pause' : 'play', 16), on ? 'Pause' : 'Play'); - this.playBtn.setAttribute('aria-pressed', String(on)); } cancelAnimationFrame(this.raf); if (!on) return; @@ -284,11 +284,12 @@ export class SimulationPanel extends CamPanel { slider.addEventListener('input', () => { this.play(false); this.t = (Number(slider.value) / 1000) * res.time; this.showAt(this.t); }); this.slider = slider; this.clock = h('div', { class: 'field-label cam-clock', 'aria-live': 'off' }); - const play = h('button', { class: 'btn small', type: 'button', 'aria-pressed': String(this.playing) }, icon(this.playing ? 'pause' : 'play', 16), this.playing ? 'Pause' : 'Play') as HTMLButtonElement; + const play = h('button', { class: 'btn small', type: 'button' }, icon(this.playing ? 'pause' : 'play', 16), this.playing ? 'Pause' : 'Play') as HTMLButtonElement; play.addEventListener('click', () => this.play(!this.playing)); this.playBtn = play; - const speeds = [1, 5, 20, 100, 500].map((x) => ({ value: String(x), label: `${x}×` })); const auto = String(Math.max(1, Math.round(res.time / 20))); + // A preset equal to the whole-program speed would be a second selected option. + const speeds = [1, 5, 20, 100, 500].filter((x) => String(x) !== auto).map((x) => ({ value: String(x), label: `${x}×` })); const speed = h('select', { class: 'input', 'aria-label': 'Playback speed' }) as HTMLSelectElement; for (const o of [{ value: auto, label: 'Whole program in 20 s' }, ...speeds]) speed.append(h('option', { value: o.value, selected: Number(o.value) === Math.round(this.speed) }, o.label)); speed.addEventListener('change', () => { this.speed = Number(speed.value); }); diff --git a/src/parametric/tests/e2e/cam.spec.ts b/src/parametric/tests/e2e/cam.spec.ts index 547dbfa07..d011d33a1 100644 --- a/src/parametric/tests/e2e/cam.spec.ts +++ b/src/parametric/tests/e2e/cam.spec.ts @@ -60,6 +60,13 @@ test('machines a part from the CAM tab: setup, tools, operations, simulation and await page.locator('[data-cmd="cam:simulate"]').click(); await expect(page.getByText('No collisions')).toBeVisible({ timeout: 90_000 }); await expect(page.getByLabel('Program position')).toBeVisible(); + // Play and Pause name the action, not a pressed state; one speed is chosen. + const play = page.getByRole('button', { name: 'Play', exact: true }); + await play.click(); + await expect(page.getByRole('button', { name: 'Pause', exact: true })).not.toHaveAttribute('aria-pressed'); + await page.getByRole('button', { name: 'Pause', exact: true }).click(); + await expect(play).toBeVisible(); + expect(await page.getByLabel('Playback speed').evaluate((s) => [...(s as HTMLSelectElement).options].filter((o) => o.defaultSelected).length)).toBe(1); await page.getByRole('button', { name: 'Exit Simulation' }).click(); // G-code with peck drilling cycles, downloaded. From 8c983e2af8f38d4a37be2269d6205d97380f5cb4 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:55:20 -0700 Subject: [PATCH 27/34] Parametric CAM: tool library list keeps the chosen tool in view and tells screen readers which it is Arrow keys moved the choice out of sight in a long list and nothing was announced; Home and End go to the first and last tool. --- src/parametric/src/app/cam/dialogs.ts | 19 ++++++++++++------- src/parametric/tests/e2e/cam.spec.ts | 8 ++++++++ 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/parametric/src/app/cam/dialogs.ts b/src/parametric/src/app/cam/dialogs.ts index 3f33995e3..674b4dffd 100644 --- a/src/parametric/src/app/cam/dialogs.ts +++ b/src/parametric/src/app/cam/dialogs.ts @@ -37,24 +37,29 @@ export async function toolLibraryDialog(app: App, ws: CamWorkspace, select?: str nextLocal++; return `__add${nextLocal}`; }; + const listId = nextDomId('tools'); const drawList = () => { list.textContent = ''; - for (const t of [...tools].sort((a, b) => a.number - b.number)) { - const opt = h('div', { role: 'option', class: 'cam-tool', 'aria-selected': String(t === current), tabindex: '-1' }, + list.removeAttribute('aria-activedescendant'); + for (const [k, t] of [...tools].sort((a, b) => a.number - b.number).entries()) { + // The list keeps the focus; the tool chosen is its active option (read out, kept in view). + const opt = h('div', { id: `${listId}-${k}`, role: 'option', class: 'cam-tool', 'aria-selected': String(t === current) }, h('span', { class: 'num' }, `T${t.number}`), h('span', { class: 'grow' }, t.name), h('span', { class: 'muted' }, `${TOOL_TYPE_LABELS[t.type]} · ${formatLen(t.diameter)}`)); opt.addEventListener('click', () => { current = t; drawList(); drawForm(); }); list.append(opt); + if (t === current) list.setAttribute('aria-activedescendant', opt.id); } + list.querySelector('[aria-selected="true"]')?.scrollIntoView({ block: 'nearest' }); }; const formatLen = (mm: number) => `${Number((mm / u.scale).toPrecision(6))} ${u.length}`; list.addEventListener('keydown', (e) => { const sorted = [...tools].sort((a, b) => a.number - b.number); const i = current ? sorted.indexOf(current) : -1; - if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { - e.preventDefault(); - current = sorted[Math.max(0, Math.min(sorted.length - 1, i + (e.key === 'ArrowDown' ? 1 : -1)))] ?? null; - drawList(); drawForm(); - } + const to = e.key === 'ArrowDown' ? i + 1 : e.key === 'ArrowUp' ? i - 1 : e.key === 'Home' ? 0 : e.key === 'End' ? sorted.length - 1 : null; + if (to === null) return; + e.preventDefault(); + current = sorted[Math.max(0, Math.min(sorted.length - 1, to))] ?? null; + drawList(); drawForm(); }); const drawForm = () => { form.textContent = ''; diff --git a/src/parametric/tests/e2e/cam.spec.ts b/src/parametric/tests/e2e/cam.spec.ts index d011d33a1..e129f27d5 100644 --- a/src/parametric/tests/e2e/cam.spec.ts +++ b/src/parametric/tests/e2e/cam.spec.ts @@ -105,6 +105,14 @@ test('CAM panels follow the tool library, deletions and the post settings', asyn const before = await length.innerText(); await page.getByRole('button', { name: 'Tool Library...' }).click(); const tools = page.getByRole('dialog', { name: 'Tool Library' }); + // The keyboard moves through the tools, the one chosen being the list's active option. + const list = tools.getByRole('listbox', { name: 'Tools' }); + await list.focus(); + await page.keyboard.press('End'); + const active = () => list.evaluate((l) => document.getElementById(l.getAttribute('aria-activedescendant') ?? '')?.textContent ?? ''); + expect(await active()).toMatch(/^T8 *10 mm chamfer/); + await page.keyboard.press('Home'); + expect(await active()).toMatch(/^T1 *12 mm flat/); const dia = tools.getByRole('textbox', { name: 'Diameter' }); await dia.fill('3'); await dia.press('Tab'); From 2f7e59127b75c874fe21764a9c0b3f938d30c50f Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:57:08 -0700 Subject: [PATCH 28/34] Parametric CAM: an out-of-date toolpath is drawn where it was cut, not moved by the changed setup Turning a setup over drew its old toolpaths in the new placement, floating above the part. --- src/parametric/src/app/cam/workspace.ts | 14 +++++++++----- src/parametric/tests/e2e/cam.spec.ts | 25 +++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/src/parametric/src/app/cam/workspace.ts b/src/parametric/src/app/cam/workspace.ts index 7507c86ba..db790f411 100644 --- a/src/parametric/src/app/cam/workspace.ts +++ b/src/parametric/src/app/cam/workspace.ts @@ -17,6 +17,8 @@ export type OpState = 'none' | 'busy' | 'ok' | 'stale' | 'error' | 'suppressed'; interface OpResult { key: string; toolpath?: Toolpath; + /** Where the setup put the part when it was made: an out-of-date toolpath shows where it was cut. */ + frame?: MachineFrame | null; stats?: PathStats; error?: string; } @@ -281,6 +283,7 @@ export class CamWorkspace { if (this.results.get(o.id)?.key === key) continue; let job: GenerateJob; try { job = this.jobFor(now.setup, now.op); } catch (e) { this.results.set(o.id, { key, error: (e as Error).message }); failed++; this.changed(); continue; } + const frame = this.frameOf(now.setup); this.busy = { id: o.id, progress: 0 }; this.changed(); this.app.setStatus(`Generating ${now.op.name}...`); @@ -289,7 +292,7 @@ export class CamWorkspace { if (this.busy?.id === o.id) { this.busy.progress = v; this.app.setStatus(`Generating ${now.op.name}... ${Math.round(v * 100)}%`); for (const fn of this.listeners) fn(); } }); if (gen !== this.generation) return; - this.results.set(o.id, { key, toolpath: tp }); + this.results.set(o.id, { key, toolpath: tp, frame }); } catch (e) { if (e instanceof CamCancelled) { this.busy = null; this.changed(); return; } this.results.set(o.id, { key, error: (e as Error).message }); @@ -307,7 +310,8 @@ export class CamWorkspace { /** Keeps a toolpath made for an operation's preview as its result (the key it was made for). */ adopt(id: Id, key: string, toolpath: Toolpath) { - this.results.set(id, { key, toolpath }); + const f = this.cam && findOp(this.cam, id); + this.results.set(id, { key, toolpath, frame: f ? this.frameOf(f.setup) : null }); this.changed(); } @@ -362,8 +366,8 @@ export class CamWorkspace { } const shown: PathLines[] = []; const focusSetup = this.focus ? cam.setups.find((s) => s.id === this.focus || s.ops.some((o) => o.id === this.focus)) : null; - const add = (setup: CamSetup, tp: Toolpath) => { - const f = this.frameOf(setup); + const add = (setup: CamSetup, tp: Toolpath, frame?: MachineFrame | null) => { + const f = frame ?? this.frameOf(setup); if (!f) return; let c = this.lineCache.get(tp); if (!c || c.frame !== f) { c = { frame: f, lines: pathLines(tp, f) }; this.lineCache.set(tp, c); } @@ -379,7 +383,7 @@ export class CamWorkspace { if (o.suppressed) continue; if (this.focus && this.focus !== s.id && this.focus !== o.id) continue; const res = this.results.get(o.id); - if (res?.toolpath) add(s, res.toolpath); + if (res?.toolpath) add(s, res.toolpath, res.frame); } } } diff --git a/src/parametric/tests/e2e/cam.spec.ts b/src/parametric/tests/e2e/cam.spec.ts index e129f27d5..b78f2e022 100644 --- a/src/parametric/tests/e2e/cam.spec.ts +++ b/src/parametric/tests/e2e/cam.spec.ts @@ -133,6 +133,31 @@ test('CAM panels follow the tool library, deletions and the post settings', asyn }, null, { timeout: 90_000 }); expect(await page.evaluate(() => (window as unknown as { generated: number }).generated)).toBe(0); + // A toolpath out of date after the setup turns the part over stays where it was cut. + const cutRange = () => page.evaluate(() => { + const lines = (window as unknown as W).__parametric.renderer as unknown as { lines: Map }; + const p = lines.lines.get('camCut')!.positions; + let lo = Infinity, hi = -Infinity; + for (let i = 1; i < p.length; i += 3) { lo = Math.min(lo, p[i]); hi = Math.max(hi, p[i]); } + return [lo.toFixed(2), hi.toFixed(2)]; + }); + const range = await cutRange(); + await page.getByRole('treeitem', { name: 'Setup1' }).dblclick(); + await page.getByLabel('Tool direction').selectOption('-Y'); + await page.locator('.confirm-corner .ok').click(); + await page.waitForFunction(() => { + const app = (window as unknown as W).__parametric; + const s = app.store.doc.cam!.setups[0]; + return s.axis === '-Y' && app.cam!.state(s, s.ops[0]) === 'stale'; + }); + expect(await cutRange()).toEqual(range); + await page.keyboard.press('ControlOrMeta+z'); + await page.waitForFunction(() => { + const app = (window as unknown as W).__parametric; + const s = app.store.doc.cam!.setups[0]; + return s.axis === '+Y' && app.cam!.state(s, s.ops[0]) === 'ok'; + }); + // Download pressed right after changing the controller writes that controller's program. await page.locator('[data-cmd="cam:post"]').click(); const post = page.getByRole('dialog', { name: 'Post Process' }); From 0997ae08be7d89db675d2d9a05811a406bc02d44 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:57:40 -0700 Subject: [PATCH 29/34] Parametric CAM: mark a program number that is not one instead of silently keeping the old one Download wrote the previous number with no sign that the typed one was refused. --- src/parametric/src/app/cam/dialogs.ts | 13 ++++++++++++- src/parametric/tests/e2e/cam.spec.ts | 13 ++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/parametric/src/app/cam/dialogs.ts b/src/parametric/src/app/cam/dialogs.ts index 674b4dffd..c99e41995 100644 --- a/src/parametric/src/app/cam/dialogs.ts +++ b/src/parametric/src/app/cam/dialogs.ts @@ -237,7 +237,16 @@ export async function postDialog(app: App, ws: CamWorkspace) { const refresh = () => { preview.textContent = 'Writing...'; pending = make(); }; const setupChecks = cam.setups.map((s) => checkbox(s.name, true, (v) => { if (v) chosen.add(s.id); else chosen.delete(s.id); refresh(); })); const progNum = h('input', { class: 'input', id: nextDomId('prog'), inputmode: 'numeric', value: String(post.program) }) as HTMLInputElement; - progNum.addEventListener('change', () => { const n = Math.round(Number(progNum.value)); if (n >= 1 && n <= 99999) { post.program = n; refresh(); } }); + const progBad = 'The program number is a whole number from 1 to 99999.'; + progNum.addEventListener('change', () => { + const n = Number(progNum.value.trim()); + const ok = progNum.value.trim() !== '' && Number.isInteger(n) && n >= 1 && n <= 99999; + progNum.classList.toggle('invalid', !ok); + if (!ok) { progNum.setAttribute('aria-invalid', 'true'); progNum.title = progBad; return; } + progNum.removeAttribute('aria-invalid'); + progNum.title = ''; + if (n !== post.program) { post.program = n; refresh(); } + }); const body = h('div', { class: 'cam-post' }, h('div', { class: 'cam-post-side' }, selectField('Machine controller', post.controller, Object.entries(CONTROLLER_LABELS).map(([value, label]) => ({ value: value as CamController, label })), (v) => { post.controller = v; refresh(); }), @@ -255,6 +264,8 @@ export async function postDialog(app: App, ws: CamWorkspace) { buttons: [{ label: 'Cancel', value: 'cancel' }, { label: 'Copy', value: 'copy' }, { label: 'Download G-code', primary: true, value: 'ok' }], onAction: async (val) => { if (val === 'cancel') return; + // Not written with a number other than the one typed. + if (progNum.getAttribute('aria-invalid')) { status.hidden = false; status.className = 'pm-msg error'; status.textContent = progBad; progNum.focus(); return false; } // Settings just changed: what is written is the program for them. await pending; if (!code) { status.hidden = false; status.className = 'pm-msg error'; status.textContent = 'There is no G-code to write.'; return false; } diff --git a/src/parametric/tests/e2e/cam.spec.ts b/src/parametric/tests/e2e/cam.spec.ts index b78f2e022..e29440ead 100644 --- a/src/parametric/tests/e2e/cam.spec.ts +++ b/src/parametric/tests/e2e/cam.spec.ts @@ -162,6 +162,17 @@ test('CAM panels follow the tool library, deletions and the post settings', asyn await page.locator('[data-cmd="cam:post"]').click(); const post = page.getByRole('dialog', { name: 'Post Process' }); await expect(post.getByLabel('G-code preview')).toContainText('O1001', { timeout: 60_000 }); + // A program number that is not one is marked, and nothing is written with another number. + const prog = post.getByLabel('Program number'); + await prog.fill('12a'); + await prog.press('Tab'); + await expect(prog).toHaveAttribute('aria-invalid', 'true'); + await post.getByRole('button', { name: 'Download G-code' }).click(); + await expect(post.getByText('The program number is a whole number from 1 to 99999.')).toBeVisible(); + await prog.fill('1002'); + await prog.press('Tab'); + await expect(prog).not.toHaveAttribute('aria-invalid'); + await expect(post.getByLabel('G-code preview')).toContainText('O1002'); const download = page.waitForEvent('download'); await post.evaluate((dialog) => { const controller = dialog.querySelector('select')!; @@ -172,7 +183,7 @@ test('CAM panels follow the tool library, deletions and the post settings', asyn const file = await download; expect(file.suggestedFilename()).toMatch(/\.gcode$/); const fs = await import('node:fs'); - expect(new TextDecoder().decode(fs.readFileSync((await file.path())!))).not.toContain('O1001'); + expect(new TextDecoder().decode(fs.readFileSync((await file.path())!))).not.toContain('O1002'); // An operation deleted from the tree while its panel is open is not brought back by OK. await page.getByRole('treeitem', { name: /^Contour1/ }).dblclick(); From 11546b25c160413464f2336038805e1dbaf9d99f Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:59:41 -0700 Subject: [PATCH 30/34] Parametric CAM: tool library OK stops at a field holding text that is not a value It closed and kept the last valid value, discarding what was typed, where panels show the reason and focus the field. --- src/parametric/src/app/cam/dialogs.ts | 3 +++ src/parametric/tests/e2e/cam.spec.ts | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/src/parametric/src/app/cam/dialogs.ts b/src/parametric/src/app/cam/dialogs.ts index c99e41995..f57a0d25b 100644 --- a/src/parametric/src/app/cam/dialogs.ts +++ b/src/parametric/src/app/cam/dialogs.ts @@ -128,6 +128,9 @@ export async function toolLibraryDialog(app: App, ws: CamWorkspace, select?: str buttons: [{ label: 'Cancel', value: 'cancel' }, { label: 'OK', primary: true, value: 'ok' }], onAction: (val) => { if (val !== 'ok') return; + // As in the panels: text that could not be read is not silently replaced by the last valid value. + const bad = [...form.querySelectorAll('.input[aria-invalid="true"]')].find((x) => x.getClientRects().length > 0); + if (bad) { msg.hidden = false; msg.className = 'pm-msg error'; msg.textContent = `${bad.getAttribute('aria-label') ?? 'Value'}: ${bad.title || 'not a valid value'}`; bad.focus(); return false; } const numbers = tools.map((t) => t.number); if (new Set(numbers).size !== numbers.length) { msg.hidden = false; msg.className = 'pm-msg error'; msg.textContent = 'Two tools have the same number. Give each tool its own number.'; return false; } if (tools.some((t) => !t.name.trim())) { msg.hidden = false; msg.className = 'pm-msg error'; msg.textContent = 'Every tool needs a name.'; return false; } diff --git a/src/parametric/tests/e2e/cam.spec.ts b/src/parametric/tests/e2e/cam.spec.ts index e29440ead..da9984b90 100644 --- a/src/parametric/tests/e2e/cam.spec.ts +++ b/src/parametric/tests/e2e/cam.spec.ts @@ -114,6 +114,12 @@ test('CAM panels follow the tool library, deletions and the post settings', asyn await page.keyboard.press('Home'); expect(await active()).toMatch(/^T1 *12 mm flat/); const dia = tools.getByRole('textbox', { name: 'Diameter' }); + // Text that is not a size keeps the dialog open rather than dropping what was typed. + await dia.fill('-2'); + await dia.press('Tab'); + await tools.getByRole('button', { name: 'OK' }).click(); + await expect(tools.getByText(/^Diameter: /)).toBeVisible(); + await expect(dia).toBeFocused(); await dia.fill('3'); await dia.press('Tab'); await tools.getByRole('button', { name: 'OK' }).click(); From f90ed0ee62359a7624da04026b02b91ada582d3b Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 11:59:58 -0700 Subject: [PATCH 31/34] Parametric CAM: simulation of a program with no moves shows its time instead of a blank clock --- src/parametric/src/app/cam/simulate-panel.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/app/cam/simulate-panel.ts b/src/parametric/src/app/cam/simulate-panel.ts index a3d377b95..f4f211b2e 100644 --- a/src/parametric/src/app/cam/simulate-panel.ts +++ b/src/parametric/src/app/cam/simulate-panel.ts @@ -233,7 +233,8 @@ export class SimulationPanel extends CamPanel { // The tool: between the timeline points around t. const tl = res.timeline; const n = tl.length / 6; - if (!n) return; + // An empty program (no moves) still shows its time. + if (!n) { this.app.renderer.setSolid('camTool', null); if (this.clock) this.clock.textContent = `${formatTime(0)} / ${formatTime(res.time)}`; return; } let a = 0, b = n - 1; while (a < b) { const m = (a + b) >> 1; if (tl[m * 6 + 3] < t) a = m + 1; else b = m; } const i = a; From 3c2ac73f91304067fed3b6d767590a0c99f959a4 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 12:02:26 -0700 Subject: [PATCH 32/34] Parametric CAM: simulation runs in its own worker, so leaving it no longer stops generation Exit Simulation cancelled the generation worker, stopping toolpaths still being generated. --- src/parametric/src/app/cam/simulate-panel.ts | 4 ++-- src/parametric/src/app/cam/workspace.ts | 18 ++++++++++++++-- src/parametric/tests/e2e/cam.spec.ts | 22 ++++++++++++++++++++ 3 files changed, 40 insertions(+), 4 deletions(-) diff --git a/src/parametric/src/app/cam/simulate-panel.ts b/src/parametric/src/app/cam/simulate-panel.ts index f4f211b2e..23a0a7e24 100644 --- a/src/parametric/src/app/cam/simulate-panel.ts +++ b/src/parametric/src/app/cam/simulate-panel.ts @@ -190,7 +190,7 @@ export class SimulationPanel extends CamPanel { this.phase = 'Simulating...'; this.app.refreshPanel(); try { - const res = await ws.client.simulate(setup, { steps, rapidFeed: cam.post.rapidFeed }, (v) => { + const res = await ws.simulate(setup, { steps, rapidFeed: cam.post.rapidFeed }, (v) => { this.progress = v; const bar = this.el.querySelector('progress'); if (bar) bar.value = v; @@ -331,7 +331,7 @@ export class SimulationPanel extends CamPanel { this.disposed = true; this.playing = false; cancelAnimationFrame(this.raf); - this.ws.client.cancel(); + this.ws.cancelSimulation(); this.app.renderer.setSolid('camStock', null); this.app.renderer.setSolid('camTool', null); this.app.showModelMesh(); diff --git a/src/parametric/src/app/cam/workspace.ts b/src/parametric/src/app/cam/workspace.ts index db790f411..bbc67b1a7 100644 --- a/src/parametric/src/app/cam/workspace.ts +++ b/src/parametric/src/app/cam/workspace.ts @@ -4,7 +4,8 @@ // toolpaths, stock and work origin drawn in the graphics area. import { CamCancelled, CamClient } from '../../cam/client'; -import { type GenerateJob, type ModelCylinder, stlTriangles } from '../../cam/engine'; +import { type GenerateJob, type ModelCylinder, type SimulateJob, stlTriangles } from '../../cam/engine'; +import type { SimResult } from '../../cam/simulate'; import { type MachineFrame, machineFrame, toModel } from '../../cam/frame'; import { PLUNGE, RAPID, type PathStats, type Toolpath, expandMoves, pathStats } from '../../cam/toolpath'; import type { Vec3 } from '../../math/vec'; @@ -67,6 +68,8 @@ export class CamWorkspace { readonly client = new CamClient(); /** A second worker for the preview of the operation being edited, so it never waits for (or stops) generation. */ private readonly previewClient = new CamClient(); + /** A third for simulation, so leaving a simulation never stops generation. */ + private readonly simClient = new CamClient(); private results = new Map(); private meshVersion = -1; private tris: Float32Array | null = null; @@ -104,6 +107,7 @@ export class CamWorkspace { private reset() { this.client.cancel(); this.previewClient.cancel(); + this.simClient.cancel(); this.results.clear(); this.tris = null; this.meshVersion = -1; @@ -149,7 +153,7 @@ export class CamWorkspace { this.tris = tris.length ? tris : null; this.meshVersion = version; this.frames.clear(); - if (this.tris) for (const c of [this.client, this.previewClient]) c.setMesh(`g${version}`, this.tris); + if (this.tris) for (const c of [this.client, this.previewClient, this.simClient]) c.setMesh(`g${version}`, this.tris); return this.tris; } catch { return null; @@ -328,6 +332,16 @@ export class CamWorkspace { this.previewClient.cancel(); } + /** Simulates a setup's steps (in the simulation's own worker). */ + simulate(setup: CamSetup, job: SimulateJob, progress?: (v: number) => void): Promise { + return this.simClient.simulate(setup, job, progress); + } + + /** Stops a simulation in progress (generation goes on). */ + cancelSimulation() { + this.simClient.cancel(); + } + /** Stops generation in progress. */ cancel() { this.client.cancel(); diff --git a/src/parametric/tests/e2e/cam.spec.ts b/src/parametric/tests/e2e/cam.spec.ts index da9984b90..c8332ca88 100644 --- a/src/parametric/tests/e2e/cam.spec.ts +++ b/src/parametric/tests/e2e/cam.spec.ts @@ -69,6 +69,28 @@ test('machines a part from the CAM tab: setup, tools, operations, simulation and expect(await page.getByLabel('Playback speed').evaluate((s) => [...(s as HTMLSelectElement).options].filter((o) => o.defaultSelected).length)).toBe(1); await page.getByRole('button', { name: 'Exit Simulation' }).click(); + // Leaving a simulation while toolpaths are being generated does not stop the generation. + expect(await page.evaluate(async () => { + const app = (window as unknown as W).__parametric; + const ws = app.cam!; + const s = app.store.doc.cam!.setups[0]; + const stopped: string[] = []; + const generate = ws.client.generate.bind(ws.client); + ws.client.generate = (job, progress) => { + const p = generate(job, progress); + p.catch((e: Error) => stopped.push(`${job.op.name}: ${e.message}`)); + return p; + }; + ws.forget(s.ops.map((o) => o.id)); + const done = ws.generate(); + app.commands.run('cam:simulate'); + while (!ws.busy) await new Promise((r) => setTimeout(r, 10)); + await app.closePanel(false); + await done; + ws.client.generate = generate; + return stopped; + })).toEqual([]); + // G-code with peck drilling cycles, downloaded. await page.locator('[data-cmd="cam:post"]').click(); const post = page.getByRole('dialog', { name: 'Post Process' }); From 1959f2241659621a6c55090c34a36f22350125f6 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 12:03:52 -0700 Subject: [PATCH 33/34] Parametric CAM: the face picked for a setup's direction stays in its box The panel redrew with the box empty right after the pick; choosing another direction clears it. --- src/parametric/src/app/cam/panels.ts | 8 +++++++- src/parametric/tests/e2e/cam.spec.ts | 13 +++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/parametric/src/app/cam/panels.ts b/src/parametric/src/app/cam/panels.ts index fe65c5b3d..c6f967e91 100644 --- a/src/parametric/src/app/cam/panels.ts +++ b/src/parametric/src/app/cam/panels.ts @@ -82,6 +82,8 @@ export class SetupPanel extends CamPanel { helpText = 'Where the part sits on the machine: the direction the tool comes from, the stock around the part and the work origin (G54).'; private s: CamSetup; private dirty = false; + /** The flat face picked for the direction, shown in its box while the direction is its own. */ + private topFace: SelBoxItem[] = []; constructor(private app: App, private ws: CamWorkspace, setup: CamSetup, private readonly isNew: boolean) { super(); @@ -112,9 +114,13 @@ export class SetupPanel extends CamPanel { const s = this.s; const ctx = this.app.unitContext(); const face = new SelectionBox(this, 'Top face (sets the direction)', { face: true, planarOnly: true }, (it) => this.toFace(it), (items) => { + this.topFace = items; const f = items[0]?.data as { axis: CamAxis } | undefined; if (f) { s.axis = f.axis; this.changed(); this.app.refreshPanel(); } }, { single: true, placeholder: 'Optional: a flat face facing the tool', icon: 'camSetup' }); + // Redrawn with the direction it set (a direction chosen since replaces it). + if ((this.topFace[0]?.data as { axis: CamAxis } | undefined)?.axis !== s.axis) this.topFace = []; + face.setItems(this.topFace); const stock = s.stock; const offsets = h('div', {}, len('Sides', stock.side, ctx, (v) => { stock.side = v; this.changed(); }), @@ -133,7 +139,7 @@ export class SetupPanel extends CamPanel { return [ section('Setup', [ nameField('Name', s.name, (v) => { s.name = v; this.dirty = true; }), - selectField('Tool direction', s.axis, AXES, (v) => { s.axis = v; this.changed(); }, 'camSetup'), + selectField('Tool direction', s.axis, AXES, (v) => { s.axis = v; this.topFace = []; face.setItems([]); this.changed(); }, 'camSetup'), face.el, h('div', { class: 'field-label' }, 'Turn about the tool'), segmented('Turn about the tool', String(s.rotation) as '0', [0, 90, 180, 270].map((a) => ({ value: String(a) as '0', label: `${a}°` })), (v) => { s.rotation = Number(v); this.changed(); }), diff --git a/src/parametric/tests/e2e/cam.spec.ts b/src/parametric/tests/e2e/cam.spec.ts index c8332ca88..d7c8acfe3 100644 --- a/src/parametric/tests/e2e/cam.spec.ts +++ b/src/parametric/tests/e2e/cam.spec.ts @@ -118,6 +118,19 @@ test('CAM panels follow the tool library, deletions and the post settings', asyn await page.waitForFunction(() => !!(window as unknown as W).__parametric.bbox); await page.getByRole('tab', { name: 'CAM' }).click(); await page.locator('[data-cmd="cam:setup"]').click(); + // A flat face picked for the direction stays in its box; choosing a direction clears it. + await expect(page.getByRole('heading', { name: 'New Setup' })).toBeVisible(); + await page.evaluate(() => { + const app = (window as unknown as W).__parametric; + const i = app.faces.findIndex((f) => f.type === 'plane' && f.normal![1] < -0.99); + app.panel!.onPick({ kind: 'face', index: i, name: app.faces[i].name }, false); + }); + await expect(page.getByLabel('Tool direction')).toHaveValue('-Y'); + const placeholder = page.locator('.pm-content').getByText('Optional: a flat face facing the tool'); + await expect(placeholder).toBeHidden(); + await expect(page.locator('.pm-content').getByText(/^Face \(plane\)/)).toBeVisible(); + await page.getByLabel('Tool direction').selectOption('+Y'); + await expect(placeholder).toBeVisible(); await page.locator('.confirm-corner .ok').click(); // A smaller tool chosen in the tool library while the operation is open previews again. From d18aa5b348ed601f4bbd49c652054c938d8875e2 Mon Sep 17 00:00:00 2001 From: Nariman Jelveh Date: Fri, 27 Nov 2026 12:06:43 -0700 Subject: [PATCH 34/34] Parametric CAM: simulate again when the tool library changes while the simulation is open The panel kept showing the stock cut by the old tools. --- src/parametric/src/app/cam/simulate-panel.ts | 28 +++++++++++++++++--- src/parametric/tests/e2e/cam.spec.ts | 12 +++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/src/parametric/src/app/cam/simulate-panel.ts b/src/parametric/src/app/cam/simulate-panel.ts index 23a0a7e24..048de4701 100644 --- a/src/parametric/src/app/cam/simulate-panel.ts +++ b/src/parametric/src/app/cam/simulate-panel.ts @@ -166,10 +166,32 @@ export class SimulationPanel extends CamPanel { return this.ws.cam?.setups.find((s) => s.id === this.setupId) ?? null; } + /** Each start replaces the one before (the tool library changed). */ + private runs = 0; + + /** The tools changed: what was simulated no longer holds, so the setup is simulated again. */ + toolsChanged() { + this.runs++; + this.ws.cancelSimulation(); + this.play(false); + this.res = null; + this.error = null; + this.progress = 0; + this.phase = 'Generating toolpaths...'; + this.tools = []; + this.names = []; + this.shownSnap = -1; + this.setMessage(null); + this.app.renderer.setSolid('camStock', null); + this.app.renderer.setSolid('camTool', null); + void this.start(); + } + private async start() { const ws = this.ws; + const run = ++this.runs; await ws.generate([this.setupId]); - if (this.disposed) return; + if (this.disposed || run !== this.runs) return; const setup = this.setup(); const cam = ws.cam; if (!setup || !cam) return; @@ -195,7 +217,7 @@ export class SimulationPanel extends CamPanel { const bar = this.el.querySelector('progress'); if (bar) bar.value = v; }); - if (this.disposed) return; + if (this.disposed || run !== this.runs) return; this.res = res; this.frame = ws.frameOf(setup); this.t = res.time; @@ -203,7 +225,7 @@ export class SimulationPanel extends CamPanel { this.showAt(this.t); this.app.refreshPanel(); } catch (e) { - if (this.disposed || e instanceof CamCancelled) return; + if (this.disposed || run !== this.runs || e instanceof CamCancelled) return; this.error = (e as Error).message; this.app.refreshPanel(); } diff --git a/src/parametric/tests/e2e/cam.spec.ts b/src/parametric/tests/e2e/cam.spec.ts index d7c8acfe3..fa3deb8d8 100644 --- a/src/parametric/tests/e2e/cam.spec.ts +++ b/src/parametric/tests/e2e/cam.spec.ts @@ -226,6 +226,18 @@ test('CAM panels follow the tool library, deletions and the post settings', asyn const fs = await import('node:fs'); expect(new TextDecoder().decode(fs.readFileSync((await file.path())!))).not.toContain('O1002'); + // The simulation runs again with the tool chosen in the tool library while it is open. + await page.locator('[data-cmd="cam:simulate"]').click(); + const removed = page.locator('.cam-stats tr', { hasText: 'Material removed' }).locator('td'); + await expect(removed).toBeVisible({ timeout: 90_000 }); + const removedBefore = await removed.innerText(); + await page.locator('[data-cmd="cam:tools"]').click(); + await tools.getByRole('textbox', { name: 'Diameter' }).fill('6'); + await tools.getByRole('textbox', { name: 'Diameter' }).press('Tab'); + await tools.getByRole('button', { name: 'OK' }).click(); + await expect(removed).not.toHaveText(removedBefore, { timeout: 90_000 }); + await page.getByRole('button', { name: 'Exit Simulation' }).click(); + // An operation deleted from the tree while its panel is open is not brought back by OK. await page.getByRole('treeitem', { name: /^Contour1/ }).dblclick(); await expect(page.getByRole('heading', { name: 'Contour1' })).toBeVisible();