From 697980e9acff6d506943726300475e0d883fe519 Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:07:23 -0700 Subject: [PATCH 01/26] Flat: tests for contour-parallel passes, outside in (#38) --- python/tests/test_flat_offset.py | 341 +++++++++++++++++++++++++++++++ 1 file changed, 341 insertions(+) create mode 100644 python/tests/test_flat_offset.py diff --git a/python/tests/test_flat_offset.py b/python/tests/test_flat_offset.py new file mode 100644 index 0000000..dadb07b --- /dev/null +++ b/python/tests/test_flat_offset.py @@ -0,0 +1,341 @@ +"""Flat-area finishing in contour-parallel passes, outside in (#38). + +Every check here is measured on the motion stream and the simulated stock +against analytic parts, independently of the planner. +""" + +import math +import unittest + +import numpy as np + +import camlib +from camlib.cadquery import export_stock_mesh, export_surface_mesh +from camlib.simulation import OperationUpdate, Simulation, Update +from camlib.tools import HolderSection, ToolAssembly + +R = 2.0 # cutter radius +STEPOVER = 1.5 +CELL = 0.25 + + +def tool(): + return ToolAssembly( + "mill4", + camlib.EndMill("em4", diameter=4, flute_length=20, overall_length=50), + 30, + 60, + (HolderSection(30, 60, 4, 4),), + ) + + +# Parts as unions of boxes (x0, y0, z0, x1, y1, z1), with pockets cut out. +# `boxes` are added, `pockets` removed, `bosses` added after the pockets. +STEPPED = dict( + boxes=[(0, 0, 0, 24, 16, 4)], + pockets=[], + bosses=[(8, 4, 4, 16, 12, 7)], + extent=(0, 0, 24, 16), +) +# A block with a pocket; in the pocket a short island and, 3 mm beside it +# (narrower than the 4 mm tool), a boss standing well above the block. +ISLAND = dict( + boxes=[(0, 0, 0, 30, 20, 6)], + pockets=[(3, 3, 3, 27, 17, 6)], + bosses=[(7, 8, 3, 13, 12, 5), (16, 8, 3, 20, 12, 9)], + extent=(0, 0, 30, 20), +) + + +def solid(spec, skin=0.0): + """The part, or with `skin` mm left on every flat (walls to size): the + blank a flat finishing pass meets after roughing.""" + import cadquery as cq + + def box(b, top_skin): + x0, y0, z0, x1, y1, z1 = b + return cq.Workplane("XY").box(x1 - x0, y1 - y0, z1 - z0 + top_skin, centered=False).translate((x0, y0, z0)) + + shape = None + for b in spec["boxes"]: + s = box(b, skin) + shape = s if shape is None else shape.union(s) + for p in spec["pockets"]: + x0, y0, z0, x1, y1, z1 = p + shape = shape.cut(box((x0, y0, z0 + skin, x1, y1, z1 + skin + 1), 0)) + for b in spec["bosses"]: + shape = shape.union(box(b, skin)) + return shape + + +def height(spec, x, y): + """Analytic top of the part at (x, y) (numpy arrays).""" + h = np.zeros(np.broadcast(x, y).shape) + inside = lambda r: (x >= r[0]) & (x <= r[3]) & (y >= r[1]) & (y <= r[4]) # noqa: E731 + for b in spec["boxes"]: + h = np.where(inside(b), np.maximum(h, b[5]), h) + for p in spec["pockets"]: + strict = (x > p[0]) & (x < p[3]) & (y > p[1]) & (y < p[4]) + h = np.where(strict, p[2], h) + for b in spec["bosses"]: + h = np.where(inside(b), np.maximum(h, b[5]), h) + return h + + +class Field: + """The part sampled on a fine grid: distance from a point to the part + standing above a height.""" + + def __init__(self, spec, step=0.05): + x0, y0, x1, y1 = spec["extent"] + xs = np.arange(x0, x1 + step / 2, step) + ys = np.arange(y0, y1 + step / 2, step) + self.X, self.Y = np.meshgrid(xs, ys) + self.H = height(spec, self.X, self.Y) + self.step = step + self._above = {} + + def above(self, z): + key = round(z, 6) + if key not in self._above: + m = self.H > z + 1e-6 + self._above[key] = np.stack([self.X[m], self.Y[m]], axis=1) + return self._above[key] + + def clearance(self, p, z): + """XY distance from p to the part above z (inf if none); exact to + the sampling step.""" + pts = self.above(z) + if len(pts) == 0: + return math.inf + return float(np.min(np.hypot(pts[:, 0] - p[0], pts[:, 1] - p[1]))) + + +def flat_op(spec, entry=camlib.RampEntry(angle_deg=3, min_length_mm=1), **changes): + surface = export_surface_mesh(solid(spec), source=dict(model="flat-offset", revision="1")) + t = tool() + op = camlib.Flat( + "flats", + t, + surface, + 0, + STEPOVER, + 14, + feed_mm_min=600, + plunge_mm_min=150, + spindle_rpm=12000, + tool_number=1, + length_register=1, + coolant="flood", + entry=entry, + **changes, + ) + return t, op + + +def run(spec, skin=0.1): + """Run Flat on the roughed blank; return (report, motions, stock + snapshots before each motion as (nx, ny, dx, dy, heights), final state).""" + t, op = flat_op(spec) + stock = camlib.StockSpec.from_mesh(export_stock_mesh(solid(spec, skin)), CELL) + motions, before = [], [] + report = None + with Simulation( + stock=stock, + tools=(t,), + operations=(op,), + revision="1", + initial_position_mm=(0, 0, 14), + verification=camlib.StreamChecks(stock_contact=camlib.StockContactOptions()), + ) as sim: + s = sim.state + snapshot = list(s.heights) + for update in sim.run_operations(): + if isinstance(update, OperationUpdate) and update.stage == "end": + report = update.report + if isinstance(update, Update): + motions.append(update.motion) + before.append(snapshot) + snapshot = list(s.heights) + assert sim.state.finished + grid = (s.nx, s.ny, s.dx, s.dy, tuple(s.min_mm)) + final = list(s.heights) + return report, motions, before, grid, final + + +def stock_top_near(grid, heights, p, radius): + """Highest stock cell upper bound whose cell rectangle comes within + `radius` of p (what the tool's disk at p can touch).""" + nx, ny, dx, dy, lo = grid + top = -math.inf + for j in range(ny): + for i in range(nx): + x0, y0 = lo[0] + i * dx, lo[1] + j * dy + ex = max(x0 - p[0], 0, p[0] - (x0 + dx)) + ey = max(y0 - p[1], 0, p[1] - (y0 + dy)) + if math.hypot(ex, ey) < radius: + top = max(top, heights[2 * (j * nx + i) + 1]) + return top + + +def points(m, n=None): + c = m["curve"] + a, b = c["start"], c["end"] + length = math.hypot(b[0] - a[0], b[1] - a[1]) + n = n or max(2, int(length / 0.05) + 1) + return [[a[k] + (b[k] - a[k]) * i / (n - 1) for k in range(3)] for i in range(n)] + + +def vertical_plunges(motions): + out = [] + for m in motions: + a, b = m["curve"]["start"], m["curve"]["end"] + if m["kind"] == "plunge" and math.hypot(b[0] - a[0], b[1] - a[1]) < 1e-9: + out.append(m) + return out + + +def level_cuts(motions, z): + return [ + m + for m in motions + if m["kind"] in ("cut", "link", "lead") + and all(abs(p[2] - z) < 1e-6 for p in (m["curve"]["start"], m["curve"]["end"])) + ] + + +def seg_distance(p, a, b): + ax, ay, bx, by = a[0], a[1], b[0], b[1] + vx, vy = bx - ax, by - ay + l2 = vx * vx + vy * vy + t = 0 if l2 == 0 else max(0, min(1, ((p[0] - ax) * vx + (p[1] - ay) * vy) / l2)) + return math.hypot(p[0] - ax - t * vx, p[1] - ay - t * vy) + + +def rect_outline_distance(p, r): + """Distance from p to the outline of rectangle r = (x0, y0, x1, y1).""" + x0, y0, x1, y1 = r + inside = x0 <= p[0] <= x1 and y0 <= p[1] <= y1 + if inside: + return min(p[0] - x0, x1 - p[0], p[1] - y0, y1 - p[1]) + return math.hypot(max(x0 - p[0], 0, p[0] - x1), max(y0 - p[1], 0, p[1] - y1)) + + +_cache = {} + + +def cached(name): + if name not in _cache: + _cache[name] = run({"stepped": STEPPED, "island": ISLAND}[name]) + return _cache[name] + + +class FlatOffsetTest(unittest.TestCase): + def test_each_edge_ring_is_entered_once(self): + # Entries are the vertical plunges. A connected flat is entered once + # per ring along its edge or a wall it cannot link across: the + # stepped part has three (the boss top's edge, the base's outer edge + # and the base's ring round the boss). Today: one per raster run. + report, motions, *_ = cached("stepped") + plunges = len(vertical_plunges(motions)) + self.assertLessEqual(plunges, 3, f"{plunges} entries; runs={report['runs']}") + self.assertEqual(plunges, report["runs"]) + self.assertGreater(report.get("links_at_depth", 0), 0) + + def test_open_edges_are_entered_from_the_side_in_air(self): + # The boss top and the base's outer edge are open: their first ring + # is entered by a vertical plunge where the tool's disk touches no + # stock above the plunge's end (measured on the stock before the + # move), then a horizontal lead into the ring. Only the ring round + # the boss (walled, 0.1 mm skin left on the flat) may need a ramp. + report, motions, before, grid, _ = cached("stepped") + in_air = 0 + for m in vertical_plunges(motions): + b = m["curve"]["end"] + top = stock_top_near(grid, before[motions.index(m)], b, R) + if top <= b[2] + 1e-6: + in_air += 1 + self.assertGreaterEqual(in_air, 2, f"in-air entries {in_air}") + self.assertLessEqual(report.get("ramped_entries", 0), 1) + + def test_first_ring_of_each_level_follows_its_edge(self): + # Outside in: the first loop cut at each level is the ring a radius + # outside the level's outer edge (boss top: the 8 x 8 boss; base: + # the 24 x 16 block), all the way round. + _, motions, *_ = cached("stepped") + for z, rect in ((7.0, (8, 4, 16, 12)), (4.0, (0, 0, 24, 16))): + cuts = [m for m in level_cuts(motions, z) if m["kind"] == "cut"] + self.assertTrue(cuts, z) + start = cuts[0]["curve"]["start"] + ring, travelled = [], 0.0 + for m in cuts: + ring.append(m) + a, b = m["curve"]["start"], m["curve"]["end"] + travelled += math.hypot(b[0] - a[0], b[1] - a[1]) + if travelled > 1 and math.hypot(b[0] - start[0], b[1] - start[1]) < 1e-6: + break + worst = max(abs(rect_outline_distance(p, rect) - R) for m in ring for p in points(m)) + self.assertLessEqual(worst, 0.01, f"Z{z}: first loop strays {worst:.4f} mm from the edge ring") + perimeter = 2 * (rect[2] - rect[0] + rect[3] - rect[1]) + 2 * math.pi * R + self.assertGreater(travelled, 0.98 * perimeter, f"Z{z}: first loop {travelled:.3f} of {perimeter:.3f} mm") + + def test_coverage_of_every_reachable_flat_point(self): + # Every flat point at least a radius (+0.01) from the part standing + # above it lies under the tool's disk on some cut at its level. + for name, spec in (("stepped", STEPPED), ("island", ISLAND)): + _, motions, *_ = cached(name) + field = Field(spec) + x0, y0, x1, y1 = spec["extent"] + worst = (0.0, None) + for x in np.arange(x0 + 0.125, x1, 0.25): + for y in np.arange(y0 + 0.125, y1, 0.25): + z = float(height(spec, np.array(x), np.array(y))) + if z <= 0 or field.clearance((x, y), z) < R + 0.01: + continue + segs = [(m["curve"]["start"], m["curve"]["end"]) for m in level_cuts(motions, z)] + d = min((seg_distance((x, y), a, b) for a, b in segs), default=math.inf) + if d > worst[0]: + worst = (d, (x, y, z)) + self.assertLessEqual( + worst[0], R - 1e-6, f"{name}: uncovered flat point {worst[1]} {worst[0]:.4f} mm from any cut" + ) + + def test_tool_never_reaches_into_the_part_above_its_tip(self): + # On every feed move (cut, link, lead, plunge, ramp) the tool's + # axis stays at least a radius (less 1e-4) from every part point + # above its tip: measured against the analytic part, including the + # tall boss 3 mm beside the island. + for name, spec in (("stepped", STEPPED), ("island", ISLAND)): + _, motions, *_ = cached(name) + field = Field(spec) + worst = (math.inf, None) + for m in motions: + if m["kind"] == "rapid": + continue + for p in points(m, 9): + c = field.clearance(p, p[2]) + if c < worst[0]: + worst = (c, (m["id"], m["kind"], [round(v, 4) for v in p])) + self.assertGreaterEqual( + worst[0], + R - 1e-4 - field.step, + f"{name}: tool reaches {R - worst[0]:.4f} mm into the part at {worst[1]}", + ) + + def test_never_cuts_below_the_part(self): + for name, spec in (("stepped", STEPPED), ("island", ISLAND)): + _, _, _, grid, final = cached(name) + nx, ny, dx, dy, lo = grid + worst = 0.0 + for j in range(ny): + for i in range(nx): + xs = np.array([lo[0] + i * dx, lo[0] + (i + 1) * dx]) + ys = np.array([lo[1] + j * dy, lo[1] + (j + 1) * dy]) + X, Y = np.meshgrid(xs, ys) + lowest = float(np.min(height(spec, X, Y))) + worst = max(worst, lowest - final[2 * (j * nx + i) + 1]) + self.assertLessEqual(worst, 1e-6, f"{name}: stock cut {worst:.4f} mm below the part") + + +if __name__ == "__main__": + unittest.main() From 1efec45388d2a0b4b162268da643eeec33cfede6 Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:03:15 -0700 Subject: [PATCH 02/26] WIP: flat contour-parallel offset passes (draft) --- src/flat.rs | 927 ++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 756 insertions(+), 171 deletions(-) diff --git a/src/flat.rs b/src/flat.rs index 99cef8a..fc5d18b 100644 --- a/src/flat.rs +++ b/src/flat.rs @@ -1,13 +1,16 @@ //! Flat-area finishing (the usual Flat/Horizontal strategy): finds the //! horizontal faces of a part and finishes each at its exact height with a -//! flat end mill, in raster rows, entering each run with a vertical plunge. +//! flat end mill, in contour-parallel passes that offset each flat's tool +//! centre region inward, outside in, linked at depth where the link is +//! proven, and entered from the side in air where a pass runs along an open +//! edge. //! //! Proof: every cut is a horizontal line at the cut height. It is kept only //! where the highest point of the part (and the machining base) under the //! tool's swept disk (a capsule in XY) is not above the cut height plus the //! tolerance. That maximum is computed exactly per triangle (a linear //! function over the convex triangle-capsule intersection peaks at one of its -//! extreme points); runs that fail are halved until they pass or vanish. +//! extreme points); chords that fail are halved until they pass or vanish. use crate::{ facing::TraverseAxis, motion::{Coolant, Curve, Event, Motion, MoveKind, SpindleDirection, Vec3}, @@ -101,8 +104,15 @@ pub struct FlatReport { pub strategy: &'static str, pub geometric_residual_status: ResidualStatus, pub levels_z_mm: Vec, + /// Loops cut (closed offset loops and the open stretches a loop was split + /// into by dropped chords). pub rows: usize, pub runs: usize, + /// Closed offset loops planned, before any chord was dropped. + pub loops: usize, + /// Links cut at depth between the passes of one chain. + #[serde(skip_serializing_if = "is_zero")] + pub links_at_depth: usize, pub cut_length_mm: f64, /// Row length near flats that could not be proven clear and was dropped. pub dropped_length_mm: f64, @@ -1506,11 +1516,52 @@ impl Index { } } -#[derive(Clone, Copy)] -struct Run { - a: [f64; 2], - b: [f64; 2], - z: f64, +/// One cut pass at a fixed height: the flattened polyline of a closed loop +/// (the last point repeats the first) or of the stretches of a loop that were +/// proven and allowed (an open piece). +struct Piece { + pts: Vec, +} +impl Piece { + fn start(&self) -> Vec3 { + self.pts[0] + } + fn end(&self) -> Vec3 { + self.pts[self.pts.len() - 1] + } + fn length(&self) -> f64 { + self.pts + .windows(2) + .map(|w| (w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1])) + .sum() + } + fn strokes(&self) -> Vec { + self.pts + .windows(2) + .map(|w| crate::pocket::Stroke::line([w[0][0], w[0][1]], [w[1][0], w[1][1]])) + .collect() + } +} + +/// One entry and the passes cut before the tool retracts: consecutive passes +/// are joined by links at depth. +struct Chain { + pieces: Vec, + /// Side-entry candidates of the first pass: vertices (at most one per + /// 1 mm of the pass) with the outward normal, away from the region (right + /// of travel). + side: Vec<([f64; 2], [f64; 2])>, +} + +/// How the chain is entered, decided against the live stock when reached. +enum Entry { + /// Vertical plunge in air at `p`, then a lead at cutting feed to the + /// pass's start. + Side { p: [f64; 2] }, + /// Vertical plunge at the pass's start. + Plunge, + /// Ramp down the first pass from the stock's top over it. + Ramp { top: f64, points: Vec }, } #[derive(Clone, Copy, PartialEq, Eq)] @@ -1518,10 +1569,11 @@ enum Phase { Lift, Approach, Descend, - Plunge, + Enter, + Lead, Ramp, Cut, - Retract, + PieceEnd, Rise, Done, } @@ -1530,10 +1582,17 @@ pub struct FlatPlan { op: FlatOperation, spec: StockSpec, heights: crate::heights::Heights, - runs: Vec, - run: usize, + index: Index, + seen: Vec, + stamp: u32, + chains: Vec, + chain: usize, + piece: usize, + vertex: usize, phase: Phase, radius: f64, + limits: Option, + entry: Option, ramp: std::collections::VecDeque, initial: Vec3, position: Vec3, @@ -1697,148 +1756,145 @@ impl FlatPlan { l.0, cutter.cutting_length_mm )); } - let axis = if op.axis == TraverseAxis::X { 0 } else { 1 }; - let cross = 1 - axis; let region_limits = op .limits .as_ref() .filter(|l| !l.is_empty()) .map(|l| crate::limits::PreparedLimits::new(l, r, op.tolerance_mm)) .transpose()?; - let mut seen = vec![0u32; index.tris.len()]; + // The part as a height field over XY, for the per-chord proofs and the + // side entries' leads. + let target = crate::roughing::PreparedRoughingTarget::prepare( + op.surface.clone(), + op.tolerance_mm, + cancel, + )?; + let mut seen = vec![0u32; index.len()]; let mut stamp = 0u32; - let mut runs = vec![]; - let (mut rows, mut dropped) = (0usize, 0f64); - for &(level, lo, hi) in &levels { + let h = op.stepover_mm.min(r) / 4.; + let mut chains: Vec = vec![]; + let (mut rows, mut loops, mut links, mut dropped) = (0usize, 0usize, 0usize, 0f64); + let mut tool_xy = [initial[0], initial[1]]; + for &(level, _, _) in &levels { + if cancel.is_cancelled() { + return Err("flat-area planning cancelled".into()); + } let z = level + op.stock_to_leave_mm; - let (c0, c1) = (lo[cross] - r, hi[cross] + r); - let (a0, a1) = (lo[axis] - r, hi[axis] + r); - let intervals = ((c1 - c0) / op.stepover_mm).ceil().max(1.) as usize; - let pitch = (c1 - c0) / intervals as f64; - let h = op.stepover_mm.min(r) / 4.; - let samples = ((a1 - a0) / h).ceil().max(1.) as usize; - crate::resources::check_memory( - (intervals as u128 + 1) * (samples as u128 + 1) * 8, - "flat-area rows", - )?; - for row in 0..=intervals { - if cancel.is_cancelled() { - return Err("flat-area planning cancelled".into()); - } - let c = c0 + row as f64 * pitch; - let point = |s: usize| { - let mut p = [0.; 2]; - p[axis] = a0 + (a1 - a0) * s as f64 / samples as f64; - p[cross] = c; - p - }; - // Samples where the tool rests on this flat. - let on = |p: [f64; 2], seen: &mut [u32], stamp: &mut u32| { - let height = index.max_height(p, p, r, seen, stamp); - (height - level).abs() <= op.level_tolerance_mm - }; - let mut row_runs = vec![]; - let mut start = None; - for s in 0..=samples { - let inside = on(point(s), &mut seen, &mut stamp); - match (inside, start) { - (true, None) => start = Some(s), - (false, Some(s0)) => { - if s - 1 > s0 { - row_runs.push((point(s0), point(s - 1))); - } - start = None; - } - _ => {} - } - } - if let Some(s0) = start - && samples > s0 - { - row_runs.push((point(s0), point(samples))); - } - if row_runs.is_empty() { - continue; - } - rows += 1; - if rows % 2 == 0 { - row_runs.reverse(); - for run in &mut row_runs { - *run = (run.1, run.0); + // The tool centres resting on this level, as a planar region. + let Some(region) = + level_region(&target, level, op.level_tolerance_mm, r, op.tolerance_mm, cancel)? + else { + continue; + }; + // Offset loops per connected component, outside in. + let groups = level_loops(®ion, r, op.stepover_mm, op.tolerance_mm, cancel)?; + let level_chains = chains.len(); + // Nearest component first. + let mut order: Vec = (0..groups.len()).collect(); + order.sort_by(|&a, &b| { + groups[a] + .distance(tool_xy) + .total_cmp(&groups[b].distance(tool_xy)) + .then(a.cmp(&b)) + }); + for gi in order { + for ring in groups[gi].ordered(tool_xy) { + if cancel.is_cancelled() { + return Err("flat-area planning cancelled".into()); } - } - // Prove each run; halve failures down to h / 16. - let mut stack: Vec<([f64; 2], [f64; 2], u32)> = - row_runs.into_iter().rev().map(|(a, b)| (a, b, 0)).collect(); - while let Some((a, b, depth)) = stack.pop() { - let length = (b[0] - a[0]).hypot(b[1] - a[1]); - if index.max_height(a, b, r, &mut seen, &mut stamp) <= z + op.tolerance_mm { - let Some(limits) = ®ion_limits else { - runs.push(Run { a, b, z }); - continue; + loops += 1; + // Each closed loop starts at its vertex nearest the tool. + let ring = rotate_to_nearest(ring, tool_xy); + // Prove each chord; halve failures down to h / 16, keep + // only the stretches inside the limits. + let pieces = prove_ring( + &ring, + z, + r, + &index, + &mut seen, + &mut stamp, + h, + op.tolerance_mm, + region_limits.as_ref(), + &mut dropped, + cancel, + )?; + for piece in pieces { + rows += 1; + // Consecutive passes join into one chain by a link at + // depth when the link is short, proven and allowed; + // otherwise the chain ends and a new one begins. + let linked = chains.len() > level_chains && { + let prev = chains[chains.len() - 1].pieces.last().unwrap().end(); + let next = piece.start(); + let length = (next[0] - prev[0]).hypot(next[1] - prev[1]); + length <= 2. * op.stepover_mm + && index.max_height( + [prev[0], prev[1]], + [next[0], next[1]], + r, + &mut seen, + &mut stamp, + ) <= z + op.tolerance_mm + && allows_segment( + region_limits.as_ref(), + [prev[0], prev[1]], + [next[0], next[1]], + z, + op.tolerance_mm, + )? }; - // Only the stretches proven inside the limits. - let line = crate::motion::Curve::Line { - start: [a[0], a[1], z], - end: [b[0], b[1], z], - }; - let mut kept = 0.; - for [t0, t1] in limits.allowed_spans(&line, true)? { - let at = |t: f64| [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])]; - let (p, q) = (at(t0), at(t1)); - if (q[0] - p[0]).hypot(q[1] - p[1]) > op.tolerance_mm { - runs.push(Run { a: p, b: q, z }); - kept += (t1 - t0) * length; - } + if linked { + let last = chains.len() - 1; + chains[last].pieces.push(piece); + links += 1; + } else { + let side = side_candidates(&piece); + chains.push(Chain { + pieces: vec![piece], + side, + }); } - dropped += length - kept; - continue; - } - if length <= h / 16. || depth >= 32 { - dropped += length; - continue; + let end = chains[chains.len() - 1].pieces.last().unwrap().end(); + tool_xy = [end[0], end[1]]; } - let m = [(a[0] + b[0]) / 2., (a[1] + b[1]) / 2.]; - stack.push((m, b, depth + 1)); - stack.push((a, m, depth + 1)); } } } - // Rejoin halves that were both proven (same line, touching). - let mut merged: Vec = Vec::with_capacity(runs.len()); - for run in runs { - if let Some(last) = merged.last_mut() - && last.b == run.a - && last.z == run.z - { - last.b = run.b; - continue; - } - merged.push(run); - } let report = FlatReport { strategy: "flat", geometric_residual_status: ResidualStatus::Pending, levels_z_mm: levels.iter().map(|l| l.0).collect(), rows, - runs: merged.len(), - cut_length_mm: merged + runs: chains.len(), + loops, + links_at_depth: links, + cut_length_mm: chains .iter() - .map(|r| (r.b[0] - r.a[0]).hypot(r.b[1] - r.a[1])) + .flat_map(|c| c.pieces.iter()) + .map(Piece::length) .sum(), dropped_length_mm: dropped, runs_completed: 0, ramped_entries: 0, - clearance_proof: "exact maximum part height under each horizontal cut's swept disk (triangle-capsule extreme points) at most the cut height plus tolerance; vertical entries above proven runs", + clearance_proof: "exact maximum part height under each horizontal cut's swept disk (triangle-capsule extreme points) at most the cut height plus tolerance; contour-parallel offset passes outside in, side entry in air on open edges, links at depth and when chains break", }; Ok(Self { op, spec: spec.clone(), heights, - runs: merged, - run: 0, + index, + seen, + stamp: 0, + chains, + chain: 0, + piece: 0, + vertex: 0, phase: Phase::Lift, radius: r, + limits: region_limits, + entry: None, ramp: Default::default(), initial, position: initial, @@ -1851,35 +1907,37 @@ impl FlatPlan { pub fn report(&self) -> &FlatReport { &self.report } - /// What enters the run at `run.a` after the rapid descent: a straight - /// plunge where no live stock stands above the run's height there (the + /// What enters the pass at its start after the rapid descent: a straight + /// plunge where no live stock stands above the pass's height there (the /// cells' upper bounds, within a tolerance), otherwise a ramp from the - /// stock's top over the whole run, down the run by the declared - /// `RampEntry`. Each ramp point lies vertically above the proven run, so - /// it clears the part as the run does. A run the ramp does not fit, or - /// stock above a run with no entry declared, is refused: a flat end mill + /// stock's top over the whole pass, down the pass by the declared + /// `RampEntry`. Each ramp point lies vertically above the proven pass, so + /// it clears the part as the pass does. A pass the ramp does not fit, or + /// stock above a pass with no entry declared, is refused: a flat end mill /// is never plunged into stock. fn plunge_or_ramp( &self, - run: Run, + piece: &Piece, stock: &Stock, cancel: &impl CancelSignal, ) -> Result)>, String> { - let at_start = stock.top_under_disk(run.a, self.radius); - if at_start <= run.z + self.op.tolerance_mm { + let a = piece.start(); + let at_start = stock.top_under_disk([a[0], a[1]], self.radius); + if at_start <= a[2] + self.op.tolerance_mm { return Ok(None); } - let length = (run.b[0] - run.a[0]).hypot(run.b[1] - run.a[1]); - let top = run_stock_top(stock, run, self.radius, cancel)?; + let length = piece.length(); + let top = piece_stock_top(piece, stock, self.radius, cancel)?; + let b = piece.end(); let which = format!( "flat-area run from ({:.3}, {:.3}) to ({:.3}, {:.3}) at Z{:.3}, {length:.3} mm long, has stock up to Z{top:.3} ({:.3} mm above it, {:.3} mm above it at its start)", - run.a[0], - run.a[1], - run.b[0], - run.b[1], - run.z, - top - run.z, - at_start - run.z + a[0], + a[1], + b[0], + b[1], + a[2], + top - a[2], + at_start - a[2] ); let Some(entry) = self.op.entry.as_ref().and_then(|e| e.ramp()) else { return Err(format!( @@ -1897,20 +1955,78 @@ impl FlatPlan { self.heights.feed )); } - let chain = [crate::pocket::Stroke::line(run.a, run.b)]; + let chain = piece.strokes(); let curves = entry - .zigzag(&chain, top, run.z) + .zigzag(&chain, top, a[2]) .map_err(|why| format!("{which}: {why}. Use a steeper declared angle, a longer run, or rough this area first"))?; let mut points = vec![]; - let first = curves.first().map_or(run.a, |c| { + let first = curves.first().map_or([a[0], a[1]], |c| { let q = c.start(); [q[0], q[1]] }); - // Over the run at the stock's top, then down the legs. + // Over the pass at the stock's top, then down the legs. points.push([first[0], first[1], top]); points.extend(curves.iter().map(|c| c.end())); Ok(Some((top, points))) } + /// How the current chain is entered, decided against the live stock: from + /// the side in air where the first pass runs along an open edge (the + /// plunge point's disk touches no stock above the cut and the lead is + /// proven and allowed), otherwise the declared rule (`plunge_or_ramp`). + fn decide_entry(&mut self, stock: &Stock, cancel: &impl CancelSignal) -> Result { + let piece = &self.chains[self.chain].pieces[self.piece]; + let z = piece.start()[2]; + let tol = self.op.tolerance_mm; + let closed = piece.pts.first() == piece.pts.last(); + let mut best: Option<([f64; 2], [f64; 2])> = None; + for (v, n) in &self.chains[self.chain].side { + if cancel.is_cancelled() { + return Err("flat-area planning cancelled".into()); + } + if !closed && *v != [piece.pts[0][0], piece.pts[0][1]] { + continue; + } + // Outward, trying the shortest offset first. + for l in [0.25 * self.radius, 0.5 * self.radius, self.radius, 1.5 * self.radius, 2. * self.radius] { + let p = [v[0] + l * n[0], v[1] + l * n[1]]; + if stock.top_under_disk(p, self.radius) > z + tol { + continue; + } + if self.index.max_height(p, *v, self.radius, &mut self.seen, &mut self.stamp) + > z + tol + { + continue; + } + if !allows_segment(self.limits.as_ref(), p, *v, z, tol)? { + continue; + } + let nearer = best.map_or(true, |(bv, _)| { + (v[0] - self.position[0]).hypot(v[1] - self.position[1]) + < (bv[0] - self.position[0]).hypot(bv[1] - self.position[1]) + }); + if nearer { + best = Some((*v, p)); + } + break; + } + } + if let Some((v, p)) = best { + // The loop is cut from the entry vertex. + if closed && (piece.pts[0][0] != v[0] || piece.pts[0][1] != v[1]) { + let piece = &mut self.chains[self.chain].pieces[self.piece]; + rotate_piece(piece, v); + } + return Ok(Entry::Side { p }); + } + let piece = &self.chains[self.chain].pieces[self.piece]; + match self.plunge_or_ramp(piece, stock, cancel)? { + None => Ok(Entry::Plunge), + Some((top, points)) => { + self.report.ramped_entries += 1; + Ok(Entry::Ramp { top, points }) + } + } + } pub fn prefix_events(&self) -> Vec { vec![ Event::WorkOffset { @@ -1977,37 +2093,60 @@ impl FlatPlan { Phase::Lift => ( [p[0], p[1], self.heights.clearance], MoveKind::Rapid, - if self.runs.is_empty() { + if self.chains.is_empty() { Phase::Done } else { Phase::Approach }, ), Phase::Approach => { - let a = self.runs[self.run].a; - ([a[0], a[1], p[2]], MoveKind::Rapid, Phase::Descend) + // The entry is decided here, against the live stock: the + // rapid goes over the plunge point (a side entry) or the + // pass's start. + let entry = self.decide_entry(stock, cancel)?; + let over = match &entry { + Entry::Side { p: over } => *over, + _ => { + let a = self.chains[self.chain].pieces[self.piece].start(); + [a[0], a[1]] + } + }; + self.entry = Some(entry); + ([over[0], over[1], p[2]], MoveKind::Rapid, Phase::Descend) } Phase::Descend => ( [p[0], p[1], self.heights.feed], MoveKind::Rapid, - Phase::Plunge, + Phase::Enter, ), - Phase::Plunge => { - let run = self.runs[self.run]; - match self.plunge_or_ramp(run, stock, cancel)? { - Some((top, points)) => { + Phase::Enter => { + let a = self.chains[self.chain].pieces[self.piece].start(); + match self.entry.take().expect("entry plan") { + Entry::Side { .. } => ( + [p[0], p[1], a[2]], + MoveKind::Plunge, + Phase::Lead, + ), + Entry::Plunge => ([p[0], p[1], a[2]], MoveKind::Plunge, Phase::Cut), + Entry::Ramp { top, points } => { self.ramp = points.into(); - self.report.ramped_entries += 1; - // Down through air to the stock's top over the run. + // Down through air to the stock's top over the pass. ( - [p[0], p[1], top.min(p[2]).max(run.z)], + [p[0], p[1], top.min(p[2]).max(a[2])], MoveKind::Plunge, - Phase::Ramp, + if self.ramp.is_empty() { + Phase::Cut + } else { + Phase::Ramp + }, ) } - None => ([p[0], p[1], run.z], MoveKind::Plunge, Phase::Cut), } } + Phase::Lead => { + let a = self.chains[self.chain].pieces[self.piece].start(); + ([a[0], a[1], a[2]], MoveKind::Lead, Phase::Cut) + } Phase::Ramp => { let end = self.ramp.pop_front().expect("ramp move"); ramp_feed = Some( @@ -2028,18 +2167,40 @@ impl FlatPlan { ) } Phase::Cut => { - let run = self.runs[self.run]; - ([run.b[0], run.b[1], run.z], MoveKind::Cut, Phase::Retract) + let pts = &self.chains[self.chain].pieces[self.piece].pts; + let end = pts[self.vertex + 1]; + self.vertex += 1; + ( + end, + MoveKind::Cut, + if self.vertex + 1 < pts.len() { + Phase::Cut + } else { + Phase::PieceEnd + }, + ) + } + Phase::PieceEnd => { + if self.piece + 1 < self.chains[self.chain].pieces.len() { + // A proven link at depth to the next pass. + let next = self.chains[self.chain].pieces[self.piece + 1].start(); + self.piece += 1; + self.vertex = 0; + (next, MoveKind::Link, Phase::Cut) + } else { + ( + [p[0], p[1], self.heights.feed.max(p[2])], + MoveKind::Retract, + Phase::Rise, + ) + } } - Phase::Retract => ( - [p[0], p[1], self.heights.feed.max(p[2])], - MoveKind::Retract, - Phase::Rise, - ), Phase::Rise => { - self.run += 1; + self.chain += 1; + self.piece = 0; + self.vertex = 0; self.report.runs_completed += 1; - let last = self.run == self.runs.len(); + let last = self.chain == self.chains.len(); let z = if last { self.heights.clearance } else { @@ -2079,19 +2240,33 @@ impl FlatPlan { } /// Highest live stock upper bound over the cells the cutter's disk touches -/// anywhere along a run: sampled at no more than half a cell apart, each -/// sample's disk widened to cover the capsule between samples. -fn run_stock_top( +/// anywhere along a pass: sampled at no more than half a cell apart along +/// each chord, each sample's disk widened to cover the capsule between +/// samples. +fn piece_stock_top( + piece: &Piece, stock: &Stock, - run: Run, r: f64, cancel: &impl CancelSignal, ) -> Result { - segment_stock_top(stock, run.a, run.b, r, cancel) + let mut top = f64::MIN; + for w in piece.pts.windows(2) { + if cancel.is_cancelled() { + return Err("planning cancelled while reading the stock".into()); + } + top = top.max(segment_stock_top( + stock, + [w[0][0], w[0][1]], + [w[1][0], w[1][1]], + r, + cancel, + )?); + } + Ok(top) } /// Highest live stock upper bound over the cells a disk of radius `r` -/// touches anywhere along the segment from `a` to `b` (see `run_stock_top`). +/// touches anywhere along the segment from `a` to `b` (see `piece_stock_top`). pub(crate) fn segment_stock_top( stock: &Stock, a: [f64; 2], @@ -2119,6 +2294,416 @@ pub(crate) fn segment_stock_top( Ok(top) } +/// The region of tool centres resting on the flat level `z`: the shadow of +/// the part standing above `z - level_tolerance`, grown by the cutter radius +/// (every position whose disk touches the part within a tolerance below the +/// level), minus the shadow of the part standing above the level, grown by +/// the radius plus the shadows' stated errors (the pattern of +/// `waterline::flat_level_loops`): every position whose disk would reach the +/// part above the level. The "above" shadow's tip is picked so its +/// `protected_from_z_mm` is strictly above `z + level_tolerance`; nothing +/// standing above the level leaves the resting region alone. What is left is +/// exactly where a cut at `z + stock_to_leave_mm` rests on the level. +fn level_region( + target: &crate::roughing::PreparedRoughingTarget, + z: f64, + level_tolerance: f64, + r: f64, + tolerance: f64, + cancel: &impl CancelSignal, +) -> Result, String> { + use crate::planar::{Boolean, ConstructionOptions}; + let options = ConstructionOptions { tolerance_mm: tolerance }; + let source_error = target.mesh().surface_error_mm; + let mut work = 0usize; + let below = target + .shadow_for_cutter(z - level_tolerance, 0., r, &mut work, cancel) + .map_err(|e| format!("flat-area shadow at Z{z}: {e}"))?; + if below.region.components.is_empty() { + return Ok(None); + } + // The shadow's numerical reserve, from its own report. + let numerical = (z - level_tolerance) - below.report.protected_from_z_mm - source_error; + let resting = below + .region + .prepare(options) + .map_err(|e| format!("flat-area region at Z{z}: {e}"))? + .offset_prepared(-r) + .map_err(|e| format!("flat-area region at Z{z}: {e}"))? + .into_parts() + .1; + let above_tip = z + level_tolerance + source_error + numerical + 16. * tolerance; + let above = target + .shadow_for_cutter(above_tip, 0., r, &mut work, cancel) + .map_err(|e| format!("flat-area shadow at Z{z}: {e}"))?; + let region = if above.region.components.is_empty() { + resting + } else { + let reach = r + (above.report.boundary_error_mm - source_error).max(0.); + let blocked = above + .region + .prepare(options) + .map_err(|e| format!("flat-area region at Z{z}: {e}"))? + .offset_prepared(-reach) + .map_err(|e| format!("flat-area region at Z{z}: {e}"))? + .into_parts() + .1; + resting + .boolean_prepared(&blocked, Boolean::Difference) + .map_err(|e| format!("flat-area region at Z{z}: {e}"))? + .into_parts() + .1 + }; + if region.definition().components.is_empty() { + return Ok(None); + } + Ok(Some(region)) +} + +/// The offset loops of one connected component of a level's region: the +/// outer-boundary loops and the hole loops, each with its inward offset. +struct LoopGroup { + outers: Vec<(f64, Vec<[f64; 2]>)>, + holes: Vec<(f64, Vec<[f64; 2]>)>, +} +impl LoopGroup { + fn distance(&self, p: [f64; 2]) -> f64 { + let nearest = |rings: &[(f64, Vec<[f64; 2]>)]| { + rings + .iter() + .flat_map(|(_, ring)| ring.iter()) + .map(|v| (v[0] - p[0]).hypot(v[1] - p[1])) + .fold(f64::INFINITY, f64::min) + }; + nearest(&self.outers).min(nearest(&self.holes)) + } + /// The rings in cut order: outer loops before hole loops, offset + /// ascending (outside in), nearest the tool first at the same offset. + fn ordered(&self, tool: [f64; 2]) -> Vec> { + let near = |ring: &[[f64; 2]]| { + ring.iter() + .map(|v| (v[0] - tool[0]).hypot(v[1] - tool[1])) + .fold(f64::INFINITY, f64::min) + }; + let sort = |rings: &[(f64, Vec<[f64; 2]>)]| -> Vec> { + let mut order: Vec = (0..rings.len()).collect(); + order.sort_by(|&a, &b| { + rings[a] + .0 + .total_cmp(&rings[b].0) + .then(near(&rings[a].1).total_cmp(&near(&rings[b].1))) + .then(a.cmp(&b)) + }); + order.into_iter().map(|i| rings[i].1.clone()).collect() + }; + let mut all = sort(&self.outers); + all.extend(sort(&self.holes)); + all + } +} + +/// The offset loops of `region`, grouped per connected component: offsets +/// inward by 0, stepover, 2 stepover, ... while non-empty, then the core: +/// after the last non-empty offset `d`, while the region offset by +/// `d + r - 16 tolerances` is still non-empty, the loops at `d + stepover/2` +/// are added and the check repeats, so the disk covers every reachable point. +/// Arcs are flattened to chords with sagitta at most `tolerance`; outer +/// boundaries end up counter-clockwise and holes clockwise (climb with a +/// clockwise spindle). +fn level_loops( + region: &crate::planar::PreparedRegion, + r: f64, + stepover: f64, + tolerance: f64, + cancel: &impl CancelSignal, +) -> Result, String> { + let options = crate::planar::ConstructionOptions { tolerance_mm: tolerance }; + let guard = 16. * tolerance; + let mut groups = vec![]; + for component in ®ion.definition().components { + if cancel.is_cancelled() { + return Err("flat-area planning cancelled".into()); + } + let single = crate::planar::PlanarRegion { + version: 1, + units: "mm".into(), + name: "flat-level-region".into(), + boundary_error_mm: region.definition().boundary_error_mm, + components: vec![component.clone()], + source: serde_json::Value::Null, + }; + let prepared = single + .prepare(options) + .map_err(|e| format!("flat-area loop region: {e}"))?; + let mut outers: Vec<(f64, Vec<[f64; 2]>)> = vec![]; + let mut holes: Vec<(f64, Vec<[f64; 2]>)> = vec![]; + let mut collect = |eroded: &crate::planar::PreparedRegion, + d: f64| + -> Result<(), String> { + let mut vertices = 0usize; + for c in &eroded.definition().components { + outers.push((d, flatten_boundary(&c.outer, tolerance, true)?)); + for hole in &c.holes { + holes.push((d, flatten_boundary(hole, tolerance, false)?)); + } + vertices += c.outer.vertices.len() + c.holes.iter().map(|h| h.vertices.len()).sum::(); + } + crate::resources::check_memory(vertices as u128 * 24, "flat-area offset loops")?; + Ok(()) + }; + let mut d = 0.; + loop { + if cancel.is_cancelled() { + return Err("flat-area planning cancelled".into()); + } + let eroded = prepared + .offset_prepared(d) + .map_err(|e| format!("flat-area loop offset: {e}"))? + .into_parts() + .1; + if eroded.definition().components.is_empty() { + break; + } + collect(&eroded, d)?; + d += stepover; + } + let mut core = d - stepover; + loop { + if cancel.is_cancelled() { + return Err("flat-area planning cancelled".into()); + } + let deeper = prepared + .offset_prepared(core + r - guard) + .map_err(|e| format!("flat-area loop offset: {e}"))? + .into_parts() + .1; + if deeper.definition().components.is_empty() { + break; + } + let step = core + stepover / 2.; + let eroded = prepared + .offset_prepared(step) + .map_err(|e| format!("flat-area loop offset: {e}"))? + .into_parts() + .1; + collect(&eroded, step)?; + core = step; + } + groups.push(LoopGroup { outers, holes }); + } + Ok(groups) +} + +/// The flattened closed polyline of a boundary: arcs as chords with sagitta +/// at most `tolerance`, the first point repeated at the end, oriented +/// counter-clockwise when `ccw` (outer boundaries) and clockwise otherwise +/// (holes): climb milling with a clockwise spindle. +fn flatten_boundary( + boundary: &crate::planar::Boundary, + tolerance: f64, + ccw: bool, +) -> Result, String> { + let n = boundary.vertices.len(); + if n < 2 { + return Err("flat-area loop boundary needs at least two vertices".into()); + } + let mut pts: Vec<[f64; 2]> = Vec::with_capacity(n + 1); + for (i, a) in boundary.vertices.iter().enumerate() { + let end = boundary.vertices[(i + 1) % n]; + pts.push([a[0], a[1]]); + if a[2] != 0. { + // The arc's centre and signed sweep, as `Stroke::from_boundary`. + let sweep = 4. * a[2].atan(); + let factor = (1. - a[2] * a[2]) / (4. * a[2]); + let center = [ + (a[0] + end[0]) / 2. - factor * (end[1] - a[1]), + (a[1] + end[1]) / 2. + factor * (end[0] - a[0]), + ]; + let radius = (a[0] - center[0]).hypot(a[1] - center[1]); + let start = (a[1] - center[1]).atan2(a[0] - center[0]); + // sagitta = radius * (1 - cos(step / 2)) <= tolerance + let half = (1. - tolerance / radius).clamp(-1., 1.).acos().max(1e-9); + let count = (sweep.abs() / (2. * half)).ceil().max(1.) as usize; + for k in 1..count { + let t = k as f64 / count as f64; + let angle = start + sweep * t; + pts.push([center[0] + radius * angle.cos(), center[1] + radius * angle.sin()]); + } + } + } + pts.push(pts[0]); + if (ccw && signed_area(&pts) < 0.) || (!ccw && signed_area(&pts) > 0.) { + pts.reverse(); + } + Ok(pts) +} + +/// Signed area of a closed polyline (the first point repeated at the end). +fn signed_area(pts: &[[f64; 2]]) -> f64 { + let mut area = 0.; + for w in pts.windows(2) { + area += w[0][0] * w[1][1] - w[1][0] * w[0][1]; + } + area / 2. +} + +/// Rotate a closed piece (the last point repeating the first) so it starts at +/// the vertex `v` (one of its own points) and ends there too. +fn rotate_piece(piece: &mut Piece, v: [f64; 2]) { + let Some(i) = piece.pts.iter().position(|p| [p[0], p[1]] == v) else { + return; + }; + let last = piece.pts.len() - 1; + let mut rotated: Vec = piece.pts[i..last].to_vec(); + rotated.extend_from_slice(&piece.pts[..=i]); + piece.pts = rotated; +} + +/// Rotate a closed ring (the last point repeating the first) so it starts at +/// the vertex nearest `tool` and ends there too. +fn rotate_to_nearest(mut ring: Vec<[f64; 2]>, tool: [f64; 2]) -> Vec<[f64; 2]> { + if ring.first() != ring.last() || ring.len() < 3 { + return ring; + } + let last = ring.len() - 1; + let (mut best, mut index) = (f64::INFINITY, 0usize); + for (i, v) in ring[..last].iter().enumerate() { + let d = (v[0] - tool[0]).hypot(v[1] - tool[1]); + if d < best { + (best, index) = (d, i); + } + } + if index == 0 { + return ring; + } + let mut rotated: Vec<[f64; 2]> = ring[index..last].to_vec(); + rotated.extend_from_slice(&ring[..=index]); + ring.clear(); + rotated +} + +/// Prove every chord of `ring` at height `z` (the highest part point under +/// the swept disk of radius `r` at most `z + tolerance`), halving failures +/// down to `h / 16`, and keep only the stretches inside the limits. Adjacent +/// proven chords merge into pieces; what cannot be proven or allowed is +/// dropped, splitting the loop into open pieces. +#[allow(clippy::too_many_arguments)] +fn prove_ring( + ring: &[[f64; 2]], + z: f64, + r: f64, + index: &Index, + seen: &mut [u32], + stamp: &mut u32, + h: f64, + tolerance: f64, + limits: Option<&crate::limits::PreparedLimits>, + dropped: &mut f64, + cancel: &impl CancelSignal, +) -> Result, String> { + let mut pieces: Vec = vec![]; + fn push(pieces: &mut Vec, a: [f64; 2], b: [f64; 2], z: f64) { + if let Some(last) = pieces.last_mut() + && last.pts.last().is_some_and(|p| [p[0], p[1]] == a) + { + last.pts.push([b[0], b[1], z]); + return; + } + pieces.push(Piece { + pts: vec![[a[0], a[1], z], [b[0], b[1], z]], + }); + } + for w in ring.windows(2) { + if cancel.is_cancelled() { + return Err("flat-area planning cancelled".into()); + } + let (a, b) = ([w[0][0], w[0][1]], [w[1][0], w[1][1]]); + let mut stack = vec![(a, b, 0u32)]; + while let Some((a, b, depth)) = stack.pop() { + if cancel.is_cancelled() { + return Err("flat-area planning cancelled".into()); + } + let length = (b[0] - a[0]).hypot(b[1] - a[1]); + if index.max_height(a, b, r, seen, stamp) <= z + tolerance { + match limits { + None => push(&mut pieces, a, b, z), + Some(limits) => { + // Only the stretches proven inside the limits. + let line = crate::motion::Curve::Line { + start: [a[0], a[1], z], + end: [b[0], b[1], z], + }; + let mut kept = 0.; + for [t0, t1] in limits.allowed_spans(&line, true)? { + let p = [a[0] + t0 * (b[0] - a[0]), a[1] + t0 * (b[1] - a[1])]; + let q = [a[0] + t1 * (b[0] - a[0]), a[1] + t1 * (b[1] - a[1])]; + if (q[0] - p[0]).hypot(q[1] - p[1]) > tolerance { + push(&mut pieces, p, q, z); + kept += (t1 - t0) * length; + } + } + *dropped += length - kept; + } + } + continue; + } + if length <= h / 16. || depth >= 32 { + *dropped += length; + continue; + } + let m = [(a[0] + b[0]) / 2., (a[1] + b[1]) / 2.]; + stack.push((m, b, depth + 1)); + stack.push((a, m, depth + 1)); + } + } + Ok(pieces) +} + +/// Side-entry candidates of a piece: its vertices, at most one per 1 mm of +/// the piece, each with the outward normal (right of travel: away from the +/// region on a counter-clockwise outer loop, into the hole on a clockwise +/// hole loop). +fn side_candidates(piece: &Piece) -> Vec<([f64; 2], [f64; 2])> { + let mut side = vec![]; + let mut taken: Option<[f64; 2]> = None; + for w in piece.pts.windows(2) { + let v = [w[0][0], w[0][1]]; + if taken.is_some_and(|p| (v[0] - p[0]).hypot(v[1] - p[1]) < 1.) { + continue; + } + let d = [w[1][0] - w[0][0], w[1][1] - w[0][1]]; + let n = d[0].hypot(d[1]); + if n <= 0. { + continue; + } + side.push((v, [d[1] / n, -d[0] / n])); + taken = Some(v); + } + side +} + +/// Whether a straight move at `z` lies entirely inside the limits (always +/// true without limits, and for a degenerate move between proven endpoints). +fn allows_segment( + limits: Option<&crate::limits::PreparedLimits>, + a: [f64; 2], + b: [f64; 2], + z: f64, + tolerance: f64, +) -> Result { + let Some(limits) = limits else { + return Ok(true); + }; + if (b[0] - a[0]).hypot(b[1] - a[1]) <= tolerance { + return Ok(true); + } + let line = crate::motion::Curve::Line { + start: [a[0], a[1], z], + end: [b[0], b[1], z], + }; + Ok(limits.allowed_spans(&line, true)?.as_slice() == [[0., 1.]]) +} + #[cfg(test)] mod tests { use super::*; From e98d604619ad2984f1986b8ad286a2eac90bc2ab Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:30:30 -0700 Subject: [PATCH 03/26] Flat tests: allow split strips' entries, check no plunge onto a finished face (#38) --- python/tests/test_flat_offset.py | 36 ++++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/python/tests/test_flat_offset.py b/python/tests/test_flat_offset.py index dadb07b..6f7f01c 100644 --- a/python/tests/test_flat_offset.py +++ b/python/tests/test_flat_offset.py @@ -231,17 +231,41 @@ def cached(name): class FlatOffsetTest(unittest.TestCase): - def test_each_edge_ring_is_entered_once(self): - # Entries are the vertical plunges. A connected flat is entered once - # per ring along its edge or a wall it cannot link across: the - # stepped part has three (the boss top's edge, the base's outer edge - # and the base's ring round the boss). Today: one per raster run. + def test_few_entries_and_links_at_depth(self): + # Entries are the vertical plunges. The stepped part needs one per + # ring along an edge or wall that cannot be linked to (boss top, + # base outer edge, ring round the boss) plus one per piece the + # offsets split off out of link reach (the base's two side strips + # at d = 3): at most 6. Today: one per raster run (39). report, motions, *_ = cached("stepped") plunges = len(vertical_plunges(motions)) - self.assertLessEqual(plunges, 3, f"{plunges} entries; runs={report['runs']}") + self.assertLessEqual(plunges, 6, f"{plunges} entries; runs={report['runs']}") self.assertEqual(plunges, report["runs"]) self.assertGreater(report.get("links_at_depth", 0), 0) + def test_no_vertical_plunge_onto_a_finished_face(self): + # No plunge marks: a vertical plunge that ends at a flat's cutting + # height never has the tool's disk over that flat's face; the tool + # comes down beside the face (side entry) or stops above the stock + # and ramps. + for name, spec in (("stepped", STEPPED), ("island", ISLAND)): + _, motions, *_ = cached(name) + field = Field(spec) + worst = (math.inf, None) + for m in vertical_plunges(motions): + b = m["curve"]["end"] + face = np.abs(field.H - b[2]) < 1e-6 + if not face.any(): + continue + d = float(np.min(np.hypot(field.X[face] - b[0], field.Y[face] - b[1]))) + if d < worst[0]: + worst = (d, [round(v, 4) for v in b]) + self.assertGreaterEqual( + worst[0], + R - 1e-6 - field.step, + f"{name}: plunge onto a finished face at {worst[1]} ({worst[0]:.4f} mm)", + ) + def test_open_edges_are_entered_from_the_side_in_air(self): # The boss top and the base's outer edge are open: their first ring # is entered by a vertical plunge where the tool's disk touches no From 4771bdcbdb152240b3cc0778e1723661f7697e0f Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:10:09 -0700 Subject: [PATCH 04/26] Flat: side entries and plunges come down beside the level's face (#38) --- src/flat.rs | 86 +++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 67 insertions(+), 19 deletions(-) diff --git a/src/flat.rs b/src/flat.rs index fc5d18b..07fa5a7 100644 --- a/src/flat.rs +++ b/src/flat.rs @@ -3,7 +3,8 @@ //! flat end mill, in contour-parallel passes that offset each flat's tool //! centre region inward, outside in, linked at depth where the link is //! proven, and entered from the side in air where a pass runs along an open -//! edge. +//! edge — the plunge always coming down beside the level's face, never onto +//! it. //! //! Proof: every cut is a horizontal line at the cut height. It is kept only //! where the highest point of the part (and the machining base) under the @@ -1551,6 +1552,9 @@ struct Chain { /// 1 mm of the pass) with the outward normal, away from the region (right /// of travel). side: Vec<([f64; 2], [f64; 2])>, + /// The level's face (the flat the pass finishes): an entry may only plunge + /// down beside it, never onto it. + face: std::sync::Arc, } /// How the chain is entered, decided against the live stock when reached. @@ -1780,8 +1784,9 @@ impl FlatPlan { return Err("flat-area planning cancelled".into()); } let z = level + op.stock_to_leave_mm; - // The tool centres resting on this level, as a planar region. - let Some(region) = + // The tool centres resting on this level, as a planar region, and + // the level's face (for keeping entries off it). + let Some((region, face)) = level_region(&target, level, op.level_tolerance_mm, r, op.tolerance_mm, cancel)? else { continue; @@ -1854,6 +1859,7 @@ impl FlatPlan { chains.push(Chain { pieces: vec![piece], side, + face: std::sync::Arc::clone(&face), }); } let end = chains[chains.len() - 1].pieces.last().unwrap().end(); @@ -1878,7 +1884,7 @@ impl FlatPlan { dropped_length_mm: dropped, runs_completed: 0, ramped_entries: 0, - clearance_proof: "exact maximum part height under each horizontal cut's swept disk (triangle-capsule extreme points) at most the cut height plus tolerance; contour-parallel offset passes outside in, side entry in air on open edges, links at depth and when chains break", + clearance_proof: "exact maximum part height under each horizontal cut's swept disk (triangle-capsule extreme points) at most the cut height plus tolerance; contour-parallel offset passes outside in, side entry in air on open edges and every vertical plunge beside the level's face (a radius outside it, the face region a superset of the flat within the shadows' stated errors), links at depth and when chains break", }; Ok(Self { op, @@ -1909,12 +1915,12 @@ impl FlatPlan { } /// What enters the pass at its start after the rapid descent: a straight /// plunge where no live stock stands above the pass's height there (the - /// cells' upper bounds, within a tolerance), otherwise a ramp from the - /// stock's top over the whole pass, down the pass by the declared - /// `RampEntry`. Each ramp point lies vertically above the proven pass, so - /// it clears the part as the pass does. A pass the ramp does not fit, or - /// stock above a pass with no entry declared, is refused: a flat end mill - /// is never plunged into stock. + /// cells' upper bounds, within a tolerance) and the disk comes down beside + /// the level's face, otherwise a ramp from the stock's top over the whole + /// pass, down the pass by the declared `RampEntry`. Each ramp point lies + /// vertically above the proven pass, so it clears the part as the pass + /// does. A pass the ramp does not fit, or stock above a pass with no entry + /// declared, is refused: a flat end mill is never plunged into stock. fn plunge_or_ramp( &self, piece: &Piece, @@ -1923,7 +1929,7 @@ impl FlatPlan { ) -> Result)>, String> { let a = piece.start(); let at_start = stock.top_under_disk([a[0], a[1]], self.radius); - if at_start <= a[2] + self.op.tolerance_mm { + if at_start <= a[2] + self.op.tolerance_mm && self.beside_face([a[0], a[1]])? { return Ok(None); } let length = piece.length(); @@ -1969,10 +1975,21 @@ impl FlatPlan { points.extend(curves.iter().map(|c| c.end())); Ok(Some((top, points))) } + /// Whether the disk at `p` comes down beside this chain's level's face: a + /// radius (less the tolerance) outside the face region, so a vertical + /// plunge at `p` never rests the disk on the flat the pass finishes. An + /// empty face region (no flat at the level) leaves the point free. + fn beside_face(&self, p: [f64; 2]) -> Result { + let q = self.chains[self.chain].face.query(p)?; + Ok(q.signed_clearance_mm + .map_or(true, |s| s <= self.op.tolerance_mm - self.radius)) + } + /// How the current chain is entered, decided against the live stock: from /// the side in air where the first pass runs along an open edge (the - /// plunge point's disk touches no stock above the cut and the lead is - /// proven and allowed), otherwise the declared rule (`plunge_or_ramp`). + /// plunge point's disk touches no stock above the cut, stays beside the + /// level's face, and the lead is proven and allowed), otherwise the + /// declared rule (`plunge_or_ramp`). fn decide_entry(&mut self, stock: &Stock, cancel: &impl CancelSignal) -> Result { let piece = &self.chains[self.chain].pieces[self.piece]; let z = piece.start()[2]; @@ -1992,6 +2009,9 @@ impl FlatPlan { if stock.top_under_disk(p, self.radius) > z + tol { continue; } + if !self.beside_face(p)? { + continue; + } if self.index.max_height(p, *v, self.radius, &mut self.seen, &mut self.stamp) > z + tol { @@ -2311,7 +2331,8 @@ fn level_region( r: f64, tolerance: f64, cancel: &impl CancelSignal, -) -> Result, String> { +) -> Result)>, String> +{ use crate::planar::{Boolean, ConstructionOptions}; let options = ConstructionOptions { tolerance_mm: tolerance }; let source_error = target.mesh().surface_error_mm; @@ -2336,8 +2357,12 @@ fn level_region( let above = target .shadow_for_cutter(above_tip, 0., r, &mut work, cancel) .map_err(|e| format!("flat-area shadow at Z{z}: {e}"))?; - let region = if above.region.components.is_empty() { - resting + let (region, face) = if above.region.components.is_empty() { + let face = below + .region + .prepare(options) + .map_err(|e| format!("flat-area face at Z{z}: {e}"))?; + (resting, face) } else { let reach = r + (above.report.boundary_error_mm - source_error).max(0.); let blocked = above @@ -2348,16 +2373,39 @@ fn level_region( .map_err(|e| format!("flat-area region at Z{z}: {e}"))? .into_parts() .1; - resting + let region = resting .boolean_prepared(&blocked, Boolean::Difference) .map_err(|e| format!("flat-area region at Z{z}: {e}"))? .into_parts() - .1 + .1; + // The level's face: the flat the pass finishes. The shadow standing + // above is eroded by its stated boundary error plus the tolerance + // before it is subtracted, so what is removed stays inside the part + // that really stands above and the face kept is a superset of the + // true flat: a point a radius outside this region is a radius + // outside the true face too. + let core = above + .region + .prepare(options) + .map_err(|e| format!("flat-area face at Z{z}: {e}"))? + .offset_prepared(above.report.boundary_error_mm + tolerance) + .map_err(|e| format!("flat-area face at Z{z}: {e}"))? + .into_parts() + .1; + let face = below + .region + .prepare(options) + .map_err(|e| format!("flat-area face at Z{z}: {e}"))? + .boolean_prepared(&core, Boolean::Difference) + .map_err(|e| format!("flat-area face at Z{z}: {e}"))? + .into_parts() + .1; + (region, face) }; if region.definition().components.is_empty() { return Ok(None); } - Ok(Some(region)) + Ok(Some((region, std::sync::Arc::new(face)))) } /// The offset loops of one connected component of a level's region: the From ecbe7d6c16d64997d82e53dfeb3f5676dc37731d Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:19:25 -0700 Subject: [PATCH 05/26] Flat: offset loops keep their arcs, proven whole or by chords --- src/flat.rs | 481 ++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 334 insertions(+), 147 deletions(-) diff --git a/src/flat.rs b/src/flat.rs index 07fa5a7..c7d3a51 100644 --- a/src/flat.rs +++ b/src/flat.rs @@ -29,6 +29,47 @@ fn level_tolerance() -> f64 { 0.001 } +/// Emitted arc moves are split so each move's chord stays within this of the +/// arc: the arc itself is exact, but moves are checked (and posted programs +/// read) through their endpoints, so a move must not sweep so far that its +/// chord cuts the corner its endpoints describe. +const ARC_MOVE_SAGITTA: f64 = 0.005; + +/// The arc stroke split into equal sub-arcs whose chords stay within +/// `sagitta` of the arc (a straight stroke passes through unchanged). +fn split_arc(seg: &crate::pocket::Stroke, sagitta: f64) -> Vec { + let Some((c, sweep)) = seg.arc else { + return vec![*seg]; + }; + let rho = (seg.a[0] - c[0]).hypot(seg.a[1] - c[1]); + let half = (1. - sagitta / rho).clamp(-1., 1.).acos().max(1e-9); + let n = ((sweep.abs() / (2. * half)).ceil().max(1.) as usize).max(1); + let start = (seg.a[1] - c[1]).atan2(seg.a[0] - c[0]); + let mut out = Vec::with_capacity(n); + for i in 0..n { + let t0 = i as f64 / n as f64; + let t1 = (i + 1) as f64 / n as f64; + let p = if i == 0 { + seg.a + } else { + let angle = start + sweep * t0; + [c[0] + rho * angle.cos(), c[1] + rho * angle.sin()] + }; + let b = if i + 1 == n { + seg.b + } else { + let angle = start + sweep * t1; + [c[0] + rho * angle.cos(), c[1] + rho * angle.sin()] + }; + out.push(crate::pocket::Stroke { + a: p, + b, + arc: Some((c, sweep * (t1 - t0))), + }); + } + out +} + #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct FlatOperation { @@ -1517,29 +1558,33 @@ impl Index { } } -/// One cut pass at a fixed height: the flattened polyline of a closed loop -/// (the last point repeats the first) or of the stretches of a loop that were -/// proven and allowed (an open piece). +/// One cut pass at a fixed height: the segments of a closed loop in travel +/// order (an open piece when only stretches of the loop were proven and +/// allowed). A segment is a straight chord or an arc of the offset loop +/// (cavalier contours' bulge), proven as a whole or as its chords. struct Piece { - pts: Vec, + /// The pass's height; every segment runs at this Z. + z: f64, + segs: Vec, } impl Piece { fn start(&self) -> Vec3 { - self.pts[0] + let a = self.segs[0].a; + [a[0], a[1], self.z] } fn end(&self) -> Vec3 { - self.pts[self.pts.len() - 1] + let b = self.segs[self.segs.len() - 1].b; + [b[0], b[1], self.z] } fn length(&self) -> f64 { - self.pts - .windows(2) - .map(|w| (w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1])) - .sum() + self.segs.iter().map(crate::profiles::stroke_length).sum() } fn strokes(&self) -> Vec { - self.pts - .windows(2) - .map(|w| crate::pocket::Stroke::line([w[0][0], w[0][1]], [w[1][0], w[1][1]])) + // The ramp walks the pass stroke by stroke; its arcs are split like + // the cut moves so no ramp leg sweeps a chord that cuts its corner. + self.segs + .iter() + .flat_map(|s| split_arc(s, ARC_MOVE_SAGITTA)) .collect() } } @@ -1564,8 +1609,10 @@ enum Entry { Side { p: [f64; 2] }, /// Vertical plunge at the pass's start. Plunge, - /// Ramp down the first pass from the stock's top over it. - Ramp { top: f64, points: Vec }, + /// Ramp down the first pass from the stock's top over it: the zigzag's + /// curves (lines and arcs on the pass, helices where a leg descends + /// along an arc), ending at the pass's start. + Ramp { top: f64, curves: Vec }, } #[derive(Clone, Copy, PartialEq, Eq)] @@ -1592,12 +1639,12 @@ pub struct FlatPlan { chains: Vec, chain: usize, piece: usize, - vertex: usize, + seg: usize, phase: Phase, radius: f64, limits: Option, entry: Option, - ramp: std::collections::VecDeque, + ramp: std::collections::VecDeque, initial: Vec3, position: Vec3, next_id: u64, @@ -1896,7 +1943,7 @@ impl FlatPlan { chains, chain: 0, piece: 0, - vertex: 0, + seg: 0, phase: Phase::Lift, radius: r, limits: region_limits, @@ -1926,7 +1973,7 @@ impl FlatPlan { piece: &Piece, stock: &Stock, cancel: &impl CancelSignal, - ) -> Result)>, String> { + ) -> Result)>, String> { let a = piece.start(); let at_start = stock.top_under_disk([a[0], a[1]], self.radius); if at_start <= a[2] + self.op.tolerance_mm && self.beside_face([a[0], a[1]])? { @@ -1965,15 +2012,10 @@ impl FlatPlan { let curves = entry .zigzag(&chain, top, a[2]) .map_err(|why| format!("{which}: {why}. Use a steeper declared angle, a longer run, or rough this area first"))?; - let mut points = vec![]; - let first = curves.first().map_or([a[0], a[1]], |c| { - let q = c.start(); - [q[0], q[1]] - }); - // Over the pass at the stock's top, then down the legs. - points.push([first[0], first[1], top]); - points.extend(curves.iter().map(|c| c.end())); - Ok(Some((top, points))) + // The curves run from the ramp's start (at the stock's top) to the + // pass's start; the vertical descent to the ramp's start happens in + // `next_motion_with_stock`. + Ok(Some((top, curves))) } /// Whether the disk at `p` comes down beside this chain's level's face: a /// radius (less the tolerance) outside the face region, so a vertical @@ -1994,13 +2036,14 @@ impl FlatPlan { let piece = &self.chains[self.chain].pieces[self.piece]; let z = piece.start()[2]; let tol = self.op.tolerance_mm; - let closed = piece.pts.first() == piece.pts.last(); + let first = piece.segs[0].a; + let closed = piece.segs.last().is_some_and(|s| s.b == first); let mut best: Option<([f64; 2], [f64; 2])> = None; for (v, n) in &self.chains[self.chain].side { if cancel.is_cancelled() { return Err("flat-area planning cancelled".into()); } - if !closed && *v != [piece.pts[0][0], piece.pts[0][1]] { + if !closed && *v != first { continue; } // Outward, trying the shortest offset first. @@ -2032,7 +2075,7 @@ impl FlatPlan { } if let Some((v, p)) = best { // The loop is cut from the entry vertex. - if closed && (piece.pts[0][0] != v[0] || piece.pts[0][1] != v[1]) { + if closed && (first[0] != v[0] || first[1] != v[1]) { let piece = &mut self.chains[self.chain].pieces[self.piece]; rotate_piece(piece, v); } @@ -2041,9 +2084,9 @@ impl FlatPlan { let piece = &self.chains[self.chain].pieces[self.piece]; match self.plunge_or_ramp(piece, stock, cancel)? { None => Ok(Entry::Plunge), - Some((top, points)) => { + Some((top, curves)) => { self.report.ramped_entries += 1; - Ok(Entry::Ramp { top, points }) + Ok(Entry::Ramp { top, curves }) } } } @@ -2105,7 +2148,9 @@ impl FlatPlan { } let p = self.position; let mut ramp_feed = None; - let (end, kind, next) = match self.phase { + // The move's curve: a straight line from the current position + // unless the phase carries one (a ramp leg or an arc of the pass). + let (end, kind, next, carried) = match self.phase { Phase::Done => { self.drained = true; return Ok(None); @@ -2118,26 +2163,32 @@ impl FlatPlan { } else { Phase::Approach }, + None, ), Phase::Approach => { // The entry is decided here, against the live stock: the - // rapid goes over the plunge point (a side entry) or the - // pass's start. + // rapid goes over the plunge point (a side entry), the + // ramp's start, or the pass's start. let entry = self.decide_entry(stock, cancel)?; let over = match &entry { Entry::Side { p: over } => *over, - _ => { + Entry::Ramp { curves, .. } => { + let f = curves[0].start(); + [f[0], f[1]] + } + Entry::Plunge => { let a = self.chains[self.chain].pieces[self.piece].start(); [a[0], a[1]] } }; self.entry = Some(entry); - ([over[0], over[1], p[2]], MoveKind::Rapid, Phase::Descend) + ([over[0], over[1], p[2]], MoveKind::Rapid, Phase::Descend, None) } Phase::Descend => ( [p[0], p[1], self.heights.feed], MoveKind::Rapid, Phase::Enter, + None, ), Phase::Enter => { let a = self.chains[self.chain].pieces[self.piece].start(); @@ -2146,11 +2197,13 @@ impl FlatPlan { [p[0], p[1], a[2]], MoveKind::Plunge, Phase::Lead, + None, ), - Entry::Plunge => ([p[0], p[1], a[2]], MoveKind::Plunge, Phase::Cut), - Entry::Ramp { top, points } => { - self.ramp = points.into(); - // Down through air to the stock's top over the pass. + Entry::Plunge => ([p[0], p[1], a[2]], MoveKind::Plunge, Phase::Cut, None), + Entry::Ramp { top, curves } => { + self.ramp = curves.into(); + // Down through air to the stock's top over the + // pass, where the ramp's first curve begins. ( [p[0], p[1], top.min(p[2]).max(a[2])], MoveKind::Plunge, @@ -2159,16 +2212,17 @@ impl FlatPlan { } else { Phase::Ramp }, + None, ) } } } Phase::Lead => { let a = self.chains[self.chain].pieces[self.piece].start(); - ([a[0], a[1], a[2]], MoveKind::Lead, Phase::Cut) + ([a[0], a[1], a[2]], MoveKind::Lead, Phase::Cut, None) } Phase::Ramp => { - let end = self.ramp.pop_front().expect("ramp move"); + let curve = self.ramp.pop_front().expect("ramp move"); ramp_feed = Some( self.op .entry @@ -2176,6 +2230,7 @@ impl FlatPlan { .and_then(|e| e.feed_mm_min()) .unwrap_or(self.op.plunge_mm_min), ); + let end = curve.end(); ( end, MoveKind::Plunge, @@ -2184,20 +2239,24 @@ impl FlatPlan { } else { Phase::Ramp }, + Some(curve), ) } Phase::Cut => { - let pts = &self.chains[self.chain].pieces[self.piece].pts; - let end = pts[self.vertex + 1]; - self.vertex += 1; + let piece = &self.chains[self.chain].pieces[self.piece]; + let seg = piece.segs[self.seg]; + let end = [seg.b[0], seg.b[1], piece.z]; + let curve = Some(seg.curve(piece.z)); + self.seg += 1; ( end, MoveKind::Cut, - if self.vertex + 1 < pts.len() { + if self.seg < piece.segs.len() { Phase::Cut } else { Phase::PieceEnd }, + curve, ) } Phase::PieceEnd => { @@ -2205,20 +2264,21 @@ impl FlatPlan { // A proven link at depth to the next pass. let next = self.chains[self.chain].pieces[self.piece + 1].start(); self.piece += 1; - self.vertex = 0; - (next, MoveKind::Link, Phase::Cut) + self.seg = 0; + (next, MoveKind::Link, Phase::Cut, None) } else { ( [p[0], p[1], self.heights.feed.max(p[2])], MoveKind::Retract, Phase::Rise, + None, ) } } Phase::Rise => { self.chain += 1; self.piece = 0; - self.vertex = 0; + self.seg = 0; self.report.runs_completed += 1; let last = self.chain == self.chains.len(); let z = if last { @@ -2230,6 +2290,7 @@ impl FlatPlan { [p[0], p[1], z.max(p[2])], MoveKind::Rapid, if last { Phase::Done } else { Phase::Approach }, + None, ) } }; @@ -2237,7 +2298,7 @@ impl FlatPlan { if end == p { continue; } - let curve = Curve::Line { start: p, end }; + let curve = carried.unwrap_or(Curve::Line { start: p, end }); curve.prepare(self.op.tolerance_mm)?; let motion = Motion { id: self.next_id, @@ -2269,18 +2330,36 @@ fn piece_stock_top( r: f64, cancel: &impl CancelSignal, ) -> Result { + let [wx, wy] = stock.cell_widths_mm(); + let step = 0.5 * wx.min(wy); let mut top = f64::MIN; - for w in piece.pts.windows(2) { + for seg in &piece.segs { if cancel.is_cancelled() { return Err("planning cancelled while reading the stock".into()); } - top = top.max(segment_stock_top( - stock, - [w[0][0], w[0][1]], - [w[1][0], w[1][1]], - r, - cancel, - )?); + match seg.arc { + None => { + top = top.max(segment_stock_top(stock, seg.a, seg.b, r, cancel)?); + } + Some((c, sweep)) => { + // The disk the tool sweeps along a sub-arc is contained in the + // capsule of radius r + sagitta around its chord, so the stock + // is read over each chord with that wider radius. + let rho = (seg.a[0] - c[0]).hypot(seg.a[1] - c[1]); + let length = rho * sweep.abs(); + let n = (length / step).ceil().max(1.) as usize; + let start = (seg.a[1] - c[1]).atan2(seg.a[0] - c[0]); + let mut a = seg.a; + for i in 1..=n { + let angle = start + sweep * (i as f64 / n as f64); + let b = [c[0] + rho * angle.cos(), c[1] + rho * angle.sin()]; + let half = sweep.abs() / (2. * n as f64); + let sagitta = rho * (1. - half.cos()); + top = top.max(segment_stock_top(stock, a, b, r + sagitta, cancel)?); + a = b; + } + } + } } Ok(top) } @@ -2411,29 +2490,29 @@ fn level_region( /// The offset loops of one connected component of a level's region: the /// outer-boundary loops and the hole loops, each with its inward offset. struct LoopGroup { - outers: Vec<(f64, Vec<[f64; 2]>)>, - holes: Vec<(f64, Vec<[f64; 2]>)>, + outers: Vec<(f64, Vec)>, + holes: Vec<(f64, Vec)>, } impl LoopGroup { fn distance(&self, p: [f64; 2]) -> f64 { - let nearest = |rings: &[(f64, Vec<[f64; 2]>)]| { + let nearest = |rings: &[(f64, Vec)]| { rings .iter() .flat_map(|(_, ring)| ring.iter()) - .map(|v| (v[0] - p[0]).hypot(v[1] - p[1])) + .map(|s| (s.a[0] - p[0]).hypot(s.a[1] - p[1])) .fold(f64::INFINITY, f64::min) }; nearest(&self.outers).min(nearest(&self.holes)) } /// The rings in cut order: outer loops before hole loops, offset /// ascending (outside in), nearest the tool first at the same offset. - fn ordered(&self, tool: [f64; 2]) -> Vec> { - let near = |ring: &[[f64; 2]]| { + fn ordered(&self, tool: [f64; 2]) -> Vec> { + let near = |ring: &[crate::pocket::Stroke]| { ring.iter() - .map(|v| (v[0] - tool[0]).hypot(v[1] - tool[1])) + .map(|s| (s.a[0] - tool[0]).hypot(s.a[1] - tool[1])) .fold(f64::INFINITY, f64::min) }; - let sort = |rings: &[(f64, Vec<[f64; 2]>)]| -> Vec> { + let sort = |rings: &[(f64, Vec)]| -> Vec> { let mut order: Vec = (0..rings.len()).collect(); order.sort_by(|&a, &b| { rings[a] @@ -2455,9 +2534,8 @@ impl LoopGroup { /// after the last non-empty offset `d`, while the region offset by /// `d + r - 16 tolerances` is still non-empty, the loops at `d + stepover/2` /// are added and the check repeats, so the disk covers every reachable point. -/// Arcs are flattened to chords with sagitta at most `tolerance`; outer -/// boundaries end up counter-clockwise and holes clockwise (climb with a -/// clockwise spindle). +/// Each loop keeps its arcs (cavalier contours' bulges); outer boundaries end +/// up counter-clockwise and holes clockwise (climb with a clockwise spindle). fn level_loops( region: &crate::planar::PreparedRegion, r: f64, @@ -2483,16 +2561,22 @@ fn level_loops( let prepared = single .prepare(options) .map_err(|e| format!("flat-area loop region: {e}"))?; - let mut outers: Vec<(f64, Vec<[f64; 2]>)> = vec![]; - let mut holes: Vec<(f64, Vec<[f64; 2]>)> = vec![]; + let mut outers: Vec<(f64, Vec)> = vec![]; + let mut holes: Vec<(f64, Vec)> = vec![]; let mut collect = |eroded: &crate::planar::PreparedRegion, d: f64| -> Result<(), String> { let mut vertices = 0usize; for c in &eroded.definition().components { - outers.push((d, flatten_boundary(&c.outer, tolerance, true)?)); + let outer = boundary_strokes(&c.outer, true)?; + if !outer.is_empty() { + outers.push((d, outer)); + } for hole in &c.holes { - holes.push((d, flatten_boundary(hole, tolerance, false)?)); + let strokes = boundary_strokes(hole, false)?; + if !strokes.is_empty() { + holes.push((d, strokes)); + } } vertices += c.outer.vertices.len() + c.holes.iter().map(|h| h.vertices.len()).sum::(); } @@ -2542,48 +2626,40 @@ fn level_loops( Ok(groups) } -/// The flattened closed polyline of a boundary: arcs as chords with sagitta -/// at most `tolerance`, the first point repeated at the end, oriented -/// counter-clockwise when `ccw` (outer boundaries) and clockwise otherwise -/// (holes): climb milling with a clockwise spindle. -fn flatten_boundary( +/// The closed segment loop of a boundary: straight chords and arcs (cavalier +/// contours' bulges, as `Stroke::from_boundary`), oriented counter-clockwise +/// when `ccw` (outer boundaries) and clockwise otherwise (holes): climb +/// milling with a clockwise spindle. Degenerate segments (zero length or zero +/// sweep) carry no geometry and are dropped or straightened. +fn boundary_strokes( boundary: &crate::planar::Boundary, - tolerance: f64, ccw: bool, -) -> Result, String> { +) -> Result, String> { let n = boundary.vertices.len(); if n < 2 { return Err("flat-area loop boundary needs at least two vertices".into()); } - let mut pts: Vec<[f64; 2]> = Vec::with_capacity(n + 1); - for (i, a) in boundary.vertices.iter().enumerate() { - let end = boundary.vertices[(i + 1) % n]; - pts.push([a[0], a[1]]); - if a[2] != 0. { - // The arc's centre and signed sweep, as `Stroke::from_boundary`. - let sweep = 4. * a[2].atan(); - let factor = (1. - a[2] * a[2]) / (4. * a[2]); - let center = [ - (a[0] + end[0]) / 2. - factor * (end[1] - a[1]), - (a[1] + end[1]) / 2. + factor * (end[0] - a[0]), - ]; - let radius = (a[0] - center[0]).hypot(a[1] - center[1]); - let start = (a[1] - center[1]).atan2(a[0] - center[0]); - // sagitta = radius * (1 - cos(step / 2)) <= tolerance - let half = (1. - tolerance / radius).clamp(-1., 1.).acos().max(1e-9); - let count = (sweep.abs() / (2. * half)).ceil().max(1.) as usize; - for k in 1..count { - let t = k as f64 / count as f64; - let angle = start + sweep * t; - pts.push([center[0] + radius * angle.cos(), center[1] + radius * angle.sin()]); + let segs: Vec = crate::pocket::Stroke::from_boundary(boundary) + .into_iter() + .filter(|s| (s.b[0] - s.a[0]).hypot(s.b[1] - s.a[1]) > 1e-12) + .map(|mut s| { + if s.arc.is_some_and(|(_, sweep)| sweep.abs() < 1e-9) { + s.arc = None; } - } - } - pts.push(pts[0]); + s + }) + .collect(); + if segs.len() < 2 { + return Ok(vec![]); + } + // Orientation from the closed chord polygon (an inscribed polygon has the + // arcs' orientation). + let mut pts: Vec<[f64; 2]> = segs.iter().map(|s| s.a).collect(); + pts.push(segs[0].a); if (ccw && signed_area(&pts) < 0.) || (!ccw && signed_area(&pts) > 0.) { - pts.reverse(); + return Ok(segs.into_iter().rev().map(crate::pocket::Stroke::reversed).collect()); } - Ok(pts) + Ok(segs) } /// Signed area of a closed polyline (the first point repeated at the end). @@ -2597,26 +2673,26 @@ fn signed_area(pts: &[[f64; 2]]) -> f64 { /// Rotate a closed piece (the last point repeating the first) so it starts at /// the vertex `v` (one of its own points) and ends there too. +/// Rotate a closed piece (its last segment ending on the first's start) so it +/// starts at the vertex `v`. fn rotate_piece(piece: &mut Piece, v: [f64; 2]) { - let Some(i) = piece.pts.iter().position(|p| [p[0], p[1]] == v) else { + let Some(i) = piece.segs.iter().position(|s| s.a == v) else { return; }; - let last = piece.pts.len() - 1; - let mut rotated: Vec = piece.pts[i..last].to_vec(); - rotated.extend_from_slice(&piece.pts[..=i]); - piece.pts = rotated; + let mut rotated: Vec = piece.segs[i..].to_vec(); + rotated.extend_from_slice(&piece.segs[..i]); + piece.segs = rotated; } -/// Rotate a closed ring (the last point repeating the first) so it starts at -/// the vertex nearest `tool` and ends there too. -fn rotate_to_nearest(mut ring: Vec<[f64; 2]>, tool: [f64; 2]) -> Vec<[f64; 2]> { - if ring.first() != ring.last() || ring.len() < 3 { +/// Rotate a closed ring of segments (the last ending on the first's start) so +/// it starts at the vertex nearest `tool` and ends there too. +fn rotate_to_nearest(ring: Vec, tool: [f64; 2]) -> Vec { + if ring.len() < 2 { return ring; } - let last = ring.len() - 1; let (mut best, mut index) = (f64::INFINITY, 0usize); - for (i, v) in ring[..last].iter().enumerate() { - let d = (v[0] - tool[0]).hypot(v[1] - tool[1]); + for (i, s) in ring.iter().enumerate() { + let d = (s.a[0] - tool[0]).hypot(s.a[1] - tool[1]); if d < best { (best, index) = (d, i); } @@ -2624,9 +2700,8 @@ fn rotate_to_nearest(mut ring: Vec<[f64; 2]>, tool: [f64; 2]) -> Vec<[f64; 2]> { if index == 0 { return ring; } - let mut rotated: Vec<[f64; 2]> = ring[index..last].to_vec(); - rotated.extend_from_slice(&ring[..=index]); - ring.clear(); + let mut rotated: Vec = ring[index..].to_vec(); + rotated.extend_from_slice(&ring[..index]); rotated } @@ -2637,7 +2712,7 @@ fn rotate_to_nearest(mut ring: Vec<[f64; 2]>, tool: [f64; 2]) -> Vec<[f64; 2]> { /// dropped, splitting the loop into open pieces. #[allow(clippy::too_many_arguments)] fn prove_ring( - ring: &[[f64; 2]], + ring: &[crate::pocket::Stroke], z: f64, r: f64, index: &Index, @@ -2650,31 +2725,61 @@ fn prove_ring( cancel: &impl CancelSignal, ) -> Result, String> { let mut pieces: Vec = vec![]; - fn push(pieces: &mut Vec, a: [f64; 2], b: [f64; 2], z: f64) { + // Append a segment, merging consecutive collinear chords of the same loop + // (direction change below 1e-9 rad, both proven, one straight move): a + // proven straight edge is not split into many chords. + fn push(pieces: &mut Vec, seg: crate::pocket::Stroke, z: f64) { if let Some(last) = pieces.last_mut() - && last.pts.last().is_some_and(|p| [p[0], p[1]] == a) + && last.z == z + && last.segs.last().is_some_and(|s| s.b == seg.a) { - last.pts.push([b[0], b[1], z]); + let l = last.segs.last_mut().unwrap(); + if l.arc.is_none() && seg.arc.is_none() { + let d0 = [l.b[0] - l.a[0], l.b[1] - l.a[1]]; + let d1 = [seg.b[0] - seg.a[0], seg.b[1] - seg.a[1]]; + let (l0, l1) = (d0[0].hypot(d0[1]), d1[0].hypot(d1[1])); + if l0 > 0. + && l1 > 0. + && (d0[0] * d1[1] - d0[1] * d1[0]).abs() <= 1e-9 * l0 * l1 + && d0[0] * d1[0] + d0[1] * d1[1] > 0. + { + l.b = seg.b; + return; + } + } + last.segs.push(seg); return; } - pieces.push(Piece { - pts: vec![[a[0], a[1], z], [b[0], b[1], z]], - }); + pieces.push(Piece { z, segs: vec![seg] }); } - for w in ring.windows(2) { - if cancel.is_cancelled() { - return Err("flat-area planning cancelled".into()); - } - let (a, b) = ([w[0][0], w[0][1]], [w[1][0], w[1][1]]); + // Prove the straight stretch from `a` to `b` with the capsule radius `rc`: + // kept where the highest part point under the capsule is not above the cut + // height plus the tolerance (split by the limits into kept spans), halved + // down to h / 16 otherwise, what cannot be proven dropped. + fn prove_line( + pieces: &mut Vec, + index: &Index, + seen: &mut [u32], + stamp: &mut u32, + a: [f64; 2], + b: [f64; 2], + rc: f64, + z: f64, + h: f64, + tolerance: f64, + limits: Option<&crate::limits::PreparedLimits>, + dropped: &mut f64, + cancel: &impl CancelSignal, + ) -> Result<(), String> { let mut stack = vec![(a, b, 0u32)]; while let Some((a, b, depth)) = stack.pop() { if cancel.is_cancelled() { return Err("flat-area planning cancelled".into()); } let length = (b[0] - a[0]).hypot(b[1] - a[1]); - if index.max_height(a, b, r, seen, stamp) <= z + tolerance { + if index.max_height(a, b, rc, seen, stamp) <= z + tolerance { match limits { - None => push(&mut pieces, a, b, z), + None => push(pieces, crate::pocket::Stroke::line(a, b), z), Some(limits) => { // Only the stretches proven inside the limits. let line = crate::motion::Curve::Line { @@ -2686,7 +2791,7 @@ fn prove_ring( let p = [a[0] + t0 * (b[0] - a[0]), a[1] + t0 * (b[1] - a[1])]; let q = [a[0] + t1 * (b[0] - a[0]), a[1] + t1 * (b[1] - a[1])]; if (q[0] - p[0]).hypot(q[1] - p[1]) > tolerance { - push(&mut pieces, p, q, z); + push(pieces, crate::pocket::Stroke::line(p, q), z); kept += (t1 - t0) * length; } } @@ -2703,28 +2808,110 @@ fn prove_ring( stack.push((m, b, depth + 1)); stack.push((a, m, depth + 1)); } + Ok(()) + } + for seg in ring { + if cancel.is_cancelled() { + return Err("flat-area planning cancelled".into()); + } + let Some((c, sweep)) = seg.arc else { + prove_line( + &mut pieces, index, seen, stamp, seg.a, seg.b, r, z, h, tolerance, limits, + dropped, cancel, + )?; + continue; + }; + // An arc of the offset loop: covered by its chords (sagitta at most + // the tolerance, refined while chords fail), each proven with the + // capsule of radius r + sagitta, which contains the arc's swept disk. + // Every chord proven, the arc is one move; otherwise the proven + // chords stand in for it. + let rho = (seg.a[0] - c[0]).hypot(seg.a[1] - c[1]); + let start = (seg.a[1] - c[1]).atan2(seg.a[0] - c[0]); + // Chords no shorter than the halving floor, so the refinement (and the + // fallback's chords) stay above what a straight chord could prove. + let count_cap = + ((sweep.abs() * rho / (h / 16.)).ceil() as usize).max(1).next_power_of_two(); + let mut count = { + let half = (1. - tolerance / rho).clamp(-1., 1.).acos().max(1e-9); + ((sweep.abs() / (2. * half)).ceil().max(1.) as usize).min(count_cap) + }; + let chord = |i: usize, count: usize| { + let t0 = i as f64 / count as f64; + let t1 = (i + 1) as f64 / count as f64; + let p = [ + c[0] + rho * (start + sweep * t0).cos(), + c[1] + rho * (start + sweep * t0).sin(), + ]; + let q = [ + c[0] + rho * (start + sweep * t1).cos(), + c[1] + rho * (start + sweep * t1).sin(), + ]; + let sagitta = rho * (1. - (sweep.abs() / (2. * count as f64)).cos()); + (p, q, sagitta) + }; + let mut proven = false; + while count <= count_cap { + if cancel.is_cancelled() { + return Err("flat-area planning cancelled".into()); + } + let all_clear = (0..count).all(|i| { + let (p, q, sagitta) = chord(i, count); + index.max_height(p, q, r + sagitta, seen, stamp) <= z + tolerance + }); + if all_clear { + proven = true; + break; + } + count *= 2; + } + // The whole arc must also sit inside the limits; otherwise its chords + // are checked against them one by one below. + let allowed = limits.map_or(Ok(true), |l| { + l.allows_curve(&seg.curve(z), true) + })?; + if proven && allowed { + // One proven arc piece, split so every move's chord stays within + // `ARC_MOVE_SAGITTA` of the arc; the proof above covers the whole + // arc, every piece of it included. + for sub in split_arc(seg, ARC_MOVE_SAGITTA) { + push(&mut pieces, sub, z); + } + continue; + } + // The arc's chords at the tolerance's sagitta, each proven with the + // arc's capsule radius; failures are halved like straight chords. + let half = (1. - tolerance / rho).clamp(-1., 1.).acos().max(1e-9); + let count = ((sweep.abs() / (2. * half)).ceil().max(1.) as usize).min(count_cap); + let sagitta = rho * (1. - (sweep.abs() / (2. * count as f64)).cos()); + for i in 0..count { + let (p, q, _) = chord(i, count); + prove_line( + &mut pieces, index, seen, stamp, p, q, r + sagitta, z, h, tolerance, limits, + dropped, cancel, + )?; + } } Ok(pieces) } -/// Side-entry candidates of a piece: its vertices, at most one per 1 mm of -/// the piece, each with the outward normal (right of travel: away from the +/// Side-entry candidates of a piece: its segment starts, at most one per 1 mm +/// of the piece, each with the outward normal (right of travel: away from the /// region on a counter-clockwise outer loop, into the hole on a clockwise -/// hole loop). +/// hole loop). On an arc the tangent at its start stands in for the chord. fn side_candidates(piece: &Piece) -> Vec<([f64; 2], [f64; 2])> { let mut side = vec![]; let mut taken: Option<[f64; 2]> = None; - for w in piece.pts.windows(2) { - let v = [w[0][0], w[0][1]]; + for seg in &piece.segs { + let v = seg.a; if taken.is_some_and(|p| (v[0] - p[0]).hypot(v[1] - p[1]) < 1.) { continue; } - let d = [w[1][0] - w[0][0], w[1][1] - w[0][1]]; - let n = d[0].hypot(d[1]); - if n <= 0. { + let d = seg.tangent(false); + if !(d[0]).is_finite() || d[0].hypot(d[1]) <= 0. { continue; } - side.push((v, [d[1] / n, -d[0] / n])); + side.push((v, [d[1], -d[0]])); taken = Some(v); } side From 6ba0c314ecec1f710f3ef3cd89162d345fb3ca5c Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:25:55 -0700 Subject: [PATCH 06/26] Flat: half-step ring where the next offset pinches off --- src/flat.rs | 74 +++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 66 insertions(+), 8 deletions(-) diff --git a/src/flat.rs b/src/flat.rs index c7d3a51..760b455 100644 --- a/src/flat.rs +++ b/src/flat.rs @@ -2534,8 +2534,12 @@ impl LoopGroup { /// after the last non-empty offset `d`, while the region offset by /// `d + r - 16 tolerances` is still non-empty, the loops at `d + stepover/2` /// are added and the check repeats, so the disk covers every reachable point. -/// Each loop keeps its arcs (cavalier contours' bulges); outer boundaries end -/// up counter-clockwise and holes clockwise (climb with a clockwise spindle). +/// With a stepover above the radius, an interval whose next offset pinched +/// off (a corner between two boundaries of the region) also gets a ring at +/// half the stepover, so the disk covers every reachable point there too +/// (stepover up to the cutter diameter). Each loop keeps its arcs (cavalier +/// contours' bulges); outer boundaries end up counter-clockwise and holes +/// clockwise (climb with a clockwise spindle). fn level_loops( region: &crate::planar::PreparedRegion, r: f64, @@ -2543,6 +2547,7 @@ fn level_loops( tolerance: f64, cancel: &impl CancelSignal, ) -> Result, String> { + use crate::planar::Boolean; let options = crate::planar::ConstructionOptions { tolerance_mm: tolerance }; let guard = 16. * tolerance; let mut groups = vec![]; @@ -2584,20 +2589,73 @@ fn level_loops( Ok(()) }; let mut d = 0.; - loop { + let mut eroded = prepared + .offset_prepared(d) + .map_err(|e| format!("flat-area loop offset: {e}"))? + .into_parts() + .1; + while !eroded.definition().components.is_empty() { if cancel.is_cancelled() { return Err("flat-area planning cancelled".into()); } - let eroded = prepared - .offset_prepared(d) + collect(&eroded, d)?; + let next = prepared + .offset_prepared(d + stepover) .map_err(|e| format!("flat-area loop offset: {e}"))? .into_parts() .1; - if eroded.definition().components.is_empty() { - break; + if stepover > r && !next.definition().components.is_empty() { + // With the stepover above the radius, points deeper than + // d + r but shallower than the next ring at d + stepover are + // covered by that ring from below only where its offset + // survives; where the offset pinched off (a corner between + // two boundaries of the region) the surviving ring stretches + // on either side can be more than 2r apart and such points + // are out of reach of every ring. They are exactly the band + // deeper than d + r - guard, outside the next offset, and + // farther than r from the next offset's area (the disk + // cannot reach them from there either): halve the gap with a + // ring at d + stepover/2, which lies at or below their depth + // (stepover <= 2r) and within stepover/2 <= r of them along + // their ray to the boundary. At a stepover at or below the + // radius no interval is deeper than d + r before the next + // ring, so this never fires. + let shallow = prepared + .offset_prepared(d + r - guard) + .map_err(|e| format!("flat-area loop offset: {e}"))? + .into_parts() + .1; + let band = shallow + .boolean_prepared(&next, Boolean::Difference) + .map_err(|e| format!("flat-area loop offset: {e}"))? + .into_parts() + .1; + if !band.definition().components.is_empty() { + let reach = next + .offset_prepared(-r) + .map_err(|e| format!("flat-area loop offset: {e}"))? + .into_parts() + .1; + let gap = band + .boolean_prepared(&reach, Boolean::Difference) + .map_err(|e| format!("flat-area loop offset: {e}"))? + .into_parts() + .1; + if !gap.definition().components.is_empty() { + let half = d + stepover / 2.; + let mid = prepared + .offset_prepared(half) + .map_err(|e| format!("flat-area loop offset: {e}"))? + .into_parts() + .1; + if !mid.definition().components.is_empty() { + collect(&mid, half)?; + } + } + } } - collect(&eroded, d)?; d += stepover; + eroded = next; } let mut core = d - stepover; loop { From c135772259c4493dccb885213c8d325f0bb98285 Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:30:28 -0700 Subject: [PATCH 07/26] Flat: docs for contour-parallel passes, arcs and half-step pinch rings --- docs/operations.md | 68 ++++++++++++------ python/camlib/operations.py | 25 ++++--- src/flat.rs | 139 +++++++++++++++++++++++++----------- 3 files changed, 161 insertions(+), 71 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 5138edb..1e909a3 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -1619,26 +1619,54 @@ Required: `surface`, `floor_z_mm`, `stepover_mm`, `clearance_z_mm`. Finds the horizontal faces above `floor_z_mm` (faces within `level_tolerance_mm`, 0.001, form one level) and finishes each level at its exact height plus `stock_to_leave_mm`, top level first, with a flat center-cutting end mill in -raster rows along `axis`. A cut is kept only where the highest point of the -part under the tool's swept disk is not above the cut (computed exactly per -facet). A run is entered by a vertical plunge where no live stock stands -above its height at its start (within `tolerance_mm`). Where stock does (roughing -left it, or the stock was not cut there yet), the run is entered by a ramp, and -only if the operation declares `entry=RampEntry(angle_deg, ...)`: the tool -plunges through air to the top of the live stock over the whole run (the highest -cell bound anywhere along it, not just at its start), then zigzags down along -the run at no more than the declared angle and at the entry's `feed_mm_min` -(default the plunge feed). A zigzag that has to reverse on the run needs the -entry's `min_length_mm`. Every ramp point lies above the proven run, so it -clears the part like the run does; the report counts the ramped runs as -`ramped_entries`. Nothing is plunged into stock on any path: a run with stock -above it and no declared entry, a ramp that does not fit (too short a run, an -angle too shallow for the run, or stock above the feed height) is refused, -naming the run, its length and the stock above it. The `flat` benchmark runs on -a blank roughed to 0.1 mm over the flats and declares a 3 degree entry. Near -walls the tool stays a -radius away; the report gives the levels, runs, cut length and any row length -that could not be proven clear (`dropped_length_mm`). +contour-parallel offset passes, outside in. The region of tool centres resting +on a level is the level's shadow grown by the cutter radius minus the shadow of +everything standing above it grown by the radius plus its stated errors, so +near walls the tool stays a radius away. Its inward offsets 0, `stepover_mm`, +2 `stepover_mm`, ... are the passes; after the last one, a core deeper than a +radius is covered by half-step passes while it lasts, and where an offset +pinches off in a corner between two boundaries of the region (the surviving +ring stretches more than a diameter apart) a half-step pass is added too, so +the disk covers every reachable flat point at stepovers up to the cutter +diameter. Offset loops are cut as arcs (the offsets' cavalier bulges), an arc +proven by its chords, each chord held to the same proof with radius +r + sagitta, and emitted as arc blocks when every chord proves; a chord that +cannot be proven is halved down to a sixteenth of the loop, and what still +fails is dropped into `dropped_length_mm`, the loop continuing as open +pieces. A cut is kept only where the highest point of the part under the +tool's swept disk is not above the cut (computed exactly per facet). Per +connected component, nearest first, the passes are cut at growing offset +depth (the outermost ring first); at the same depth outer boundary loops +before hole loops, then nearest first, and each loop starts at its vertex +nearest the tool. Consecutive pieces join into one chain by a straight link +at the cut height and cutting feed when the link is at most two stepovers +long, passes the same proof and lies inside the machine limits; otherwise the +chain ends (retract, new entry). A chain is entered beside the level's face +where the flat is open (side entry in air): the tool rapids over a point a +quarter to two radii outside the chain's first loop, away from the region, +where no stock stands within the disk above the cut, plunges vertically +through air to the cut height and leads in at cutting feed. Where no such +point exists it plunges vertically at the chain's start when no live stock +stands above its height there (within `tolerance_mm`). Where stock does +(roughing left it, or the stock was not cut there yet), the chain is entered +by a ramp, and only if the operation declares `entry=RampEntry(angle_deg, +...)`: the tool plunges through air to the top of the live stock over the +chain's first loop (the highest cell bound anywhere along it, not just at its +start), then zigzags down along that loop at no more than the declared angle +and at the entry's `feed_mm_min` (default the plunge feed); a zigzag that has +to reverse needs the entry's `min_length_mm`. Every ramp point lies above the +proven loop, so it clears the part like the loop does; the report counts +ramped chains as `ramped_entries`. Nothing is plunged into stock on any path: +a chain with stock above it and no declared entry, a ramp that does not fit +(too short a loop, an angle too shallow for the loop, or stock above the feed +height) is refused, naming the chain, its length and the stock above it. The +`flat` benchmark runs on a blank roughed to 0.1 mm over the flats and declares +a 3 degree entry. The report gives the levels, `loops` (closed offset loops +planned), `rows` (loops cut, counting the open pieces a split loop leaves), +`runs` (chains), `links_at_depth`, cut length, `runs_completed`, +`ramped_entries`, and any length that could not be proven clear +(`dropped_length_mm`). `axis` is still accepted so old jobs load, but no +longer orders anything. ## Spiral, radial and project finishing: `Spiral`, `Radial`, `Project` diff --git a/python/camlib/operations.py b/python/camlib/operations.py index c61d9dd..3562288 100644 --- a/python/camlib/operations.py +++ b/python/camlib/operations.py @@ -747,14 +747,23 @@ def to_dict(self): class Flat: """Flat-area finishing: finds the horizontal faces of ``surface`` above ``floor_z_mm`` and finishes each at its exact height (plus - ``stock_to_leave_mm``) with a flat, center-cutting end mill, in raster - rows ``stepover_mm`` apart along ``axis``. Each cut is kept only where - the part under the tool's swept disk is proven not above it. A run with no - stock above its height is entered with a vertical plunge. A run with - stock above it is refused unless ``entry=RampEntry(angle_deg, ...)`` is - declared: the tool then plunges to the stock's top over the whole run and - ramps down along the run (Z-flat tools are never plunged into stock). Faces - within ``level_tolerance_mm`` form one level.""" + ``stock_to_leave_mm``) with a flat, center-cutting end mill, in + contour-parallel offset passes worked outside in: the outermost ring of + each level first, the core last, with half-step rings where an offset + pinches off in a corner between two boundaries, so the disk covers every + reachable flat point at stepovers up to the cutter diameter. Offset + loops are cut as arcs, each proven by chords at radius r + sagitta like + the straight cuts. Every cut is kept only where the part under the tool's + swept disk is proven not above it. A chain of passes is entered beside + the level's face in air where the flat is open (a vertical plunge through + air, then a lead-in at cutting feed), else by a vertical plunge where no + stock stands above it. A chain with stock above it is refused unless + ``entry=RampEntry(angle_deg, ...)`` is declared: the tool then plunges to + the stock's top over the chain's first loop and ramps down along it + (Z-flat tools are never plunged into stock). Consecutive passes join by + straight links cut at depth when they are short, proven and inside the + machine limits. Faces within ``level_tolerance_mm`` form one level. + ``axis`` is accepted so old jobs load but no longer orders anything.""" id: str tool: object diff --git a/src/flat.rs b/src/flat.rs index 760b455..e530b4f 100644 --- a/src/flat.rs +++ b/src/flat.rs @@ -1833,8 +1833,14 @@ impl FlatPlan { let z = level + op.stock_to_leave_mm; // The tool centres resting on this level, as a planar region, and // the level's face (for keeping entries off it). - let Some((region, face)) = - level_region(&target, level, op.level_tolerance_mm, r, op.tolerance_mm, cancel)? + let Some((region, face)) = level_region( + &target, + level, + op.level_tolerance_mm, + r, + op.tolerance_mm, + cancel, + )? else { continue; }; @@ -2024,7 +2030,7 @@ impl FlatPlan { fn beside_face(&self, p: [f64; 2]) -> Result { let q = self.chains[self.chain].face.query(p)?; Ok(q.signed_clearance_mm - .map_or(true, |s| s <= self.op.tolerance_mm - self.radius)) + .is_none_or(|s| s <= self.op.tolerance_mm - self.radius)) } /// How the current chain is entered, decided against the live stock: from @@ -2047,7 +2053,13 @@ impl FlatPlan { continue; } // Outward, trying the shortest offset first. - for l in [0.25 * self.radius, 0.5 * self.radius, self.radius, 1.5 * self.radius, 2. * self.radius] { + for l in [ + 0.25 * self.radius, + 0.5 * self.radius, + self.radius, + 1.5 * self.radius, + 2. * self.radius, + ] { let p = [v[0] + l * n[0], v[1] + l * n[1]]; if stock.top_under_disk(p, self.radius) > z + tol { continue; @@ -2055,7 +2067,9 @@ impl FlatPlan { if !self.beside_face(p)? { continue; } - if self.index.max_height(p, *v, self.radius, &mut self.seen, &mut self.stamp) + if self + .index + .max_height(p, *v, self.radius, &mut self.seen, &mut self.stamp) > z + tol { continue; @@ -2063,7 +2077,7 @@ impl FlatPlan { if !allows_segment(self.limits.as_ref(), p, *v, z, tol)? { continue; } - let nearer = best.map_or(true, |(bv, _)| { + let nearer = best.is_none_or(|(bv, _)| { (v[0] - self.position[0]).hypot(v[1] - self.position[1]) < (bv[0] - self.position[0]).hypot(bv[1] - self.position[1]) }); @@ -2182,7 +2196,12 @@ impl FlatPlan { } }; self.entry = Some(entry); - ([over[0], over[1], p[2]], MoveKind::Rapid, Phase::Descend, None) + ( + [over[0], over[1], p[2]], + MoveKind::Rapid, + Phase::Descend, + None, + ) } Phase::Descend => ( [p[0], p[1], self.heights.feed], @@ -2193,12 +2212,9 @@ impl FlatPlan { Phase::Enter => { let a = self.chains[self.chain].pieces[self.piece].start(); match self.entry.take().expect("entry plan") { - Entry::Side { .. } => ( - [p[0], p[1], a[2]], - MoveKind::Plunge, - Phase::Lead, - None, - ), + Entry::Side { .. } => { + ([p[0], p[1], a[2]], MoveKind::Plunge, Phase::Lead, None) + } Entry::Plunge => ([p[0], p[1], a[2]], MoveKind::Plunge, Phase::Cut, None), Entry::Ramp { top, curves } => { self.ramp = curves.into(); @@ -2410,10 +2426,17 @@ fn level_region( r: f64, tolerance: f64, cancel: &impl CancelSignal, -) -> Result)>, String> -{ +) -> Result< + Option<( + crate::planar::PreparedRegion, + std::sync::Arc, + )>, + String, +> { use crate::planar::{Boolean, ConstructionOptions}; - let options = ConstructionOptions { tolerance_mm: tolerance }; + let options = ConstructionOptions { + tolerance_mm: tolerance, + }; let source_error = target.mesh().surface_error_mm; let mut work = 0usize; let below = target @@ -2512,17 +2535,18 @@ impl LoopGroup { .map(|s| (s.a[0] - tool[0]).hypot(s.a[1] - tool[1])) .fold(f64::INFINITY, f64::min) }; - let sort = |rings: &[(f64, Vec)]| -> Vec> { - let mut order: Vec = (0..rings.len()).collect(); - order.sort_by(|&a, &b| { - rings[a] - .0 - .total_cmp(&rings[b].0) - .then(near(&rings[a].1).total_cmp(&near(&rings[b].1))) - .then(a.cmp(&b)) - }); - order.into_iter().map(|i| rings[i].1.clone()).collect() - }; + let sort = + |rings: &[(f64, Vec)]| -> Vec> { + let mut order: Vec = (0..rings.len()).collect(); + order.sort_by(|&a, &b| { + rings[a] + .0 + .total_cmp(&rings[b].0) + .then(near(&rings[a].1).total_cmp(&near(&rings[b].1))) + .then(a.cmp(&b)) + }); + order.into_iter().map(|i| rings[i].1.clone()).collect() + }; let mut all = sort(&self.outers); all.extend(sort(&self.holes)); all @@ -2548,7 +2572,9 @@ fn level_loops( cancel: &impl CancelSignal, ) -> Result, String> { use crate::planar::Boolean; - let options = crate::planar::ConstructionOptions { tolerance_mm: tolerance }; + let options = crate::planar::ConstructionOptions { + tolerance_mm: tolerance, + }; let guard = 16. * tolerance; let mut groups = vec![]; for component in ®ion.definition().components { @@ -2568,9 +2594,7 @@ fn level_loops( .map_err(|e| format!("flat-area loop region: {e}"))?; let mut outers: Vec<(f64, Vec)> = vec![]; let mut holes: Vec<(f64, Vec)> = vec![]; - let mut collect = |eroded: &crate::planar::PreparedRegion, - d: f64| - -> Result<(), String> { + let mut collect = |eroded: &crate::planar::PreparedRegion, d: f64| -> Result<(), String> { let mut vertices = 0usize; for c in &eroded.definition().components { let outer = boundary_strokes(&c.outer, true)?; @@ -2583,7 +2607,8 @@ fn level_loops( holes.push((d, strokes)); } } - vertices += c.outer.vertices.len() + c.holes.iter().map(|h| h.vertices.len()).sum::(); + vertices += c.outer.vertices.len() + + c.holes.iter().map(|h| h.vertices.len()).sum::(); } crate::resources::check_memory(vertices as u128 * 24, "flat-area offset loops")?; Ok(()) @@ -2715,7 +2740,11 @@ fn boundary_strokes( let mut pts: Vec<[f64; 2]> = segs.iter().map(|s| s.a).collect(); pts.push(segs[0].a); if (ccw && signed_area(&pts) < 0.) || (!ccw && signed_area(&pts) > 0.) { - return Ok(segs.into_iter().rev().map(crate::pocket::Stroke::reversed).collect()); + return Ok(segs + .into_iter() + .rev() + .map(crate::pocket::Stroke::reversed) + .collect()); } Ok(segs) } @@ -2744,7 +2773,10 @@ fn rotate_piece(piece: &mut Piece, v: [f64; 2]) { /// Rotate a closed ring of segments (the last ending on the first's start) so /// it starts at the vertex nearest `tool` and ends there too. -fn rotate_to_nearest(ring: Vec, tool: [f64; 2]) -> Vec { +fn rotate_to_nearest( + ring: Vec, + tool: [f64; 2], +) -> Vec { if ring.len() < 2 { return ring; } @@ -2874,8 +2906,19 @@ fn prove_ring( } let Some((c, sweep)) = seg.arc else { prove_line( - &mut pieces, index, seen, stamp, seg.a, seg.b, r, z, h, tolerance, limits, - dropped, cancel, + &mut pieces, + index, + seen, + stamp, + seg.a, + seg.b, + r, + z, + h, + tolerance, + limits, + dropped, + cancel, )?; continue; }; @@ -2888,8 +2931,9 @@ fn prove_ring( let start = (seg.a[1] - c[1]).atan2(seg.a[0] - c[0]); // Chords no shorter than the halving floor, so the refinement (and the // fallback's chords) stay above what a straight chord could prove. - let count_cap = - ((sweep.abs() * rho / (h / 16.)).ceil() as usize).max(1).next_power_of_two(); + let count_cap = ((sweep.abs() * rho / (h / 16.)).ceil() as usize) + .max(1) + .next_power_of_two(); let mut count = { let half = (1. - tolerance / rho).clamp(-1., 1.).acos().max(1e-9); ((sweep.abs() / (2. * half)).ceil().max(1.) as usize).min(count_cap) @@ -2925,9 +2969,7 @@ fn prove_ring( } // The whole arc must also sit inside the limits; otherwise its chords // are checked against them one by one below. - let allowed = limits.map_or(Ok(true), |l| { - l.allows_curve(&seg.curve(z), true) - })?; + let allowed = limits.map_or(Ok(true), |l| l.allows_curve(&seg.curve(z), true))?; if proven && allowed { // One proven arc piece, split so every move's chord stays within // `ARC_MOVE_SAGITTA` of the arc; the proof above covers the whole @@ -2945,8 +2987,19 @@ fn prove_ring( for i in 0..count { let (p, q, _) = chord(i, count); prove_line( - &mut pieces, index, seen, stamp, p, q, r + sagitta, z, h, tolerance, limits, - dropped, cancel, + &mut pieces, + index, + seen, + stamp, + p, + q, + r + sagitta, + z, + h, + tolerance, + limits, + dropped, + cancel, )?; } } From 79923dcf11f27932635f0f0a4a2948ca9539ff18 Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:55:18 -0700 Subject: [PATCH 08/26] Flat: prove the link a side-entry rotation creates before rotating --- src/flat.rs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/flat.rs b/src/flat.rs index e530b4f..f49d278 100644 --- a/src/flat.rs +++ b/src/flat.rs @@ -2052,6 +2052,25 @@ impl FlatPlan { if !closed && *v != first { continue; } + // Rotating the closed first piece to `v` moves its end, and with + // it the chain's link at depth to the next piece: `prepare` + // proved that link from the piece's original end, the link from + // `v` never was. Accept the candidate only when the new link + // passes the same three tests as a link in `prepare`; otherwise + // try the next vertex. + if self.piece + 1 < self.chains[self.chain].pieces.len() && *v != first { + let next = self.chains[self.chain].pieces[self.piece + 1].start(); + let length = (next[0] - v[0]).hypot(next[1] - v[1]); + if length > 2. * self.op.stepover_mm + || self + .index + .max_height(*v, [next[0], next[1]], self.radius, &mut self.seen, &mut self.stamp) + > z + tol + || !allows_segment(self.limits.as_ref(), *v, [next[0], next[1]], z, tol)? + { + continue; + } + } // Outward, trying the shortest offset first. for l in [ 0.25 * self.radius, @@ -2760,8 +2779,6 @@ fn signed_area(pts: &[[f64; 2]]) -> f64 { /// Rotate a closed piece (the last point repeating the first) so it starts at /// the vertex `v` (one of its own points) and ends there too. -/// Rotate a closed piece (its last segment ending on the first's start) so it -/// starts at the vertex `v`. fn rotate_piece(piece: &mut Piece, v: [f64; 2]) { let Some(i) = piece.segs.iter().position(|s| s.a == v) else { return; From b8c46115965540d2d6f5729d36cd99f1e05b334b Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:31:54 -0700 Subject: [PATCH 09/26] Flat: a pass starting over its finished face ramps from the air above it --- src/flat.rs | 237 +++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 218 insertions(+), 19 deletions(-) diff --git a/src/flat.rs b/src/flat.rs index f49d278..dfa957c 100644 --- a/src/flat.rs +++ b/src/flat.rs @@ -1970,10 +1970,16 @@ impl FlatPlan { /// plunge where no live stock stands above the pass's height there (the /// cells' upper bounds, within a tolerance) and the disk comes down beside /// the level's face, otherwise a ramp from the stock's top over the whole - /// pass, down the pass by the declared `RampEntry`. Each ramp point lies - /// vertically above the proven pass, so it clears the part as the pass - /// does. A pass the ramp does not fit, or stock above a pass with no entry - /// declared, is refused: a flat end mill is never plunged into stock. + /// pass, down the pass by the declared `RampEntry`. When the pass starts + /// over the level's face with no stock above (so the plain plunge is + /// refused) and the stock over the pass is that face's already-cut floor, + /// the ramp leaves from the cut height plus the depth the declared ramp + /// drops over its `min_length_mm` instead: the descent stops in air above + /// the face and the ramp comes down along the pass, never straight onto + /// the finished flat. Each ramp point lies vertically above the proven + /// pass, so it clears the part as the pass does. A pass the ramp does not + /// fit, or stock above a pass with no entry declared, is refused: a flat + /// end mill is never plunged into stock. fn plunge_or_ramp( &self, piece: &Piece, @@ -2008,20 +2014,39 @@ impl FlatPlan { "{which}: the run is shorter than 16 tolerances, too short to ramp on. Rough or rest-rough this area first" )); } - if top > self.heights.feed { + // Reaching here with no stock above the start means the start is over + // the level's face (the plain plunge above refused it for that). When + // the stock over the whole pass is that face's already-cut floor (the + // cells' upper bounds sit a tolerance above the cut height after a + // cut), a ramp from the stock top has no depth: the descent to it + // would end straight down on the finished face. The ramp then leaves + // from the cut height plus the depth the declared ramp drops over its + // `min_length_mm` — `min_length_mm * tan(angle)`, the drop of one leg + // at the declared angle over the shortest span the tool may ramp on + // (the whole pass when none is declared: a one-leg ramp reverses on + // no span) — and descends along the pass as for stock. The stock top + // wins when it is higher (real stock along the pass): the descent to + // it stops at or above every stock cell under the pass, in air. + let target = if at_start <= a[2] + self.op.tolerance_mm { + let span = entry.min_length_mm.unwrap_or(length); + (a[2] + span * entry.angle_rad.tan()).max(top) + } else { + top + }; + if target > self.heights.feed { return Err(format!( - "{which}, above the feed height Z{:.3}: raise feed_z_mm/retract_z_mm or rough this area first", + "{which}, ramp start Z{target:.3} above the feed height Z{:.3}: raise feed_z_mm/retract_z_mm or rough this area first", self.heights.feed )); } let chain = piece.strokes(); let curves = entry - .zigzag(&chain, top, a[2]) + .zigzag(&chain, target, a[2]) .map_err(|why| format!("{which}: {why}. Use a steeper declared angle, a longer run, or rough this area first"))?; - // The curves run from the ramp's start (at the stock's top) to the - // pass's start; the vertical descent to the ramp's start happens in - // `next_motion_with_stock`. - Ok(Some((top, curves))) + // The curves run from the ramp's start (at the ramp's start height) + // to the pass's start; the vertical descent to the ramp's start + // happens in `next_motion_with_stock`. + Ok(Some((target, curves))) } /// Whether the disk at `p` comes down beside this chain's level's face: a /// radius (less the tolerance) outside the face region, so a vertical @@ -2616,12 +2641,12 @@ fn level_loops( let mut collect = |eroded: &crate::planar::PreparedRegion, d: f64| -> Result<(), String> { let mut vertices = 0usize; for c in &eroded.definition().components { - let outer = boundary_strokes(&c.outer, true)?; + let outer = boundary_strokes(&c.outer, true, tolerance)?; if !outer.is_empty() { outers.push((d, outer)); } for hole in &c.holes { - let strokes = boundary_strokes(hole, false)?; + let strokes = boundary_strokes(hole, false, tolerance)?; if !strokes.is_empty() { holes.push((d, strokes)); } @@ -2732,10 +2757,14 @@ fn level_loops( /// contours' bulges, as `Stroke::from_boundary`), oriented counter-clockwise /// when `ccw` (outer boundaries) and clockwise otherwise (holes): climb /// milling with a clockwise spindle. Degenerate segments (zero length or zero -/// sweep) carry no geometry and are dropped or straightened. +/// sweep) carry no geometry and are dropped or straightened. Arcs a boolean +/// or offset kernel flattened to a chord polygon are refitted from their +/// chords (`refit_arcs`) so a ring along them is one proven move instead of +/// one move per chord. fn boundary_strokes( boundary: &crate::planar::Boundary, ccw: bool, + tolerance: f64, ) -> Result, String> { let n = boundary.vertices.len(); if n < 2 { @@ -2758,14 +2787,136 @@ fn boundary_strokes( // arcs' orientation). let mut pts: Vec<[f64; 2]> = segs.iter().map(|s| s.a).collect(); pts.push(segs[0].a); - if (ccw && signed_area(&pts) < 0.) || (!ccw && signed_area(&pts) > 0.) { - return Ok(segs - .into_iter() + let flipped = (ccw && signed_area(&pts) < 0.) || (!ccw && signed_area(&pts) > 0.); + let segs = if flipped { + segs.into_iter() .rev() .map(crate::pocket::Stroke::reversed) - .collect()); + .collect() + } else { + segs + }; + Ok(refit_arcs(segs, tolerance / 4.)) +} + +/// Refit the arcs a boolean or offset kernel flattened to a chord polygon: a +/// maximal run of straight strokes whose vertices share one circle (within +/// `fit`) becomes one arc stroke again, so a ring along it is one proven move +/// — or the circumscribed polygon of the arc — instead of one move per +/// flattened chord. Only runs fully on the circle, with chords short against +/// the radius, a steady one-sided turn and a sweep under a full circle are +/// accepted; anything else stays chords, and every emitted piece is still +/// proven against the part before it is cut. +fn refit_arcs(segs: Vec, fit: f64) -> Vec { + const MIN_RUN: usize = 4; + if segs.len() < MIN_RUN { + return segs; + } + let mut pts: Vec<[f64; 2]> = segs.iter().map(|s| s.a).collect(); + pts.push(segs[segs.len() - 1].b); + let mut out: Vec = Vec::with_capacity(segs.len()); + let mut i = 0; + while i < segs.len() { + if segs[i].arc.is_some() { + out.push(segs[i]); + i += 1; + continue; + } + // The longest run of line strokes from `i` whose vertices share one + // circle: extend while the whole run still fits, and keep the last + // fit (it was checked against every vertex of the accepted run). + let mut j = i; + let mut fitted: Option<([f64; 2], f64)> = None; + while j + 1 < segs.len() + && segs[j + 1].arc.is_none() + && let Some(f) = fit_circle_run(&pts[i..=j + 2], fit) + { + fitted = Some(f); + j += 1; + } + if j - i + 1 >= MIN_RUN + && let Some((centre, sweep)) = fitted + { + out.push(crate::pocket::Stroke { + a: pts[i], + b: pts[j + 1], + arc: Some((centre, sweep)), + }); + i = j + 1; + continue; + } + out.push(segs[i]); + i += 1; + } + out +} + +/// The circle through the first, middle and last of `pts`, when every point +/// sits on it within `fit`, the chords are short against the radius, the turn +/// is steady and one-sided and the sweep stays under a full circle: the +/// centre and the signed sweep from the first to the last point. +fn fit_circle_run(pts: &[[f64; 2]], fit: f64) -> Option<([f64; 2], f64)> { + let n = pts.len(); + if n < 3 { + return None; + } + let (p, q, r) = (pts[0], pts[n / 2], pts[n - 1]); + let cross = (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]); + let long = (q[0] - p[0]).hypot(q[1] - p[1]) * (r[0] - p[0]).hypot(r[1] - p[1]); + // Collinear to the same 1e-9 rad a merged straight stretch may keep. + if long <= 0. || cross.abs() <= 1e-9 * long { + return None; + } + let (p2, q2, r2) = ( + p[0] * p[0] + p[1] * p[1], + q[0] * q[0] + q[1] * q[1], + r[0] * r[0] + r[1] * r[1], + ); + let centre = [ + (p2 * (q[1] - r[1]) + q2 * (r[1] - p[1]) + r2 * (p[1] - q[1])) / (2. * cross), + (p2 * (r[0] - q[0]) + q2 * (p[0] - r[0]) + r2 * (q[0] - p[0])) / (2. * cross), + ]; + let radius = (p[0] - centre[0]).hypot(p[1] - centre[1]); + if !radius.is_finite() || !(1e-9..=1e6).contains(&radius) { + return None; + } + // Every vertex on the circle, every chord short against the radius. + for s in pts { + if ((s[0] - centre[0]).hypot(s[1] - centre[1]) - radius).abs() > fit { + return None; + } + } + for w in pts.windows(2) { + if (w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1]) > 0.1 * radius { + return None; + } } - Ok(segs) + // A steady one-sided turn: no chord turns against the run's direction. + let mut side = 0i32; + for w in pts.windows(3) { + let t = (w[1][0] - w[0][0]) * (w[2][1] - w[1][1]) + - (w[1][1] - w[0][1]) * (w[2][0] - w[1][0]); + let sign = t.signum() as i32; + if sign != 0 { + if side == 0 { + side = sign; + } else if side != sign { + return None; + } + } + } + // The signed sweep from the first to the last point around the centre. + let mut sweep = 0.; + let mut prev = [pts[0][0] - centre[0], pts[0][1] - centre[1]]; + for &s in &pts[1..] { + let cur = [s[0] - centre[0], s[1] - centre[1]]; + sweep += (prev[0] * cur[1] - prev[1] * cur[0]).atan2(prev[0] * cur[0] + prev[1] * cur[1]); + prev = cur; + } + if !sweep.is_finite() || sweep.abs() >= 2. * std::f64::consts::PI { + return None; + } + Some((centre, sweep)) } /// Signed area of a closed polyline (the first point repeated at the end). @@ -2832,6 +2983,7 @@ fn prove_ring( cancel: &impl CancelSignal, ) -> Result, String> { let mut pieces: Vec = vec![]; + // Append a segment, merging consecutive collinear chords of the same loop // (direction change below 1e-9 rad, both proven, one straight move): a // proven straight edge is not split into many chords. @@ -2996,6 +3148,53 @@ fn prove_ring( } continue; } + // Before the chord fallback: the arc's circumscribed polygon. Its + // `sides + 1` edges are the tangents at start + k*sweep/sides + // (k = 0..sides), so the path runs a -> the intersections of + // consecutive tangents (at the mid angles, radius + // rho / cos(sweep/(2*sides))) -> b, touching the circle at the + // tangent points and ending on the arc's own endpoints. For an arc + // whose centre is on the obstacle side (a convex corner of the + // blocked region, as round the grown shadow of a boss standing + // above) every edge stays on or outside the circle, away from the + // centre, so the disk along an edge keeps at least the clearance the + // planned arc's own disk has, and the edge proves as a straight cut + // at radius r with no sagitta: the move IS the segment. The polygon + // strays from the planned ring at most + // rho * (1/cos(sweep/(2*sides)) - 1) at its vertices, held to + // `ARC_MOVE_SAGITTA` through `sides`. An edge that fails the proof + // (the centre on the region side, the polygon bulging toward the + // obstacle) sends the arc to the chords below. + let sides = { + let step = (rho / (rho + ARC_MOVE_SAGITTA)).acos().max(1e-9); + ((sweep.abs() / (2. * step)).ceil().max(1.) as usize).max(1) + }; + let reach = rho / (sweep.abs() / (2. * sides as f64)).cos(); + let mut points = Vec::with_capacity(sides + 2); + points.push(seg.a); + for k in 0..sides { + let mid = start + sweep * (k as f64 + 0.5) / sides as f64; + points.push([c[0] + reach * mid.cos(), c[1] + reach * mid.sin()]); + } + points.push(seg.b); + let mut circumscribed = true; + for pair in points.windows(2) { + if cancel.is_cancelled() { + return Err("flat-area planning cancelled".into()); + } + if index.max_height(pair[0], pair[1], r, seen, stamp) > z + tolerance + || !allows_segment(limits, pair[0], pair[1], z, tolerance)? + { + circumscribed = false; + break; + } + } + if circumscribed { + for pair in points.windows(2) { + push(&mut pieces, crate::pocket::Stroke::line(pair[0], pair[1]), z); + } + continue; + } // The arc's chords at the tolerance's sagitta, each proven with the // arc's capsule radius; failures are halved like straight chords. let half = (1. - tolerance / rho).clamp(-1., 1.).acos().max(1e-9); From ff0d05752a3968a6a651929fc84f5afd2f0673dd Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:54:53 -0700 Subject: [PATCH 10/26] Flat: drop loops the offset kernel vouches no geometry for --- src/flat.rs | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 57 insertions(+), 2 deletions(-) diff --git a/src/flat.rs b/src/flat.rs index dfa957c..7e708e5 100644 --- a/src/flat.rs +++ b/src/flat.rs @@ -2640,14 +2640,27 @@ fn level_loops( let mut holes: Vec<(f64, Vec)> = vec![]; let mut collect = |eroded: &crate::planar::PreparedRegion, d: f64| -> Result<(), String> { let mut vertices = 0usize; + // A loop the kernel vouches no geometry for is not cut: shorter + // than the guard (16 tolerances), or — the offset kernel + // quantizes vertices to its construction grid (32 tolerances per + // coordinate), so an offset that pinches to a point comes back as + // a square of side 4 * guard, 16 times the guard — every extent + // of the loop fits inside the kernel's own stated boundary error + // for this offset (8.027e-4 mm against the square's 6.4e-4 on the + // stepped test part's boss top at d = 6). Such a loop is the + // kernel's representation of a point or line, not a feature. Its + // points lie at depth d, within the stepover (at most the radius) + // of the ring at d - stepover along their ray to the boundary, so + // the disk covers them from that ring. + let error = eroded.definition().boundary_error_mm; for c in &eroded.definition().components { let outer = boundary_strokes(&c.outer, true, tolerance)?; - if !outer.is_empty() { + if !outer.is_empty() && !degenerate_loop(&outer, guard, error) { outers.push((d, outer)); } for hole in &c.holes { let strokes = boundary_strokes(hole, false, tolerance)?; - if !strokes.is_empty() { + if !strokes.is_empty() && !degenerate_loop(&strokes, guard, error) { holes.push((d, strokes)); } } @@ -2753,6 +2766,48 @@ fn level_loops( Ok(groups) } +/// Whether a loop carries no geometry the kernel vouches for: its total +/// length is below `guard` (16 tolerances), or every extent of the loop fits +/// inside `error`, the kernel's own stated boundary error for the +/// construction (see `collect` in `level_loops`). Extents cover the stroke +/// endpoints and, for arcs, the cardinal directions the sweep crosses — an +/// arc bulges past its endpoints' bounding box. +fn degenerate_loop(strokes: &[crate::pocket::Stroke], guard: f64, error: f64) -> bool { + let mut total = 0.; + let mut min = [f64::INFINITY; 2]; + let mut max = [f64::NEG_INFINITY; 2]; + for s in strokes { + total += crate::profiles::stroke_length(s); + for p in [s.a, s.b] { + for k in 0..2 { + min[k] = min[k].min(p[k]); + max[k] = max[k].max(p[k]); + } + } + if let Some((c, sweep)) = s.arc { + let rho = (s.a[0] - c[0]).hypot(s.a[1] - c[1]); + let start = (s.a[1] - c[1]).atan2(s.a[0] - c[0]); + let tau = 2. * std::f64::consts::PI; + for k in 0..4 { + let angle = k as f64 * std::f64::consts::FRAC_PI_2; + let forward = if sweep >= 0. { + (angle - start).rem_euclid(tau) + } else { + (start - angle).rem_euclid(tau) + }; + if forward <= sweep.abs() { + let p = [c[0] + rho * angle.cos(), c[1] + rho * angle.sin()]; + for k in 0..2 { + min[k] = min[k].min(p[k]); + max[k] = max[k].max(p[k]); + } + } + } + } + } + total < guard || (max[0] - min[0]).max(max[1] - min[1]) <= error +} + /// The closed segment loop of a boundary: straight chords and arcs (cavalier /// contours' bulges, as `Stroke::from_boundary`), oriented counter-clockwise /// when `ccw` (outer boundaries) and clockwise otherwise (holes): climb From 6ae023d0fb36ddd1d25426be2c9fb564ad95b60f Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:58:21 -0700 Subject: [PATCH 11/26] Flat: cargo fmt --- src/flat.rs | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/flat.rs b/src/flat.rs index 7e708e5..88f2668 100644 --- a/src/flat.rs +++ b/src/flat.rs @@ -2087,10 +2087,13 @@ impl FlatPlan { let next = self.chains[self.chain].pieces[self.piece + 1].start(); let length = (next[0] - v[0]).hypot(next[1] - v[1]); if length > 2. * self.op.stepover_mm - || self - .index - .max_height(*v, [next[0], next[1]], self.radius, &mut self.seen, &mut self.stamp) - > z + tol + || self.index.max_height( + *v, + [next[0], next[1]], + self.radius, + &mut self.seen, + &mut self.stamp, + ) > z + tol || !allows_segment(self.limits.as_ref(), *v, [next[0], next[1]], z, tol)? { continue; @@ -2949,8 +2952,8 @@ fn fit_circle_run(pts: &[[f64; 2]], fit: f64) -> Option<([f64; 2], f64)> { // A steady one-sided turn: no chord turns against the run's direction. let mut side = 0i32; for w in pts.windows(3) { - let t = (w[1][0] - w[0][0]) * (w[2][1] - w[1][1]) - - (w[1][1] - w[0][1]) * (w[2][0] - w[1][0]); + let t = + (w[1][0] - w[0][0]) * (w[2][1] - w[1][1]) - (w[1][1] - w[0][1]) * (w[2][0] - w[1][0]); let sign = t.signum() as i32; if sign != 0 { if side == 0 { @@ -3246,7 +3249,11 @@ fn prove_ring( } if circumscribed { for pair in points.windows(2) { - push(&mut pieces, crate::pocket::Stroke::line(pair[0], pair[1]), z); + push( + &mut pieces, + crate::pocket::Stroke::line(pair[0], pair[1]), + z, + ); } continue; } From 6a90f5c5379b1bcf78102679c18bfeede64c5552 Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:16:39 -0700 Subject: [PATCH 12/26] Flat tests: match a plunge's face within the level tolerance (#38) --- python/tests/test_flat_offset.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/python/tests/test_flat_offset.py b/python/tests/test_flat_offset.py index 6f7f01c..d30df2f 100644 --- a/python/tests/test_flat_offset.py +++ b/python/tests/test_flat_offset.py @@ -254,7 +254,9 @@ def test_no_vertical_plunge_onto_a_finished_face(self): worst = (math.inf, None) for m in vertical_plunges(motions): b = m["curve"]["end"] - face = np.abs(field.H - b[2]) < 1e-6 + # Within the level tolerance: the mesh puts a level a few + # 1e-5 off its analytic height (3.00001 for Z3). + face = np.abs(field.H - b[2]) <= 1e-3 if not face.any(): continue d = float(np.min(np.hypot(field.X[face] - b[0], field.Y[face] - b[1]))) From ca49e1b627cbfa11b1bccbdeb22a0f533c3e610e Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:30:37 -0700 Subject: [PATCH 13/26] Flat: climb outside in, and no moves of kernel artefacts (#38) The passes run outside in, so the stock still to cut lies inward of each ring: outer loops now run clockwise and holes counter-clockwise, putting that stock on the right of travel (climb with a clockwise spindle). Before, the outer-loop-CCW orientation of pocket walls made most flat cutting conventional (stepped part: 40 mm climb against 199 mm conventional). refit_arcs also refits runs that mix straight chords with micro-arcs on one circle (the island part's 258 sub-0.01 mm cuts at Z5), and straight stubs under ARC_MOVE_SAGITTA are absorbed into a straight neighbour (the corner grid-snap stubs). Island 899 -> 644 motions, stepped 451 -> 449. --- docs/operations.md | 7 +- python/tests/test_flat_offset.py | 46 +++++++++++++ src/flat.rs | 111 +++++++++++++++++++++---------- 3 files changed, 129 insertions(+), 35 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 1e909a3..1c25d66 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -1638,7 +1638,12 @@ tool's swept disk is not above the cut (computed exactly per facet). Per connected component, nearest first, the passes are cut at growing offset depth (the outermost ring first); at the same depth outer boundary loops before hole loops, then nearest first, and each loop starts at its vertex -nearest the tool. Consecutive pieces join into one chain by a straight link +nearest the tool. Outer boundary loops run clockwise and hole loops counter-clockwise: the +stock still to cut lies inward of each ring (the passes go outside in), on the +right of travel, so the passes climb mill with a clockwise spindle. Kernel +artefacts are not cut as moves of their own: a run of strokes on one circle +(straight chords, or chords mixed with micro-arcs) is refitted as one arc, and +a straight stub under 0.005 mm is absorbed into its straight neighbour. Consecutive pieces join into one chain by a straight link at the cut height and cutting feed when the link is at most two stepovers long, passes the same proof and lies inside the machine limits; otherwise the chain ends (retract, new entry). A chain is entered beside the level's face diff --git a/python/tests/test_flat_offset.py b/python/tests/test_flat_offset.py index d30df2f..aced831 100644 --- a/python/tests/test_flat_offset.py +++ b/python/tests/test_flat_offset.py @@ -363,5 +363,51 @@ def test_never_cuts_below_the_part(self): self.assertLessEqual(worst, 1e-6, f"{name}: stock cut {worst:.4f} mm below the part") + def test_no_moves_of_kernel_artefacts(self): + # A kernel's flattened circle (chords mixed with micro-arcs) and its + # snapped corner stubs are not cut as moves of their own: no cut, + # link or lead shorter than 5 microns (the arcs' own move sagitta). + for name in ("stepped", "island"): + _, motions, *_ = cached(name) + tiny = [ + m["id"] + for m in motions + if m["kind"] in ("cut", "link", "lead") + and math.hypot(*(m["curve"]["end"][k] - m["curve"]["start"][k] for k in (0, 1))) < 0.005 + ] + self.assertEqual(tiny, [], f"{name}: moves under 5 microns: {tiny[:10]}") + + def test_passes_climb_mill(self): + # With a clockwise spindle a pass climbs when the stock it cuts lies on + # the right of travel. Measured on the live stock: just outside the + # disk, beside the middle of each straight cut, which side still has + # stock above the cut height. + for name in ("stepped", "island"): + _, motions, before, grid, _ = cached(name) + nx, ny, dx, dy, lo = grid + side = {"climb": 0.0, "conventional": 0.0} + for m, snap in zip(motions, before): + c = m["curve"] + a, b = c["start"], c["end"] + length = math.hypot(b[0] - a[0], b[1] - a[1]) + if m["kind"] != "cut" or c.get("kind", "line") != "line" or length < 1e-6: + continue + tx, ty = (b[0] - a[0]) / length, (b[1] - a[1]) / length + mid = ((a[0] + b[0]) / 2, (a[1] + b[1]) / 2) + + def stock(sign): + for d in (R * 0.8, R * 0.95): + x, y = mid[0] + sign * ty * d, mid[1] - sign * tx * d + i, j = int((x - lo[0]) / dx), int((y - lo[1]) / dy) + if 0 <= i < nx and 0 <= j < ny and snap[2 * (j * nx + i) + 1] > a[2] + 0.02: + return True + return False + + right, left = stock(1), stock(-1) + if right != left: + side["climb" if right else "conventional"] += length + self.assertGreater(side["climb"], 3 * side["conventional"], f"{name}: {side}") + + if __name__ == "__main__": unittest.main() diff --git a/src/flat.rs b/src/flat.rs index 88f2668..0f1f127 100644 --- a/src/flat.rs +++ b/src/flat.rs @@ -1594,7 +1594,7 @@ impl Piece { struct Chain { pieces: Vec, /// Side-entry candidates of the first pass: vertices (at most one per - /// 1 mm of the pass) with the outward normal, away from the region (right + /// 1 mm of the pass) with the outward normal, away from the region (left /// of travel). side: Vec<([f64; 2], [f64; 2])>, /// The level's face (the flat the pass finishes): an entry may only plunge @@ -2609,8 +2609,10 @@ impl LoopGroup { /// off (a corner between two boundaries of the region) also gets a ring at /// half the stepover, so the disk covers every reachable point there too /// (stepover up to the cutter diameter). Each loop keeps its arcs (cavalier -/// contours' bulges); outer boundaries end up counter-clockwise and holes -/// clockwise (climb with a clockwise spindle). +/// contours' bulges); outer boundaries end up clockwise and holes +/// counter-clockwise: the passes run outside in, so the stock still to cut +/// lies inward of each ring, on the right of travel — climb milling with a +/// clockwise spindle. fn level_loops( region: &crate::planar::PreparedRegion, r: f64, @@ -2657,12 +2659,12 @@ fn level_loops( // the disk covers them from that ring. let error = eroded.definition().boundary_error_mm; for c in &eroded.definition().components { - let outer = boundary_strokes(&c.outer, true, tolerance)?; + let outer = boundary_strokes(&c.outer, false, tolerance)?; if !outer.is_empty() && !degenerate_loop(&outer, guard, error) { outers.push((d, outer)); } for hole in &c.holes { - let strokes = boundary_strokes(hole, false, tolerance)?; + let strokes = boundary_strokes(hole, true, tolerance)?; if !strokes.is_empty() && !degenerate_loop(&strokes, guard, error) { holes.push((d, strokes)); } @@ -2813,8 +2815,7 @@ fn degenerate_loop(strokes: &[crate::pocket::Stroke], guard: f64, error: f64) -> /// The closed segment loop of a boundary: straight chords and arcs (cavalier /// contours' bulges, as `Stroke::from_boundary`), oriented counter-clockwise -/// when `ccw` (outer boundaries) and clockwise otherwise (holes): climb -/// milling with a clockwise spindle. Degenerate segments (zero length or zero +/// when `ccw` and clockwise otherwise. Degenerate segments (zero length or zero /// sweep) carry no geometry and are dropped or straightened. Arcs a boolean /// or offset kernel flattened to a chord polygon are refitted from their /// chords (`refit_arcs`) so a ring along them is one proven move instead of @@ -2854,41 +2855,83 @@ fn boundary_strokes( } else { segs }; - Ok(refit_arcs(segs, tolerance / 4.)) + Ok(absorb_stubs(refit_arcs(segs, tolerance / 4.))) +} + +/// Absorb the straight stubs of a closed ring — a stroke shorter than +/// `ARC_MOVE_SAGITTA`, where a kernel snapped two vertices of one corner a +/// few microns apart — into a neighbouring straight stroke, which then runs +/// to (or from) the stub's far end: the ring moves by less than the stub's +/// length, within what the arcs' moves already stray, and is proven as it +/// is afterwards. A stub between two arcs stays. +fn absorb_stubs(mut segs: Vec) -> Vec { + let mut k = 0; + while segs.len() > 3 && k < segs.len() { + let s = segs[k]; + let n = segs.len(); + if s.arc.is_some() || (s.b[0] - s.a[0]).hypot(s.b[1] - s.a[1]) >= ARC_MOVE_SAGITTA { + k += 1; + continue; + } + let (next, prev) = ((k + 1) % n, (k + n - 1) % n); + if segs[next].arc.is_none() { + segs[next].a = s.a; + } else if segs[prev].arc.is_none() { + segs[prev].b = s.b; + } else { + k += 1; + continue; + } + segs.remove(k); + } + segs } /// Refit the arcs a boolean or offset kernel flattened to a chord polygon: a -/// maximal run of straight strokes whose vertices share one circle (within -/// `fit`) becomes one arc stroke again, so a ring along it is one proven move -/// — or the circumscribed polygon of the arc — instead of one move per -/// flattened chord. Only runs fully on the circle, with chords short against -/// the radius, a steady one-sided turn and a sweep under a full circle are -/// accepted; anything else stays chords, and every emitted piece is still -/// proven against the part before it is cut. +/// maximal run of strokes whose vertices share one circle (within `fit`) +/// becomes one arc stroke again, so a ring along it is one proven move — or +/// the circumscribed polygon of the arc — instead of one move per flattened +/// chord. A run may mix straight chords with short arcs (the kernels also +/// return a flattened circle as alternating micro-arcs and micro-chords): an +/// arc joins a run through its end and mid points, which must sit on the +/// fitted circle like every vertex. Only runs fully on the circle, with +/// chords short against the radius, a steady one-sided turn and a sweep under +/// a full circle are accepted; anything else stays as it was, and every +/// emitted piece is still proven against the part before it is cut. fn refit_arcs(segs: Vec, fit: f64) -> Vec { const MIN_RUN: usize = 4; if segs.len() < MIN_RUN { return segs; } - let mut pts: Vec<[f64; 2]> = segs.iter().map(|s| s.a).collect(); - pts.push(segs[segs.len() - 1].b); + // A stroke's points before its end: the start, and an arc's mid point. + let inner = |s: &crate::pocket::Stroke| -> Vec<[f64; 2]> { + match s.arc { + None => vec![s.a], + Some((c, sweep)) => { + let rho = (s.a[0] - c[0]).hypot(s.a[1] - c[1]); + let mid = (s.a[1] - c[1]).atan2(s.a[0] - c[0]) + sweep / 2.; + vec![s.a, [c[0] + rho * mid.cos(), c[1] + rho * mid.sin()]] + } + } + }; let mut out: Vec = Vec::with_capacity(segs.len()); let mut i = 0; while i < segs.len() { - if segs[i].arc.is_some() { - out.push(segs[i]); - i += 1; - continue; - } - // The longest run of line strokes from `i` whose vertices share one - // circle: extend while the whole run still fits, and keep the last - // fit (it was checked against every vertex of the accepted run). + // The longest run of strokes from `i` whose points share one circle: + // extend while the whole run still fits, and keep the last fit (it was + // checked against every point of the accepted run). + let mut pts = inner(&segs[i]); let mut j = i; let mut fitted: Option<([f64; 2], f64)> = None; - while j + 1 < segs.len() - && segs[j + 1].arc.is_none() - && let Some(f) = fit_circle_run(&pts[i..=j + 2], fit) - { + while j + 1 < segs.len() { + let mut trial = pts.clone(); + trial.extend(inner(&segs[j + 1])); + trial.push(segs[j + 1].b); + let Some(f) = fit_circle_run(&trial, fit) else { + break; + }; + trial.pop(); + pts = trial; fitted = Some(f); j += 1; } @@ -2896,8 +2939,8 @@ fn refit_arcs(segs: Vec, fit: f64) -> Vec Vec<([f64; 2], [f64; 2])> { let mut side = vec![]; @@ -3300,7 +3343,7 @@ fn side_candidates(piece: &Piece) -> Vec<([f64; 2], [f64; 2])> { if !(d[0]).is_finite() || d[0].hypot(d[1]) <= 0. { continue; } - side.push((v, [d[1], -d[0]])); + side.push((v, [-d[1], d[0]])); taken = Some(v); } side From 7e382dd854a544c3451db6b915ae9521757cf950 Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:57:18 -0700 Subject: [PATCH 14/26] Flat tests: ruff format (#38) --- python/tests/test_flat_offset.py | 1 - 1 file changed, 1 deletion(-) diff --git a/python/tests/test_flat_offset.py b/python/tests/test_flat_offset.py index aced831..0fbfc7e 100644 --- a/python/tests/test_flat_offset.py +++ b/python/tests/test_flat_offset.py @@ -362,7 +362,6 @@ def test_never_cuts_below_the_part(self): worst = max(worst, lowest - final[2 * (j * nx + i) + 1]) self.assertLessEqual(worst, 1e-6, f"{name}: stock cut {worst:.4f} mm below the part") - def test_no_moves_of_kernel_artefacts(self): # A kernel's flattened circle (chords mixed with micro-arcs) and its # snapped corner stubs are not cut as moves of their own: no cut, From 521b0d018651494adcd5b1817158e9c9177ca56f Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:57:33 -0700 Subject: [PATCH 15/26] Flat docs: climb direction and the circumscribed-polygon fallback (#38) --- docs/operations.md | 108 +++++++++++++++++++++++---------------------- 1 file changed, 55 insertions(+), 53 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 1c25d66..70012f3 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -1619,59 +1619,61 @@ Required: `surface`, `floor_z_mm`, `stepover_mm`, `clearance_z_mm`. Finds the horizontal faces above `floor_z_mm` (faces within `level_tolerance_mm`, 0.001, form one level) and finishes each level at its exact height plus `stock_to_leave_mm`, top level first, with a flat center-cutting end mill in -contour-parallel offset passes, outside in. The region of tool centres resting -on a level is the level's shadow grown by the cutter radius minus the shadow of -everything standing above it grown by the radius plus its stated errors, so -near walls the tool stays a radius away. Its inward offsets 0, `stepover_mm`, -2 `stepover_mm`, ... are the passes; after the last one, a core deeper than a -radius is covered by half-step passes while it lasts, and where an offset -pinches off in a corner between two boundaries of the region (the surviving -ring stretches more than a diameter apart) a half-step pass is added too, so -the disk covers every reachable flat point at stepovers up to the cutter -diameter. Offset loops are cut as arcs (the offsets' cavalier bulges), an arc -proven by its chords, each chord held to the same proof with radius -r + sagitta, and emitted as arc blocks when every chord proves; a chord that -cannot be proven is halved down to a sixteenth of the loop, and what still -fails is dropped into `dropped_length_mm`, the loop continuing as open -pieces. A cut is kept only where the highest point of the part under the -tool's swept disk is not above the cut (computed exactly per facet). Per -connected component, nearest first, the passes are cut at growing offset -depth (the outermost ring first); at the same depth outer boundary loops -before hole loops, then nearest first, and each loop starts at its vertex -nearest the tool. Outer boundary loops run clockwise and hole loops counter-clockwise: the -stock still to cut lies inward of each ring (the passes go outside in), on the -right of travel, so the passes climb mill with a clockwise spindle. Kernel -artefacts are not cut as moves of their own: a run of strokes on one circle -(straight chords, or chords mixed with micro-arcs) is refitted as one arc, and -a straight stub under 0.005 mm is absorbed into its straight neighbour. Consecutive pieces join into one chain by a straight link -at the cut height and cutting feed when the link is at most two stepovers -long, passes the same proof and lies inside the machine limits; otherwise the -chain ends (retract, new entry). A chain is entered beside the level's face -where the flat is open (side entry in air): the tool rapids over a point a -quarter to two radii outside the chain's first loop, away from the region, -where no stock stands within the disk above the cut, plunges vertically -through air to the cut height and leads in at cutting feed. Where no such -point exists it plunges vertically at the chain's start when no live stock -stands above its height there (within `tolerance_mm`). Where stock does -(roughing left it, or the stock was not cut there yet), the chain is entered -by a ramp, and only if the operation declares `entry=RampEntry(angle_deg, -...)`: the tool plunges through air to the top of the live stock over the -chain's first loop (the highest cell bound anywhere along it, not just at its -start), then zigzags down along that loop at no more than the declared angle -and at the entry's `feed_mm_min` (default the plunge feed); a zigzag that has -to reverse needs the entry's `min_length_mm`. Every ramp point lies above the -proven loop, so it clears the part like the loop does; the report counts -ramped chains as `ramped_entries`. Nothing is plunged into stock on any path: -a chain with stock above it and no declared entry, a ramp that does not fit -(too short a loop, an angle too shallow for the loop, or stock above the feed -height) is refused, naming the chain, its length and the stock above it. The -`flat` benchmark runs on a blank roughed to 0.1 mm over the flats and declares -a 3 degree entry. The report gives the levels, `loops` (closed offset loops -planned), `rows` (loops cut, counting the open pieces a split loop leaves), -`runs` (chains), `links_at_depth`, cut length, `runs_completed`, -`ramped_entries`, and any length that could not be proven clear -(`dropped_length_mm`). `axis` is still accepted so old jobs load, but no -longer orders anything. +contour-parallel offset passes, outside in. Every pass is climb milled with a +clockwise spindle: cut outside in, the stock still to cut lies inward of each +ring, so outer loops run clockwise and hole loops counter-clockwise, keeping it +on the right of travel. The region of tool centres resting on a level is the +level's shadow grown by the cutter radius minus the shadow of everything +standing above it grown by the radius plus its stated errors, so near walls the +tool stays a radius away. Its inward offsets 0, `stepover_mm`, 2 `stepover_mm`, +... are the passes; after the last one, a core deeper than a radius is covered +by half-step passes while it lasts, and where an offset pinches off in a corner +between two boundaries of the region (the surviving ring stretches more than a +diameter apart) a half-step pass is added too, so the disk covers every +reachable flat point at stepovers up to the cutter diameter. Offset loops are +cut as arcs (the offsets' cavalier bulges), an arc proven by its chords, each +chord held to the same proof with radius r + sagitta, and emitted as arc blocks +when every chord proves; when a chord fails, the arc's circumscribed polygon +(tangent edges whose vertices stray at most 0.005 mm outside the arc) is tried +next, each edge proven as a straight cut, before falling back to the chords; a +chord that cannot be proven is halved down to a sixteenth of the loop, and what +still fails is dropped into `dropped_length_mm`, the loop continuing as open +pieces. A cut is kept only where the highest point of the part under the tool's +swept disk is not above the cut (computed exactly per facet). Per connected +component, nearest first, the passes are cut at growing offset depth (the +outermost ring first); at the same depth outer boundary loops before hole +loops, then nearest first, and each loop starts at its vertex nearest the tool. +Kernel artefacts are not cut as moves of their own: a run of strokes on one +circle (straight chords, or chords mixed with micro-arcs) is refitted as one +arc, and a straight stub under 0.005 mm is absorbed into its straight +neighbour. Consecutive pieces join into one chain by a straight link at the cut +height and cutting feed when the link is at most two stepovers long, passes the +same proof and lies inside the machine limits; otherwise the chain ends +(retract, new entry). A chain is entered beside the level's face where the flat +is open (side entry in air): the tool rapids over a point a quarter to two +radii outside the chain's first loop, away from the region, where no stock +stands within the disk above the cut, plunges vertically through air to the cut +height and leads in at cutting feed. Where no such point exists it plunges +vertically at the chain's start when no live stock stands above its height +there (within `tolerance_mm`). Where stock does (roughing left it, or the stock +was not cut there yet), the chain is entered by a ramp, and only if the +operation declares `entry=RampEntry(angle_deg, ...)`: the tool plunges through +air to the top of the live stock over the chain's first loop (the highest cell +bound anywhere along it, not just at its start), then zigzags down along that +loop at no more than the declared angle and at the entry's `feed_mm_min` +(default the plunge feed); a zigzag that has to reverse needs the entry's +`min_length_mm`. Every ramp point lies above the proven loop, so it clears the +part like the loop does; the report counts ramped chains as `ramped_entries`. +Nothing is plunged into stock on any path: a chain with stock above it and no +declared entry, a ramp that does not fit (too short a loop, an angle too +shallow for the loop, or stock above the feed height) is refused, naming the +chain, its length and the stock above it. The `flat` benchmark runs on a blank +roughed to 0.1 mm over the flats and declares a 3 degree entry. The report +gives the levels, `loops` (closed offset loops planned), `rows` (loops cut, +counting the open pieces a split loop leaves), `runs` (chains), +`links_at_depth`, cut length, `runs_completed`, `ramped_entries`, and any +length that could not be proven clear (`dropped_length_mm`). `axis` is still +accepted so old jobs load, but no longer orders anything. ## Spiral, radial and project finishing: `Spiral`, `Radial`, `Project` From 6de461dc7c84b9ea0daa9f6b5c14aeede53d6efc Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:12:02 -0700 Subject: [PATCH 16/26] Flat: no passes over air or finished floor (#38) --- docs/operations.md | 77 +++-- python/camlib/operations.py | 12 +- python/tests/test_flat_offset.py | 52 ++- src/flat.rs | 575 ++++++++++++++++++++++++++++--- 4 files changed, 623 insertions(+), 93 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 70012f3..0370697 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -1623,23 +1623,32 @@ contour-parallel offset passes, outside in. Every pass is climb milled with a clockwise spindle: cut outside in, the stock still to cut lies inward of each ring, so outer loops run clockwise and hole loops counter-clockwise, keeping it on the right of travel. The region of tool centres resting on a level is the -level's shadow grown by the cutter radius minus the shadow of everything -standing above it grown by the radius plus its stated errors, so near walls the -tool stays a radius away. Its inward offsets 0, `stepover_mm`, 2 `stepover_mm`, -... are the passes; after the last one, a core deeper than a radius is covered -by half-step passes while it lasts, and where an offset pinches off in a corner -between two boundaries of the region (the surviving ring stretches more than a -diameter apart) a half-step pass is added too, so the disk covers every -reachable flat point at stepovers up to the cutter diameter. Offset loops are -cut as arcs (the offsets' cavalier bulges), an arc proven by its chords, each -chord held to the same proof with radius r + sagitta, and emitted as arc blocks -when every chord proves; when a chord fails, the arc's circumscribed polygon -(tangent edges whose vertices stray at most 0.005 mm outside the arc) is tried -next, each edge proven as a straight cut, before falling back to the chords; a -chord that cannot be proven is halved down to a sixteenth of the loop, and what -still fails is dropped into `dropped_length_mm`, the loop continuing as open -pieces. A cut is kept only where the highest point of the part under the tool's -swept disk is not above the cut (computed exactly per facet). Per connected +level's shadow grown by the radius less one stepover (none at a stepover of a +radius or more), so past an open edge the outermost pass runs that far outside +the face and its disk takes one stepover of it like every later pass, minus the +shadow of everything standing above it grown by the radius plus its stated +errors, so near walls the tool stays a radius away. Its inward offsets 0, +`stepover_mm`, 2 `stepover_mm`, ... are the passes; after the last one, a core +deeper than a radius is covered by half-step passes while it lasts, and where +an offset pinches off in a corner between two boundaries of the region (the +surviving ring stretches more than a diameter apart) a half-step pass is added +too, so the disk covers every reachable flat point at stepovers up to the +cutter diameter. An inner pass is planned only while floor remains deeper than +the passes before it reach (more than a sliver thinner than the offset kernel's +stated error, which it cannot tell from a line), and it is cut only along the +stretches whose disk reaches that floor, less what the passes already kept at +its depth sweep. A gap between two kept stretches is cut through when that +takes no longer than a new entry's descent from the feed height at the plunge +feed, or is at most two stepovers. Offset loops are cut as arcs (the offsets' +cavalier bulges), an arc proven by its chords, each chord held to the same +proof with radius r + sagitta, and emitted as arc blocks when every chord +proves; when a chord fails, the arc's circumscribed polygon (tangent edges +whose vertices stray at most 0.005 mm outside the arc) is tried next, each edge +proven as a straight cut, before falling back to the chords; a chord that +cannot be proven is halved down to a sixteenth of the loop, and what still +fails is dropped into `dropped_length_mm`, the loop continuing as open pieces. +A cut is kept only where the highest point of the part under the tool's swept +disk is not above the cut (computed exactly per facet). Per connected component, nearest first, the passes are cut at growing offset depth (the outermost ring first); at the same depth outer boundary loops before hole loops, then nearest first, and each loop starts at its vertex nearest the tool. @@ -1658,22 +1667,24 @@ vertically at the chain's start when no live stock stands above its height there (within `tolerance_mm`). Where stock does (roughing left it, or the stock was not cut there yet), the chain is entered by a ramp, and only if the operation declares `entry=RampEntry(angle_deg, ...)`: the tool plunges through -air to the top of the live stock over the chain's first loop (the highest cell -bound anywhere along it, not just at its start), then zigzags down along that -loop at no more than the declared angle and at the entry's `feed_mm_min` -(default the plunge feed); a zigzag that has to reverse needs the entry's -`min_length_mm`. Every ramp point lies above the proven loop, so it clears the -part like the loop does; the report counts ramped chains as `ramped_entries`. -Nothing is plunged into stock on any path: a chain with stock above it and no -declared entry, a ramp that does not fit (too short a loop, an angle too -shallow for the loop, or stock above the feed height) is refused, naming the -chain, its length and the stock above it. The `flat` benchmark runs on a blank -roughed to 0.1 mm over the flats and declares a 3 degree entry. The report -gives the levels, `loops` (closed offset loops planned), `rows` (loops cut, -counting the open pieces a split loop leaves), `runs` (chains), -`links_at_depth`, cut length, `runs_completed`, `ramped_entries`, and any -length that could not be proven clear (`dropped_length_mm`). `axis` is still -accepted so old jobs load, but no longer orders anything. +air to the top of the live stock over the stretch of the chain's first loop the +ramp travels (the highest cell bound anywhere along that stretch; the whole +loop when the ramp has to reverse on it), then zigzags down along that loop at +no more than the declared angle (over each move's chord, so a leg along an arc +descends a little shallower) and at the entry's `feed_mm_min` (default the +plunge feed); a zigzag that has to reverse needs the entry's `min_length_mm`. +Every ramp point lies above the proven loop, so it clears the part like the +loop does; the report counts ramped chains as `ramped_entries`. Nothing is +plunged into stock on any path: a chain with stock above it and no declared +entry, a ramp that does not fit (too short a loop, an angle too shallow for the +loop, or stock above the feed height) is refused, naming the chain, its length +and the stock above it. The `flat` benchmark runs on a blank roughed to 0.1 mm +over the flats and declares a 3 degree entry. The report gives the levels, +`loops` (closed offset loops planned), `rows` (loops cut, counting the open +pieces a split loop leaves), `runs` (chains), `links_at_depth`, cut length, +`runs_completed`, `ramped_entries`, and any length that could not be proven +clear (`dropped_length_mm`). `axis` is still accepted so old jobs load, but no +longer orders anything. ## Spiral, radial and project finishing: `Spiral`, `Radial`, `Project` diff --git a/python/camlib/operations.py b/python/camlib/operations.py index 3562288..8d897f5 100644 --- a/python/camlib/operations.py +++ b/python/camlib/operations.py @@ -749,9 +749,12 @@ class Flat: ``floor_z_mm`` and finishes each at its exact height (plus ``stock_to_leave_mm``) with a flat, center-cutting end mill, in contour-parallel offset passes worked outside in: the outermost ring of - each level first, the core last, with half-step rings where an offset - pinches off in a corner between two boundaries, so the disk covers every - reachable flat point at stepovers up to the cutter diameter. Offset + each level first (past an open edge its centre runs the radius less one + stepover outside the face, so it takes one stepover like every later + pass), the core last, with half-step rings where an offset pinches off + in a corner between two boundaries, so the disk covers every reachable + flat point at stepovers up to the cutter diameter. An inner ring is cut + only where it finishes floor the rings before it have not reached. Offset loops are cut as arcs, each proven by chords at radius r + sagitta like the straight cuts. Every cut is kept only where the part under the tool's swept disk is proven not above it. A chain of passes is entered beside @@ -759,7 +762,8 @@ class Flat: air, then a lead-in at cutting feed), else by a vertical plunge where no stock stands above it. A chain with stock above it is refused unless ``entry=RampEntry(angle_deg, ...)`` is declared: the tool then plunges to - the stock's top over the chain's first loop and ramps down along it + the stock's top over the stretch of the chain's first loop the ramp + travels and ramps down along it (Z-flat tools are never plunged into stock). Consecutive passes join by straight links cut at depth when they are short, proven and inside the machine limits. Faces within ``level_tolerance_mm`` form one level. diff --git a/python/tests/test_flat_offset.py b/python/tests/test_flat_offset.py index 0fbfc7e..66811f3 100644 --- a/python/tests/test_flat_offset.py +++ b/python/tests/test_flat_offset.py @@ -186,6 +186,18 @@ def points(m, n=None): return [[a[k] + (b[k] - a[k]) * i / (n - 1) for k in range(3)] for i in range(n)] +def arc_points(c, step=0.05): + a, ce = c["start"], c["center"] + rho = math.hypot(a[0] - ce[0], a[1] - ce[1]) + a0 = math.atan2(a[1] - ce[1], a[0] - ce[0]) + sweep = c["sweep_rad"] + n = max(2, int(rho * abs(sweep) / step) + 1) + return [ + [ce[0] + rho * math.cos(a0 + sweep * i / (n - 1)), ce[1] + rho * math.sin(a0 + sweep * i / (n - 1)), a[2]] + for i in range(n) + ] + + def vertical_plunges(motions): out = [] for m in motions: @@ -285,9 +297,11 @@ def test_open_edges_are_entered_from_the_side_in_air(self): self.assertLessEqual(report.get("ramped_entries", 0), 1) def test_first_ring_of_each_level_follows_its_edge(self): - # Outside in: the first loop cut at each level is the ring a radius - # outside the level's outer edge (boss top: the 8 x 8 boss; base: - # the 24 x 16 block), all the way round. + # Outside in: the first loop cut at each level runs round the + # level's outer edge (boss top: the 8 x 8 boss; base: the 24 x 16 + # block), all the way round, its centre the radius less one stepover + # outside the edge: its disk takes one stepover of the face, like + # every later pass, rather than rolling a radius outside it in air. _, motions, *_ = cached("stepped") for z, rect in ((7.0, (8, 4, 16, 12)), (4.0, (0, 0, 24, 16))): cuts = [m for m in level_cuts(motions, z) if m["kind"] == "cut"] @@ -300,9 +314,9 @@ def test_first_ring_of_each_level_follows_its_edge(self): travelled += math.hypot(b[0] - a[0], b[1] - a[1]) if travelled > 1 and math.hypot(b[0] - start[0], b[1] - start[1]) < 1e-6: break - worst = max(abs(rect_outline_distance(p, rect) - R) for m in ring for p in points(m)) + worst = max(abs(rect_outline_distance(p, rect) - (R - STEPOVER)) for m in ring for p in points(m)) self.assertLessEqual(worst, 0.01, f"Z{z}: first loop strays {worst:.4f} mm from the edge ring") - perimeter = 2 * (rect[2] - rect[0] + rect[3] - rect[1]) + 2 * math.pi * R + perimeter = 2 * (rect[2] - rect[0] + rect[3] - rect[1]) + 2 * math.pi * (R - STEPOVER) self.assertGreater(travelled, 0.98 * perimeter, f"Z{z}: first loop {travelled:.3f} of {perimeter:.3f} mm") def test_coverage_of_every_reachable_flat_point(self): @@ -407,6 +421,34 @@ def stock(sign): side["climb" if right else "conventional"] += length self.assertGreater(side["climb"], 3 * side["conventional"], f"{name}: {side}") + def test_passes_do_not_run_over_finished_floor(self): + # Measured on the live stock before each move: the length of the + # level passes (cuts, links and leads at a flat's height) whose disk + # (less 0.1 mm) has no stock standing 0.02 mm above the cut — air + # beside an open edge, or floor an earlier pass already finished. + # A first ring rolling a radius outside every open edge, and inner + # rings run all the way round a rim or top that earlier rings had + # already covered, made this 47 % (stepped) and 45 % (island). + for name in ("stepped", "island"): + _, motions, before, grid, _ = cached(name) + nx, ny, dx, dy, lo = grid + xs = lo[0] + (np.arange(nx) + 0.5) * dx + ys = lo[1] + (np.arange(ny) + 0.5) * dy + X, Y = np.meshgrid(xs, ys) + total = idle = 0.0 + for m, snap in zip(motions, before): + c = m["curve"] + z = c["start"][2] + if m["kind"] not in ("cut", "link", "lead") or abs(c["end"][2] - z) > 1e-6: + continue + H = np.array(snap[1::2]).reshape(ny, nx) + ps = points(m) if c.get("kind", "line") == "line" else arc_points(c) + length = sum(math.dist(p[:2], q[:2]) for p, q in zip(ps, ps[1:])) + live = [bool((H[(X - p[0]) ** 2 + (Y - p[1]) ** 2 < (R - 0.1) ** 2] > z + 0.02).any()) for p in ps] + total += length + idle += length * (1 - sum(live) / len(live)) + self.assertLess(idle, 0.1 * total, f"{name}: {idle:.1f} of {total:.1f} mm over no stock") + if __name__ == "__main__": unittest.main() diff --git a/src/flat.rs b/src/flat.rs index 0f1f127..996cf55 100644 --- a/src/flat.rs +++ b/src/flat.rs @@ -1579,6 +1579,24 @@ impl Piece { fn length(&self) -> f64 { self.segs.iter().map(crate::profiles::stroke_length).sum() } + /// The first `length` of the piece (all of it when shorter). + fn prefix(&self, length: f64) -> Piece { + let mut segs = vec![]; + let mut left = length; + for seg in &self.segs { + if left <= 0. { + break; + } + let l = crate::profiles::stroke_length(seg); + if l <= left { + segs.push(*seg); + } else { + segs.push(sub_stroke(seg, 0., left / l)); + } + left -= l; + } + Piece { z: self.z, segs } + } fn strokes(&self) -> Vec { // The ramp walks the pass stroke by stroke; its arcs are split like // the cut moves so no ramp leg sweeps a chord that cuts its corner. @@ -1838,6 +1856,7 @@ impl FlatPlan { level, op.level_tolerance_mm, r, + op.stepover_mm, op.tolerance_mm, cancel, )? @@ -1845,7 +1864,13 @@ impl FlatPlan { continue; }; // Offset loops per connected component, outside in. - let groups = level_loops(®ion, r, op.stepover_mm, op.tolerance_mm, cancel)?; + // A loop cut only in stretches is cut through a gap between two + // of them when that takes no longer than a new entry's descent + // from the feed height at the plunge feed (and through any gap of + // up to two stepovers, as a link at depth would). + let bridge = (2. * op.stepover_mm) + .max((heights.feed - z).max(0.) * op.feed_mm_min / op.plunge_mm_min); + let groups = level_loops(®ion, r, op.stepover_mm, op.tolerance_mm, bridge, cancel)?; let level_chains = chains.len(); // Nearest component first. let mut order: Vec = (0..groups.len()).collect(); @@ -1856,13 +1881,25 @@ impl FlatPlan { .then(a.cmp(&b)) }); for gi in order { - for ring in groups[gi].ordered(tool_xy) { + for (_, ring, runs) in groups[gi].ordered(tool_xy) { if cancel.is_cancelled() { return Err("flat-area planning cancelled".into()); } loops += 1; - // Each closed loop starts at its vertex nearest the tool. - let ring = rotate_to_nearest(ring, tool_xy); + // An inner loop is cut only where its disk reaches floor + // the loops before it left; a short stretch between two + // such places is cut through rather than left for a link. + let ring = match runs { + // Each closed loop starts at its vertex nearest the tool. + None => rotate_to_nearest(ring, tool_xy), + // Open stretches in loop order from the one starting + // nearest the tool; prove_ring splits them into + // pieces where they do not meet. + Some(runs) => open_runs_from_nearest(runs, tool_xy), + }; + if ring.is_empty() { + continue; + } // Prove each chord; halve failures down to h / 16, keep // only the stretches inside the limits. let pieces = prove_ring( @@ -2014,6 +2051,28 @@ impl FlatPlan { "{which}: the run is shorter than 16 tolerances, too short to ramp on. Rough or rest-rough this area first" )); } + // Moves are read through their endpoints (posted programs, checks): + // a helix leg along an arc of the pass drops its depth over the arc, + // so over its chord it is steeper by the arc's length over the + // chord's. The ramp descends at the angle whose slope over every + // move's chord stays within the declared one. + let chain = piece.strokes(); + let stretch = chain + .iter() + .filter(|s| s.arc.is_some()) + .map(|s| { + let chord = (s.b[0] - s.a[0]).hypot(s.b[1] - s.a[1]); + if chord > 0. { + crate::profiles::stroke_length(s) / chord + } else { + 1. + } + }) + .fold(1., f64::max); + let entry = &crate::entry::RampEntry { + angle_rad: (entry.angle_rad.tan() / stretch).atan(), + ..entry.clone() + }; // Reaching here with no stock above the start means the start is over // the level's face (the plain plunge above refused it for that). When // the stock over the whole pass is that face's already-cut floor (the @@ -2027,19 +2086,44 @@ impl FlatPlan { // no span) — and descends along the pass as for stock. The stock top // wins when it is higher (real stock along the pass): the descent to // it stops at or above every stock cell under the pass, in air. - let target = if at_start <= a[2] + self.op.tolerance_mm { + // + // The ramp travels only the start of the pass when one leg descends + // the whole depth (the leg's length is the depth over the angle's + // tangent): it starts above the stock over that stretch, not over the + // whole pass, whose far side may run past part standing far above + // (cells along a taller wall). Starting from the floor above, the + // start height rises to the stock top over the stretch the ramp from + // it would travel until that stretch has no stock above it; when the + // stretch reaches the whole pass (the ramp reverses on it) the stock + // top over the whole pass is the floor. + let tan = entry.angle_rad.tan(); + let mut target = if at_start <= a[2] + self.op.tolerance_mm { let span = entry.min_length_mm.unwrap_or(length); - (a[2] + span * entry.angle_rad.tan()).max(top) + a[2] + span * tan } else { - top + at_start }; + loop { + if cancel.is_cancelled() { + return Err("flat-area planning cancelled".into()); + } + let span = (target - a[2]) / tan; + if span >= length { + target = target.max(top); + break; + } + let over = piece_stock_top(&piece.prefix(span), stock, self.radius, cancel)?; + if over <= target { + break; + } + target = over; + } if target > self.heights.feed { return Err(format!( "{which}, ramp start Z{target:.3} above the feed height Z{:.3}: raise feed_z_mm/retract_z_mm or rough this area first", self.heights.feed )); } - let chain = piece.strokes(); let curves = entry .zigzag(&chain, target, a[2]) .map_err(|why| format!("{which}: {why}. Use a steeper declared angle, a longer run, or rough this area first"))?; @@ -2456,21 +2540,31 @@ pub(crate) fn segment_stock_top( Ok(top) } -/// The region of tool centres resting on the flat level `z`: the shadow of -/// the part standing above `z - level_tolerance`, grown by the cutter radius -/// (every position whose disk touches the part within a tolerance below the -/// level), minus the shadow of the part standing above the level, grown by -/// the radius plus the shadows' stated errors (the pattern of -/// `waterline::flat_level_loops`): every position whose disk would reach the -/// part above the level. The "above" shadow's tip is picked so its -/// `protected_from_z_mm` is strictly above `z + level_tolerance`; nothing -/// standing above the level leaves the resting region alone. What is left is -/// exactly where a cut at `z + stock_to_leave_mm` rests on the level. +/// The region of tool centres the passes on the flat level `z` run in: the +/// shadow of the part standing above `z - level_tolerance`, grown by the +/// overhang `r - stepover` (none at a stepover of a radius or more), minus +/// the shadow of the part standing above the level, grown by the radius plus +/// the shadows' stated errors (the pattern of `waterline::flat_level_loops`): +/// every position whose disk would reach the part above the level. The +/// "above" shadow's tip is picked so its `protected_from_z_mm` is strictly +/// above `z + level_tolerance`; nothing standing above the level leaves the +/// region alone. Every point of the region rests the disk on the level. +/// +/// The overhang sets where the outermost pass runs past an open edge of the +/// face (one where the part drops away): its centre `r - stepover` outside +/// the edge, so its disk reaches `stepover` onto the face — the same width +/// every later pass takes — instead of rolling along the edge a radius +/// outside it and cutting nothing (the face is still covered: it lies inside +/// the region, and the passes cover the region). This is the usual facing +/// practice of running the tool part-way past the edge. Next to part standing +/// above the level the region still ends a radius (plus errors) from it, so +/// the outermost pass there runs along the wall. fn level_region( target: &crate::roughing::PreparedRoughingTarget, z: f64, level_tolerance: f64, r: f64, + stepover: f64, tolerance: f64, cancel: &impl CancelSignal, ) -> Result< @@ -2498,7 +2592,7 @@ fn level_region( .region .prepare(options) .map_err(|e| format!("flat-area region at Z{z}: {e}"))? - .offset_prepared(-r) + .offset_prepared(-(r - stepover).max(0.)) .map_err(|e| format!("flat-area region at Z{z}: {e}"))? .into_parts() .1; @@ -2559,16 +2653,25 @@ fn level_region( /// The offset loops of one connected component of a level's region: the /// outer-boundary loops and the hole loops, each with its inward offset. +/// One offset loop: its offset depth, its closed strokes, and the stretches +/// of it that are cut when only part of it finishes floor no other loop +/// covers (`None`: the whole loop; see `trim_ring`). +type Ring = ( + f64, + Vec, + Option>>, +); + struct LoopGroup { - outers: Vec<(f64, Vec)>, - holes: Vec<(f64, Vec)>, + outers: Vec, + holes: Vec, } impl LoopGroup { fn distance(&self, p: [f64; 2]) -> f64 { - let nearest = |rings: &[(f64, Vec)]| { + let nearest = |rings: &[Ring]| { rings .iter() - .flat_map(|(_, ring)| ring.iter()) + .flat_map(|(_, ring, _)| ring.iter()) .map(|s| (s.a[0] - p[0]).hypot(s.a[1] - p[1])) .fold(f64::INFINITY, f64::min) }; @@ -2576,24 +2679,23 @@ impl LoopGroup { } /// The rings in cut order: outer loops before hole loops, offset /// ascending (outside in), nearest the tool first at the same offset. - fn ordered(&self, tool: [f64; 2]) -> Vec> { + fn ordered(&self, tool: [f64; 2]) -> Vec { let near = |ring: &[crate::pocket::Stroke]| { ring.iter() .map(|s| (s.a[0] - tool[0]).hypot(s.a[1] - tool[1])) .fold(f64::INFINITY, f64::min) }; - let sort = - |rings: &[(f64, Vec)]| -> Vec> { - let mut order: Vec = (0..rings.len()).collect(); - order.sort_by(|&a, &b| { - rings[a] - .0 - .total_cmp(&rings[b].0) - .then(near(&rings[a].1).total_cmp(&near(&rings[b].1))) - .then(a.cmp(&b)) - }); - order.into_iter().map(|i| rings[i].1.clone()).collect() - }; + let sort = |rings: &[Ring]| -> Vec { + let mut order: Vec = (0..rings.len()).collect(); + order.sort_by(|&a, &b| { + rings[a] + .0 + .total_cmp(&rings[b].0) + .then(near(&rings[a].1).total_cmp(&near(&rings[b].1))) + .then(a.cmp(&b)) + }); + order.into_iter().map(|i| rings[i].clone()).collect() + }; let mut all = sort(&self.outers); all.extend(sort(&self.holes)); all @@ -2618,6 +2720,7 @@ fn level_loops( r: f64, stepover: f64, tolerance: f64, + bridge: f64, cancel: &impl CancelSignal, ) -> Result, String> { use crate::planar::Boolean; @@ -2641,9 +2744,15 @@ fn level_loops( let prepared = single .prepare(options) .map_err(|e| format!("flat-area loop region: {e}"))?; - let mut outers: Vec<(f64, Vec)> = vec![]; - let mut holes: Vec<(f64, Vec)> = vec![]; - let mut collect = |eroded: &crate::planar::PreparedRegion, d: f64| -> Result<(), String> { + // Loops as (depth, strokes, the depth the loops before them reach, + // when they are only cut where they reach past it). + type Pending = (f64, Vec, Option); + let mut outers: Vec = vec![]; + let mut holes: Vec = vec![]; + let mut collect = |eroded: &crate::planar::PreparedRegion, + d: f64, + need: Option| + -> Result<(), String> { let mut vertices = 0usize; // A loop the kernel vouches no geometry for is not cut: shorter // than the guard (16 tolerances), or — the offset kernel @@ -2661,12 +2770,12 @@ fn level_loops( for c in &eroded.definition().components { let outer = boundary_strokes(&c.outer, false, tolerance)?; if !outer.is_empty() && !degenerate_loop(&outer, guard, error) { - outers.push((d, outer)); + outers.push((d, outer, need)); } for hole in &c.holes { let strokes = boundary_strokes(hole, true, tolerance)?; if !strokes.is_empty() && !degenerate_loop(&strokes, guard, error) { - holes.push((d, strokes)); + holes.push((d, strokes, need)); } } vertices += c.outer.vertices.len() @@ -2685,7 +2794,26 @@ fn level_loops( if cancel.is_cancelled() { return Err("flat-area planning cancelled".into()); } - collect(&eroded, d)?; + // The rings so far (at 0, s, ..., d - s) already cover every point + // of the region within d - s + r of its boundary: a point at depth + // t >= d' lies t - d' from the boundary of the offset at d' (the + // erosion's complement is the boundary's complement grown by d'). + // A ring at d is cut only while points deeper than that remain; + // otherwise it would only run over floor the earlier rings have + // finished (a narrow rim offset from both sides, a small top). + // What is left must be more than the kernel's picture of a line + // (`uncovered`). + // Where such points remain, the ring is cut only where its disk + // reaches them. + let need = if d > 0. { + if uncovered(&prepared, d - stepover + r, tolerance, guard)?.is_none() { + break; + } + Some(d - stepover + r) + } else { + None + }; + collect(&eroded, d, need)?; let next = prepared .offset_prepared(d + stepover) .map_err(|e| format!("flat-area loop offset: {e}"))? @@ -2736,7 +2864,7 @@ fn level_loops( .into_parts() .1; if !mid.definition().components.is_empty() { - collect(&mid, half)?; + collect(&mid, half, None)?; } } } @@ -2749,12 +2877,7 @@ fn level_loops( if cancel.is_cancelled() { return Err("flat-area planning cancelled".into()); } - let deeper = prepared - .offset_prepared(core + r - guard) - .map_err(|e| format!("flat-area loop offset: {e}"))? - .into_parts() - .1; - if deeper.definition().components.is_empty() { + if uncovered(&prepared, core + r, tolerance, guard)?.is_none() { break; } let step = core + stepover / 2.; @@ -2763,14 +2886,194 @@ fn level_loops( .map_err(|e| format!("flat-area loop offset: {e}"))? .into_parts() .1; - collect(&eroded, step)?; + collect(&eroded, step, Some(core + r))?; core = step; } - groups.push(LoopGroup { outers, holes }); + // Loops cut only where they finish floor nothing else covers: per + // depth reached, the points deeper than it, less what each loop's + // kept stretches sweep (outer loops first, as they are cut). + let (mut done_outers, mut done_holes): (Vec, Vec) = (vec![], vec![]); + let mut depths: Vec = outers.iter().chain(&holes).filter_map(|p| p.2).collect(); + depths.sort_by(f64::total_cmp); + depths.dedup(); + let mut needs: Vec<(f64, Option)> = vec![]; + for depth in depths { + needs.push((depth, uncovered(&prepared, depth, tolerance, guard)?)); + } + let outer_count = outers.len(); + for (index, (d, strokes, reach)) in outers.into_iter().chain(holes).enumerate() { + if cancel.is_cancelled() { + return Err("flat-area planning cancelled".into()); + } + let runs = match reach { + None => None, + Some(reach) => { + let slot = needs + .iter_mut() + .find(|(depth, _)| *depth == reach) + .expect("every reach has its region"); + match slot.1.take() { + None => Some(vec![]), + Some(need) => { + let runs = trim_ring(&strokes, &need, r, bridge, guard, cancel)?; + let swept = match &runs { + None => vec![strokes.clone()], + Some(runs) => runs.clone(), + }; + slot.1 = subtract_swept(need, &swept, r, tolerance, guard)?; + runs + } + } + } + }; + if runs.as_ref().is_some_and(|runs| runs.is_empty()) { + continue; + } + if index < outer_count { + done_outers.push((d, strokes, runs)); + } else { + done_holes.push((d, strokes, runs)); + } + } + groups.push(LoopGroup { + outers: done_outers, + holes: done_holes, + }); } Ok(groups) } +/// The points of `prepared` deeper than `depth` (the reach of the rings cut +/// so far), or `None` when there are none: the offset by `depth` plus the +/// tolerance, without what is only the kernel's picture of a line +/// (`without_slivers`). Such a sliver is left where two rings' reach meets +/// exactly (a rim offset from both sides whose width is a whole number of +/// passes): the offset returns the meeting line as a strip of no width the +/// kernel can vouch for, which no ring needs to cover. +fn uncovered( + prepared: &crate::planar::PreparedRegion, + depth: f64, + tolerance: f64, + guard: f64, +) -> Result, String> { + let deeper = prepared + .offset_prepared(depth + tolerance) + .map_err(|e| format!("flat-area loop offset: {e}"))? + .into_parts() + .1; + without_slivers(deeper, guard) +} + +/// `region` without its slivers — strips thinner than twice its own stated +/// boundary error plus `guard` (16 tolerances, as for degenerate loops), +/// which the kernel cannot tell from a line: the morphological opening +/// (eroded by that width `e`, grown back by it), or `None` when nothing is +/// left. The opening keeps every point that lies in a disk of radius `e` +/// inside the region; a point it drops at a corner tip lies within +/// `e / sin(angle / 2)` of what is kept (twice `e` down to 60 degrees), and +/// `trim_ring` keeps loops within that margin. +fn without_slivers( + region: crate::planar::PreparedRegion, + guard: f64, +) -> Result, String> { + if region.definition().components.is_empty() { + return Ok(None); + } + let e = region.definition().boundary_error_mm + guard; + let core = region + .offset_prepared(e) + .map_err(|e| format!("flat-area loop offset: {e}"))? + .into_parts() + .1; + if core.definition().components.is_empty() { + return Ok(None); + } + let opened = core + .offset_prepared(-e) + .map_err(|e| format!("flat-area loop offset: {e}"))? + .into_parts() + .1; + Ok((!opened.definition().components.is_empty()).then_some(opened)) +} + +/// `need` without what the disk of radius `r` sweeps along the strokes of +/// `runs` (straight strokes as capsules; arcs by their chords, each capsule's +/// radius reduced by the chord's sagitta so it stays inside the arc's swept +/// disk), then without slivers; `None` when nothing is left. +fn subtract_swept( + need: crate::planar::PreparedRegion, + runs: &[Vec], + r: f64, + tolerance: f64, + guard: f64, +) -> Result, String> { + use crate::planar::{Boolean, Boundary, Component, ConstructionOptions, PlanarRegion}; + let options = ConstructionOptions { + tolerance_mm: tolerance, + }; + let mut capsules: Vec = vec![]; + let mut capsule = |a: [f64; 2], b: [f64; 2], radius: f64| { + let d = [b[0] - a[0], b[1] - a[1]]; + let length = d[0].hypot(d[1]); + if length <= guard || radius <= guard { + return; + } + let n = [-d[1] / length * radius, d[0] / length * radius]; + capsules.push(Component { + outer: Boundary { + vertices: vec![ + [a[0] - n[0], a[1] - n[1], 0.], + [b[0] - n[0], b[1] - n[1], 1.], + [b[0] + n[0], b[1] + n[1], 0.], + [a[0] + n[0], a[1] + n[1], 1.], + ], + }, + holes: vec![], + }); + }; + for seg in runs.iter().flatten() { + match seg.arc { + None => capsule(seg.a, seg.b, r), + Some((c, sweep)) => { + let rho = (seg.a[0] - c[0]).hypot(seg.a[1] - c[1]); + let sagitta = 0.01_f64.min(rho); + let half = (1. - sagitta / rho).clamp(-1., 1.).acos().max(1e-6); + let n = ((sweep.abs() / (2. * half)).ceil() as usize).clamp(1, 4096); + let sag = rho * (1. - (sweep.abs() / (2. * n as f64)).cos()); + for k in 0..n { + let t0 = k as f64 / n as f64; + let t1 = (k + 1) as f64 / n as f64; + capsule(stroke_point(seg, t0), stroke_point(seg, t1), r - sag); + } + } + } + } + let mut need = need; + // Each capsule on its own: they overlap, and the components of one + // region must not. + for c in capsules { + if need.definition().components.is_empty() { + return Ok(None); + } + let swept = PlanarRegion { + version: 1, + units: "mm".into(), + name: "flat-swept-capsule".into(), + boundary_error_mm: 0., + components: vec![c], + source: serde_json::Value::Null, + } + .prepare(options) + .map_err(|e| format!("flat-area swept region: {e}"))?; + need = need + .boolean_prepared(&swept, Boolean::Difference) + .map_err(|e| format!("flat-area swept region: {e}"))? + .into_parts() + .1; + } + without_slivers(need, guard) +} + /// Whether a loop carries no geometry the kernel vouches for: its total /// length is below `guard` (16 tolerances), or every extent of the loop fits /// inside `error`, the kernel's own stated boundary error for the @@ -3040,6 +3343,176 @@ fn rotate_piece(piece: &mut Piece, v: [f64; 2]) { piece.segs = rotated; } +/// Sampling step along a loop when trimming it to the floor it must finish. +const TRIM_STEP_MM: f64 = 0.25; + +/// The stretches of the closed `ring` whose disk of radius `r` can reach +/// `need` (the points the loops before it leave uncovered), in loop order and +/// each in the loop's direction, or `None` when the whole loop is needed. +/// The loop is read in pieces of at most `TRIM_STEP_MM`; a piece is kept +/// when its middle lies within `r` plus half the piece's length of `need` +/// (the region's signed clearance, a distance, so no point of a dropped +/// piece comes within `r` of `need`). A dropped stretch no longer than +/// `bridge` between kept ones is kept as well: the pass is proven along it, +/// and cutting through is shorter than leaving and coming back. Keeping is +/// the conservative side: every point of `need` the whole loop would cover, +/// the kept stretches cover. +fn trim_ring( + ring: &[crate::pocket::Stroke], + need: &crate::planar::PreparedRegion, + r: f64, + bridge: f64, + guard: f64, + cancel: &impl CancelSignal, +) -> Result>>, String> { + if need.definition().components.is_empty() { + return Ok(Some(vec![])); + } + // The reach kept around `need`: the radius, plus twice the sliver width + // `without_slivers` may have opened off a corner tip. + let reach = r + 2. * (need.definition().boundary_error_mm + guard); + // Pieces as (stroke index, t0, t1, length, kept). + let mut pieces: Vec<(usize, f64, f64, f64, bool)> = vec![]; + for (i, seg) in ring.iter().enumerate() { + if cancel.is_cancelled() { + return Err("flat-area planning cancelled".into()); + } + let length = crate::profiles::stroke_length(seg); + let n = ((length / TRIM_STEP_MM).ceil() as usize).max(1); + for k in 0..n { + let (t0, t1) = (k as f64 / n as f64, (k + 1) as f64 / n as f64); + let mid = stroke_point(seg, (t0 + t1) / 2.); + let q = need.query(mid)?; + let distance = (-q.signed_clearance_mm.unwrap_or(f64::NEG_INFINITY)).max(0.); + pieces.push(( + i, + t0, + t1, + length / n as f64, + distance <= reach + length / n as f64 / 2., + )); + } + } + let count = pieces.len(); + let Some(first_kept) = pieces.iter().position(|p| p.4) else { + return Ok(Some(vec![])); + }; + if pieces.iter().all(|p| p.4) { + return Ok(None); + } + // Bridge short dropped stretches between kept ones, around the loop. + let mut k = 0; + while k < count { + let at = (first_kept + k) % count; + if pieces[at].4 { + k += 1; + continue; + } + let mut end = k; + let mut gap = 0.; + while end < count && !pieces[(first_kept + end) % count].4 { + gap += pieces[(first_kept + end) % count].3; + end += 1; + } + if gap <= bridge { + for j in k..end { + pieces[(first_kept + j) % count].4 = true; + } + } + k = end; + } + if pieces.iter().all(|p| p.4) { + return Ok(None); + } + // Start right after a dropped piece, so no stretch wraps the seam. + let start = (0..count) + .map(|k| (first_kept + k) % count) + .find(|&at| pieces[at].4 && !pieces[(at + count - 1) % count].4) + .unwrap_or(first_kept); + let mut runs: Vec> = vec![]; + let mut current: Vec = vec![]; + let mut open: Option<(usize, f64, f64)> = None; + let flush = |open: &mut Option<(usize, f64, f64)>, current: &mut Vec| { + if let Some((i, t0, t1)) = open.take() { + current.push(sub_stroke(&ring[i], t0, t1)); + } + }; + for k in 0..count { + let (i, t0, t1, _, kept) = pieces[(start + k) % count]; + if !kept { + flush(&mut open, &mut current); + if !current.is_empty() { + runs.push(std::mem::take(&mut current)); + } + continue; + } + match open { + Some((j, a, _)) if j == i => open = Some((j, a, t1)), + _ => { + flush(&mut open, &mut current); + open = Some((i, t0, t1)); + } + } + } + flush(&mut open, &mut current); + if !current.is_empty() { + runs.push(current); + } + Ok(Some(runs)) +} + +/// The point of a stroke at parameter `t` (0 at its start, 1 at its end). +fn stroke_point(seg: &crate::pocket::Stroke, t: f64) -> [f64; 2] { + if t <= 0. { + return seg.a; + } + if t >= 1. { + return seg.b; + } + match seg.arc { + None => [ + seg.a[0] + t * (seg.b[0] - seg.a[0]), + seg.a[1] + t * (seg.b[1] - seg.a[1]), + ], + Some((c, sweep)) => { + let rho = (seg.a[0] - c[0]).hypot(seg.a[1] - c[1]); + let angle = (seg.a[1] - c[1]).atan2(seg.a[0] - c[0]) + sweep * t; + [c[0] + rho * angle.cos(), c[1] + rho * angle.sin()] + } + } +} + +/// The part of a stroke between parameters `t0` and `t1`, ending exactly on +/// the stroke's own endpoints where it reaches them. +fn sub_stroke(seg: &crate::pocket::Stroke, t0: f64, t1: f64) -> crate::pocket::Stroke { + crate::pocket::Stroke { + a: stroke_point(seg, t0), + b: stroke_point(seg, t1), + arc: seg.arc.map(|(c, sweep)| (c, sweep * (t1 - t0))), + } +} + +/// Open stretches of one loop, in loop order, starting from the stretch whose +/// start is nearest `tool`, as one stroke list (stretches that do not meet +/// are split into separate pieces when proven). +fn open_runs_from_nearest( + runs: Vec>, + tool: [f64; 2], +) -> Vec { + let first = runs + .iter() + .enumerate() + .min_by(|(_, a), (_, b)| { + let d = |s: &[crate::pocket::Stroke]| (s[0].a[0] - tool[0]).hypot(s[0].a[1] - tool[1]); + d(a).total_cmp(&d(b)) + }) + .map_or(0, |(i, _)| i); + let n = runs.len(); + (0..n) + .flat_map(|k| runs[(first + k) % n].iter().copied()) + .collect() +} + /// Rotate a closed ring of segments (the last ending on the first's start) so /// it starts at the vertex nearest `tool` and ends there too. fn rotate_to_nearest( From 452a95efc0954f32ee224da8b101556bc9cfb0d3 Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:55:39 -0700 Subject: [PATCH 17/26] Flat: a pass's sweep counts for every later ring (#38) --- python/tests/test_flat_offset.py | 3 ++- src/flat.rs | 27 +++++++++++++++------------ 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/python/tests/test_flat_offset.py b/python/tests/test_flat_offset.py index 66811f3..0c92d05 100644 --- a/python/tests/test_flat_offset.py +++ b/python/tests/test_flat_offset.py @@ -17,6 +17,7 @@ R = 2.0 # cutter radius STEPOVER = 1.5 CELL = 0.25 +INITIAL_Z = 14 def tool(): @@ -145,7 +146,7 @@ def run(spec, skin=0.1): tools=(t,), operations=(op,), revision="1", - initial_position_mm=(0, 0, 14), + initial_position_mm=(0, 0, INITIAL_Z), verification=camlib.StreamChecks(stock_contact=camlib.StockContactOptions()), ) as sim: s = sim.state diff --git a/src/flat.rs b/src/flat.rs index 996cf55..f6a07c1 100644 --- a/src/flat.rs +++ b/src/flat.rs @@ -2909,26 +2909,29 @@ fn level_loops( None => None, Some(reach) => { let slot = needs - .iter_mut() - .find(|(depth, _)| *depth == reach) + .iter() + .position(|(depth, _)| *depth == reach) .expect("every reach has its region"); - match slot.1.take() { + match &needs[slot].1 { None => Some(vec![]), - Some(need) => { - let runs = trim_ring(&strokes, &need, r, bridge, guard, cancel)?; - let swept = match &runs { - None => vec![strokes.clone()], - Some(runs) => runs.clone(), - }; - slot.1 = subtract_swept(need, &swept, r, tolerance, guard)?; - runs - } + Some(need) => trim_ring(&strokes, need, r, bridge, guard, cancel)?, } } }; if runs.as_ref().is_some_and(|runs| runs.is_empty()) { continue; } + // What this loop's kept stretches sweep is finished for every later loop, + // whatever depth that loop reaches past. + let swept = match &runs { + None => vec![strokes.clone()], + Some(runs) => runs.clone(), + }; + for (_, need) in needs.iter_mut() { + if let Some(region) = need.take() { + *need = subtract_swept(region, &swept, r, tolerance, guard)?; + } + } if index < outer_count { done_outers.push((d, strokes, runs)); } else { From d97b7c812ae95bcaa49d1b69ac947d496f6866f5 Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:45:07 -0700 Subject: [PATCH 18/26] Flat: plunge in air with tangent arc lead-in and lead-out (#38) --- docs/operations.md | 67 +++++---- python/camlib/operations.py | 14 +- python/tests/test_flat_offset.py | 52 +++++++ src/flat.rs | 234 ++++++++++++++++++++++++++++++- 4 files changed, 330 insertions(+), 37 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 0370697..a25a320 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -1658,33 +1658,46 @@ arc, and a straight stub under 0.005 mm is absorbed into its straight neighbour. Consecutive pieces join into one chain by a straight link at the cut height and cutting feed when the link is at most two stepovers long, passes the same proof and lies inside the machine limits; otherwise the chain ends -(retract, new entry). A chain is entered beside the level's face where the flat -is open (side entry in air): the tool rapids over a point a quarter to two -radii outside the chain's first loop, away from the region, where no stock -stands within the disk above the cut, plunges vertically through air to the cut -height and leads in at cutting feed. Where no such point exists it plunges -vertically at the chain's start when no live stock stands above its height -there (within `tolerance_mm`). Where stock does (roughing left it, or the stock -was not cut there yet), the chain is entered by a ramp, and only if the -operation declares `entry=RampEntry(angle_deg, ...)`: the tool plunges through -air to the top of the live stock over the stretch of the chain's first loop the -ramp travels (the highest cell bound anywhere along that stretch; the whole -loop when the ramp has to reverse on it), then zigzags down along that loop at -no more than the declared angle (over each move's chord, so a leg along an arc -descends a little shallower) and at the entry's `feed_mm_min` (default the -plunge feed); a zigzag that has to reverse needs the entry's `min_length_mm`. -Every ramp point lies above the proven loop, so it clears the part like the -loop does; the report counts ramped chains as `ramped_entries`. Nothing is -plunged into stock on any path: a chain with stock above it and no declared -entry, a ramp that does not fit (too short a loop, an angle too shallow for the -loop, or stock above the feed height) is refused, naming the chain, its length -and the stock above it. The `flat` benchmark runs on a blank roughed to 0.1 mm -over the flats and declares a 3 degree entry. The report gives the levels, -`loops` (closed offset loops planned), `rows` (loops cut, counting the open -pieces a split loop leaves), `runs` (chains), `links_at_depth`, cut length, -`runs_completed`, `ramped_entries`, and any length that could not be proven -clear (`dropped_length_mm`). `axis` is still accepted so old jobs load, but no -longer orders anything. +(retract, new entry). Where a side of the chain's first pass has no live stock +above the cut (beside an open edge, or floor earlier passes have finished), the +chain is entered by a vertical plunge through air and a quarter-circle lead-in +of the tool's radius, tangent to the pass at its start: flat at the cut height +and cutting feed when the plunge point lies a radius beside the face, otherwise +a helix that stops above the finished floor (radius × √2 × the tangent of the +declared ramp angle) and descends to the pass at no more than the ramp's angle +over its chord, at the ramp's feed (with no ramp declared that side does not +qualify). The arc is proven clear of the part by its chords at radius r + +sagitta and must lie inside the machine limits. A chain ends with a flat +tangent quarter-circle lead-out of the tool's radius where the disk at its end +touches no stock above the cut; otherwise it retracts at the pass's end. The +report counts them as `arc_lead_ins` and `arc_lead_outs`. Otherwise a chain is +entered beside the level's face where the flat is open (side entry in air): the +tool rapids over a point a quarter to two radii outside the chain's first loop, +away from the region, where no stock stands within the disk above the cut, +plunges vertically through air to the cut height and leads in at cutting feed. +Where no such point exists it plunges vertically at the chain's start when no +live stock stands above its height there (within `tolerance_mm`). Where stock +does (roughing left it, or the stock was not cut there yet), the chain is +entered by a ramp, and only if the operation declares +`entry=RampEntry(angle_deg, ...)`: the tool plunges through air to the top of +the live stock over the stretch of the chain's first loop the ramp travels (the +highest cell bound anywhere along that stretch; the whole loop when the ramp +has to reverse on it), then zigzags down along that loop at no more than the +declared angle (over each move's chord, so a leg along an arc descends a little +shallower) and at the entry's `feed_mm_min` (default the plunge feed); a zigzag +that has to reverse needs the entry's `min_length_mm`. Every ramp point lies +above the proven loop, so it clears the part like the loop does; the report +counts ramped chains as `ramped_entries`. Nothing is plunged into stock on any +path: a chain with stock above it and no declared entry, a ramp that does not +fit (too short a loop, an angle too shallow for the loop, or stock above the +feed height) is refused, naming the chain, its length and the stock above it. +The `flat` benchmark runs on a blank roughed to 0.1 mm over the flats and +declares a 3 degree entry. The report gives the levels, `loops` (closed offset +loops planned), `rows` (loops cut, counting the open pieces a split loop +leaves), `runs` (chains), `links_at_depth`, cut length, `runs_completed`, +`ramped_entries`, `arc_lead_ins`, `arc_lead_outs`, and any length that could +not be proven clear (`dropped_length_mm`). `axis` is still accepted so old jobs +load, but no longer orders anything. ## Spiral, radial and project finishing: `Spiral`, `Radial`, `Project` diff --git a/python/camlib/operations.py b/python/camlib/operations.py index 8d897f5..7c5188d 100644 --- a/python/camlib/operations.py +++ b/python/camlib/operations.py @@ -757,10 +757,16 @@ class Flat: only where it finishes floor the rings before it have not reached. Offset loops are cut as arcs, each proven by chords at radius r + sagitta like the straight cuts. Every cut is kept only where the part under the tool's - swept disk is proven not above it. A chain of passes is entered beside - the level's face in air where the flat is open (a vertical plunge through - air, then a lead-in at cutting feed), else by a vertical plunge where no - stock stands above it. A chain with stock above it is refused unless + swept disk is proven not above it. A chain of passes is entered by a + vertical plunge through air and a quarter-circle lead-in of the tool's + radius, tangent to the pass, wherever a side of the pass has no stock + above it (beside an open edge, or floor earlier passes finished): flat + at cutting feed when the plunge point is a radius beside the face, else a + helix that stops above the finished floor and descends at the declared + ramp's angle. A chain ends with a tangent quarter-circle lead-out of the + same radius where its end point is clear. Otherwise a chain is entered + beside the face in air (a straight lead-in), else by a vertical plunge + where no stock stands above it. A chain with stock above it is refused unless ``entry=RampEntry(angle_deg, ...)`` is declared: the tool then plunges to the stock's top over the stretch of the chain's first loop the ramp travels and ramps down along it diff --git a/python/tests/test_flat_offset.py b/python/tests/test_flat_offset.py index 0c92d05..afa4832 100644 --- a/python/tests/test_flat_offset.py +++ b/python/tests/test_flat_offset.py @@ -450,6 +450,58 @@ def test_passes_do_not_run_over_finished_floor(self): idle += length * (1 - sum(live) / len(live)) self.assertLess(idle, 0.1 * total, f"{name}: {idle:.1f} of {total:.1f} mm over no stock") + def test_entries_plunge_in_air_and_lead_in_and_out_on_tangent_arcs(self): + # A run is entered by a vertical plunge in air and a quarter-circle + # lead-in of the tool's radius, tangent to the pass where it joins it + # (flat beside a face; over a finished face a helix stops above the + # floor and descends at the declared 3 degrees over its chord), and + # left by a tangent quarter-circle lead-out of the same radius before + # the retract. Measured on the motion stream: radius, sweep, slope, + # and the direction on both sides of each joint. + def tangent(c, end): + if c.get("kind", "line") == "line": + d = [c["end"][0] - c["start"][0], c["end"][1] - c["start"][1]] + else: + p = c["end"] if end else c["start"] + ce, sign = c["center"], math.copysign(1, c["sweep_rad"]) + d = [-(p[1] - ce[1]) * sign, (p[0] - ce[0]) * sign] + n = math.hypot(*d) + return [d[0] / n, d[1] / n] + + for name in ("stepped", "island"): + report, motions, *_ = cached(name) + self.assertGreater(report.get("arc_lead_ins", 0), 0, name) + self.assertGreater(report.get("arc_lead_outs", 0), 0, name) + ins = outs = 0 + for i, m in enumerate(motions[1:-1], 1): + c = m["curve"] + if c.get("kind") not in ("arc", "helix") or m["kind"] not in ("lead", "plunge"): + continue + prev, nxt = motions[i - 1], motions[i + 1] + lead_in = prev in vertical_plunges([prev]) and nxt["kind"] == "cut" + rise = ( + nxt["curve"]["end"][2] > nxt["curve"]["start"][2] + and math.dist(nxt["curve"]["end"][:2], nxt["curve"]["start"][:2]) < 1e-9 + ) + lead_out = m["kind"] == "lead" and prev["kind"] in ("cut", "link") and rise + if not (lead_in or lead_out): + continue + a, ce = c["start"], c["center"] + self.assertAlmostEqual(math.hypot(a[0] - ce[0], a[1] - ce[1]), R, delta=1e-6) + self.assertAlmostEqual(abs(c["sweep_rad"]), math.pi / 2, delta=1e-9) + if lead_in: + ins += 1 + t0, t1 = tangent(c, True), tangent(nxt["curve"], False) + drop = c["start"][2] - c["end"][2] + chord = math.dist(c["start"][:2], c["end"][:2]) + self.assertLessEqual(drop / chord, math.tan(math.radians(3)) + 1e-9, (name, c)) + else: + outs += 1 + t0, t1 = tangent(prev["curve"], True), tangent(c, False) + self.assertGreater(t0[0] * t1[0] + t0[1] * t1[1], 1 - 1e-9, (name, i, c)) + self.assertEqual(ins, report["arc_lead_ins"], name) + self.assertEqual(outs, report["arc_lead_outs"], name) + if __name__ == "__main__": unittest.main() diff --git a/src/flat.rs b/src/flat.rs index f6a07c1..31a5145 100644 --- a/src/flat.rs +++ b/src/flat.rs @@ -163,6 +163,14 @@ pub struct FlatReport { /// live stock stood above the run's height at its start. #[serde(skip_serializing_if = "is_zero")] pub ramped_entries: usize, + /// Runs entered by a vertical plunge in air and a tangent arc lead-in + /// whose radius is the tool's radius (see `FlatPlan::arc_lead_in`). + #[serde(skip_serializing_if = "is_zero")] + pub arc_lead_ins: usize, + /// Runs left by a tangent arc lead-out of the tool's radius before the + /// retract (see `FlatPlan::arc_lead_out`). + #[serde(skip_serializing_if = "is_zero")] + pub arc_lead_outs: usize, pub clearance_proof: &'static str, } @@ -1631,6 +1639,12 @@ enum Entry { /// curves (lines and arcs on the pass, helices where a leg descends /// along an arc), ending at the pass's start. Ramp { top: f64, curves: Vec }, + /// Vertical plunge in air at `lead`'s start, then the tangent arc lead-in + /// `lead` to the pass's start: flat at the pass's height (a lead at + /// cutting feed) or, when the plunge point is over the level's finished + /// face, a helix descending to it at the declared ramp's angle (at the + /// ramp's feed). + Arc { lead: Curve, helical: bool }, } #[derive(Clone, Copy, PartialEq, Eq)] @@ -1640,9 +1654,11 @@ enum Phase { Descend, Enter, Lead, + ArcIn, Ramp, Cut, PieceEnd, + Leave, Rise, Done, } @@ -1663,6 +1679,7 @@ pub struct FlatPlan { limits: Option, entry: Option, ramp: std::collections::VecDeque, + lead: Option<(Curve, bool)>, initial: Vec3, position: Vec3, next_id: u64, @@ -1974,6 +1991,8 @@ impl FlatPlan { dropped_length_mm: dropped, runs_completed: 0, ramped_entries: 0, + arc_lead_ins: 0, + arc_lead_outs: 0, clearance_proof: "exact maximum part height under each horizontal cut's swept disk (triangle-capsule extreme points) at most the cut height plus tolerance; contour-parallel offset passes outside in, side entry in air on open edges and every vertical plunge beside the level's face (a radius outside it, the face region a superset of the flat within the shadows' stated errors), links at depth and when chains break", }; Ok(Self { @@ -1992,6 +2011,7 @@ impl FlatPlan { limits: region_limits, entry: None, ramp: Default::default(), + lead: None, initial, position: initial, next_id: first_id, @@ -2132,6 +2152,156 @@ impl FlatPlan { // happens in `next_motion_with_stock`. Ok(Some((target, curves))) } + /// Whether the disk of radius `self.radius` swept along the arc about + /// `c` of radius `rho` from angle `start` through `sweep` stays clear of + /// the part at height `z`: the arc's chords at the tolerance's sagitta, + /// each proven with the capsule of radius r + sagitta, which contains the + /// arc's swept disk (as for the arcs of a pass in `prove_ring`). + fn arc_clear(&mut self, c: [f64; 2], rho: f64, start: f64, sweep: f64, z: f64) -> bool { + let tol = self.op.tolerance_mm; + let half = (1. - tol / rho).clamp(-1., 1.).acos().max(1e-9); + let count = ((sweep.abs() / (2. * half)).ceil().max(1.) as usize).min(4096); + let sagitta = rho * (1. - (sweep.abs() / (2. * count as f64)).cos()); + let at = |t: f64| { + let angle = start + sweep * t; + [c[0] + rho * angle.cos(), c[1] + rho * angle.sin()] + }; + (0..count).all(|i| { + let (p, q) = ( + at(i as f64 / count as f64), + at((i + 1) as f64 / count as f64), + ); + self.index + .max_height(p, q, self.radius + sagitta, &mut self.seen, &mut self.stamp) + <= z + tol + }) + } + + /// The arc lead-in to the pass starting at `v` (height `z`) along the unit + /// tangent `t`, as in established CAM practice: a quarter circle of the + /// tool's radius, tangent to the pass at `v`, whose centre lies on the + /// normal at `v`, entered by a vertical plunge at its start. Of the two + /// sides of the pass, a side qualifies when the plunge point's disk + /// touches no stock above the pass's height (on an inner pass that is + /// the floor the passes before it finished, which lies more than a + /// stepover from the pass once the radius exceeds the stepover), the arc + /// is proven clear of the part, and the limits allow it. A plunge point a + /// radius beside the level's face comes down in air beside the flat and + /// the lead is flat at the pass's height; over the face the plunge stops + /// above the floor and the lead descends to the pass as a helix at the + /// declared ramp's angle over its chord (no ramp declared: no such side). + /// Beside the face wins; `None` when no side qualifies. + fn arc_lead_in( + &mut self, + stock: &Stock, + v: [f64; 2], + t: [f64; 2], + z: f64, + ) -> Result, String> { + let tol = self.op.tolerance_mm; + let rho = self.radius; + let mut found: Option = None; + for s in [1., -1.] { + let n = [-t[1] * s, t[0] * s]; + let c = [v[0] + rho * n[0], v[1] + rho * n[1]]; + let p = [c[0] - rho * t[0], c[1] - rho * t[1]]; + if stock.top_under_disk(p, rho) > z + tol { + continue; + } + let beside = self.beside_face(p)?; + let rise = if beside { + 0. + } else { + match self.op.entry.as_ref().and_then(|e| e.ramp()) { + Some(ramp) => rho * std::f64::consts::SQRT_2 * ramp.angle_rad.tan(), + None => continue, + } + }; + if z + rise > self.heights.feed { + continue; + } + let start = (p[1] - c[1]).atan2(p[0] - c[0]); + let sweep = s * std::f64::consts::FRAC_PI_2; + if !self.arc_clear(c, rho, start, sweep, z) { + continue; + } + let lead = if beside { + Curve::Arc { + start: [p[0], p[1], z], + end: [v[0], v[1], z], + center: [c[0], c[1], z], + plane: crate::motion::Plane::Xy, + sweep_rad: sweep, + } + } else { + Curve::Helix { + start: [p[0], p[1], z + rise], + end: [v[0], v[1], z], + center: [c[0], c[1], z + rise], + plane: crate::motion::Plane::Xy, + sweep_rad: sweep, + } + }; + if let Some(l) = &self.limits + && !l.allows_curve(&lead, true)? + { + continue; + } + let better = matches!(found, None | Some(Entry::Arc { helical: true, .. })) && beside; + if found.is_none() || better { + found = Some(Entry::Arc { + lead, + helical: !beside, + }); + } + } + Ok(found) + } + + /// The arc lead-out from the pass ending at `v` (height `z`) along the + /// unit tangent `t`: a quarter circle of the tool's radius, tangent to the + /// pass at `v`, flat at the pass's height, on a side where the disk at its + /// end (where the retract lifts) touches no stock above the pass, proven + /// clear of the part and allowed by the limits; `None` when neither side + /// qualifies (the retract then lifts at `v`). + fn arc_lead_out( + &mut self, + stock: &Stock, + v: [f64; 2], + t: [f64; 2], + z: f64, + ) -> Result, String> { + let tol = self.op.tolerance_mm; + let rho = self.radius; + for s in [1., -1.] { + let n = [-t[1] * s, t[0] * s]; + let c = [v[0] + rho * n[0], v[1] + rho * n[1]]; + let e = [c[0] + rho * t[0], c[1] + rho * t[1]]; + if stock.top_under_disk(e, rho) > z + tol { + continue; + } + let start = (v[1] - c[1]).atan2(v[0] - c[0]); + let sweep = s * std::f64::consts::FRAC_PI_2; + if !self.arc_clear(c, rho, start, sweep, z) { + continue; + } + let lead = Curve::Arc { + start: [v[0], v[1], z], + end: [e[0], e[1], z], + center: [c[0], c[1], z], + plane: crate::motion::Plane::Xy, + sweep_rad: sweep, + }; + if let Some(l) = &self.limits + && !l.allows_curve(&lead, true)? + { + continue; + } + return Ok(Some(lead)); + } + Ok(None) + } + /// Whether the disk at `p` comes down beside this chain's level's face: a /// radius (less the tolerance) outside the face region, so a vertical /// plunge at `p` never rests the disk on the flat the pass finishes. An @@ -2224,8 +2394,18 @@ impl FlatPlan { let piece = &mut self.chains[self.chain].pieces[self.piece]; rotate_piece(piece, v); } + let t = self.chains[self.chain].pieces[self.piece].segs[0].tangent(false); + if let Some(entry) = self.arc_lead_in(stock, v, t, z)? { + self.report.arc_lead_ins += 1; + return Ok(entry); + } return Ok(Entry::Side { p }); } + let t = self.chains[self.chain].pieces[self.piece].segs[0].tangent(false); + if let Some(entry) = self.arc_lead_in(stock, first, t, z)? { + self.report.arc_lead_ins += 1; + return Ok(entry); + } let piece = &self.chains[self.chain].pieces[self.piece]; match self.plunge_or_ramp(piece, stock, cancel)? { None => Ok(Entry::Plunge), @@ -2325,6 +2505,10 @@ impl FlatPlan { let a = self.chains[self.chain].pieces[self.piece].start(); [a[0], a[1]] } + Entry::Arc { lead, .. } => { + let f = lead.start(); + [f[0], f[1]] + } }; self.entry = Some(entry); ( @@ -2347,6 +2531,12 @@ impl FlatPlan { ([p[0], p[1], a[2]], MoveKind::Plunge, Phase::Lead, None) } Entry::Plunge => ([p[0], p[1], a[2]], MoveKind::Plunge, Phase::Cut, None), + Entry::Arc { lead, helical } => { + // Straight down in air to the lead's start. + let f = lead.start(); + self.lead = Some((lead, helical)); + ([p[0], p[1], f[2]], MoveKind::Plunge, Phase::ArcIn, None) + } Entry::Ramp { top, curves } => { self.ramp = curves.into(); // Down through air to the stock's top over the @@ -2368,6 +2558,23 @@ impl FlatPlan { let a = self.chains[self.chain].pieces[self.piece].start(); ([a[0], a[1], a[2]], MoveKind::Lead, Phase::Cut, None) } + Phase::ArcIn => { + let (lead, helical) = self.lead.take().expect("arc lead-in"); + let kind = if helical { + // A helical lead descends as a ramp: at the ramp's feed. + ramp_feed = Some( + self.op + .entry + .as_ref() + .and_then(|e| e.feed_mm_min()) + .unwrap_or(self.op.plunge_mm_min), + ); + MoveKind::Plunge + } else { + MoveKind::Lead + }; + (lead.end(), kind, Phase::Cut, Some(lead)) + } Phase::Ramp => { let curve = self.ramp.pop_front().expect("ramp move"); ramp_feed = Some( @@ -2414,14 +2621,29 @@ impl FlatPlan { self.seg = 0; (next, MoveKind::Link, Phase::Cut, None) } else { - ( - [p[0], p[1], self.heights.feed.max(p[2])], - MoveKind::Retract, - Phase::Rise, - None, - ) + let piece = &self.chains[self.chain].pieces[self.piece]; + let (v, z) = ([p[0], p[1]], piece.z); + let t = piece.segs[piece.segs.len() - 1].tangent(true); + match self.arc_lead_out(stock, v, t, z)? { + Some(lead) => { + self.report.arc_lead_outs += 1; + (lead.end(), MoveKind::Lead, Phase::Leave, Some(lead)) + } + None => ( + [p[0], p[1], self.heights.feed.max(p[2])], + MoveKind::Retract, + Phase::Rise, + None, + ), + } } } + Phase::Leave => ( + [p[0], p[1], self.heights.feed.max(p[2])], + MoveKind::Retract, + Phase::Rise, + None, + ), Phase::Rise => { self.chain += 1; self.piece = 0; From 4018f98045bd1338691d739a73f5f0def3783bc8 Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:45:25 -0700 Subject: [PATCH 19/26] Flat tests: ramp cases on stock wider than the part (#38) --- python/tests/test_flat.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/python/tests/test_flat.py b/python/tests/test_flat.py index b83f0fe..b30b54a 100644 --- a/python/tests/test_flat.py +++ b/python/tests/test_flat.py @@ -16,7 +16,7 @@ def part(): return base.union(boss) -def roughed(cell=0.25): +def roughed(cell=0.25, margin=0.0): """The part with 0.1 mm left on the flats and the walls to size: the blank a flat finishing pass meets after roughing.""" import cadquery as cq @@ -24,7 +24,8 @@ def roughed(cell=0.25): blank = ( cq.Workplane("XY") - .box(24, 16, 4.1, centered=False) + .box(24 + 2 * margin, 16 + 2 * margin, 4.1, centered=False) + .translate((-margin, -margin, 0)) .union(cq.Workplane("XY").box(8, 8, 3, centered=False).translate((8, 4, 4.1))) ) return camlib.StockSpec.from_mesh(export_stock_mesh(blank), cell) @@ -137,7 +138,7 @@ def test_no_plunge_enters_live_stock_and_ramps_follow_the_declared_entry(self): report, snapshot = None, None plunges, ramp_feeds, slopes = 0, set(), [] radius = 2.0 - with self.simulation(tool, op, roughed()) as sim: + with self.simulation(tool, op, roughed(margin=10)) as sim: s = sim.state snapshot = list(s.heights) for update in sim.run_operations(): @@ -179,16 +180,17 @@ def test_a_run_under_stock_with_no_entry_is_refused_by_name(self): pass def test_a_ramp_that_does_not_fit_is_refused_not_plunged(self): + wide = camlib.StockSpec((-10, -10, 0), (34, 26, 8), 0.25) # 4 mm of stock at 3 degrees needs about 76 mm of travel: the ramp # must reverse on a 24 mm run, which needs a declared min_length_mm. tool, op = self.flat(camlib.RampEntry(angle_deg=3)) with self.assertRaisesRegex(Exception, "min_length_mm is not set"): - with self.simulation(tool, op) as sim: + with self.simulation(tool, op, wide) as sim: for _ in sim.run_operations(): pass tool, op = self.flat(camlib.RampEntry(angle_deg=3, min_length_mm=100)) with self.assertRaisesRegex(Exception, "shorter than min_length_mm"): - with self.simulation(tool, op) as sim: + with self.simulation(tool, op, wide) as sim: for _ in sim.run_operations(): pass From d6a312a5ca24343c00741267dca87758ef78a3b2 Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:03:42 -0700 Subject: [PATCH 20/26] Flat: rounded plunges and radial stock left on walls (#38) --- docs/operations.md | 47 ++++--- python/camlib/operations.py | 3 + python/tests/test_flat_offset.py | 103 +++++++++++++-- src/flat.rs | 215 ++++++++++++++++++++++++++++++- 4 files changed, 335 insertions(+), 33 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index a25a320..d8a7251 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -1626,13 +1626,15 @@ on the right of travel. The region of tool centres resting on a level is the level's shadow grown by the radius less one stepover (none at a stepover of a radius or more), so past an open edge the outermost pass runs that far outside the face and its disk takes one stepover of it like every later pass, minus the -shadow of everything standing above it grown by the radius plus its stated -errors, so near walls the tool stays a radius away. Its inward offsets 0, -`stepover_mm`, 2 `stepover_mm`, ... are the passes; after the last one, a core -deeper than a radius is covered by half-step passes while it lasts, and where -an offset pinches off in a corner between two boundaries of the region (the -surviving ring stretches more than a diameter apart) a half-step pass is added -too, so the disk covers every reachable flat point at stepovers up to the +shadow of everything standing above it grown by the radius plus +`radial_stock_to_leave_mm` (default 0) plus its stated errors, so near walls +the tool stays a radius plus the radial stock away and cuts only the horizontal +faces: the walls keep their radial stock for a wall finish. Its inward offsets +0, `stepover_mm`, 2 `stepover_mm`, ... are the passes; after the last one, a +core deeper than a radius is covered by half-step passes while it lasts, and +where an offset pinches off in a corner between two boundaries of the region +(the surviving ring stretches more than a diameter apart) a half-step pass is +added too, so the disk covers every reachable flat point at stepovers up to the cutter diameter. An inner pass is planned only while floor remains deeper than the passes before it reach (more than a sliver thinner than the offset kernel's stated error, which it cannot tell from a line), and it is cut only along the @@ -1670,15 +1672,22 @@ qualify). The arc is proven clear of the part by its chords at radius r + sagitta and must lie inside the machine limits. A chain ends with a flat tangent quarter-circle lead-out of the tool's radius where the disk at its end touches no stock above the cut; otherwise it retracts at the pass's end. The -report counts them as `arc_lead_ins` and `arc_lead_outs`. Otherwise a chain is -entered beside the level's face where the flat is open (side entry in air): the -tool rapids over a point a quarter to two radii outside the chain's first loop, -away from the region, where no stock stands within the disk above the cut, -plunges vertically through air to the cut height and leads in at cutting feed. -Where no such point exists it plunges vertically at the chain's start when no -live stock stands above its height there (within `tolerance_mm`). Where stock -does (roughing left it, or the stock was not cut there yet), the chain is -entered by a ramp, and only if the operation declares +report counts them as `arc_lead_ins` and `arc_lead_outs`. Every vertical plunge +that lands in air (side entries, arc lead-ins, plunges at a chain's start) +stops a tool radius higher and a radius back along the move that follows, and +turns to horizontal on a quarter circle of the tool's radius in the vertical +plane of that move (one XZ or YZ arc when the move runs along X or Y, otherwise +its chords within 5 microns), at cutting feed; the span is proven clear of the +part and of live stock at the landing height and inside the limits, otherwise +the plunge comes straight down. The report counts these as `rounded_plunges`. +Otherwise a chain is entered beside the level's face where the flat is open +(side entry in air): the tool rapids over a point a quarter to two radii +outside the chain's first loop, away from the region, where no stock stands +within the disk above the cut, plunges vertically through air to the cut height +and leads in at cutting feed. Where no such point exists it plunges vertically +at the chain's start when no live stock stands above its height there (within +`tolerance_mm`). Where stock does (roughing left it, or the stock was not cut +there yet), the chain is entered by a ramp, and only if the operation declares `entry=RampEntry(angle_deg, ...)`: the tool plunges through air to the top of the live stock over the stretch of the chain's first loop the ramp travels (the highest cell bound anywhere along that stretch; the whole loop when the ramp @@ -1695,9 +1704,9 @@ The `flat` benchmark runs on a blank roughed to 0.1 mm over the flats and declares a 3 degree entry. The report gives the levels, `loops` (closed offset loops planned), `rows` (loops cut, counting the open pieces a split loop leaves), `runs` (chains), `links_at_depth`, cut length, `runs_completed`, -`ramped_entries`, `arc_lead_ins`, `arc_lead_outs`, and any length that could -not be proven clear (`dropped_length_mm`). `axis` is still accepted so old jobs -load, but no longer orders anything. +`ramped_entries`, `arc_lead_ins`, `arc_lead_outs`, `rounded_plunges`, and any +length that could not be proven clear (`dropped_length_mm`). `axis` is still +accepted so old jobs load, but no longer orders anything. ## Spiral, radial and project finishing: `Spiral`, `Radial`, `Project` diff --git a/python/camlib/operations.py b/python/camlib/operations.py index 7c5188d..8c0343e 100644 --- a/python/camlib/operations.py +++ b/python/camlib/operations.py @@ -797,6 +797,9 @@ class Flat: # How a run under stock is entered: RampEntry(angle_deg, ...). None: no # stock stands above the runs, and one that does is refused. entry: object | None = None + # Radial stock left on the walls: the passes stay this much farther than + # the cutter's radius from everything standing above a flat. + radial_stock_to_leave_mm: float = 0 def to_dict(self): result = {field: getattr(self, field) for field in self.__dataclass_fields__} diff --git a/python/tests/test_flat_offset.py b/python/tests/test_flat_offset.py index afa4832..8d8a84f 100644 --- a/python/tests/test_flat_offset.py +++ b/python/tests/test_flat_offset.py @@ -134,10 +134,10 @@ def flat_op(spec, entry=camlib.RampEntry(angle_deg=3, min_length_mm=1), **change return t, op -def run(spec, skin=0.1): +def run(spec, skin=0.1, **changes): """Run Flat on the roughed blank; return (report, motions, stock snapshots before each motion as (nx, ny, dx, dy, heights), final state).""" - t, op = flat_op(spec) + t, op = flat_op(spec, **changes) stock = camlib.StockSpec.from_mesh(export_stock_mesh(solid(spec, skin)), CELL) motions, before = [], [] report = None @@ -380,14 +380,14 @@ def test_never_cuts_below_the_part(self): def test_no_moves_of_kernel_artefacts(self): # A kernel's flattened circle (chords mixed with micro-arcs) and its # snapped corner stubs are not cut as moves of their own: no cut, - # link or lead shorter than 5 microns (the arcs' own move sagitta). + # link or lead shorter than 5 microns (the arcs' own move sagitta), + # measured in 3D (a rounded plunge's chords descend mostly in Z). for name in ("stepped", "island"): _, motions, *_ = cached(name) tiny = [ m["id"] for m in motions - if m["kind"] in ("cut", "link", "lead") - and math.hypot(*(m["curve"]["end"][k] - m["curve"]["start"][k] for k in (0, 1))) < 0.005 + if m["kind"] in ("cut", "link", "lead") and math.dist(m["curve"]["end"], m["curve"]["start"]) < 0.005 ] self.assertEqual(tiny, [], f"{name}: moves under 5 microns: {tiny[:10]}") @@ -475,10 +475,22 @@ def tangent(c, end): ins = outs = 0 for i, m in enumerate(motions[1:-1], 1): c = m["curve"] - if c.get("kind") not in ("arc", "helix") or m["kind"] not in ("lead", "plunge"): + if ( + c.get("kind") not in ("arc", "helix") + or c.get("plane") != "xy" + or m["kind"] not in ("lead", "plunge") + ): continue prev, nxt = motions[i - 1], motions[i + 1] - lead_in = prev in vertical_plunges([prev]) and nxt["kind"] == "cut" + # A ramp's helix legs also end on a pass: a lead-in is told + # apart by its shape (quarter circle of the tool's radius); + # the counts below must then match the report's. + a, ce = c["start"], c["center"] + quarter = ( + abs(math.hypot(a[0] - ce[0], a[1] - ce[1]) - R) < 1e-6 + and abs(abs(c["sweep_rad"]) - math.pi / 2) < 1e-9 + ) + lead_in = nxt["kind"] == "cut" and (m["kind"] == "lead" or quarter) rise = ( nxt["curve"]["end"][2] > nxt["curve"]["start"][2] and math.dist(nxt["curve"]["end"][:2], nxt["curve"]["start"][:2]) < 1e-9 @@ -486,7 +498,6 @@ def tangent(c, end): lead_out = m["kind"] == "lead" and prev["kind"] in ("cut", "link") and rise if not (lead_in or lead_out): continue - a, ce = c["start"], c["center"] self.assertAlmostEqual(math.hypot(a[0] - ce[0], a[1] - ce[1]), R, delta=1e-6) self.assertAlmostEqual(abs(c["sweep_rad"]), math.pi / 2, delta=1e-9) if lead_in: @@ -502,6 +513,82 @@ def tangent(c, end): self.assertEqual(ins, report["arc_lead_ins"], name) self.assertEqual(outs, report["arc_lead_outs"], name) + def test_plunges_turn_to_horizontal_on_a_quarter_circle(self): + # A vertical plunge stops a tool radius above where it used to land + # and turns to horizontal on a quarter circle of the tool's radius in + # the vertical plane of the move that follows: the turn ends a radius + # lower and a radius on, every point of it on that circle (its chords + # within 5 microns), leaving horizontally in the direction the + # next move starts in. + for name in ("stepped", "island"): + report, motions, *_ = cached(name) + self.assertGreater(report.get("rounded_plunges", 0), 0, name) + turns = 0 + for i, m in enumerate(motions): + if m not in vertical_plunges([m]): + continue + j, path = i + 1, [] + while ( + motions[j]["kind"] == "lead" + and motions[j]["curve"]["end"][2] < motions[j]["curve"]["start"][2] - 1e-9 + ): + path.append(motions[j]) + j += 1 + if not path: + continue + turns += 1 + top, end = path[0]["curve"]["start"], path[-1]["curve"]["end"] + self.assertEqual(top, m["curve"]["end"], name) + self.assertAlmostEqual(top[2] - end[2], R, delta=1e-9) + self.assertAlmostEqual(math.dist(top[:2], end[:2]), R, delta=1e-9) + centre = [end[0], end[1], top[2]] + for t in path: + c = t["curve"] + for q in (c["start"], c["end"]): + self.assertAlmostEqual(math.dist(q, centre), R, delta=1e-9) + if c["kind"] == "line": + mid = [(a + b) / 2 for a, b in zip(c["start"], c["end"])] + self.assertLessEqual(R - math.dist(mid, centre), 0.005 + 1e-9) + d = [end[0] - top[0], end[1] - top[1]] + nxt = motions[j]["curve"] + if nxt.get("kind", "line") == "line": + e = [nxt["end"][0] - nxt["start"][0], nxt["end"][1] - nxt["start"][1]] + else: + a, ce, sign = nxt["start"], nxt["center"], math.copysign(1, nxt["sweep_rad"]) + e = [-(a[1] - ce[1]) * sign, (a[0] - ce[0]) * sign] + cos = (d[0] * e[0] + d[1] * e[1]) / (math.hypot(*d) * math.hypot(*e)) + self.assertGreater(cos, 1 - 1e-9, (name, motions[j])) + self.assertEqual(turns, report["rounded_plunges"], name) + + def test_radial_stock_is_left_on_every_wall(self): + # With radial_stock_to_leave_mm the passes cut only the flats: on every + # feed move the tool's axis stays a radius plus that stock (less the + # sampling step and 1e-4) from every part point above its tip, + # measured against the analytic part (the short island's walls, the + # tall boss beside it, the pocket and boss walls). + radial = 0.1 + for name, spec in (("stepped", STEPPED), ("island", ISLAND)): + _, motions, *_ = run(spec, radial_stock_to_leave_mm=radial) + field = Field(spec) + worst = (math.inf, None) + for m in motions: + if m["kind"] == "rapid": + continue + ps = ( + arc_points(m["curve"]) + if m["curve"].get("kind") == "arc" and m["curve"].get("plane") == "xy" + else points(m, 9) + ) + for p in ps: + c = field.clearance(p, p[2]) + if c < worst[0]: + worst = (c, (m["id"], m["kind"], [round(v, 4) for v in p])) + self.assertGreaterEqual( + worst[0], + R + radial - 1e-4 - field.step, + f"{name}: tool within {worst[0] - R:.4f} mm of a wall at {worst[1]}", + ) + if __name__ == "__main__": unittest.main() diff --git a/src/flat.rs b/src/flat.rs index 31a5145..45a64c7 100644 --- a/src/flat.rs +++ b/src/flat.rs @@ -85,6 +85,11 @@ pub struct FlatOperation { /// Axial stock left on the flats. #[serde(default)] pub stock_to_leave_mm: f64, + /// Radial stock left on the walls: the passes keep this much farther + /// from every surface standing above the flat than the cutter's radius, + /// so they cut only the horizontal faces. + #[serde(default)] + pub radial_stock_to_leave_mm: f64, /// Faces within this height of each other form one flat level. #[serde(default = "level_tolerance")] pub level_tolerance_mm: f64, @@ -126,6 +131,7 @@ impl FlatOperation { clearance_z_mm: self.clearance_z_mm, axis: self.axis, stock_to_leave_mm: self.stock_to_leave_mm, + radial_stock_to_leave_mm: self.radial_stock_to_leave_mm, level_tolerance_mm: self.level_tolerance_mm, feed_mm_min: self.feed_mm_min, plunge_mm_min: self.plunge_mm_min, @@ -171,6 +177,10 @@ pub struct FlatReport { /// retract (see `FlatPlan::arc_lead_out`). #[serde(skip_serializing_if = "is_zero")] pub arc_lead_outs: usize, + /// Vertical plunges that turn to horizontal through a quarter circle of + /// the tool's radius in the vertical plane (see `FlatPlan::plunge_turn`). + #[serde(skip_serializing_if = "is_zero")] + pub rounded_plunges: usize, pub clearance_proof: &'static str, } @@ -1653,6 +1663,7 @@ enum Phase { Approach, Descend, Enter, + Turn, Lead, ArcIn, Ramp, @@ -1680,6 +1691,8 @@ pub struct FlatPlan { entry: Option, ramp: std::collections::VecDeque, lead: Option<(Curve, bool)>, + turn: std::collections::VecDeque, + after_turn: Phase, initial: Vec3, position: Vec3, next_id: u64, @@ -1707,6 +1720,7 @@ impl FlatPlan { op.stepover_mm, op.clearance_z_mm, op.stock_to_leave_mm, + op.radial_stock_to_leave_mm, op.level_tolerance_mm, op.feed_mm_min, op.plunge_mm_min, @@ -1754,6 +1768,13 @@ impl FlatPlan { op.stock_to_leave_mm ), ), + ( + op.radial_stock_to_leave_mm >= 0., + format!( + "radial_stock_to_leave_mm {} must not be negative", + op.radial_stock_to_leave_mm + ), + ), ( op.level_tolerance_mm >= op.tolerance_mm && op.level_tolerance_mm <= 0.1, format!( @@ -1873,6 +1894,7 @@ impl FlatPlan { level, op.level_tolerance_mm, r, + op.radial_stock_to_leave_mm, op.stepover_mm, op.tolerance_mm, cancel, @@ -1993,6 +2015,7 @@ impl FlatPlan { ramped_entries: 0, arc_lead_ins: 0, arc_lead_outs: 0, + rounded_plunges: 0, clearance_proof: "exact maximum part height under each horizontal cut's swept disk (triangle-capsule extreme points) at most the cut height plus tolerance; contour-parallel offset passes outside in, side entry in air on open edges and every vertical plunge beside the level's face (a radius outside it, the face region a superset of the flat within the shadows' stated errors), links at depth and when chains break", }; Ok(Self { @@ -2012,6 +2035,8 @@ impl FlatPlan { entry: None, ramp: Default::default(), lead: None, + turn: Default::default(), + after_turn: Phase::Cut, initial, position: initial, next_id: first_id, @@ -2302,6 +2327,102 @@ impl FlatPlan { Ok(None) } + /// The turn at the bottom of a vertical plunge onto `p` at height `z0`, + /// where the move that follows leaves along the unit direction `d`: the + /// plunge stops a tool radius higher, a radius back along `d`, and a + /// quarter circle of the tool's radius in the vertical plane through `d` + /// turns it to horizontal at `p`, tangent to the plunge above and to the + /// move after (one arc in the XZ or YZ plane when `d` runs along X or Y, + /// otherwise its chords at `ARC_MOVE_SAGITTA`, inside the circle). + /// Taken where the disk over the whole turn's span at `z0` is clear of + /// live stock above `z0` and of the part, the span lies inside the + /// limits, and the plunge's new bottom is below the feed height; `None` + /// otherwise (the plunge then comes straight down onto `p`). + fn plunge_turn( + &mut self, + stock: &Stock, + p: [f64; 2], + d: [f64; 2], + z0: f64, + cancel: &impl CancelSignal, + ) -> Result>, String> { + let tol = self.op.tolerance_mm; + let rho = self.radius; + if z0 + rho > self.heights.feed { + return Ok(None); + } + let along_x = d[1].abs() <= 1e-12; + let along_y = d[0].abs() <= 1e-12; + let s = if along_x { + [p[0] - rho * d[0].signum(), p[1]] + } else if along_y { + [p[0], p[1] - rho * d[1].signum()] + } else { + [p[0] - rho * d[0], p[1] - rho * d[1]] + }; + if segment_stock_top(stock, s, p, rho, cancel)? > z0 + tol + || self + .index + .max_height(s, p, rho, &mut self.seen, &mut self.stamp) + > z0 + tol + || !allows_segment(self.limits.as_ref(), s, p, z0, tol)? + { + return Ok(None); + } + let start = [s[0], s[1], z0 + rho]; + let end = [p[0], p[1], z0]; + let center = [p[0], p[1], z0 + rho]; + if along_x || along_y { + let plane = if along_x { + crate::motion::Plane::Xz + } else { + crate::motion::Plane::Yz + }; + let [u, v, _] = plane.axes(); + let angle = |q: [f64; 3]| (q[v] - center[v]).atan2(q[u] - center[u]); + let mut sweep = angle(end) - angle(start); + if sweep > std::f64::consts::PI { + sweep -= 2. * std::f64::consts::PI; + } else if sweep < -std::f64::consts::PI { + sweep += 2. * std::f64::consts::PI; + } + return Ok(Some(vec![Curve::Arc { + start, + end, + center, + plane, + sweep_rad: sweep, + }])); + } + let half = (1. - ARC_MOVE_SAGITTA / rho) + .clamp(-1., 1.) + .acos() + .max(1e-9); + let count = ((std::f64::consts::FRAC_PI_2 / (2. * half)).ceil().max(1.) as usize).min(4096); + let at = |k: usize| { + if k == 0 { + return start; + } + if k == count { + return end; + } + let theta = std::f64::consts::FRAC_PI_2 * k as f64 / count as f64; + [ + p[0] - rho * theta.cos() * d[0], + p[1] - rho * theta.cos() * d[1], + z0 + rho - rho * theta.sin(), + ] + }; + Ok(Some( + (0..count) + .map(|k| Curve::Line { + start: at(k), + end: at(k + 1), + }) + .collect(), + )) + } + /// Whether the disk at `p` comes down beside this chain's level's face: a /// radius (less the tolerance) outside the face region, so a vertical /// plunge at `p` never rests the disk on the flat the pass finishes. An @@ -2495,6 +2616,57 @@ impl FlatPlan { // rapid goes over the plunge point (a side entry), the // ramp's start, or the pass's start. let entry = self.decide_entry(stock, cancel)?; + // Where the plunge lands, the direction the move after it + // leaves in, and the phase after the plunge. + let landing = { + let piece = &self.chains[self.chain].pieces[self.piece]; + let a = piece.start(); + match &entry { + Entry::Side { p: q } => { + let (dx, dy) = (a[0] - q[0], a[1] - q[1]); + let n = dx.hypot(dy); + (n > 0.).then(|| (*q, [dx / n, dy / n], a[2], Phase::Lead)) + } + Entry::Arc { lead, .. } => { + let (Curve::Arc { + start, + center, + sweep_rad, + .. + } + | Curve::Helix { + start, + center, + sweep_rad, + .. + }) = lead + else { + unreachable!("an arc lead is an arc or a helix") + }; + let sign = sweep_rad.signum(); + let (rx, ry) = (start[0] - center[0], start[1] - center[1]); + let n = rx.hypot(ry); + Some(( + [start[0], start[1]], + [-ry * sign / n, rx * sign / n], + start[2], + Phase::ArcIn, + )) + } + Entry::Plunge => { + Some(([a[0], a[1]], piece.segs[0].tangent(false), a[2], Phase::Cut)) + } + Entry::Ramp { .. } => None, + } + }; + self.turn.clear(); + if let Some((q, d, z0, after)) = landing + && let Some(turn) = self.plunge_turn(stock, q, d, z0, cancel)? + { + self.report.rounded_plunges += 1; + self.turn = turn.into(); + self.after_turn = after; + } let over = match &entry { Entry::Side { p: over } => *over, Entry::Ramp { curves, .. } => { @@ -2510,6 +2682,13 @@ impl FlatPlan { [f[0], f[1]] } }; + let over = match self.turn.front() { + Some(first) => { + let f = first.start(); + [f[0], f[1]] + } + None => over, + }; self.entry = Some(entry); ( [over[0], over[1], p[2]], @@ -2526,7 +2705,7 @@ impl FlatPlan { ), Phase::Enter => { let a = self.chains[self.chain].pieces[self.piece].start(); - match self.entry.take().expect("entry plan") { + let planned = match self.entry.take().expect("entry plan") { Entry::Side { .. } => { ([p[0], p[1], a[2]], MoveKind::Plunge, Phase::Lead, None) } @@ -2552,8 +2731,26 @@ impl FlatPlan { None, ) } + }; + // A rounded plunge stops at the turn's top; the turn + // lands where the plain plunge would have. + match self.turn.front() { + Some(first) => { + let f = first.start(); + ([p[0], p[1], f[2]], MoveKind::Plunge, Phase::Turn, None) + } + None => planned, } } + Phase::Turn => { + let curve = self.turn.pop_front().expect("turn move"); + let next = if self.turn.is_empty() { + self.after_turn + } else { + Phase::Turn + }; + (curve.end(), MoveKind::Lead, next, Some(curve)) + } Phase::Lead => { let a = self.chains[self.chain].pieces[self.piece].start(); ([a[0], a[1], a[2]], MoveKind::Lead, Phase::Cut, None) @@ -2766,8 +2963,9 @@ pub(crate) fn segment_stock_top( /// shadow of the part standing above `z - level_tolerance`, grown by the /// overhang `r - stepover` (none at a stepover of a radius or more), minus /// the shadow of the part standing above the level, grown by the radius plus -/// the shadows' stated errors (the pattern of `waterline::flat_level_loops`): -/// every position whose disk would reach the part above the level. The +/// `radial` (the radial stock left on the walls) plus the shadows' stated +/// errors (the pattern of `waterline::flat_level_loops`): every position +/// whose disk would come within `radial` of the part above the level. The /// "above" shadow's tip is picked so its `protected_from_z_mm` is strictly /// above `z + level_tolerance`; nothing standing above the level leaves the /// region alone. Every point of the region rests the disk on the level. @@ -2779,13 +2977,16 @@ pub(crate) fn segment_stock_top( /// outside it and cutting nothing (the face is still covered: it lies inside /// the region, and the passes cover the region). This is the usual facing /// practice of running the tool part-way past the edge. Next to part standing -/// above the level the region still ends a radius (plus errors) from it, so -/// the outermost pass there runs along the wall. +/// above the level the region still ends a radius plus `radial` (plus +/// errors) from it, so the outermost pass there runs along the wall, the +/// wall's radial stock left standing. +#[allow(clippy::too_many_arguments)] fn level_region( target: &crate::roughing::PreparedRoughingTarget, z: f64, level_tolerance: f64, r: f64, + radial: f64, stepover: f64, tolerance: f64, cancel: &impl CancelSignal, @@ -2829,7 +3030,9 @@ fn level_region( .map_err(|e| format!("flat-area face at Z{z}: {e}"))?; (resting, face) } else { - let reach = r + (above.report.boundary_error_mm - source_error).max(0.); + // A radius plus the radial stock left on the walls off everything + // standing above the level. + let reach = r + radial + (above.report.boundary_error_mm - source_error).max(0.); let blocked = above .region .prepare(options) From 3743b06660e08ea98d98ccfb1a8eddcea55fd6bb Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:12:04 -0700 Subject: [PATCH 21/26] Flat: finish each area before the next; rounded plunges over finished floor (#38) --- docs/operations.md | 62 +++++---- python/tests/test_flat_offset.py | 71 +++++++++++ src/flat.rs | 208 +++++++++++++++++++++++++++++-- 3 files changed, 306 insertions(+), 35 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index d8a7251..c1f8c61 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -1654,32 +1654,42 @@ disk is not above the cut (computed exactly per facet). Per connected component, nearest first, the passes are cut at growing offset depth (the outermost ring first); at the same depth outer boundary loops before hole loops, then nearest first, and each loop starts at its vertex nearest the tool. -Kernel artefacts are not cut as moves of their own: a run of strokes on one -circle (straight chords, or chords mixed with micro-arcs) is refitted as one -arc, and a straight stub under 0.005 mm is absorbed into its straight -neighbour. Consecutive pieces join into one chain by a straight link at the cut -height and cutting feed when the link is at most two stepovers long, passes the -same proof and lies inside the machine limits; otherwise the chain ends -(retract, new entry). Where a side of the chain's first pass has no live stock -above the cut (beside an open edge, or floor earlier passes have finished), the -chain is entered by a vertical plunge through air and a quarter-circle lead-in -of the tool's radius, tangent to the pass at its start: flat at the cut height -and cutting feed when the plunge point lies a radius beside the face, otherwise -a helix that stops above the finished floor (radius × √2 × the tangent of the -declared ramp angle) and descends to the pass at no more than the ramp's angle -over its chord, at the ramp's feed (with no ramp declared that side does not -qualify). The arc is proven clear of the part by its chords at radius r + -sagitta and must lie inside the machine limits. A chain ends with a flat -tangent quarter-circle lead-out of the tool's radius where the disk at its end -touches no stock above the cut; otherwise it retracts at the pass's end. The -report counts them as `arc_lead_ins` and `arc_lead_outs`. Every vertical plunge -that lands in air (side entries, arc lead-ins, plunges at a chain's start) -stops a tool radius higher and a radius back along the move that follows, and -turns to horizontal on a quarter circle of the tool's radius in the vertical -plane of that move (one XZ or YZ arc when the move runs along X or Y, otherwise -its chords within 5 microns), at cutting feed; the span is proven clear of the -part and of live stock at the landing height and inside the limits, otherwise -the plunge comes straight down. The report counts these as `rounded_plunges`. +Where the offsets split a level into separate areas (the strips either side of +a boss), each area is finished, outside in, before the tool crosses to the +next: a loop or a kept stretch of one waits only for the shallower ones whose +swept disk overlaps its own, and of those whose turn has come the nearest is +cut next. This order is used when it needs fewer entries than the plain depth +order, or as many with less travel. Kernel artefacts are not cut as moves of +their own: a run of strokes on one circle (straight chords, or chords mixed +with micro-arcs) is refitted as one arc, and a straight stub under 0.005 mm is +absorbed into its straight neighbour. Consecutive pieces join into one chain by +a straight link at the cut height and cutting feed when the link is at most two +stepovers long, passes the same proof and lies inside the machine limits; +otherwise the chain ends (retract, new entry). Where a side of the chain's +first pass has no live stock above the cut (beside an open edge, or floor +earlier passes have finished), the chain is entered by a vertical plunge +through air and a quarter-circle lead-in of the tool's radius, tangent to the +pass at its start: flat at the cut height and cutting feed when the plunge +point lies a radius beside the face, otherwise a helix that stops above the +finished floor (radius × √2 × the tangent of the declared ramp angle) and +descends to the pass at no more than the ramp's angle over its chord, at the +ramp's feed (with no ramp declared that side does not qualify). The arc is +proven clear of the part by its chords at radius r + sagitta and must lie +inside the machine limits. A chain ends with a flat tangent quarter-circle +lead-out of the tool's radius where the disk at its end touches no stock above +the cut; otherwise it retracts at the pass's end. The report counts them as +`arc_lead_ins` and `arc_lead_outs`. Every vertical plunge that lands in air +(side entries, arc lead-ins, plunges at a chain's start) stops a tool radius +higher and a radius back along the move that follows, and turns to horizontal +on a quarter circle of the tool's radius in the vertical plane of that move +(one XZ or YZ arc when the move runs along X or Y, otherwise its chords within +5 microns), at cutting feed; the span is proven clear of the part and of live +stock at the landing height and inside the limits, otherwise the plunge comes +straight down. The report counts these as `rounded_plunges`. Because a rounded +plunge reaches the floor moving sideways, a plunge may also land over the +level's face where no stock stands above the pass: there the arc lead-in is +flat, and a pass start with no stock above it is plunged and turned instead of +ramped. A helical lead-in, or a ramp, is used only where the turn does not fit. Otherwise a chain is entered beside the level's face where the flat is open (side entry in air): the tool rapids over a point a quarter to two radii outside the chain's first loop, away from the region, where no stock stands diff --git a/python/tests/test_flat_offset.py b/python/tests/test_flat_offset.py index 8d8a84f..9497792 100644 --- a/python/tests/test_flat_offset.py +++ b/python/tests/test_flat_offset.py @@ -46,6 +46,22 @@ def tool(): bosses=[(7, 8, 3, 13, 12, 5), (16, 8, 3, 20, 12, 9)], extent=(0, 0, 30, 20), ) +# A wide block with a boss in the middle whose offsets split the block's +# level into separate areas either side of the boss. +WIDE = dict( + boxes=[(0, 0, 0, 60, 40, 4)], + pockets=[], + bosses=[(20, 10, 4, 40, 30, 7)], + extent=(0, 0, 60, 40), +) +# STEPPED at 1.89 times the size: a lead-in that starts over floor the first +# lap finished. +STEPPED_LARGE = dict( + boxes=[(0, 0, 0, 45.4, 30.2, 4)], + pockets=[], + bosses=[(15.1, 7.6, 4, 30.2, 22.7, 7)], + extent=(0, 0, 45.4, 30.2), +) def solid(spec, skin=0.0): @@ -589,6 +605,61 @@ def test_radial_stock_is_left_on_every_wall(self): f"{name}: tool within {worst[0] - R:.4f} mm of a wall at {worst[1]}", ) + def test_each_area_is_finished_before_crossing_to_the_next(self): + # The base level of WIDE splits into areas left and right of the + # boss. Each is finished before the tool moves on: between cutting + # moves on the base level, the tool crosses from one side of the boss + # to the other through the air (a retract and rapid) at most once. + _, motions, *_ = run(WIDE) + x0, x1 = WIDE["bosses"][0][0], WIDE["bosses"][0][3] + z = WIDE["boxes"][0][5] + crossings, side, lifted = 0, None, False + for m in motions: + c = m["curve"] + if m["kind"] in ("rapid", "retract"): + lifted = True + continue + if m["kind"] != "cut" or abs(c["start"][2] - z) > 1e-6: + continue + x = c["start"][0] + here = "left" if x < x0 else "right" if x > x1 else None + if here is None: + continue + if lifted and side is not None and here != side: + crossings += 1 + side, lifted = here, False + self.assertLessEqual(crossings, 1) + + def test_entries_over_finished_floor_plunge_rather_than_spiral(self): + # A pass whose arc lead-in starts over floor already finished (no + # stock above the pass under the tool) is entered by a plunge that + # turns to horizontal, not by a helix down onto the floor. + parts = (("stepped", STEPPED), ("large", STEPPED_LARGE), ("wide", WIDE), ("island", ISLAND)) + for name, spec in parts: + _, motions, before, grid, _ = run(spec) + for i in range(1, len(motions)): + c, prev = motions[i]["curve"], motions[i - 1]["curve"] + vertical = ( + motions[i - 1]["kind"] == "plunge" + and prev.get("kind", "line") == "line" + and math.hypot(prev["end"][0] - prev["start"][0], prev["end"][1] - prev["start"][1]) < 1e-9 + ) + lead_in = ( + vertical + and c.get("kind") == "helix" + and i + 1 < len(motions) + and motions[i + 1]["kind"] != "plunge" + ) + if not lead_in: + continue + # A helix between a vertical plunge and the pass is a helical + # lead-in (a ramp continues with more plunging moves); it is + # only allowed where stock under the plunge point stands above + # the pass (no plunge in air there). + p, z = c["start"], c["end"][2] + top = stock_top_near(grid, before[i], p, R) + self.assertGreater(top, z + 0.05, (name, motions[i]["id"], p)) + if __name__ == "__main__": unittest.main() diff --git a/src/flat.rs b/src/flat.rs index 45a64c7..aa032ec 100644 --- a/src/flat.rs +++ b/src/flat.rs @@ -1920,11 +1920,11 @@ impl FlatPlan { .then(a.cmp(&b)) }); for gi in order { - for (_, ring, runs) in groups[gi].ordered(tool_xy) { + loops += groups[gi].outers.len() + groups[gi].holes.len(); + for (_, ring, runs) in groups[gi].ordered(tool_xy, 2. * r, 2. * op.stepover_mm) { if cancel.is_cancelled() { return Err("flat-area planning cancelled".into()); } - loops += 1; // An inner loop is cut only where its disk reaches floor // the loops before it left; a short stretch between two // such places is cut through rather than left for a link. @@ -2222,6 +2222,7 @@ impl FlatPlan { v: [f64; 2], t: [f64; 2], z: f64, + cancel: &impl CancelSignal, ) -> Result, String> { let tol = self.op.tolerance_mm; let rho = self.radius; @@ -2233,7 +2234,14 @@ impl FlatPlan { if stock.top_under_disk(p, rho) > z + tol { continue; } - let beside = self.beside_face(p)?; + // Over the face, a plunge whose last radius turns to horizontal + // (`plunge_turn`, along the arc's tangent at `p`, which is -n) + // reaches the floor moving sideways and never dwells on it: the + // lead is flat there too. + let beside = self.beside_face(p)? || { + let d = [-n[0], -n[1]]; + self.plunge_turn(stock, p, d, z, cancel)?.is_some() + }; let rise = if beside { 0. } else { @@ -2516,17 +2524,28 @@ impl FlatPlan { rotate_piece(piece, v); } let t = self.chains[self.chain].pieces[self.piece].segs[0].tangent(false); - if let Some(entry) = self.arc_lead_in(stock, v, t, z)? { + if let Some(entry) = self.arc_lead_in(stock, v, t, z, cancel)? { self.report.arc_lead_ins += 1; return Ok(entry); } return Ok(Entry::Side { p }); } let t = self.chains[self.chain].pieces[self.piece].segs[0].tangent(false); - if let Some(entry) = self.arc_lead_in(stock, first, t, z)? { + if let Some(entry) = self.arc_lead_in(stock, first, t, z, cancel)? { self.report.arc_lead_ins += 1; return Ok(entry); } + // A pass start over the face with no stock above it is plunged when + // the plunge turns to horizontal there (`plunge_turn`): the disk never + // dwells on the floor it finishes. + let a = self.chains[self.chain].pieces[self.piece].start(); + if stock.top_under_disk([a[0], a[1]], self.radius) <= z + tol + && self + .plunge_turn(stock, [a[0], a[1]], t, z, cancel)? + .is_some() + { + return Ok(Entry::Plunge); + } let piece = &self.chains[self.chain].pieces[self.piece]; match self.plunge_or_ramp(piece, stock, cancel)? { None => Ok(Entry::Plunge), @@ -3103,8 +3122,11 @@ impl LoopGroup { nearest(&self.outers).min(nearest(&self.holes)) } /// The rings in cut order: outer loops before hole loops, offset - /// ascending (outside in), nearest the tool first at the same offset. - fn ordered(&self, tool: [f64; 2]) -> Vec { + /// ascending (outside in), nearest the tool first at the same offset; + /// then, within the outer and within the hole loops, area by area + /// (`by_area`) where that takes fewer entries, so each area is finished, + /// outside in, before the tool crosses to the next. + fn ordered(&self, tool: [f64; 2], gap: f64, link: f64) -> Vec { let near = |ring: &[crate::pocket::Stroke]| { ring.iter() .map(|s| (s.a[0] - tool[0]).hypot(s.a[1] - tool[1])) @@ -3121,12 +3143,180 @@ impl LoopGroup { }); order.into_iter().map(|i| rings[i].clone()).collect() }; - let mut all = sort(&self.outers); - all.extend(sort(&self.holes)); + let mut all = by_area(sort(&self.outers), tool, gap, link); + let at = all + .last() + .and_then(|(_, ring, runs)| match runs { + Some(runs) => runs.last().and_then(|r| r.last()).map(|s| s.b), + None => ring.first().map(|s| s.a), + }) + .unwrap_or(tool); + all.extend(by_area(sort(&self.holes), at, gap, link)); all } } +/// `rings` (in cut order: offset ascending) reordered area by area when +/// that takes fewer entries. Each full ring and each kept stretch of a +/// trimmed ring is one item; an item waits for every shallower item within +/// `gap` of it (the cutter's diameter: every shallower item whose swept +/// disk overlaps its own), so every area is still cut outside in and no +/// item runs over floor a deeper one finished first; of the items whose +/// turn has come, the one nearest the tool is cut next. Where the offsets +/// split a level into separate areas (the strips either side of a boss), +/// the tool then finishes one area before crossing to the next instead of +/// visiting every area once per offset. The new order is taken only when +/// it needs fewer entries (moves to the next item longer than `link`, the +/// longest link at depth), or as many over less travel; otherwise the +/// rings keep their order. Cut order does not change what is cut: each item +/// was kept for the floor it alone reaches, and its proof and entry are +/// decided against the part and the live stock as before. +fn by_area(rings: Vec, tool: [f64; 2], gap: f64, link: f64) -> Vec { + let mut items: Vec = vec![]; + for (d, ring, runs) in &rings { + match runs { + None => items.push((*d, ring.clone(), None)), + Some(runs) => { + for run in runs.iter().filter(|r| !r.is_empty()) { + items.push((*d, ring.clone(), Some(vec![run.clone()]))); + } + } + } + } + let lines: Vec> = items + .iter() + .map(|item| match &item.2 { + None => item.1.clone(), + Some(runs) => runs.concat(), + }) + .collect(); + let points: Vec> = lines + .iter() + .map(|run| { + run.iter() + .flat_map(|s| (0..4).map(move |k| stroke_point(s, k as f64 / 4.))) + .chain(run.last().map(|s| s.b)) + .collect() + }) + .collect(); + let distance = |p: [f64; 2], s: &crate::pocket::Stroke| { + if s.arc.is_none() { + dist2_to_segment(p, s.a, s.b).sqrt() + } else { + (0..=16) + .map(|k| { + let x = stroke_point(s, k as f64 / 16.); + (x[0] - p[0]).hypot(x[1] - p[1]) + }) + .fold(f64::INFINITY, f64::min) + } + }; + let near = |i: usize, j: usize| { + points[i] + .iter() + .any(|p| lines[j].iter().any(|s| distance(*p, s) <= gap)) + || points[j] + .iter() + .any(|p| lines[i].iter().any(|s| distance(*p, s) <= gap)) + }; + let n = items.len(); + let mut waits: Vec> = vec![vec![]; n]; + for j in 0..n { + for i in 0..n { + if items[i].0 < items[j].0 && near(i, j) { + waits[j].push(i); + } + } + } + let hypot = |p: [f64; 2], q: [f64; 2]| (p[0] - q[0]).hypot(p[1] - q[1]); + // Where an item is entered and left from `at`: a closed ring at its + // vertex nearest the tool (`rotate_to_nearest`), a stretch from its first + // stroke to its last. + let ends = |strokes: &[crate::pocket::Stroke], closed: bool, at: [f64; 2]| { + if closed { + let v = strokes + .iter() + .map(|s| s.a) + .min_by(|p, q| hypot(*p, at).total_cmp(&hypot(*q, at))) + .unwrap_or(at); + (v, v) + } else { + ( + strokes.first().map_or(at, |s| s.a), + strokes.last().map_or(at, |s| s.b), + ) + } + }; + // (entries, travel) of a walk over (strokes, closed) pieces. + let cost = |walk: &[(Vec, bool)]| { + let (mut entries, mut travel, mut at) = (0usize, 0f64, tool); + for (strokes, closed) in walk { + let (start, end) = ends(strokes, *closed, at); + let jump = hypot(at, start); + if jump > link { + entries += 1; + } + travel += jump; + at = end; + } + (entries, travel) + }; + let mut done = vec![false; n]; + let mut order: Vec = vec![]; + let mut at = tool; + while order.len() < n { + let next = (0..n) + .filter(|&j| !done[j] && waits[j].iter().all(|&i| done[i])) + .min_by(|&a, &b| { + let d = |k: usize| { + points[k] + .iter() + .map(|p| hypot(*p, at)) + .fold(f64::INFINITY, f64::min) + }; + d(a).total_cmp(&d(b)).then(a.cmp(&b)) + }) + .expect("the shallowest item left waits for nothing"); + done[next] = true; + order.push(next); + at = ends(&lines[next], items[next].2.is_none(), at).1; + } + let by_area: Vec<(Vec, bool)> = order + .iter() + .map(|&i| (lines[i].clone(), items[i].2.is_none())) + .collect(); + // The rings as they are: a trimmed ring's stretches in loop order from + // the one starting nearest the tool (`open_runs_from_nearest`). + let mut as_is: Vec<(Vec, bool)> = vec![]; + let mut at = tool; + for (_, ring, runs) in &rings { + match runs { + None => { + at = ends(ring, true, at).1; + as_is.push((ring.clone(), true)); + } + Some(runs) => { + let runs: Vec<&Vec> = + runs.iter().filter(|r| !r.is_empty()).collect(); + let first = (0..runs.len()) + .min_by(|&a, &b| hypot(runs[a][0].a, at).total_cmp(&hypot(runs[b][0].a, at))) + .unwrap_or(0); + for k in 0..runs.len() { + let run = runs[(first + k) % runs.len()]; + at = run.last().map_or(at, |s| s.b); + as_is.push((run.clone(), false)); + } + } + } + } + let (new, old) = (cost(&by_area), cost(&as_is)); + if new.0 < old.0 || (new.0 == old.0 && new.1 < old.1) { + order.into_iter().map(|i| items[i].clone()).collect() + } else { + rings + } +} + /// The offset loops of `region`, grouped per connected component: offsets /// inward by 0, stepover, 2 stepover, ... while non-empty, then the core: /// after the last non-empty offset `d`, while the region offset by From f9e132c5ab1b6ff42337297ac4e8dd8f5c2db202 Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Thu, 19 Nov 2026 09:50:41 -0700 Subject: [PATCH 22/26] Flat: arc ramp entries through shallow stock (#38) --- docs/operations.md | 51 ++++---- python/tests/test_flat_offset.py | 48 ++++++- src/flat.rs | 207 ++++++++++++++++++++++++++++++- 3 files changed, 278 insertions(+), 28 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index c1f8c61..450019a 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -1696,27 +1696,36 @@ outside the chain's first loop, away from the region, where no stock stands within the disk above the cut, plunges vertically through air to the cut height and leads in at cutting feed. Where no such point exists it plunges vertically at the chain's start when no live stock stands above its height there (within -`tolerance_mm`). Where stock does (roughing left it, or the stock was not cut -there yet), the chain is entered by a ramp, and only if the operation declares -`entry=RampEntry(angle_deg, ...)`: the tool plunges through air to the top of -the live stock over the stretch of the chain's first loop the ramp travels (the -highest cell bound anywhere along that stretch; the whole loop when the ramp -has to reverse on it), then zigzags down along that loop at no more than the -declared angle (over each move's chord, so a leg along an arc descends a little -shallower) and at the entry's `feed_mm_min` (default the plunge feed); a zigzag -that has to reverse needs the entry's `min_length_mm`. Every ramp point lies -above the proven loop, so it clears the part like the loop does; the report -counts ramped chains as `ramped_entries`. Nothing is plunged into stock on any -path: a chain with stock above it and no declared entry, a ramp that does not -fit (too short a loop, an angle too shallow for the loop, or stock above the -feed height) is refused, naming the chain, its length and the stock above it. -The `flat` benchmark runs on a blank roughed to 0.1 mm over the flats and -declares a 3 degree entry. The report gives the levels, `loops` (closed offset -loops planned), `rows` (loops cut, counting the open pieces a split loop -leaves), `runs` (chains), `links_at_depth`, cut length, `runs_completed`, -`ramped_entries`, `arc_lead_ins`, `arc_lead_outs`, `rounded_plunges`, and any -length that could not be proven clear (`dropped_length_mm`). `axis` is still -accepted so old jobs load, but no longer orders anything. +`tolerance_mm`). A pass start under no more stock than an arc ramp can take is +entered by one smooth descent along the pass's line, as with a plunge and an +arc lead-in: the tool plunges through air, an arc of its radius turns it to the +declared ramp angle above the stock, a straight leg at that angle goes through +the stock, and an arc of its radius turns it level onto the pass. The stock is +never met steeper than the declared angle, and the whole descent starts at most +four tool radii behind the pass start (about half a millimetre of stock at 3 +degrees). Deeper stock is ramped along the pass as follows. Where stock does +(roughing left it, or the stock was not cut there yet), the chain is entered by +a ramp, and only if the operation declares `entry=RampEntry(angle_deg, ...)`: +the tool plunges through air to the top of the live stock over the stretch of +the chain's first loop the ramp travels (the highest cell bound anywhere along +that stretch; the whole loop when the ramp has to reverse on it), then zigzags +down along that loop at no more than the declared angle (over each move's +chord, so a leg along an arc descends a little shallower) and at the entry's +`feed_mm_min` (default the plunge feed); a zigzag that has to reverse needs the +entry's `min_length_mm`. Every ramp point lies above the proven loop, so it +clears the part like the loop does; the report counts ramped chains as +`ramped_entries`. Nothing is plunged into stock on any path: a chain with stock +above it and no declared entry, a ramp that does not fit (too short a loop, an +angle too shallow for the loop, or stock above the feed height) is refused, +naming the chain, its length and the stock above it. The `flat` benchmark runs +on a blank roughed to 0.1 mm over the flats and declares a 3 degree entry. The +report gives the levels, `loops` (closed offset loops planned), `rows` (loops +cut, counting the open pieces a split loop leaves), `runs` (chains), +`links_at_depth`, cut length, `runs_completed`, `ramped_entries`, `arc_ramps` +(arc-ramp entries, also counted in `ramped_entries`), `arc_lead_ins`, +`arc_lead_outs`, `rounded_plunges`, and any length that could not be proven +clear (`dropped_length_mm`). `axis` is still accepted so old jobs load, but no +longer orders anything. ## Spiral, radial and project finishing: `Spiral`, `Radial`, `Project` diff --git a/python/tests/test_flat_offset.py b/python/tests/test_flat_offset.py index 9497792..833f91b 100644 --- a/python/tests/test_flat_offset.py +++ b/python/tests/test_flat_offset.py @@ -550,7 +550,8 @@ def test_plunges_turn_to_horizontal_on_a_quarter_circle(self): ): path.append(motions[j]) j += 1 - if not path: + if not path or motions[j]["kind"] == "plunge": + # No turn, or an arc ramp's upper arc (its own test). continue turns += 1 top, end = path[0]["curve"]["start"], path[-1]["curve"]["end"] @@ -660,6 +661,51 @@ def test_entries_over_finished_floor_plunge_rather_than_spiral(self): top = stock_top_near(grid, before[i], p, R) self.assertGreater(top, z + 0.05, (name, motions[i]["id"], p)) + def test_arc_ramps_meet_the_stock_at_the_declared_angle(self): + # A pass start under stock is entered by one smooth descent: a + # vertical plunge, an arc of the tool's radius through air above the + # stock under the tool (measured on the live stock), then moves that + # descend no steeper than the declared 3 degree ramp onto the pass, + # arriving level. Each is counted in arc_ramps. + slope = math.tan(math.radians(3)) + 1e-9 + for name in ("island", "wide"): + if name == "island": + report, motions, before, grid, _ = cached(name) + else: + report, motions, before, grid, _ = run(WIDE, radial_stock_to_leave_mm=0.1) + ramps = 0 + for i, m in enumerate(motions): + if m not in vertical_plunges([m]): + continue + j = i + 1 + air = [] + while ( + motions[j]["kind"] == "lead" + and motions[j]["curve"]["end"][2] < motions[j]["curve"]["start"][2] - 1e-9 + ): + air.append(j) + j += 1 + if not air or motions[j]["kind"] != "plunge": + continue + ramps += 1 + for k in air: + q = motions[k]["curve"]["end"] + top = stock_top_near(grid, before[k], q, R) + self.assertGreaterEqual(q[2], top - 1e-9, (name, motions[k]["id"])) + last = None + while motions[j]["kind"] == "plunge": + c = motions[j]["curve"] + a, b = c["start"], c["end"] + span = math.hypot(b[0] - a[0], b[1] - a[1]) + self.assertGreater(span, 0, (name, motions[j]["id"])) + self.assertLessEqual((a[2] - b[2]) / span, slope, (name, motions[j]["id"])) + last = c + j += 1 + self.assertEqual(motions[j]["kind"], "cut", name) + self.assertAlmostEqual(last["end"][2], motions[j]["curve"]["start"][2], delta=1e-9) + self.assertEqual(ramps, report.get("arc_ramps", 0), name) + self.assertGreater(ramps, 0, name) + if __name__ == "__main__": unittest.main() diff --git a/src/flat.rs b/src/flat.rs index aa032ec..ac9827b 100644 --- a/src/flat.rs +++ b/src/flat.rs @@ -22,6 +22,10 @@ use crate::{ }; use serde::{Deserialize, Serialize}; +/// How far behind the pass start (in cutter radii) an arc ramp may begin +/// (`FlatPlan::arc_ramp`), as far as a waterline side entry is searched. +const ARC_RAMP_REACH_RADII: f64 = 4.; + fn x_axis() -> TraverseAxis { TraverseAxis::X } @@ -181,6 +185,10 @@ pub struct FlatReport { /// the tool's radius in the vertical plane (see `FlatPlan::plunge_turn`). #[serde(skip_serializing_if = "is_zero")] pub rounded_plunges: usize, + /// Entries through stock on one smooth descent along the pass's line + /// (see `FlatPlan::arc_ramp`): counted in `ramped_entries` too. + #[serde(skip_serializing_if = "is_zero")] + pub arc_ramps: usize, pub clearance_proof: &'static str, } @@ -1645,10 +1653,17 @@ enum Entry { Side { p: [f64; 2] }, /// Vertical plunge at the pass's start. Plunge, - /// Ramp down the first pass from the stock's top over it: the zigzag's - /// curves (lines and arcs on the pass, helices where a leg descends - /// along an arc), ending at the pass's start. - Ramp { top: f64, curves: Vec }, + /// Ramp down from `top` (reached through air) to the pass's start: the + /// zigzag's curves down the first pass (lines and arcs on the pass, + /// helices where a leg descends along an arc), or an arc ramp's descent + /// along the pass's line (`FlatPlan::arc_ramp`), whose first `air` + /// moves run through air above the stock (at the cutting feed, like a + /// lead) and the rest at the ramp's feed. + Ramp { + top: f64, + curves: Vec, + air: usize, + }, /// Vertical plunge in air at `lead`'s start, then the tangent arc lead-in /// `lead` to the pass's start: flat at the pass's height (a lead at /// cutting feed) or, when the plunge point is over the level's finished @@ -1690,6 +1705,8 @@ pub struct FlatPlan { limits: Option, entry: Option, ramp: std::collections::VecDeque, + /// How many of `ramp`'s first moves run through air (`Entry::Ramp`). + ramp_air: usize, lead: Option<(Curve, bool)>, turn: std::collections::VecDeque, after_turn: Phase, @@ -2016,6 +2033,7 @@ impl FlatPlan { arc_lead_ins: 0, arc_lead_outs: 0, rounded_plunges: 0, + arc_ramps: 0, clearance_proof: "exact maximum part height under each horizontal cut's swept disk (triangle-capsule extreme points) at most the cut height plus tolerance; contour-parallel offset passes outside in, side entry in air on open edges and every vertical plunge beside the level's face (a radius outside it, the face region a superset of the flat within the shadows' stated errors), links at depth and when chains break", }; Ok(Self { @@ -2034,6 +2052,7 @@ impl FlatPlan { limits: region_limits, entry: None, ramp: Default::default(), + ramp_air: 0, lead: None, turn: Default::default(), after_turn: Phase::Cut, @@ -2431,6 +2450,166 @@ impl FlatPlan { )) } + /// A ramp into stock as one smooth descent onto the pass start `p` + /// (height `z`) along the pass's direction `d`, in the vertical plane + /// through `d`, as in established CAM practice for a plunge with an arc + /// lead-in: a vertical plunge through air, a quarter-circle-like arc of + /// the tool's radius turning it to the declared ramp angle above the + /// stock, a straight leg at that angle through the stock, and an arc of + /// the tool's radius turning it to horizontal, tangent to the pass at `p`. + /// The stock is met only on the leg and the last arc, never steeper than + /// the declared angle. Taken where a ramp is declared, live stock stands + /// above `z` under the span (at most the stock top over the whole span; + /// the upper arc ends above it), the disk over the span is clear of the + /// part at `z` (every point of the path is at or above `z`), the span lies + /// inside the limits and the plunge's bottom is below the feed height; + /// `None` otherwise (the zigzag ramp along the pass, `plunge_or_ramp`). + /// At most `ARC_RAMP_REACH_RADII` radii long (about half a millimetre of + /// stock at 3 degrees); deeper stock is ramped along the pass. Returns + /// the plunge's bottom, the descent's moves, and how many of them (the + /// upper arc) run through air. + fn arc_ramp( + &mut self, + stock: &Stock, + p: [f64; 2], + d: [f64; 2], + z: f64, + cancel: &impl CancelSignal, + ) -> Result, usize)>, String> { + let tol = self.op.tolerance_mm; + let rho = self.radius; + let Some(ramp) = self.op.entry.as_ref().and_then(|e| e.ramp()) else { + return Ok(None); + }; + let n = d[0].hypot(d[1]); + if n <= 0. { + return Ok(None); + } + let d = [d[0] / n, d[1] / n]; + let along_x = d[1].abs() <= 1e-12; + let along_y = d[0].abs() <= 1e-12; + let d = if along_x { + [d[0].signum(), 0.] + } else if along_y { + [0., d[1].signum()] + } else { + d + }; + let (sin, cos, tan) = ( + ramp.angle_rad.sin(), + ramp.angle_rad.cos(), + ramp.angle_rad.tan(), + ); + // Heights above z, distances along d (0 at p, negative behind it). + let bottom = rho * (1. - cos); + let mut stock_top = stock.top_under_disk(p, rho) - z; + if stock_top <= tol { + return Ok(None); + } + let mut shape = None; + for _ in 0..4 { + if cancel.is_cancelled() { + return Err("flat-area planning cancelled".into()); + } + // The upper arc ends a tolerance above the stock. + let h_a = (stock_top + tol).max(bottom); + let u_b = -rho * sin; + let u_a = u_b - (h_a - bottom) / tan; + let u_t = u_a - rho * (1. - sin); + let h_t = h_a + rho * cos; + let t = [p[0] + u_t * d[0], p[1] + u_t * d[1]]; + let top = segment_stock_top(stock, t, p, rho, cancel)? - z; + if top <= stock_top + 1e-9 { + shape = Some((h_a, u_b, u_a, u_t, h_t, t)); + break; + } + stock_top = top; + } + let Some((h_a, u_b, u_a, u_t, h_t, t)) = shape else { + return Ok(None); + }; + // No farther out than four radii, as far as a waterline side entry + // is searched: deeper stock is ramped along the pass instead. + if -u_t > ARC_RAMP_REACH_RADII * rho + || z + h_t > self.heights.feed + || self + .index + .max_height(t, p, rho, &mut self.seen, &mut self.stamp) + > z + tol + || !allows_segment(self.limits.as_ref(), t, p, z, tol)? + { + return Ok(None); + } + let at = |u: f64, h: f64| [p[0] + u * d[0], p[1] + u * d[1], z + h]; + let arc = |start: [f64; 3], end: [f64; 3], center: [f64; 3]| -> Vec { + if along_x || along_y { + let plane = if along_x { + crate::motion::Plane::Xz + } else { + crate::motion::Plane::Yz + }; + let [u, v, _] = plane.axes(); + let angle = |q: [f64; 3]| (q[v] - center[v]).atan2(q[u] - center[u]); + let mut sweep = angle(end) - angle(start); + if sweep > std::f64::consts::PI { + sweep -= 2. * std::f64::consts::PI; + } else if sweep < -std::f64::consts::PI { + sweep += 2. * std::f64::consts::PI; + } + return vec![Curve::Arc { + start, + end, + center, + plane, + sweep_rad: sweep, + }]; + } + // Chords at ARC_MOVE_SAGITTA, inside the circle, in (u, h). + let to_uh = |q: [f64; 3]| ((q[0] - p[0]) * d[0] + (q[1] - p[1]) * d[1], q[2] - z); + let (cu, ch) = to_uh(center); + let (su, sh) = to_uh(start); + let (eu, eh) = to_uh(end); + let a0 = (sh - ch).atan2(su - cu); + let mut sweep = (eh - ch).atan2(eu - cu) - a0; + if sweep > std::f64::consts::PI { + sweep -= 2. * std::f64::consts::PI; + } else if sweep < -std::f64::consts::PI { + sweep += 2. * std::f64::consts::PI; + } + let half = (1. - ARC_MOVE_SAGITTA / rho) + .clamp(-1., 1.) + .acos() + .max(1e-9); + let count = ((sweep.abs() / (2. * half)).ceil().max(1.) as usize).min(4096); + let point = |k: usize| { + if k == 0 { + return start; + } + if k == count { + return end; + } + let a = a0 + sweep * k as f64 / count as f64; + at(cu + rho * a.cos(), ch + rho * a.sin()) + }; + (0..count) + .map(|k| Curve::Line { + start: point(k), + end: point(k + 1), + }) + .collect() + }; + let mut curves = arc(at(u_t, h_t), at(u_a, h_a), at(u_t + rho, h_t)); + let air = curves.len(); + if u_a < u_b - 1e-9 { + curves.push(Curve::Line { + start: at(u_a, h_a), + end: at(u_b, bottom), + }); + } + curves.extend(arc(at(u_b, bottom), at(0., 0.), at(0., rho))); + Ok(Some((z + h_t, curves, air))) + } + /// Whether the disk at `p` comes down beside this chain's level's face: a /// radius (less the tolerance) outside the face region, so a vertical /// plunge at `p` never rests the disk on the flat the pass finishes. An @@ -2546,12 +2725,21 @@ impl FlatPlan { { return Ok(Entry::Plunge); } + if let Some((top, curves, air)) = self.arc_ramp(stock, [a[0], a[1]], t, z, cancel)? { + self.report.ramped_entries += 1; + self.report.arc_ramps += 1; + return Ok(Entry::Ramp { top, curves, air }); + } let piece = &self.chains[self.chain].pieces[self.piece]; match self.plunge_or_ramp(piece, stock, cancel)? { None => Ok(Entry::Plunge), Some((top, curves)) => { self.report.ramped_entries += 1; - Ok(Entry::Ramp { top, curves }) + Ok(Entry::Ramp { + top, + curves, + air: 0, + }) } } } @@ -2735,8 +2923,9 @@ impl FlatPlan { self.lead = Some((lead, helical)); ([p[0], p[1], f[2]], MoveKind::Plunge, Phase::ArcIn, None) } - Entry::Ramp { top, curves } => { + Entry::Ramp { top, curves, air } => { self.ramp = curves.into(); + self.ramp_air = air; // Down through air to the stock's top over the // pass, where the ramp's first curve begins. ( @@ -2791,6 +2980,12 @@ impl FlatPlan { }; (lead.end(), kind, Phase::Cut, Some(lead)) } + Phase::Ramp if self.ramp_air > 0 => { + // Through air above the stock: like a lead. + self.ramp_air -= 1; + let curve = self.ramp.pop_front().expect("ramp move"); + (curve.end(), MoveKind::Lead, Phase::Ramp, Some(curve)) + } Phase::Ramp => { let curve = self.ramp.pop_front().expect("ramp move"); ramp_feed = Some( From 799eca9c9eddd8c99f2e55d73c0e0df49d997c55 Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:21:04 -0700 Subject: [PATCH 23/26] Flat: arc ramps beside the pass and mid-lap (#38) --- docs/operations.md | 50 +++++----- python/tests/test_flat_offset.py | 6 ++ src/flat.rs | 158 +++++++++++++++++++++++++++++-- 3 files changed, 185 insertions(+), 29 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 450019a..cf3494b 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -1703,29 +1703,33 @@ declared ramp angle above the stock, a straight leg at that angle goes through the stock, and an arc of its radius turns it level onto the pass. The stock is never met steeper than the declared angle, and the whole descent starts at most four tool radii behind the pass start (about half a millimetre of stock at 3 -degrees). Deeper stock is ramped along the pass as follows. Where stock does -(roughing left it, or the stock was not cut there yet), the chain is entered by -a ramp, and only if the operation declares `entry=RampEntry(angle_deg, ...)`: -the tool plunges through air to the top of the live stock over the stretch of -the chain's first loop the ramp travels (the highest cell bound anywhere along -that stretch; the whole loop when the ramp has to reverse on it), then zigzags -down along that loop at no more than the declared angle (over each move's -chord, so a leg along an arc descends a little shallower) and at the entry's -`feed_mm_min` (default the plunge feed); a zigzag that has to reverse needs the -entry's `min_length_mm`. Every ramp point lies above the proven loop, so it -clears the part like the loop does; the report counts ramped chains as -`ramped_entries`. Nothing is plunged into stock on any path: a chain with stock -above it and no declared entry, a ramp that does not fit (too short a loop, an -angle too shallow for the loop, or stock above the feed height) is refused, -naming the chain, its length and the stock above it. The `flat` benchmark runs -on a blank roughed to 0.1 mm over the flats and declares a 3 degree entry. The -report gives the levels, `loops` (closed offset loops planned), `rows` (loops -cut, counting the open pieces a split loop leaves), `runs` (chains), -`links_at_depth`, cut length, `runs_completed`, `ramped_entries`, `arc_ramps` -(arc-ramp entries, also counted in `ramped_entries`), `arc_lead_ins`, -`arc_lead_outs`, `rounded_plunges`, and any length that could not be proven -clear (`dropped_length_mm`). `axis` is still accepted so old jobs load, but no -longer orders anything. +degrees). Where the stock beside a wall is too tall to ramp along the pass, the +arc ramp comes down beside the pass start on its open side instead and the tool +turns into the pass on a level arc lead-in. A closed lap with no such room at +its start is entered the same way at the middle of one of its straight sides, +and the lap starts and ends there. Deeper stock is ramped along the pass as +follows. Where stock does (roughing left it, or the stock was not cut there +yet), the chain is entered by a ramp, and only if the operation declares +`entry=RampEntry(angle_deg, ...)`: the tool plunges through air to the top of +the live stock over the stretch of the chain's first loop the ramp travels (the +highest cell bound anywhere along that stretch; the whole loop when the ramp +has to reverse on it), then zigzags down along that loop at no more than the +declared angle (over each move's chord, so a leg along an arc descends a little +shallower) and at the entry's `feed_mm_min` (default the plunge feed); a zigzag +that has to reverse needs the entry's `min_length_mm`. Every ramp point lies +above the proven loop, so it clears the part like the loop does; the report +counts ramped chains as `ramped_entries`. Nothing is plunged into stock on any +path: a chain with stock above it and no declared entry, a ramp that does not +fit (too short a loop, an angle too shallow for the loop, or stock above the +feed height) is refused, naming the chain, its length and the stock above it. +The `flat` benchmark runs on a blank roughed to 0.1 mm over the flats and +declares a 3 degree entry. The report gives the levels, `loops` (closed offset +loops planned), `rows` (loops cut, counting the open pieces a split loop +leaves), `runs` (chains), `links_at_depth`, cut length, `runs_completed`, +`ramped_entries`, `arc_ramps` (arc-ramp entries, also counted in +`ramped_entries`), `arc_lead_ins`, `arc_lead_outs`, `rounded_plunges`, and any +length that could not be proven clear (`dropped_length_mm`). `axis` is still +accepted so old jobs load, but no longer orders anything. ## Spiral, radial and project finishing: `Spiral`, `Radial`, `Project` diff --git a/python/tests/test_flat_offset.py b/python/tests/test_flat_offset.py index 833f91b..f7aa6f1 100644 --- a/python/tests/test_flat_offset.py +++ b/python/tests/test_flat_offset.py @@ -701,6 +701,12 @@ def test_arc_ramps_meet_the_stock_at_the_declared_angle(self): self.assertLessEqual((a[2] - b[2]) / span, slope, (name, motions[j]["id"])) last = c j += 1 + # A ramp started beside the pass leads into it on a flat arc. + if motions[j]["kind"] == "lead": + c = motions[j]["curve"] + self.assertAlmostEqual(c["start"][2], last["end"][2], delta=1e-9) + self.assertAlmostEqual(c["end"][2], last["end"][2], delta=1e-9) + j += 1 self.assertEqual(motions[j]["kind"], "cut", name) self.assertAlmostEqual(last["end"][2], motions[j]["curve"]["start"][2], delta=1e-9) self.assertEqual(ramps, report.get("arc_ramps", 0), name) diff --git a/src/flat.rs b/src/flat.rs index ac9827b..2cb7235 100644 --- a/src/flat.rs +++ b/src/flat.rs @@ -1658,11 +1658,15 @@ enum Entry { /// helices where a leg descends along an arc), or an arc ramp's descent /// along the pass's line (`FlatPlan::arc_ramp`), whose first `air` /// moves run through air above the stock (at the cutting feed, like a - /// lead) and the rest at the ramp's feed. + /// lead) and the rest at the ramp's feed; or an arc ramp onto the start of + /// a flat arc lead-in, `then`. Ramp { top: f64, curves: Vec, air: usize, + /// A flat arc lead-in from the descent's end to the pass's start + /// (`FlatPlan::ramped_arc_lead_in`). + then: Option, }, /// Vertical plunge in air at `lead`'s start, then the tangent arc lead-in /// `lead` to the pass's start: flat at the pass's height (a lead at @@ -2310,6 +2314,74 @@ impl FlatPlan { Ok(found) } + /// The arc lead-in to the pass starting at `v` (height `z`, unit tangent + /// `t`) entered through shallow stock: the flat quarter circle of + /// `arc_lead_in`, on a side where stock stands above the pass at its + /// start, reached by an arc ramp (`arc_ramp`) that descends along the + /// arc's tangent there (or, where the part is in the way, along the + /// pass's direction) and ends level at its start. The descent stays a + /// radius and more away from the pass, so it reads the stock beside the + /// pass rather than at the pass (next to a wall the stock grid carries + /// the wall's height in the cells beside it); the arc itself runs level + /// at the pass's height, as the passes do. `None` when neither side + /// qualifies. + fn ramped_arc_lead_in( + &mut self, + stock: &Stock, + v: [f64; 2], + t: [f64; 2], + z: f64, + cancel: &impl CancelSignal, + ) -> Result, String> { + let tol = self.op.tolerance_mm; + let rho = self.radius; + let n = t[0].hypot(t[1]); + if n <= 0. { + return Ok(None); + } + let t = [t[0] / n, t[1] / n]; + for s in [1., -1.] { + let n = [-t[1] * s, t[0] * s]; + let c = [v[0] + rho * n[0], v[1] + rho * n[1]]; + let p = [c[0] - rho * t[0], c[1] - rho * t[1]]; + if stock.top_under_disk(p, rho) <= z + tol { + continue; + } + let start = (p[1] - c[1]).atan2(p[0] - c[0]); + let sweep = s * std::f64::consts::FRAC_PI_2; + if !self.arc_clear(c, rho, start, sweep, z) { + continue; + } + let lead = Curve::Arc { + start: [p[0], p[1], z], + end: [v[0], v[1], z], + center: [c[0], c[1], z], + plane: crate::motion::Plane::Xy, + sweep_rad: sweep, + }; + if let Some(l) = &self.limits + && !l.allows_curve(&lead, true)? + { + continue; + } + // Along the arc's tangent at its start first (one smooth path); + // where the part is in the way, along the pass's direction either + // way (the descent then meets the arc at a corner, at depth, as + // passes meet at their corners). + for d in [[-n[0], -n[1]], t, [-t[0], -t[1]]] { + if let Some((top, curves, air)) = self.arc_ramp(stock, p, d, z, cancel)? { + return Ok(Some(Entry::Ramp { + top, + curves, + air, + then: Some(lead), + })); + } + } + } + Ok(None) + } + /// The arc lead-out from the pass ending at `v` (height `z`) along the /// unit tangent `t`: a quarter circle of the tool's radius, tangent to the /// pass at `v`, flat at the pass's height, on a side where the disk at its @@ -2728,7 +2800,72 @@ impl FlatPlan { if let Some((top, curves, air)) = self.arc_ramp(stock, [a[0], a[1]], t, z, cancel)? { self.report.ramped_entries += 1; self.report.arc_ramps += 1; - return Ok(Entry::Ramp { top, curves, air }); + return Ok(Entry::Ramp { + top, + curves, + air, + then: None, + }); + } + if let Some(entry) = self.ramped_arc_lead_in(stock, first, t, z, cancel)? { + self.report.ramped_entries += 1; + self.report.arc_ramps += 1; + self.report.arc_lead_ins += 1; + return Ok(entry); + } + // A closed first pass may also be entered at the middle of one of its + // straight strokes, where the arc lead-in fits there and not at its + // corner: each half of the split stroke is part of the proven + // stroke. Alone in its chain the pass starts and ends there; with a + // pass linked after it (proven from its original end), it runs from + // there to its original start and then once round in full, so it + // still ends where the link was proven (the stretch before its + // original start is cut twice). The strokes nearest the tool first, + // then the shortest such lead-up. + if closed { + let segs = self.chains[self.chain].pieces[self.piece].segs.clone(); + let linked = self.piece + 1 < self.chains[self.chain].pieces.len(); + let mut order: Vec = (0..segs.len()) + .filter(|&i| { + segs[i].arc.is_none() + && crate::profiles::stroke_length(&segs[i]) >= 4. * self.radius + }) + .collect(); + let middle = |i: usize| stroke_point(&segs[i], 0.5); + let here = [self.position[0], self.position[1]]; + if linked { + order.reverse(); + } else { + order.sort_by(|&a, &b| { + let (ma, mb) = (middle(a), middle(b)); + (ma[0] - here[0]) + .hypot(ma[1] - here[1]) + .total_cmp(&(mb[0] - here[0]).hypot(mb[1] - here[1])) + .then(a.cmp(&b)) + }); + } + for i in order { + if cancel.is_cancelled() { + return Err("flat-area planning cancelled".into()); + } + let m = middle(i); + let t = segs[i].tangent(false); + if let Some(entry) = self.ramped_arc_lead_in(stock, m, t, z, cancel)? { + let mut split = vec![sub_stroke(&segs[i], 0.5, 1.)]; + split.extend_from_slice(&segs[i + 1..]); + if linked { + split.extend_from_slice(&segs); + } else { + split.extend_from_slice(&segs[..i]); + split.push(sub_stroke(&segs[i], 0., 0.5)); + } + self.chains[self.chain].pieces[self.piece].segs = split; + self.report.ramped_entries += 1; + self.report.arc_ramps += 1; + self.report.arc_lead_ins += 1; + return Ok(entry); + } + } } let piece = &self.chains[self.chain].pieces[self.piece]; match self.plunge_or_ramp(piece, stock, cancel)? { @@ -2739,6 +2876,7 @@ impl FlatPlan { top, curves, air: 0, + then: None, }) } } @@ -2923,9 +3061,15 @@ impl FlatPlan { self.lead = Some((lead, helical)); ([p[0], p[1], f[2]], MoveKind::Plunge, Phase::ArcIn, None) } - Entry::Ramp { top, curves, air } => { + Entry::Ramp { + top, + curves, + air, + then, + } => { self.ramp = curves.into(); self.ramp_air = air; + self.lead = then.map(|lead| (lead, false)); // Down through air to the stock's top over the // pass, where the ramp's first curve begins. ( @@ -2999,10 +3143,12 @@ impl FlatPlan { ( end, MoveKind::Plunge, - if self.ramp.is_empty() { - Phase::Cut - } else { + if !self.ramp.is_empty() { Phase::Ramp + } else if self.lead.is_some() { + Phase::ArcIn + } else { + Phase::Cut }, Some(curve), ) From 8406442dacc18525e52cf49bce5cb36abc6a9efb Mon Sep 17 00:00:00 2001 From: Wookie1 <6943491+Wookie1@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:39:03 -0700 Subject: [PATCH 24/26] Bench: flat expectations for offset passes (#38) --- bench/expectations/flat.json | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/bench/expectations/flat.json b/bench/expectations/flat.json index be6f2c8..1c1bbfa 100644 --- a/bench/expectations/flat.json +++ b/bench/expectations/flat.json @@ -2,33 +2,33 @@ "name": "flat", "operations": { "flats": { - "air_cut_mm": 426.794, - "cut_mm": 964.771, - "cycle_seconds_exact_stop": 190.983, - "cycle_seconds_tangent": 190.983, - "link_mm": 0.0, - "moves": 222, - "plunges": 105, - "rapid_mm": 458.843, - "removed_mm3": 36.021, - "retracts": 39 + "air_cut_mm": 39.466, + "cut_mm": 329.128, + "cycle_seconds_exact_stop": 40.432, + "cycle_seconds_tangent": 38.895, + "link_mm": 7.789, + "moves": 197, + "plunges": 3, + "rapid_mm": 55.442, + "removed_mm3": 37.571, + "retracts": 3 } }, "toolpath": { - "cycle_seconds_exact_stop": 190.983, - "cycle_seconds_tangent": 190.983, + "cycle_seconds_exact_stop": 40.432, + "cycle_seconds_tangent": 38.895, "material": { "leftover_mm3": [ - 0.95, - 104.629 + 0.0, + 103.079 ], "overcut_mm3": [ 0.0, - 24.404 + 48.004 ] }, - "moves": 222, + "moves": 197, "post_error": null, - "posted_blocks": 245 + "posted_blocks": 224 } } From 98814e6ee996feab21bf10319a1eeb6416366eab Mon Sep 17 00:00:00 2001 From: RobitOverlord <193709524+10-X-eng@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:25:29 -0600 Subject: [PATCH 25/26] Preserve unswept flat stock and verify cutter paths along their arcs --- docs/operations.md | 3 +- python/tests/test_flat_offset.py | 79 +++++++++++++++++++++----------- src/flat.rs | 7 ++- src/planar.rs | 24 ++++++++++ tests/planar.rs | 18 ++++++++ 5 files changed, 102 insertions(+), 29 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index cf3494b..84d9451 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -1639,7 +1639,8 @@ cutter diameter. An inner pass is planned only while floor remains deeper than the passes before it reach (more than a sliver thinner than the offset kernel's stated error, which it cannot tell from a line), and it is cut only along the stretches whose disk reaches that floor, less what the passes already kept at -its depth sweep. A gap between two kept stretches is cut through when that +its depth sweep. Floor remaining between those cutter sweeps stays eligible for +subsequent passes, even where the remaining strip is narrow. A gap between two kept stretches is cut through when that takes no longer than a new entry's descent from the feed height at the plunge feed, or is at most two stepovers. Offset loops are cut as arcs (the offsets' cavalier bulges), an arc proven by its chords, each chord held to the same diff --git a/python/tests/test_flat_offset.py b/python/tests/test_flat_offset.py index f7aa6f1..1d1c240 100644 --- a/python/tests/test_flat_offset.py +++ b/python/tests/test_flat_offset.py @@ -38,6 +38,14 @@ def tool(): bosses=[(8, 4, 4, 16, 12, 7)], extent=(0, 0, 24, 16), ) +# Doubling the footprint puts short, nearly parallel chords next to each +# other on a remaining-floor boundary that also contains arcs. +STEPPED_DOUBLE = dict( + boxes=[(0, 0, 0, 48, 32, 4)], + pockets=[], + bosses=[(16, 8, 4, 32, 24, 7)], + extent=(0, 0, 48, 32), +) # A block with a pocket; in the pocket a short island and, 3 mm beside it # (narrower than the 4 mm tool), a boss standing well above the block. ISLAND = dict( @@ -198,21 +206,23 @@ def stock_top_near(grid, heights, p, radius): def points(m, n=None): c = m["curve"] a, b = c["start"], c["end"] - length = math.hypot(b[0] - a[0], b[1] - a[1]) - n = n or max(2, int(length / 0.05) + 1) - return [[a[k] + (b[k] - a[k]) * i / (n - 1) for k in range(3)] for i in range(n)] - - -def arc_points(c, step=0.05): - a, ce = c["start"], c["center"] - rho = math.hypot(a[0] - ce[0], a[1] - ce[1]) - a0 = math.atan2(a[1] - ce[1], a[0] - ce[0]) - sweep = c["sweep_rad"] - n = max(2, int(rho * abs(sweep) / step) + 1) - return [ - [ce[0] + rho * math.cos(a0 + sweep * i / (n - 1)), ce[1] + rho * math.sin(a0 + sweep * i / (n - 1)), a[2]] - for i in range(n) - ] + if c.get("kind", "line") == "line": + n = n or max(2, math.ceil(math.dist(a, b) / 0.05) + 1) + return [[a[k] + (b[k] - a[k]) * i / (n - 1) for k in range(3)] for i in range(n)] + u, v, w = {"xy": (0, 1, 2), "xz": (2, 0, 1), "yz": (1, 2, 0)}[c["plane"]] + center, sweep = c["center"], c["sweep_rad"] + radius = math.hypot(a[u] - center[u], a[v] - center[v]) + start = math.atan2(a[v] - center[v], a[u] - center[u]) + n = n or max(2, math.ceil(math.hypot(radius * sweep, b[w] - a[w]) / 0.05) + 1) + samples = [] + for i in range(n): + t = i / (n - 1) + q = list(a) + q[u] = center[u] + radius * math.cos(start + t * sweep) + q[v] = center[v] + radius * math.sin(start + t * sweep) + q[w] = a[w] + t * (b[w] - a[w]) + samples.append(q) + return samples def vertical_plunges(motions): @@ -241,6 +251,20 @@ def seg_distance(p, a, b): return math.hypot(p[0] - ax - t * vx, p[1] - ay - t * vy) +def level_distance(p, c): + a, b = c["start"], c["end"] + if c.get("kind", "line") == "line": + return seg_distance(p, a, b) + assert c["plane"] == "xy" and a[2] == b[2] + x, y = c["center"][:2] + start = math.atan2(a[1] - y, a[0] - x) + angle = math.atan2(p[1] - y, p[0] - x) + sweep = c["sweep_rad"] + if ((angle - start) * math.copysign(1, sweep)) % math.tau <= abs(sweep): + return abs(math.hypot(p[0] - x, p[1] - y) - math.hypot(a[0] - x, a[1] - y)) + return min(math.dist(p, a[:2]), math.dist(p, b[:2])) + + def rect_outline_distance(p, r): """Distance from p to the outline of rectangle r = (x0, y0, x1, y1).""" x0, y0, x1, y1 = r @@ -255,11 +279,19 @@ def rect_outline_distance(p, r): def cached(name): if name not in _cache: - _cache[name] = run({"stepped": STEPPED, "island": ISLAND}[name]) + _cache[name] = run({"stepped": STEPPED, "island": ISLAND, "double": STEPPED_DOUBLE}[name]) return _cache[name] class FlatOffsetTest(unittest.TestCase): + def test_measurement_follows_arc_and_helix_instead_of_chord(self): + c = dict(kind="arc", plane="xy", start=[2, 0, 4], end=[-2, 0, 4], center=[0, 0, 4], sweep_rad=-math.pi) + self.assertEqual(level_distance((0, 0), c), 2) + self.assertEqual(level_distance((0, -2), c), 0) + self.assertAlmostEqual(level_distance((0, 2), c), math.sqrt(8)) + h = dict(c, kind="helix", end=[-2, 0, 2]) + self.assertTrue(np.allclose(points({"curve": h}, 3)[1], [0, -2, 3])) + def test_few_entries_and_links_at_depth(self): # Entries are the vertical plunges. The stepped part needs one per # ring along an edge or wall that cannot be linked to (boss top, @@ -339,18 +371,18 @@ def test_first_ring_of_each_level_follows_its_edge(self): def test_coverage_of_every_reachable_flat_point(self): # Every flat point at least a radius (+0.01) from the part standing # above it lies under the tool's disk on some cut at its level. - for name, spec in (("stepped", STEPPED), ("island", ISLAND)): + for name, spec in (("stepped", STEPPED), ("island", ISLAND), ("double", STEPPED_DOUBLE)): _, motions, *_ = cached(name) field = Field(spec) x0, y0, x1, y1 = spec["extent"] + levels = {z: level_cuts(motions, z) for z in np.unique(field.H) if z > 0} worst = (0.0, None) for x in np.arange(x0 + 0.125, x1, 0.25): for y in np.arange(y0 + 0.125, y1, 0.25): z = float(height(spec, np.array(x), np.array(y))) if z <= 0 or field.clearance((x, y), z) < R + 0.01: continue - segs = [(m["curve"]["start"], m["curve"]["end"]) for m in level_cuts(motions, z)] - d = min((seg_distance((x, y), a, b) for a, b in segs), default=math.inf) + d = min((level_distance((x, y), m["curve"]) for m in levels[z]), default=math.inf) if d > worst[0]: worst = (d, (x, y, z)) self.assertLessEqual( @@ -459,7 +491,7 @@ def test_passes_do_not_run_over_finished_floor(self): if m["kind"] not in ("cut", "link", "lead") or abs(c["end"][2] - z) > 1e-6: continue H = np.array(snap[1::2]).reshape(ny, nx) - ps = points(m) if c.get("kind", "line") == "line" else arc_points(c) + ps = points(m) length = sum(math.dist(p[:2], q[:2]) for p, q in zip(ps, ps[1:])) live = [bool((H[(X - p[0]) ** 2 + (Y - p[1]) ** 2 < (R - 0.1) ** 2] > z + 0.02).any()) for p in ps] total += length @@ -591,12 +623,7 @@ def test_radial_stock_is_left_on_every_wall(self): for m in motions: if m["kind"] == "rapid": continue - ps = ( - arc_points(m["curve"]) - if m["curve"].get("kind") == "arc" and m["curve"].get("plane") == "xy" - else points(m, 9) - ) - for p in ps: + for p in points(m, None if m["curve"].get("kind") == "arc" else 9): c = field.clearance(p, p[2]) if c < worst[0]: worst = (c, (m["id"], m["kind"], [round(v, 4) for v in p])) diff --git a/src/flat.rs b/src/flat.rs index 2cb7235..d90b87d 100644 --- a/src/flat.rs +++ b/src/flat.rs @@ -3958,7 +3958,7 @@ fn without_slivers( /// `need` without what the disk of radius `r` sweeps along the strokes of /// `runs` (straight strokes as capsules; arcs by their chords, each capsule's /// radius reduced by the chord's sagitta so it stays inside the arc's swept -/// disk), then without slivers; `None` when nothing is left. +/// disk); `None` when nothing is left. fn subtract_swept( need: crate::planar::PreparedRegion, runs: &[Vec], @@ -4030,7 +4030,10 @@ fn subtract_swept( .into_parts() .1; } - without_slivers(need, guard) + // The remaining floor may be narrow where two sweeps nearly meet. + // Keep it for trim_ring: eroding and regrowing it here would discard + // material that neither cutter sweep covered. + Ok((!need.definition().components.is_empty()).then_some(need)) } /// Whether a loop carries no geometry the kernel vouches for: its total diff --git a/src/planar.rs b/src/planar.rs index 76efbed..92f4e3d 100644 --- a/src/planar.rs +++ b/src/planar.rs @@ -513,6 +513,11 @@ fn boundary_to_polyline( let mut intersect = None; p.visit_self_intersects_opt( &mut |i: PlineIntersect| { + if let PlineIntersect::Overlapping(hit) = &i + && adjacent_lines_only_share_vertex(&p, hit.start_index1, hit.start_index2) + { + return cavalier_contours::core::Control::Continue; + } intersect = Some(i); cavalier_contours::core::Control::Break(()) }, @@ -537,6 +542,25 @@ fn boundary_to_polyline( Ok(p) } +/// The arc backend can report overlapping adjacent short chords in a mixed +/// loop. Strictly ordered projections on either axis prove that two straight +/// segments share just the middle vertex, independently of the backend. +fn adjacent_lines_only_share_vertex(p: &Polyline, i: usize, j: usize) -> bool { + let n = p.vertex_count(); + let first = if (i + 1) % n == j { + i + } else if (j + 1) % n == i { + j + } else { + return false; + }; + let a = p.at(first); + let b = p.at((first + 1) % n); + let c = p.at((first + 2) % n); + let ordered = |a, b, c| (a < b && b < c) || (c < b && b < a); + a.bulge == 0. && b.bulge == 0. && (ordered(a.x, b.x, c.x) || ordered(a.y, b.y, c.y)) +} + fn boundary_neighbors(p: &Polyline, index: usize) -> [[f64; 3]; 4] { std::array::from_fn(|i| { let v = p.at((index + p.vertex_count() - 1 + i) % p.vertex_count()); diff --git a/tests/planar.rs b/tests/planar.rs index 96cd019..0606950 100644 --- a/tests/planar.rs +++ b/tests/planar.rs @@ -248,6 +248,24 @@ fn all_boolean_operations_match_rectangle_area_identities() { } } +#[test] +fn mixed_boundary_distinguishes_ordered_short_chords_from_backtracking() { + let mut boundary = Boundary { + vertices: vec![ + [0., 0., 0.], + [0.000002422, 0.000243125, 0.], + [-0.000002187, 0.004437265, 0.], + [-0.000002187, 2., -0.25], + [2., 2., 0.], + [2., 0., 0.], + ], + }; + prepared(&single(boundary.clone())); + // The third vertex now lies halfway back along the preceding line. + boundary.vertices[2] = [0.000001211, 0.0001215625, 0.]; + assert!(single(boundary).prepare(ConstructionOptions::default()).is_err()); +} + #[test] fn curved_siblings_cannot_hide_a_straight_loop_self_intersection() { // Nonzero signed area, so the area guard alone cannot reject this crossing. From 940656fb49e4d6b4f0fd0a2051dc54c13ba91256 Mon Sep 17 00:00:00 2001 From: RobitOverlord <193709524+10-X-eng@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:37:46 -0600 Subject: [PATCH 26/26] Subtract overlapping flat cutter sweeps in one bounded planar operation --- src/flat.rs | 41 +++++++++++++---------------------------- src/planar.rs | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 28 deletions(-) diff --git a/src/flat.rs b/src/flat.rs index d90b87d..d988b16 100644 --- a/src/flat.rs +++ b/src/flat.rs @@ -3885,7 +3885,7 @@ fn level_loops( }; for (_, need) in needs.iter_mut() { if let Some(region) = need.take() { - *need = subtract_swept(region, &swept, r, tolerance, guard)?; + *need = subtract_swept(region, &swept, r, guard, cancel)?; } } if index < outer_count { @@ -3963,13 +3963,10 @@ fn subtract_swept( need: crate::planar::PreparedRegion, runs: &[Vec], r: f64, - tolerance: f64, guard: f64, + cancel: &impl CancelSignal, ) -> Result, String> { - use crate::planar::{Boolean, Boundary, Component, ConstructionOptions, PlanarRegion}; - let options = ConstructionOptions { - tolerance_mm: tolerance, - }; + use crate::planar::{Boundary, Component}; let mut capsules: Vec = vec![]; let mut capsule = |a: [f64; 2], b: [f64; 2], radius: f64| { let d = [b[0] - a[0], b[1] - a[1]]; @@ -3991,6 +3988,9 @@ fn subtract_swept( }); }; for seg in runs.iter().flatten() { + if cancel.is_cancelled() { + return Err("flat-area planning cancelled".into()); + } match seg.arc { None => capsule(seg.a, seg.b, r), Some((c, sweep)) => { @@ -4007,29 +4007,14 @@ fn subtract_swept( } } } - let mut need = need; - // Each capsule on its own: they overlap, and the components of one - // region must not. - for c in capsules { - if need.definition().components.is_empty() { - return Ok(None); - } - let swept = PlanarRegion { - version: 1, - units: "mm".into(), - name: "flat-swept-capsule".into(), - boundary_error_mm: 0., - components: vec![c], - source: serde_json::Value::Null, - } - .prepare(options) - .map_err(|e| format!("flat-area swept region: {e}"))?; - need = need - .boolean_prepared(&swept, Boolean::Difference) - .map_err(|e| format!("flat-area swept region: {e}"))? - .into_parts() - .1; + if capsules.is_empty() { + return Ok(Some(need)); } + let need = need + .subtract_sweeps(capsules, cancel) + .map_err(|e| format!("flat-area swept region: {e}"))? + .into_parts() + .1; // The remaining floor may be narrow where two sweeps nearly meet. // Keep it for trim_ring: eroding and regrowing it here would discard // material that neither cutter sweep covered. diff --git a/src/planar.rs b/src/planar.rs index 92f4e3d..40324fe 100644 --- a/src/planar.rs +++ b/src/planar.rs @@ -962,6 +962,47 @@ impl PreparedRegion { } self.integer_boolean_prepared(other, operation, error) } + /// Subtract the union of overlapping cutter sweeps in one operation. + /// Intermediate capsule seams may touch or overlap, even though the + /// boundary of their combined sweep is unambiguous. Chording and grid + /// rounding use the same error budget as the two-region integer boolean. + pub(crate) fn subtract_sweeps( + &self, + sweeps: Vec, + cancel: &impl crate::stock::CancelSignal, + ) -> Result { + let tolerance = self.options.tolerance_mm; + let chord = tolerance / 8.; + let grid = (tolerance / 128.).max(1e-8); + let mut clipper = Clipper64::new(); + clipper.add_subject(&integer_paths(self, self.origin, grid, chord)?); + for component in sweeps { + if cancel.is_cancelled() { + return Err("sweep subtraction cancelled".into()); + } + let sweep = PlanarRegion { + version: 1, + units: "mm".into(), + name: "swept-capsule".into(), + boundary_error_mm: 0., + components: vec![component], + source: serde_json::Value::Null, + } + .prepare(self.options)?; + clipper.add_clip(&integer_paths(&sweep, self.origin, grid, chord)?); + } + let mut closed = Vec::new(); + if !clipper.execute(ClipType::Difference, FillRule::NonZero, &mut closed, None) { + return Err("integer sweep difference failed".into()); + } + self.integer_result( + closed, + "clipper2_rust_1.2.0_chorded", + self.definition.boundary_error_mm + tolerance, + chord, + grid, + ) + } fn integer_boolean_prepared( &self, other: &PreparedRegion,