diff --git a/crates/kernel/src/boolean_diagnostics.rs b/crates/kernel/src/boolean_diagnostics.rs index dc3e0100e..b160980fb 100644 --- a/crates/kernel/src/boolean_diagnostics.rs +++ b/crates/kernel/src/boolean_diagnostics.rs @@ -77,6 +77,11 @@ impl BooleanFallback { pub struct BooleanDiagnostics { pub events: Vec, pub truncated: bool, + /// Why candidates of the retries that led to the result were discarded before they were + /// measured (#3020: a coarse candidate whose edges run far outside the operands, which + /// meshing never finished). Left out of the report when there are none. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub rejected: Vec, } impl BooleanDiagnostics { @@ -88,6 +93,18 @@ impl BooleanDiagnostics { } } + fn push_rejected(&mut self, reason: String) { + // A candidate checked twice (picked, then taken) is noted once. + if self.rejected.contains(&reason) { + return; + } + if self.rejected.len() < MAX_EVENTS { + self.rejected.push(reason); + } else { + self.truncated = true; + } + } + /// Why the result is not verified, when it ignores a place where the bodies seem to pass /// through each other ([`BooleanStrategy::UnverifiedShortcut`]). pub fn unverified(&self) -> Option { @@ -163,10 +180,24 @@ pub(crate) fn record(event: BooleanFallback) { }); } +/// Note a candidate discarded before it was measured, and why. +pub(crate) fn reject(reason: String) { + REPORT.with(|cell| { + if let Ok(mut report) = cell.try_borrow_mut() + && let Some(report) = report.as_mut() + { + report.push_rejected(reason); + } + }); +} + pub(crate) fn merge(report: BooleanDiagnostics) { for event in report.events { record(event); } + for reason in report.rejected { + reject(reason); + } if report.truncated { REPORT.with(|cell| { if let Ok(mut report) = cell.try_borrow_mut() @@ -197,6 +228,26 @@ mod tests { assert!(capture_boolean_diagnostics(|| {}).1.events.is_empty()); } + /// Candidates discarded unmeasured (#3020) are reported with the attempt that led to the + /// result, once each, and not at all when there are none. + #[test] + fn rejected_candidates_follow_the_accepted_attempt() { + let (_, report) = capture_boolean_diagnostics(|| { + let (_, discarded) = capture_boolean_diagnostics(|| reject("from a discarded attempt".into())); + assert_eq!(discarded.rejected.len(), 1); + let (_, accepted) = capture_boolean_diagnostics(|| { + reject("runaway edge".into()); + reject("runaway edge".into()); + record(BooleanFallback::new(BooleanStrategy::ToolNudge)); + }); + merge(accepted); + }); + assert_eq!(report.rejected, vec!["runaway edge".to_string()]); + assert!(serde_json::to_string(&report).unwrap().contains("\"rejected\":[\"runaway edge\"]")); + let plain = capture_boolean_diagnostics(|| record(BooleanFallback::new(BooleanStrategy::ToolNudge))).1; + assert!(!serde_json::to_string(&plain).unwrap().contains("rejected")); + } + /// Only retries whose result can differ from the exact one make a warning; the summary /// lists every retry. #[test] diff --git a/crates/kernel/src/candidate_reach.rs b/crates/kernel/src/candidate_reach.rs new file mode 100644 index 000000000..75992c4ff --- /dev/null +++ b/crates/kernel/src/candidate_reach.rs @@ -0,0 +1,127 @@ +//! A boolean candidate whose edges run far outside its operands is discarded before it is +//! meshed (#3020). +//! +//! The retries of a boolean mesh every candidate to measure its volume. A candidate made at a +//! coarse tolerance can come out with an edge that leaves the body altogether: in the design of +//! #3020, a face of a revolved dovetail (a cone) got a trim loop several metres long on a part +//! 155 mm across, its points kilometres from the cone, and meshing that face never finished. +//! Its volume (±1e10 mm³) would have failed the check anyway; only measuring it hung. +//! +//! Every edge of a union, a cut or an intersection lies on the operands' faces, within the +//! boolean's tolerance (a small fraction of their size). So a candidate with a point of an edge +//! further outside the box the operands span than [`MARGIN`] of their size is not a result of +//! the operation, whatever its faces are, and it is discarded without meshing it. That needs no +//! search for the edge's points on its faces' surfaces, which is the very thing that runs away +//! on such a face. + +use std::collections::HashSet; + +use solidcraft_geom::{Aabb3, Mesh, Vec3}; +use truck_modeling as mt; + +use crate::body::{Body, from_p3}; + +#[cfg(test)] +#[path = "candidate_reach_tests.rs"] +mod tests; + +/// Samples along each edge, ends included: a runaway edge leaves the body over a good part of +/// its length (the loop of #3020 was thousands of times the body's size). +const EDGE_SAMPLES: u32 = 16; + +/// How far an edge of a candidate may run outside the box of the operands' meshes, as a fraction +/// of the operands' size: well above any boolean tolerance (2e-3 of the size at the coarsest) and +/// the temporary face shifts of the retries (1.4e-2 of it), well below the metres a runaway edge +/// spans. +pub(crate) const MARGIN: f64 = 0.05; + +/// Where a candidate's edges may run when the operands could not be meshed: their edges only +/// bound them loosely (a sphere's seam spans half of it), so the box of those grows by their +/// whole size. +const MARGIN_UNMESHED: f64 = 1.0; + +/// The box the operands of a boolean span, grown by the room a result's edges may take. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Reach { + bounds: Aabb3, + margin: f64, +} + +impl Reach { + /// The reach of operands `a` and `b` of size `size`, from their meshes where both were made + /// (`meshes`), else from their edges. `None` when neither gives a finite box. + pub(crate) fn new(a: &Body, b: &Body, meshes: (Option<&Mesh>, Option<&Mesh>), size: f64) -> Option { + let mut bounds = Aabb3::EMPTY; + let margin = match meshes { + (Some(ma), Some(mb)) => { + ma.positions.iter().chain(&mb.positions).for_each(|p| bounds.add(*p)); + MARGIN * size + } + _ => { + for body in [a, b] { + edge_points(body, |p| { + bounds.add(p); + true + })?; + } + MARGIN_UNMESHED * size + } + }; + (!bounds.is_empty() && margin.is_finite() && margin > 0.0).then_some(Reach { bounds, margin }) + } + + /// Why `candidate` cannot be a result of a boolean of these operands: an edge of it runs + /// further outside them than the margin, or has a point that is not finite. `None` when its + /// edges stay within reach, and when they could not be sampled (it is then meshed and + /// checked as before). + pub(crate) fn runaway(&self, candidate: &Body) -> Option { + let (lo, hi) = (self.bounds.min, self.bounds.max); + let mut worst = 0.0f64; + let mut infinite = false; + edge_points(candidate, |p| { + if !p.is_finite() { + infinite = true; + return false; + } + let outside = Vec3::new(excess(p.x, lo.x, hi.x), excess(p.y, lo.y, hi.y), excess(p.z, lo.z, hi.z)).len(); + worst = worst.max(outside); + true + })?; + if infinite { + Some("a result whose edge has points that are not finite".into()) + } else if worst > self.margin { + Some(format!("a result whose edge runs {worst:.4e} mm outside the operands (more than {:.4e} mm), not meshed to measure it", self.margin)) + } else { + None + } + } +} + +/// How far `x` lies outside `[lo, hi]`. +fn excess(x: f64, lo: f64, hi: f64) -> f64 { + (lo - x).max(x - hi).max(0.0) +} + +/// Visits [`EDGE_SAMPLES`] points along each edge of `body` (once per edge) until `visit` says +/// stop. `None` when the curves could not be evaluated. +fn edge_points(body: &Body, mut visit: impl FnMut(Vec3) -> bool) -> Option<()> { + crate::guard("candidate edges", || { + use mt::{BoundedCurve, ParametricCurve}; + let mut seen = HashSet::new(); + for edge in body.solid.edge_iter() { + if !seen.insert(edge.id()) { + continue; + } + let curve = edge.curve(); + let (t0, t1) = curve.range_tuple(); + for i in 0..=EDGE_SAMPLES { + let t = t0 + (t1 - t0) * f64::from(i) / f64::from(EDGE_SAMPLES); + if !visit(from_p3(curve.subs(t))) { + return Ok(()); + } + } + } + Ok(()) + }) + .ok() +} diff --git a/crates/kernel/src/candidate_reach_tests.rs b/crates/kernel/src/candidate_reach_tests.rs new file mode 100644 index 000000000..e237b6b6d --- /dev/null +++ b/crates/kernel/src/candidate_reach_tests.rs @@ -0,0 +1,106 @@ +//! A boolean candidate with a trim loop that runs off its surface is discarded fast (#3020). +//! +//! In the design of #3020 a coarse candidate of a nudged union came out with a face on a cone +//! (a revolved line: its profile parameter bounded to [0, 1], its angle periodic) whose trim +//! loop left the cone and ran thousands of profile lengths along its continuation, kilometres +//! from the part. Meshing that face to measure the candidate never finished. Here such a face +//! is made on purpose: the check finds its edge outside the operands without meshing it. + +use std::time::{Duration, Instant}; + +use solidcraft_geom::Vec3; +use truck_modeling::{self as mt, ParametricSurface, builder}; + +use super::{MARGIN, Reach}; +use crate::body::Body; + +/// The cone of the report: a profile line 2 mm out and 4 mm up from radius 20 mm (its length, +/// √20 mm, is the |∂S/∂u| measured on the runaway face), turned about Z. +fn cone() -> mt::Surface { + let profile = mt::Curve::Line(mt::Line(mt::Point3::new(20.0, 0.0, 0.0), mt::Point3::new(22.0, 0.0, 4.0))); + mt::Surface::RevolutedCurve(mt::Processor::new(mt::RevolutedCurve::by_revolution(profile, mt::Point3::new(0.0, 0.0, 0.0), mt::Vector3::unit_z()))) +} + +/// A solid of one face of `surface` bounded by straight edges through `corners`, given in the +/// surface's parameters and moved `off` mm off it along its normal. +fn face_body(surface: &mt::Surface, corners: &[(f64, f64, f64)]) -> Body { + use mt::ParametricSurface3D; + let vertices: Vec = corners.iter().map(|&(u, v, off)| builder::vertex(surface.subs(u, v) + surface.normal(u, v) * off)).collect(); + let edges: Vec = (0..vertices.len()).map(|i| builder::line(&vertices[i], &vertices[(i + 1) % vertices.len()])).collect(); + let face = mt::Face::new(vec![edges.into_iter().collect()], surface.clone()); + let solid = mt::Solid::new_unchecked(vec![vec![face].into()]); + Body::new(solid).unwrap() +} + +/// The operands: a plate and the cone's own patch, which spans u in [0, 1] (radius 20-22 mm, +/// 4 mm high) over a quarter turn. +fn operands() -> (Body, Body) { + let plate = crate::box_solid(Vec3::new(-30.0, -30.0, -6.0), Vec3::new(30.0, 30.0, 0.0)).unwrap(); + let patch = face_body(&cone(), &[(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.5, 0.0), (0.0, 1.5, 0.0)]); + (plate, patch) +} + +fn reach(a: &Body, b: &Body) -> Reach { + let size = a.size().max(b.size()); + let meshes = (a.tessellate_with(size * 5e-4, true).unwrap(), b.tessellate_with(size * 5e-4, true).unwrap()); + Reach::new(a, b, (Some(&meshes.0), Some(&meshes.1)), size).unwrap() +} + +/// The runaway face: on the cone, its loop leaves the patch at u = 0 and follows the cone's +/// continuation out to u = -2450 (as the logged loop did, -2452 … 1349), 1.5 mm off it, and +/// back. +fn runaway() -> Body { + face_body(&cone(), &[(1.0, 0.2, 0.0), (1.0, 1.3, 0.0), (0.0, 1.3, 0.0), (-2450.0, 0.9, 1.5), (-2450.0, 0.6, 1.5), (0.0, 0.2, 0.0)]) +} + +#[test] +fn a_candidate_with_a_trim_loop_off_its_surface_is_rejected_fast() { + let (a, b) = operands(); + let reach = reach(&a, &b); + let candidate = runaway(); + let start = Instant::now(); + let reason = reach.runaway(&candidate); + let took = start.elapsed(); + let reason = reason.expect("an edge kilometres outside the operands"); + assert!(reason.contains("outside the operands"), "{reason}"); + assert!(took < Duration::from_secs(1), "{took:?}"); +} + +#[test] +fn sound_candidates_stay_within_reach() { + let (a, b) = operands(); + let reach = reach(&a, &b); + // The operands themselves, and a union of the plate with a cylinder standing on it. + assert_eq!(reach.runaway(&a), None); + assert_eq!(reach.runaway(&b), None); + let post = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, 5.0, 20.0).unwrap(); + let reach = self::reach(&a, &post); + let union = crate::boolean(&a, &post, crate::BoolOp::Union).unwrap().unwrap(); + assert_eq!(reach.runaway(&union), None); +} + +#[test] +fn an_edge_just_past_the_margin_is_out_of_reach() { + let (a, b) = operands(); + let size = a.size().max(b.size()); + let reach = reach(&a, &b); + // A box reaching past the plate's side by twice the margin, and one within it. + let top = Vec3::new(30.0, 30.0, 0.0); + let past = crate::box_solid(Vec3::new(0.0, 0.0, -6.0), top + Vec3::X * (2.0 * MARGIN * size)).unwrap(); + let within = crate::box_solid(Vec3::new(0.0, 0.0, -6.0), top + Vec3::X * (0.5 * MARGIN * size)).unwrap(); + assert!(reach.runaway(&past).is_some()); + assert_eq!(reach.runaway(&within), None); +} + +/// The bound on a loop's span is in lengths of a bounded parameter's range: a plane's unit box +/// is only a chart, so a plate thousands of millimetres across (its loops thousands of units +/// wide) still meshes, as does a long cylinder. +#[test] +fn large_faces_still_mesh() { + let plate = crate::box_solid(Vec3::new(-2500.0, -2500.0, 0.0), Vec3::new(2500.0, 2500.0, 3.0)).unwrap(); + let rod = crate::cylinder(Vec3::ZERO, Vec3::Z, 0.5, 3000.0).unwrap(); + for body in [plate, rod] { + assert!(!body.tessellate_with(0.05, true).unwrap().triangles.is_empty()); + assert_eq!(body.unmeshed_faces(), 0); + } +} diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs index 6f852793d..b68810477 100644 --- a/crates/kernel/src/lib.rs +++ b/crates/kernel/src/lib.rs @@ -28,6 +28,7 @@ mod boundary; mod boundary_network; mod bridge; mod build; +mod candidate_reach; #[cfg(test)] mod chamfer_sides_curved_tests; mod clearance; diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index 9309b6336..3339aa851 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -7,7 +7,7 @@ use truck_modeling as mt; use std::collections::HashMap; use crate::body::{Body, Solid, from_p3}; -use crate::boolean_diagnostics::{BooleanFallback, BooleanStrategy, capture_boolean_diagnostics, merge, record}; +use crate::boolean_diagnostics::{BooleanFallback, BooleanStrategy, capture_boolean_diagnostics, merge, record, reject}; use crate::boolean_record::{self as recorded, Traced}; use crate::{KernelError, Result, guard, record}; @@ -1289,6 +1289,9 @@ where _ => (volume(a), volume(b)), }; let slack = 2e-3 * (va + vb) + 1e-9; + // Where a result's edges can run: a candidate with an edge far outside the operands is + // discarded before it is meshed (#3020), as meshing such a face may never finish. + let reach = crate::candidate_reach::Reach::new(a, b, (meshes.0.as_ref(), meshes.1.as_ref()), size); // Volume bounds, then membership against the operands (catches misclassified pieces), on // one mesh of the result. Returns (plausible, volume). // Shells that touch were never fused: coincident back-to-back faces leave the intersection @@ -1306,6 +1309,10 @@ where && crate::coplanar::faces_touch(a, b) }; let check = |r: &Body| -> (bool, f64) { + if let Some(reason) = reach.as_ref().and_then(|reach| reach.runaway(r)) { + reject(reason); + return (false, f64::NAN); + } let Ok(mr) = r.tessellate_with(tol_m, true) else { return (false, f64::NAN) }; let v = mr.measure().volume; let bounds = plausible(v, op, va, vb, slack); diff --git a/docs/robustness.md b/docs/robustness.md index 168601cea..ebb88d888 100644 --- a/docs/robustness.md +++ b/docs/robustness.md @@ -99,6 +99,11 @@ tolerances and leaves the exact result, so it is recorded but not warned about. `timeline.inspect` and `doc.inspect` expose every retry in the feature's `boolean_diagnostics`, including the strategy and the applied translation, rotation, face offset and tessellation tolerance in millimetres/radians. +Candidates those retries discarded before measuring them are listed in its +`rejected`, with the reason: a candidate with an edge further outside the +operands than 5% of their size cannot be their union, cut or intersection, +and meshing one (a trim loop running metres along a cone's continuation) +could take minutes or never finish (#3020). A common shift of both operands is reversed on the result. Coincident-face separation and bore offsets describe temporary working geometry; they are not