diff --git a/bench/expectations/rest-pocket.json b/bench/expectations/rest-pocket.json index 300c2ae..93bdbd6 100644 --- a/bench/expectations/rest-pocket.json +++ b/bench/expectations/rest-pocket.json @@ -14,33 +14,33 @@ "retracts": 1 }, "pocket": { - "air_cut_mm": 7.999, - "cut_mm": 99.328, - "cycle_seconds_exact_stop": 16.66, - "cycle_seconds_tangent": 16.66, - "link_mm": 5.333, - "moves": 30, - "plunges": 4, - "rapid_mm": 44.26, + "air_cut_mm": 11.999, + "cut_mm": 149.991, + "cycle_seconds_exact_stop": 25.322, + "cycle_seconds_tangent": 25.322, + "link_mm": 7.999, + "moves": 45, + "plunges": 6, + "rapid_mm": 61.789, "removed_mm3": 124.0, - "retracts": 4 + "retracts": 6 }, "rest": { - "air_cut_mm": 116.994, - "cut_mm": 206.49, - "cycle_seconds_exact_stop": 26.343, - "cycle_seconds_tangent": 26.103, - "link_mm": 82.496, - "moves": 82, - "plunges": 4, - "rapid_mm": 36.804, + "air_cut_mm": 175.491, + "cut_mm": 310.735, + "cycle_seconds_exact_stop": 39.917, + "cycle_seconds_tangent": 39.557, + "link_mm": 123.743, + "moves": 123, + "plunges": 6, + "rapid_mm": 55.803, "removed_mm3": 2.0, - "retracts": 8 + "retracts": 12 } }, "toolpath": { - "cycle_seconds_exact_stop": 69.862, - "cycle_seconds_tangent": 69.622, + "cycle_seconds_exact_stop": 92.098, + "cycle_seconds_tangent": 91.738, "material": { "leftover_mm3": [ 0.0, @@ -51,8 +51,8 @@ 66.004 ] }, - "moves": 130, + "moves": 186, "post_error": null, - "posted_blocks": 169 + "posted_blocks": 225 } } diff --git a/docs/operations.md b/docs/operations.md index cf19b8d..0a748ef 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -192,8 +192,24 @@ without a word: **A top below the remaining stock** (`Pocket` and `AdaptivePocket`, issue #129). `top_z_mm` may be below the stock's original top when earlier operations removed the material: the depth (and the cutting-length check) is -then measured from `top_z_mm`. Every stock cell meeting the `region` must be at -or below it. Stock may stand higher outside the region, for example a low +then measured from `top_z_mm`, and an `AdaptivePocket` plans its first level +from it (#344), so no level is deeper than `stepdown_mm`. Every stock cell +meeting the `region` must be at or below it, within the stock model's band +of 16 x `tolerance_mm`; the run checks this against the committed stock, so a +lower top needs the stock (an `AdaptivePocket` planned without it is refused). +Where stock inside that band stands above `top_z_mm` within the cutter's reach, +the depths are measured from the highest of it instead +(`stock_top.reachable_upper_z_mm` in the report, #344): `stepdown_mm` is a +strict maximum below the stock model. The model cannot tell a faced top's +sweep error from material, so a top faced to exactly `top_z_mm` can gain a last, +nearly empty depth when the depth is a whole number of stepdowns. The floor is +checked against the authored top first. If the stock changes before the first motion and +stands higher than the top the depths were planned from, where the cutter +reaches, the run refuses. After the first motion, the next move requires the +complete preceding sweep to have been committed with the matching tool and +stock. A replacement stock may have refilled earlier levels even if its top +and generation still match; plan the operation again against that stock. +Stock may stand higher outside the region, for example a low pocket beside a tall wall, when the tool assembly clears it: - Before any motion, the neck, shank and every holder section are checked diff --git a/fixtures/posts/rust/standalone-rest.nc b/fixtures/posts/rust/standalone-rest.nc index bd2e897..072146a 100644 --- a/fixtures/posts/rust/standalone-rest.nc +++ b/fixtures/posts/rust/standalone-rest.nc @@ -65,6 +65,21 @@ G1 X12 Y10 Z3 F600 G1 X6 Y10 Z3 F600 G1 X6 Y6 Z3 F600 G0 X6 Y6 Z8 +G0 X6 Y6.667 Z8 +G1 X6 Y6.667 Z3 F150 +G1 X12 Y6.667 Z3 F600 +G1 X12 Y8 Z3 F600 +G1 X6 Y8 Z3 F600 +G1 X6 Y9.333 Z3 F600 +G1 X12 Y9.333 Z3 F600 +G0 X12 Y9.333 Z8 +G0 X6 Y6 Z8 +G1 X6 Y6 Z3 F150 +G1 X12 Y6 Z3 F600 +G1 X12 Y10 Z3 F600 +G1 X6 Y10 Z3 F600 +G1 X6 Y6 Z3 F600 +G0 X6 Y6 Z8 M9 M5 G54 @@ -155,6 +170,47 @@ G1 X5 Y11 Z3 F600 G1 X5 Y5 Z3 F600 G0 X5 Y5 Z6.5 G0 X5 Y5 Z8 +G0 X5 Y5.375 Z8 +G0 X5 Y5.375 Z6.5 +G1 X5 Y5.375 Z3 F150 +G1 X13 Y5.375 Z3 F600 +G1 X13 Y6.125 Z3 F600 +G1 X12 Y6.125 Z3 F600 +G1 X6 Y6.125 Z3 F600 +G1 X5 Y6.125 Z3 F600 +G1 X5 Y6.875 Z3 F600 +G1 X6 Y6.875 Z3 F600 +G1 X12 Y6.875 Z3 F600 +G1 X13 Y6.875 Z3 F600 +G1 X13 Y7.625 Z3 F600 +G1 X12 Y7.625 Z3 F600 +G1 X6 Y7.625 Z3 F600 +G1 X5 Y7.625 Z3 F600 +G1 X5 Y8.375 Z3 F600 +G1 X6 Y8.375 Z3 F600 +G1 X12 Y8.375 Z3 F600 +G1 X13 Y8.375 Z3 F600 +G1 X13 Y9.125 Z3 F600 +G1 X12 Y9.125 Z3 F600 +G1 X6 Y9.125 Z3 F600 +G1 X5 Y9.125 Z3 F600 +G1 X5 Y9.875 Z3 F600 +G1 X6 Y9.875 Z3 F600 +G1 X12 Y9.875 Z3 F600 +G1 X13 Y9.875 Z3 F600 +G1 X13 Y10.625 Z3 F600 +G1 X5 Y10.625 Z3 F600 +G0 X5 Y10.625 Z6.5 +G0 X5 Y10.625 Z8 +G0 X5 Y5 Z8 +G0 X5 Y5 Z6.5 +G1 X5 Y5 Z3 F150 +G1 X13 Y5 Z3 F600 +G1 X13 Y11 Z3 F600 +G1 X5 Y11 Z3 F600 +G1 X5 Y5 Z3 F600 +G0 X5 Y5 Z6.5 +G0 X5 Y5 Z8 M9 M5 G49 diff --git a/src/pocket.rs b/src/pocket.rs index 0e99679..a3bc862 100644 --- a/src/pocket.rs +++ b/src/pocket.rs @@ -580,6 +580,11 @@ pub struct StockTopReport { /// Stock cells above the top that the assembly proof examined. #[serde(skip_serializing_if = "Option::is_none")] pub assembly_checked_cells: Option, + /// Highest stock above the authored top, within the stock model's band + /// (16 x tolerance_mm), where the cutter can reach it. The depth levels + /// are placed from it, so no level cuts deeper than a stepdown (#344). + #[serde(skip_serializing_if = "Option::is_none")] + pub reachable_upper_z_mm: Option, } /// What a lower top needs to know about the operation, to judge stock left @@ -700,10 +705,21 @@ impl Outside { /// judged by the tool assembly (`Outside`). pub(crate) struct StockTop { ceiling: f64, + /// The top the depths are planned from (`planning_top`). + planned: f64, identity: u64, + tool: ToolAssembly, + pending: Option, + started: bool, outside: Outside, pub(crate) report: StockTopReport, } +struct StockTopScan { + maximum: f64, + examined: usize, + reachable: Option, + tall: Option, +} impl StockTop { pub(crate) fn prepare( stock: &Stock, @@ -719,41 +735,68 @@ impl StockTop { if !tolerance.is_finite() || !(1e-7..=0.01).contains(&tolerance) { return Err("pocket tolerance_mm must be finite in [1e-7, 0.01]".into()); } + // Checked here, against the authored top, because the depths may be + // planned from a higher one (below) that would hide it (#344). + if scope.lowest_tip_z >= top { + return Err(format!( + "operation {}: floor_z_mm plus bottom allowance (Z{}) must be below top_z_mm {top}", + scope.operation, scope.lowest_tip_z + )); + } let ceiling = top + 16. * tolerance; let mut outside = Outside::new(scope, tolerance)?; - let (maximum, examined) = Self::scan(stock, top, ceiling, &mut outside, cancel)?; - spec.max_mm[2] = top; + let scan = Self::scan(stock, top, ceiling, &outside, cancel)?; + let planned = Self::planning_top(top, scan.reachable); + spec.max_mm[2] = planned; stock.request_sweep_receipts(); - let tall = outside.highest; + outside.highest = scan.tall; Ok(( spec, Some(Self { ceiling, + planned, identity: stock.identity(), + tool: scope.tool.clone(), + pending: None, + started: false, outside, report: StockTopReport { authored_top_z_mm: top, - maximum_upper_z_mm: maximum, + maximum_upper_z_mm: scan.maximum, checked_cells: stock.cells().len(), generation: stock.generation(), - outside_upper_z_mm: tall, - assembly_checked_cells: tall.map(|_| examined), + outside_upper_z_mm: scan.tall, + assembly_checked_cells: scan.tall.map(|_| scan.examined), + reachable_upper_z_mm: scan.reachable, }, }), )) } - /// The highest stock, and how many cells above the top were examined. + /// The top the depths are planned from. Stock the top accepts within + /// the model's band may still stand above it where the cutter reaches: + /// the depths then start from the highest of it, so no depth of cut is + /// deeper than `stepdown_mm` below the stock model (#344). `stepdown_mm` + /// is a strict maximum: the model cannot tell a faced top's sweep error + /// from material, so that error is treated as material too. + fn planning_top(top: f64, reachable: Option) -> f64 { + reachable.filter(|h| *h > top).unwrap_or(top) + } + pub(crate) fn planned_top(&self) -> f64 { + self.planned + } + /// The highest stock, how many cells above the ceiling were examined, + /// and the highest stock above the top (up to the ceiling) that the + /// cutter can reach. fn scan( stock: &Stock, top: f64, ceiling: f64, - outside: &mut Outside, + o: &Outside, cancel: &impl CancelSignal, - ) -> Result<(f64, usize), String> { + ) -> Result { let mut maximum = f64::NEG_INFINITY; let [dx, dy] = stock.cell_widths_mm(); let half = dx.hypot(dy) / 2.; - let o = &*outside; let reach = o .sections .iter() @@ -762,12 +805,32 @@ impl StockTop { // Per section, the highest obstruction within its radius. let mut blocked = vec![None::; o.sections.len()]; let mut examined = 0; + let mut reachable = None; for (i, cell) in stock.cells().iter().enumerate() { if i.is_multiple_of(1024) && cancel.is_cancelled() { return Err("pocket stock-top inspection cancelled".into()); } maximum = maximum.max(cell.upper_mm); + if cell.upper_mm <= top { + continue; + } + let p = stock.cell_center(i).ok_or("stock cell outside the grid")?; + // The distance from this cell to the region's bounding box bounds + // its distance to the region from below: far cells need no query. + let b = o.region_bounds; + let far = ((b[0] - p[0]).max(p[0] - b[2]).max(0.)) + .hypot((b[1] - p[1]).max(p[1] - b[3]).max(0.)) + - half; if cell.upper_mm <= ceiling { + // A centre in the proven centre set has clearance >= r - slack, + // so its cutter cannot reach outside the region by more + // than slack (plus the numerical guard). + if far <= o.guard + o.slack + && o.upper_clearance_at(p)? + half + o.guard + o.slack >= 0. + { + reachable = + Some(reachable.map_or(cell.upper_mm, |h: f64| h.max(cell.upper_mm))); + } continue; } let refuse = || { @@ -776,14 +839,7 @@ impl StockTop { cell.upper_mm ) }; - let p = stock.cell_center(i).ok_or("stock cell outside the grid")?; examined += 1; - // The distance from this cell to the region's bounding box bounds - // its distance to the region from below: far cells need no query. - let b = o.region_bounds; - let far = ((b[0] - p[0]).max(p[0] - b[2]).max(0.)) - .hypot((b[1] - p[1]).max(p[1] - b[3]).max(0.)) - - half; if far > reach + o.guard + o.slack { continue; } @@ -844,34 +900,67 @@ impl StockTop { o.operation, o.clearance )); } - outside.highest = tall; - Ok((maximum, examined)) + Ok(StockTopScan { + maximum, + examined, + reachable, + tall, + }) } pub(crate) fn validate( &mut self, stock: &Stock, cancel: &impl CancelSignal, ) -> Result<(), String> { - if stock.identity() != self.identity { - // Native monotone commits preserve this height bound. Foreign, - // restored or undone state is assessed afresh instead of trusted. - if !stock - .last_sweep_receipt() - .is_some_and(|r| r.base_identity == self.identity) - { - let (_, _) = Self::scan( - stock, - self.report.authored_top_z_mm, - self.ceiling, - &mut self.outside, - cancel, - )?; + if let Some(pending) = &self.pending { + // Later depths and queued links depend on the *exact* preceding + // sweep. Rescanning the top cannot prove that a cleared layer + // is still clear on foreign or restored stock. + if !stock.last_sweep_receipt().is_some_and(|r| { + r.base_identity == self.identity + && r.motion.commits(pending) + && r.tool == self.tool + && r.fraction == 1. + }) { + return Err(format!( + "operation {}: commit the complete preceding motion with the matching cutter and stock before continuing; replan if the stock was replaced", + self.outside.operation + )); + } + self.pending = None; + } else if stock.identity() != self.identity { + // A preceding commit may already have been acknowledged by a + // call whose planning query was then interrupted. + if self.started { + return Err(format!( + "operation {}: the stock changed during planning; replan against the replacement stock", + self.outside.operation + )); + } + let scan = Self::scan( + stock, + self.report.authored_top_z_mm, + self.ceiling, + &self.outside, + cancel, + )?; + let needed = Self::planning_top(self.report.authored_top_z_mm, scan.reachable); + if needed > self.planned { + return Err(format!( + "operation {}: the stock changed after planning: stock up to Z{needed} where the cutter reaches stands above Z{}, the top the depths were planned from; plan the operation again against this stock", + self.outside.operation, self.planned + )); } - self.identity = stock.identity(); + self.outside.highest = scan.tall; } + self.identity = stock.identity(); stock.request_sweep_receipts(); Ok(()) } + pub(crate) fn expect_commit(&mut self, motion: &Motion) { + self.started = true; + self.pending = Some(motion.clone()); + } /// Refuse a planned motion that leaves the proven centre set below the /// remaining stock (or goes below the operation's lowest tip there). pub(crate) fn admit(&self, motion: &Motion) -> Result<(), String> { @@ -1408,6 +1497,11 @@ impl PocketPlan { }; let (envelope, bound) = StockTop::prepare(stock, op.top_z_mm, op.tolerance_mm, &scope, cancel)?; + // The depths start from the top `StockTop` planned (#344). + let mut op = op; + if let Some(b) = &bound { + op.top_z_mm = b.planned_top(); + } let mut plan = Self::prepare(op, assembly, &envelope, initial, first_motion_id, cancel)?; if let Some(bound) = bound { plan.activate_layer(initial, first_motion_id, stock.spec())?; @@ -2740,9 +2834,6 @@ impl PocketPlan { // Up to the motion before this one; the call that ends the plan // (it returns no motion) has them all. self.report.entry_proofs_unresolved = self.entry_proofs_unresolved(); - if let Some(bound) = &mut self.stock_top { - bound.validate(stock, cancel)?; - } if self.operation.rest_tolerance_mm.is_some() || self.operation.entry.is_some() || self.report.empty_cuts.is_some() @@ -2765,6 +2856,9 @@ impl PocketPlan { self.report.rest_through_generation = Some(stock.generation()); } } + if let Some(bound) = &mut self.stock_top { + bound.validate(stock, cancel)?; + } if let Some(tool) = &self.rest_tool { // Skipped pieces and queued links assume every preceding emitted // move was fully committed to this stock with this cutter. A mere @@ -2788,8 +2882,9 @@ impl PocketPlan { self.rest_stock_identity.get_or_insert(stock.identity()); } let result = self.next_with_stock(Some(stock), cancel)?; - if let (Some(bound), Some(motion)) = (&self.stock_top, &result) { + if let (Some(bound), Some(motion)) = (&mut self.stock_top, &result) { bound.admit(motion)?; + bound.expect_commit(motion); } if self.rest_tool.is_some() && let Some(motion) = &result @@ -3366,8 +3461,20 @@ mod stock_top_tests { let stock = walled(); let (spec, bound) = StockTop::prepare(&stock, 8., 1e-5, &scope, &|| false).unwrap(); assert_eq!(spec.max_mm[2], 8.); - let bound = bound.unwrap(); + let mut bound = bound.unwrap(); assert_eq!(bound.report.outside_upper_z_mm, Some(60.)); + // A pre-motion replacement with no wall, but reachable stock above + // the planning top, must not erase the original stock's wall guard. + let mut replacement = stock.snapshot(); + for cell in &mut replacement.cells { + cell.lower_mm = 8.; + cell.upper_mm = 8.; + } + replacement.cells[40 * 120 + 30].upper_mm = 8.0001; + let replacement = Stock::from_snapshot(replacement).unwrap(); + let error = bound.validate(&replacement, &|| false).unwrap_err(); + assert!(error.contains("stock changed after planning"), "{error}"); + bound.validate(&stock, &|| false).unwrap(); // Inside the centre set (3 mm in from the edge) at any planned depth. bound .admit(&motion(MoveKind::Cut, [13., 13., 4.], [19., 27., 4.])) @@ -3393,5 +3500,25 @@ mod stock_top_tests { "{error}" ); } + // The caller may be interrupted after validating a full commit, + // but before asking the bound to record the next motion. + let mut stock = stock; + let cut = motion(MoveKind::Cut, [13., 13., 4.], [19., 27., 4.]); + bound.expect_commit(&cut); + let delta = stock + .preview_sweep( + &t.prepare().unwrap(), + &cut, + 1., + crate::stock::SweepOptions::default(), + &|| false, + ) + .unwrap(); + stock.apply_delta(&delta).unwrap(); + bound.validate(&stock, &|| false).unwrap(); + let restored = Stock::from_snapshot(stock.snapshot()).unwrap(); + let error = bound.validate(&restored, &|| false).unwrap_err(); + assert!(error.contains("stock changed during planning"), "{error}"); + bound.validate(&stock, &|| false).unwrap(); } } diff --git a/src/pocket_front.rs b/src/pocket_front.rs index 9879ea3..2d9755d 100644 --- a/src/pocket_front.rs +++ b/src/pocket_front.rs @@ -52,6 +52,10 @@ pub struct PocketFrontReport { pub max_ramp_angle_deg: Option, pub geometric_residual_status: ResidualStatus, pub diagnostics: Vec, + /// A `top_z_mm` below the stock's top, proven against the committed + /// stock as for `Pocket` (`crate::pocket::StockTop`). + #[serde(skip_serializing_if = "Option::is_none")] + pub stock_top: Option, } #[derive(Clone, Debug, Serialize)] pub struct PocketFrontLayer { @@ -70,6 +74,9 @@ pub struct PocketFrontPlan { // A declined whole-operation cap cannot be salvaged by advancing a layer. corner_refusal: Option, spec: StockSpec, + /// A lower top's proof: checked before any motion, rescanned on stock + /// it did not see committed, and each motion admitted against it. + stock_top: Option, report: PocketFrontReport, } @@ -122,6 +129,16 @@ impl PocketFrontPlan { pocket.id )); } + // A top below the stock's top is only proven against committed + // stock (`prepare_with_stock`); here the stock is the whole blank, so + // its first level would cut from the blank's top, deeper than a + // stepdown (#190 follow-up). Refused, as `Pocket` refuses it. + if pocket.top_z_mm < spec.max_mm[2] { + return Err(format!( + "adaptive pocket {}: top_z_mm {} is below the stock top {}; plan it against the committed stock after the operation that removed the stock above it, or raise the operation top", + pocket.id, pocket.top_z_mm, spec.max_mm[2] + )); + } let floor = pocket.floor_z_mm + pocket.bottom_allowance_mm; if !(pocket.stepdown_mm.is_finite() && pocket.stepdown_mm > 0.) || floor >= pocket.top_z_mm { @@ -145,7 +162,7 @@ impl PocketFrontPlan { }); let climb = op.cutting_sense.unwrap_or(CuttingSense::Climb) == CuttingSense::Climb; let guard = 16. * pocket.tolerance_mm; - let levels = ((pocket.top_z_mm - floor) / pocket.stepdown_mm - 1e-9) + let levels = ((pocket.top_z_mm - floor) / pocket.stepdown_mm) .ceil() .max(1.) as usize; let mut plans = VecDeque::new(); @@ -235,6 +252,7 @@ impl PocketFrontPlan { generation: None, corner_refusal: None, spec: spec.clone(), + stock_top: None, report: PocketFrontReport { strategy: "adaptive_pocket", clearing: "engagement_front", @@ -251,6 +269,7 @@ impl PocketFrontPlan { ramp_entries: 0, max_ramp_angle_deg: None, geometric_residual_status: ResidualStatus::Pending, + stock_top: None, diagnostics: vec![ "Each depth level follows the boundary between cut and uncut stock inside the pocket region; every cutting stroke is proven within max_engagement_deg = acos(1 - stepover/r) against the committed cleared sweeps".into(), ], @@ -265,7 +284,39 @@ impl PocketFrontPlan { first_id: u64, cancel: &impl CancelSignal, ) -> Result { - Self::prepare(op, tool, stock.spec(), initial, first_id, cancel) + // A top below the stock's top is the caller's statement that + // earlier operations removed the stock above it: proven here, as + // for `Pocket` (#129), before any motion. The levels are then + // planned from that top, each at most a stepdown deep. + let pocket = &op.pocket; + let scope = crate::pocket::ReachScope { + operation: &pocket.id, + tool, + region: &pocket.region, + lowest_tip_z: pocket.floor_z_mm + pocket.bottom_allowance_mm, + clearance_z: pocket.clearance_z_mm, + boundary_slack_mm: 0., + }; + let (envelope, bound) = crate::pocket::StockTop::prepare( + stock, + pocket.top_z_mm, + pocket.tolerance_mm, + &scope, + cancel, + ) + .map_err(|e| format!("adaptive {e}"))?; + // The levels start from the top `StockTop` planned (#344). + let mut op = op; + if let Some(b) = &bound { + op.pocket.top_z_mm = b.planned_top(); + } + let mut plan = Self::prepare(op, tool, &envelope, initial, first_id, cancel)?; + plan.spec = stock.spec().clone(); + if let Some(bound) = bound { + plan.report.stock_top = Some(bound.report.clone()); + plan.stock_top = Some(bound); + } + Ok(plan) } pub fn report(&self) -> &PocketFrontReport { &self.report @@ -304,6 +355,9 @@ impl PocketFrontPlan { "commit preceding adaptive pocket motion to matching stock before planning".into(), ); } + if let Some(bound) = &mut self.stock_top { + bound.validate(stock, cancel)?; + } loop { let Some(plan) = self.plans.front_mut() else { return Ok(None); @@ -332,6 +386,10 @@ impl PocketFrontPlan { } }; if let Some(m) = motion { + if let Some(bound) = &mut self.stock_top { + bound.admit(&m)?; + bound.expect_commit(&m); + } self.report.stock_edge_entries += plan.report().stock_edge_entries - before.0; self.report.helical_entries += plan.report().helical_entries - before.1; self.report.ramp_entries += plan.report().ramp_entries - before.2; diff --git a/tests/pocket_top.rs b/tests/pocket_top.rs index f8e0fa2..4bb1dad 100644 --- a/tests/pocket_top.rs +++ b/tests/pocket_top.rs @@ -121,12 +121,21 @@ fn pocket_and_adaptive_use_faced_stock_top_without_resetting_stock_or_extra_dept .unwrap(); let report = serde_json::to_value(plan.report()).unwrap(); if top == 8. { + assert_eq!(report["stock_top"]["generation"], current.generation()); if adaptive { - // The engagement front plans each level from the - // committed stock; it has no stock-top bound to report. - assert_eq!(report["layers"].as_array().unwrap().len(), 2); + // Levels from the operation top, a stepdown apart. + let tips: Vec = report["layers"] + .as_array() + .unwrap() + .iter() + .map(|l| l["tip_z_mm"].as_f64().unwrap()) + .collect(); + // From the faced stock model, which stands up to + // 16 x tolerance above Z8 (see `faced`): stepdown_mm is + // a strict maximum below it (#344). + assert!(tips.len() == 2 && tips[1] == 5., "{tips:?}"); + assert!((6. ..=6. + 16. * 1e-5).contains(&tips[0]), "{tips:?}"); } else { - assert_eq!(report["stock_top"]["generation"], current.generation()); assert_eq!(report["depth_passes"], 2); } } @@ -145,10 +154,11 @@ fn pocket_and_adaptive_use_faced_stock_top_without_resetting_stock_or_extra_dept // fewer; the engagement front plans each level from the stock, so // its level in the air above the faced top makes no move. if adaptive { - assert_eq!( - results[1].0, results[0].0, + assert!( + results[1].0 <= results[0].0, "a move in the air depth: {} / {}", - results[1].0, results[0].0 + results[1].0, + results[0].0 ); } else { assert!( @@ -166,17 +176,25 @@ fn pocket_and_adaptive_use_faced_stock_top_without_resetting_stock_or_extra_dept #[test] fn lower_top_rejects_uncut_and_same_generation_foreign_stock_but_accepts_restored_faced_stock() { let m = fixture(); - // Pocket only: AdaptivePocket's engagement front does not check the - // stock against top_z_mm (it plans its first level from the stock top). - // The removed orbit planner did; see the #190 pull request. - let adaptive = false; - { + for adaptive in [false, true] { let original = Stock::new(m.stock.height().unwrap().clone()).unwrap(); + let error = OperationPlan::prepare_with_stock( + operation(8., adaptive), + &m.tools[0], + &original, + m.initial_position_mm, + 1, + &|| false, + ) + .err() + .unwrap(); + assert!(error.contains("raise the operation top"), "{error}"); + // Without committed stock a lower top cannot be proven. assert!( - OperationPlan::prepare_with_stock( + OperationPlan::prepare( operation(8., adaptive), &m.tools[0], - &original, + m.stock.height().unwrap(), m.initial_position_mm, 1, &|| false @@ -259,3 +277,219 @@ fn cancelled_faced_stock_inspection_does_not_change_stock() { assert_eq!(stock.generation(), before.generation); assert_eq!(stock.cells(), before.cells); } + +/// A top within the stock-model band below uncut stock is accepted as the +/// stock top, but the first level must still be at most a stepdown below the +/// stock it meets (#344 review): measured on the stock each motion removes. +#[test] +fn top_inside_the_tolerance_band_never_cuts_deeper_than_a_stepdown() { + let m = fixture(); + for adaptive in [false, true] { + let mut op = operation(9.9, adaptive); + let pocket = match &mut op { + Operation::Pocket(p) => p, + Operation::AdaptivePocket(a) => &mut a.pocket, + _ => unreachable!(), + }; + pocket.tolerance_mm = 0.01; + pocket.stepdown_mm = 1.; + pocket.floor_z_mm = 7.; + let stepdown = pocket.stepdown_mm; + let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); + let mut plan = OperationPlan::prepare_with_stock( + op, + &m.tools[0], + &stock, + m.initial_position_mm, + 1, + &|| false, + ) + .unwrap(); + let mut deepest: f64 = 0.; + while let Some(motion) = plan.next_motion_with_stock(&stock, &|| false).unwrap() { + let before: Vec = stock.cells().iter().map(|c| c.upper_mm).collect(); + commit(&mut stock, &motion, &m); + for (b, a) in before.iter().zip(stock.cells()) { + deepest = deepest.max(b - a.upper_mm); + } + } + assert!( + deepest <= stepdown + 1e-6, + "adaptive {adaptive}: one motion removed {deepest} mm of stock depth, more than the stepdown {stepdown}" + ); + } +} + +#[test] +fn adaptive_last_level_reaches_the_floor_for_a_fractional_final_step() { + let m = fixture(); + let stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); + let floor = 8. - 5e-10; + let op = band_operation(10., true, |p| p.floor_z_mm = floor); + let plan = OperationPlan::prepare_with_stock( + op, + &m.tools[0], + &stock, + m.initial_position_mm, + 1, + &|| false, + ) + .unwrap(); + let report = serde_json::to_value(plan.report()).unwrap(); + let tips: Vec<_> = report["layers"] + .as_array() + .unwrap() + .iter() + .map(|layer| layer["tip_z_mm"].as_f64().unwrap()) + .collect(); + assert_eq!(tips, [9., 8., floor]); +} + +fn band_operation(top: f64, adaptive: bool, edit: impl Fn(&mut PocketOperation)) -> Operation { + let mut op = operation(top, adaptive); + let pocket = match &mut op { + Operation::Pocket(p) => p, + Operation::AdaptivePocket(a) => &mut a.pocket, + _ => unreachable!(), + }; + pocket.tolerance_mm = 0.01; + pocket.stepdown_mm = 1.; + pocket.floor_z_mm = 7.; + edit(pocket); + op +} + +/// #344 review: the depths are planned from the stock seen at preparation. +/// Stock supplied later that stands higher within the band, where the cutter +/// reaches, would make the next cut deeper than a stepdown: refused on the +/// rescan, before any motion. +#[test] +fn a_rescan_refuses_stock_above_the_top_the_depths_were_planned_from() { + let m = fixture(); + for adaptive in [false, true] { + let blank = Stock::new(m.stock.height().unwrap().clone()).unwrap(); + let mut lower = blank.snapshot(); + for cell in &mut lower.cells { + cell.lower_mm = 9.9; + cell.upper_mm = 9.9; + } + let lower = Stock::from_snapshot(lower).unwrap(); + let mut plan = OperationPlan::prepare_with_stock( + band_operation(9.9, adaptive, |_| ()), + &m.tools[0], + &lower, + m.initial_position_mm, + 1, + &|| false, + ) + .unwrap(); + let error = plan + .next_motion_with_stock(&blank, &|| false) + .unwrap_err(); + assert!( + error.contains("stock changed after planning") && error.contains("Z10"), + "adaptive {adaptive}: {error}" + ); + } +} + +/// #344 review: a floor above the authored top is refused even where the +/// depths would be planned from higher stock. +#[test] +fn a_floor_above_the_authored_top_is_refused_on_stock_in_the_band() { + let m = fixture(); + for adaptive in [false, true] { + let blank = Stock::new(m.stock.height().unwrap().clone()).unwrap(); + let error = OperationPlan::prepare_with_stock( + band_operation(9.9, adaptive, |p| p.floor_z_mm = 9.92), + &m.tools[0], + &blank, + m.initial_position_mm, + 1, + &|| false, + ) + .err() + .unwrap(); + assert!( + error.contains("must be below top_z_mm 9.9"), + "adaptive {adaptive}: {error}" + ); + } +} + +#[test] +fn lower_top_requires_the_planned_sweep_before_advancing_to_the_next_layer() { + let m = fixture(); + for adaptive in [false, true] { + let mut stock = Stock::new(m.stock.height().unwrap().clone()).unwrap(); + let blank = stock.snapshot(); + let mut plan = OperationPlan::prepare_with_stock( + band_operation(9.9, adaptive, |_| ()), + &m.tools[0], + &stock, + m.initial_position_mm, + 1, + &|| false, + ) + .unwrap(); + // Stop during the entry into the second level, with moves still queued. + for _ in 0..1000 { + let motion = plan.next_motion_with_stock(&stock, &|| false).unwrap().unwrap(); + let z = motion.curve.end()[2]; + if z < 8.9 && motion.kind.cuts() { + let mut restored = blank.clone(); + restored.generation = stock.generation() + 1; + let foreign = Stock::from_snapshot(restored).unwrap(); + let err = plan.next_motion_with_stock(&foreign, &|| false).unwrap_err(); + assert!(err.contains("commit the complete preceding motion"), "{err}"); + + let mut partial = stock.clone(); + let delta = partial.preview_sweep( + &m.tools[0].prepare().unwrap(), &motion, 0.5, SweepOptions::default(), &|| false, + ).unwrap(); + partial.apply_delta(&delta).unwrap(); + let err = plan.next_motion_with_stock(&partial, &|| false).unwrap_err(); + assert!(err.contains("commit the complete preceding motion"), "{err}"); + + commit(&mut stock, &motion, &m); + assert!(plan.next_motion_with_stock(&stock, &|| false).unwrap().is_some()); + break; + } + commit(&mut stock, &motion, &m); + assert!(motion.id < 1000, "did not reach the second level"); + } + } +} + +#[test] +fn stock_in_the_gap_between_pockets_does_not_raise_the_planning_top() { + let m = fixture(); + let mut low = Stock::new(m.stock.height().unwrap().clone()).unwrap().snapshot(); + for cell in &mut low.cells { + cell.lower_mm = 9.9; + cell.upper_mm = 9.9; + } + let mut raised = low.clone(); + raised.cells[48 * 160 + 80].upper_mm = 10.; + let low = Stock::from_snapshot(low).unwrap(); + let raised = Stock::from_snapshot(raised).unwrap(); + let op = band_operation(9.9, true, |p| { + p.region.components[0].outer.vertices = + vec![[1., 1., 0.], [12., 1., 0.], [12., 22., 0.], [1., 22., 0.]]; + let mut second = p.region.components[0].clone(); + for vertex in &mut second.outer.vertices { + vertex[0] += 26.; + } + p.region.components.push(second); + }); + let prepare = |stock| { + OperationPlan::prepare_with_stock( + op.clone(), &m.tools[0], stock, m.initial_position_mm, 1, &|| false, + ) + .unwrap() + }; + let report = serde_json::to_value(prepare(&raised).report()).unwrap(); + assert_eq!(report["stock_top"]["maximum_upper_z_mm"], 10.); + assert!(report["stock_top"].get("reachable_upper_z_mm").is_none()); + assert!(prepare(&low).next_motion_with_stock(&raised, &|| false).unwrap().is_some()); +} diff --git a/tests/ramp_entry.rs b/tests/ramp_entry.rs index 1eb474c..ccd8579 100644 --- a/tests/ramp_entry.rs +++ b/tests/ramp_entry.rs @@ -560,7 +560,7 @@ fn pocket_ramp_on_uneven_stock_descends_straight_only_through_air() { #[test] fn pocket_ramp_below_a_lower_authored_top_starts_at_that_top() { // A wider pocket has taken the top 2 mm; the slot starts at Z8 inside - // it. The first ramp starts at Z8, in air above the earlier floor. + // it. The first ramp starts at Z8 (the stock model's floor), in air above it. let (stock, heights) = precut([[2., 8.], [30., 16.]], 8.); let mut m = pocket_manifest(SLOT, Some(PocketEntry::Ramp(zigzag(4., 2.)))); let Operation::Pocket(p) = &mut m.operations[0] else { @@ -577,7 +577,9 @@ fn pocket_ramp_below_a_lower_authored_top_starts_at_that_top() { .filter(|m| m.curve.end()[2] < m.curve.start()[2] && horizontal(&m.curve) > 0.) .map(|m| m.curve.start()[2]) .fold(f64::NEG_INFINITY, f64::max); - assert_eq!(sloped_top, 8.); + // At the earlier floor as the stock model holds it: up to its sweep + // tolerance above Z8, where the depths are planned from (#344). + assert!((8. ..=8. + 1e-4).contains(&sloped_top), "{sloped_top}"); check_slot(&seen, &stock, true, 4., None); } diff --git a/tests/supplied.rs b/tests/supplied.rs index 9356b87..c3f0579 100644 --- a/tests/supplied.rs +++ b/tests/supplied.rs @@ -155,7 +155,11 @@ fn cut_length_at(run: &Run, operation: &str, z: f64) -> f64 { .iter() .filter(|m| m.operation == operation && m.kind == MoveKind::Cut) .filter_map(|m| match m.curve { - Curve::Line { start, end } if start[2] == z && end[2] == z => { + // Within the sweep tolerance: a level planned from the faced + // stock model sits up to 1e-5 above the nominal Z (#344). + Curve::Line { start, end } + if (start[2] - z).abs() <= 1e-4 && (end[2] - z).abs() <= 1e-4 => + { Some((end[0] - start[0]).hypot(end[1] - start[1])) } _ => None, @@ -261,8 +265,9 @@ fn the_stock_a_supplied_toolpath_leaves_is_what_the_next_operation_sees() { assert!(near(upper_at(cut, 9., y), 4.), "{}", upper_at(cut, 9., y)); assert!(upper_at(cut, 6., y) < 4. && upper_at(cut, 6., y) >= 3.5); assert!(near(upper_at(cut, 20., 2.), 5.)); - // The rest pocket (floor Z 3, in 1 mm steps: levels 4 and 3) plans from - // that stock: at Z 4 it no longer cuts along the supplied slot. + // The rest pocket (floor Z 3, in 1 mm steps from the faced stock model: + // levels near 4 and 3) plans from that stock: at Z 4 it no longer cuts + // along the supplied slot. let (after_slot, from_faced) = ( cut_length_at(&with, "rest", 4.), cut_length_at(&without, "rest", 4.),