SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Circular pattern: cutting many copies of a hole is faster (#9007) (#9038)
kaltenbrunnermarkus232a90268054
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rsindex 5987e96517..1e1cd90d6b 100644--- a/crates/doc/src/eval.rs+++ b/crates/doc/src/eval.rs@@ -2930,13 +2930,67 @@ fn clear_tools_as_one(tools: Vec<Traced>) -> Result<Vec<Traced>> {return Ok(tools);}let bodies: Vec<Body> = tools.iter().map(|t| t.body.clone()).collect();- Ok(match kernel::union_apart(&bodies)? {+ let one = match kernel::union_apart(&bodies)? {+ Some(one) => Some(one),+ // The kernel only compares the tools' boxes, so copies of a through hole close together+ // on a circle (their boxes overlap) seem to meet (#9007). Their exact shapes may still+ // be apart.+ None if tools_clearly_apart(&bodies) => kernel::join_apart(&bodies).ok().flatten(),+ None => None,+ };+ #[cfg(test)]+ cost_tests::count(|c| c.cut_tools += one.as_ref().map_or(tools.len(), |_| 1));+ Ok(match one {// Each piece's faces keep the names of the tool it is.Some(one) => vec![Traced::step(one, &tools.iter().collect::<Vec<_>>())],None => tools,})}+/// Most pairs of tools whose boxes meet that [`tools_clearly_apart`] tests.+const MAX_CLOSE_TOOL_PAIRS: usize = 4096;++/// Whether no two of `bodies` meet or touch, decided on their exact shapes. Only pairs whose+/// exact boxes, grown by twice the bodies' tolerances (as [`kernel::apart`] grows them), meet+/// are tested, by [`apart_by_union`]. `false` whenever that cannot be shown: a mesh body, a body+/// without an exact box, too many pairs to test, a union that fails.+fn tools_clearly_apart(bodies: &[Body]) -> bool {+ if bodies.len() < 2 || bodies.len() > 10_000 || bodies.iter().any(Body::is_mesh) {+ return false;+ }+ let Some(boxes) = bodies.iter().map(more::exact_box).collect::<Option<Vec<_>>>() else { return false };+ let mut order: Vec<usize> = (0..boxes.len()).collect();+ order.sort_by(|&i, &j| boxes.get(i).map_or(0.0, |b| b.min.x).total_cmp(&boxes.get(j).map_or(0.0, |b| b.min.x)));+ let mut close = Vec::new();+ for (k, &i) in order.iter().enumerate() {+ let Some(a) = boxes.get(i) else { return false };+ for &j in order.iter().skip(k + 1) {+ let Some(b) = boxes.get(j) else { return false };+ if b.min.x > a.max.x {+ break;+ }+ if more::boxes_apart(&Some(*a), &Some(*b)) {+ continue;+ }+ if close.len() == MAX_CLOSE_TOOL_PAIRS {+ return false;+ }+ close.push((i, j));+ }+ }+ close.into_iter().all(|(i, j)| matches!((bodies.get(i), bodies.get(j)), (Some(a), Some(b)) if apart_by_union(a, b)))+}++/// Whether the exact union of `a` and `b` comes out in two pieces that share no face, edge or+/// vertex. Crossing and nested bodies come out in one piece, touching ones in one or in two that+/// share an edge or a face.+fn apart_by_union(a: &Body, b: &Body) -> bool {+ match kernel::boolean(a, b, BoolOp::Union) {+ Ok(Some(u)) => u.record().material_regions().len() == 2 && u.region_contacts().is_ok_and(|c| c.is_empty()),+ _ => false,+ }+}+/// An intersect never deletes a body by accident (#5295): it is refused when nothing of a named/// target would remain, when nothing of any target would remain, or when the tools meet a target/// and the boolean still came out empty. Only an unnamed target the tools miss altogether is@@ -6169,7 +6223,6 @@ fn path_at(segs: &[kernel::PathSeg], d: f64) -> (Vec3, Vec3) {(Vec3::ZERO, Vec3::X)}-/// Whether a copy has no material to cut in any of its eligible targets./// The bodies a hole cuts: those its feature names, else its component's and its own (as/// `apply_traced` picks a cut's targets).fn hole_targets<'a>(st: &'a ModelState, f: &Feature) -> Vec<&'a ModelBody> {@@ -6199,18 +6252,120 @@ fn hole_misses(st: &ModelState, f: &Feature, tool: &Body) -> bool {targets.iter().all(|b| more::boxes_apart(&tool_box, &b.body.exact_bounds().ok()))}-fn copy_misses(st: &ModelState, f: &Feature, targets: &[String], tools: &[Traced]) -> bool {+/// The bodies a pattern's cut copies are checked against for missing them ([`copy_misses`]).+fn miss_scope<'a>(st: &'a ModelState, f: &'a Feature, targets: &'a [String]) -> impl Iterator<Item = &'a ModelBody> + 'a {let targets = if targets.is_empty() { &f.participants } else { targets };let all = targets.len() == 1 && targets.first().is_some_and(|t| t == "*");st.bodies.iter()- .filter(|b| all || if targets.is_empty() { b.component == f.component || b.feature == f.id } else { targets.contains(&b.name) })- .all(|b| {- tools.iter().all(|t| {- // An inconclusive probe is not a miss: it must not reject an otherwise valid cut.- matches!(kernel::boolean(&b.body, &t.body, BoolOp::Intersect), Ok(None))- })+ .filter(move |b| all || if targets.is_empty() { b.component == f.component || b.feature == f.id } else { targets.contains(&b.name) })+}++/// Whether a copy has no material to cut in any of its eligible targets.+fn copy_misses(st: &ModelState, f: &Feature, targets: &[String], tools: &[Traced]) -> bool {+ miss_scope(st, f, targets).all(|b| {+ tools.iter().all(|t| {+ #[cfg(test)]+ cost_tests::count(|c| c.miss_intersects += 1);+ // An inconclusive probe is not a miss: it must not reject an otherwise valid cut.+ matches!(kernel::boolean(&b.body, &t.body, BoolOp::Intersect), Ok(None))})+ })+}++/// How many of a pattern's cut copies (`instances`, ranges of `copies`) remove no material, and+/// how many copies there are. [`copy_misses`] intersects a copy with every target, which on a+/// body with many holes costs far more than cutting the copy (#9007). A copy that a point test+/// shows takes material from a target ([`shares_material`]) is not a miss, and skips it; only+/// copies the test cannot place (in an earlier hole, on the edge, thinner than its samples) are+/// intersected.+fn count_copy_misses(+ st: &ModelState,+ f: &Feature,+ targets: &[String],+ copies: &[Traced],+ instances: &[std::ops::Range<usize>],+ axes: &[Vec<(Vec3, Vec3)>],+) -> (usize, usize) {+ let scope: Vec<&ModelBody> = miss_scope(st, f, targets).collect();+ let (mut missed, mut total) = (0, 0);+ for (k, tools) in instances.iter().enumerate().filter_map(|(k, i)| Some((k, copies.get(i.clone())?))) {+ total += 1;+ let lines = axes.get(k).map_or(&[][..], Vec::as_slice);+ let takes = tools.iter().any(|t| scope.iter().any(|b| shares_material(&b.body, &t.body, lines)));+ if !takes && copy_misses(st, f, targets, tools) {+ missed += 1;+ }+ }+ (missed, total)+}++/// Whether some point lies in the material of both B-rep bodies `target` and `tool`, by their+/// exact point classification (a point on either's boundary does not count). Tried along+/// `lines` (a hole's axis: through the wall it drills into, however thin and slanted), along the+/// axes of the tool's round faces (a cylinder's axis, the middle of a slot's ends) and along the+/// three lines parallel to the axes through the middle of the box both exact boxes hold (the+/// axis of a straight hole through a plate), within that box. `false` says nothing.+fn shares_material(target: &Body, tool: &Body, lines: &[(Vec3, Vec3)]) -> bool {+ if target.is_mesh() || tool.is_mesh() {+ return false;+ }+ let (Some(a), Some(b)) = (more::exact_box(target), more::exact_box(tool)) else { return false };+ let both = a.intersection(&b);+ if both.is_empty() {+ return false;+ }+ let c = both.center();+ let mut all = lines.to_vec();+ all.extend(round_face_axes(tool, MAX_PROBED_FACES));+ all.extend([(c, Vec3::X), (c, Vec3::Y), (c, Vec3::Z)]);+ let inside = |b: &Body, p: Vec3| matches!(b.classify_point(p), Ok(kernel::PointClass::Inside));+ all.iter().any(|&(o, d)| {+ let Some((lo, hi)) = line_in_box(&both, o, d) else { return false };+ (0..SAMPLES_PER_LINE).any(|k| {+ let p = o + d * (lo + (hi - lo) * (k as f64 + 0.5) / SAMPLES_PER_LINE as f64);+ inside(tool, p) && inside(target, p)+ })+ })+}++/// Points tried on each line by [`shares_material`].+const SAMPLES_PER_LINE: usize = 16;+/// Most faces of a tool whose surfaces [`shares_material`] looks along.+const MAX_PROBED_FACES: usize = 32;++/// The axes of the round faces among the first `max` faces of `body`, from their exact surfaces:+/// a cylinder's, a cone's and a torus's axis, and the lines along X, Y and Z through a sphere's+/// centre.+fn round_face_axes(body: &Body, max: usize) -> Vec<(Vec3, Vec3)> {+ let mut lines = Vec::new();+ for face in 0..body.face_count().min(max) {+ match kernel::face_surface(body, face) {+ Some(kernel::FaceSurface::Cylinder { origin, axis, .. }) => lines.push((origin, Vec3::from(axis))),+ Some(kernel::FaceSurface::Cone { apex, axis, .. }) => lines.push((apex, Vec3::from(axis))),+ Some(kernel::FaceSurface::Torus { center, axis, .. }) => lines.push((center, Vec3::from(axis))),+ Some(kernel::FaceSurface::Sphere { center, .. }) => lines.extend([(center, Vec3::X), (center, Vec3::Y), (center, Vec3::Z)]),+ Some(kernel::FaceSurface::Plane { .. }) | None => {}+ }+ }+ lines+}++/// The stretch of the line `o + t d` inside `b`, as the range of `t`; `None` when it misses.+fn line_in_box(b: &solidcraft_geom::Aabb3, o: Vec3, d: Vec3) -> Option<(f64, f64)> {+ let (mut lo, mut hi) = (f64::NEG_INFINITY, f64::INFINITY);+ for (o, d, min, max) in [(o.x, d.x, b.min.x, b.max.x), (o.y, d.y, b.min.y, b.max.y), (o.z, d.z, b.min.z, b.max.z)] {+ if d.abs() < 1e-12 {+ if o < min || o > max {+ return None;+ }+ } else {+ let (a, c) = ((min - o) / d, (max - o) / d);+ lo = lo.max(a.min(c));+ hi = hi.min(a.max(c));+ }+ }+ (lo.is_finite() && hi.is_finite() && lo <= hi).then_some((lo, hi))}/// The deepest a pattern or mirror reaches through patterns and mirrors of features (#395).@@ -6452,6 +6607,9 @@ fn replay(let targets = if present.is_empty() { targets } else { present };let mut copies = Vec::new();let mut instances = Vec::with_capacity(mats.len());+ // Each hole copy's axes (spot and direction), where the check for copies that miss looks+ // for material first.+ let mut axes: Vec<Vec<(Vec3, Vec3)>> = Vec::new();if let FeatureKind::Hole { diameter, depth, hole, to, .. } = &src.kind {// A hole is drilled again at each copy of its spot (found on the surface there), so// a blind hole's depth counts from the face at the copy, not from the bottom of the@@ -6460,8 +6618,10 @@ fn replay(for (k, m) in mats.iter().enumerate() {let d = crate::apply_vector(m, dir).normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?;let start = copies.len();+ let mut on = Vec::with_capacity(spots.len());for p in &spots {let at = hole_on_surface(st, crate::apply_point(m, *p), d, hole_scope(src));+ on.push((at, d));let to = to.map(|t| crate::apply_point(m, t.0));let depth = hole_depth_to(st, &at, d, &to, depth)?;// Each copy's faces are named as the hole's, with the instance.@@ -6472,6 +6632,7 @@ fn replay();}instances.push(start..copies.len());+ axes.push(on);}} else if let FeatureKind::Rib { .. } = &src.kind {// A rib is built again at each copy of its sketch, against the bodies there (#4593):@@ -6498,12 +6659,9 @@ fn replay(}}if op == Operation::Cut {- for instance in &instances {- if let Some(tools) = copies.get(instance.clone()) {- total += 1;- missed += usize::from(copy_misses(st, f, &targets, tools));- }- }+ let (m, t) = count_copy_misses(st, f, &targets, &copies, &instances, &axes);+ missed += m;+ total += t;}// Copies of a cut through sheet metal are cut-outs of its flat pattern, as the cut is// (#6841): each machined into the sheets in turn, then cut from the other targets.diff --git a/crates/doc/src/eval_cost_tests.rs b/crates/doc/src/eval_cost_tests.rsindex 5e2d62f755..30996921ac 100644--- a/crates/doc/src/eval_cost_tests.rs+++ b/crates/doc/src/eval_cost_tests.rs@@ -18,8 +18,10 @@ use crate::*;/// Work counted on this thread: bodies moved, STEP texts digested, joint faces and bodies/// measured, bodies searched for by name, features searched for by id, bodies a cut (or-/// intersect) ran its booleans on, bodies searched for the cylinder a tap marking lies on, and-/// bodies whose faces a tapped hole read for its wall.+/// intersect) ran its booleans on, bodies searched for the cylinder a tap marking lies on,+/// bodies whose faces a tapped hole read for its wall, intersects run to find a pattern's copies+/// that cut nothing, and the tools a cut of many tools is made with (one when they are cut in one+/// go).#[derive(Clone, Copy, Debug, Default, PartialEq)]pub(super) struct Counts {pub moved: usize,@@ -31,6 +33,8 @@ pub(super) struct Counts {pub cut: usize,pub cylinder_search: usize,pub tapped_wall: usize,+ pub miss_intersects: usize,+ pub cut_tools: usize,}thread_local! {@@ -45,6 +49,8 @@ thread_local! {cut: 0,cylinder_search: 0,tapped_wall: 0,+ miss_intersects: 0,+ cut_tools: 0,})};}@@ -1484,3 +1490,150 @@ fn a_hole_into_a_rim_still_bores_its_sheet_beside_far_ones() {let bore = std::f64::consts::PI * (d / 2.0).powi(2) * 60.0;assert!((removed - bore).abs() < 0.02 * bore, "removed {removed} of {bore}");}++/// A 1.5 mm disc of 50 mm radius with a 3.5 mm through hole at `radius` on X, patterned `count`+/// times around Z (#9007). The pattern's id.+fn disc_with_hole_pattern(doc: &mut Document, radius: f64, count: usize) -> u64 {+ let disc = FeatureKind::Cylinder {+ base: point_expr(Vec3::ZERO),+ axis: Dir(Vec3::Z),+ radius: "50".into(),+ height: "1.5".into(),+ operation: Operation::NewBody,+ references: Vec::new(),+ };+ doc.add_feature(disc, Some("Disc")).unwrap();+ let hole: FeatureKind = serde_json::from_value(serde_json::json!({+ "type": "hole", "position": [radius, 0, 1.5], "direction": [0, 0, -1], "diameter": "3.5",+ }))+ .unwrap();+ let hole = doc.add_feature(hole, Some("Hole")).unwrap();+ hole_pattern(doc, hole, count)+}++fn hole_pattern(doc: &mut Document, hole: u64, count: usize) -> u64 {+ let pattern: FeatureKind = serde_json::from_value(serde_json::json!({+ "type": "pattern", "features": [hole],+ "pattern": {"type": "circular", "origin": [0, 0, 0], "axis": [0, 0, 1], "count": count.to_string(), "angle": "360 deg"},+ }))+ .unwrap();+ doc.add_feature(pattern, None).unwrap()+}++fn disc_volume(model: &Model) -> f64 {+ let st = model.state();+ assert_eq!(st.bodies.len(), 1);+ kernel::measure(&st.bodies[0].body).unwrap().volume+}++#[test]+fn a_circular_pattern_of_a_through_hole_cuts_its_copies_at_once() {+ // The copies' tools run twice the disc's size along Z, so the kernel's box test, which+ // grows each box by a share of the tool's size, finds them meeting (#9007); they are still+ // 4.3 mm apart, centre to centre, and are cut in one go. No copy is intersected with the+ // disc to see whether it takes material: each passes through the disc's material.+ let mut doc = Document::new("sieve");+ let pattern = disc_with_hole_pattern(&mut doc, 20.0, 29);+ let mut model = Model::new();+ let work = counted(|| model.evaluate(&doc));+ assert!(model.results.iter().all(|r| r.error.is_none() && r.warning.is_none()), "{:?}", model.results);+ assert_eq!((work.cut_tools, work.miss_intersects), (1, 0), "{work:?}");+ let hole = std::f64::consts::PI * 1.75 * 1.75 * 1.5;+ let disc = std::f64::consts::PI * 2500.0 * 1.5;+ let v = disc_volume(&model);+ assert!((v - (disc - 29.0 * hole)).abs() < 1e-3 * hole, "{v}");+ // The same copies again, landing in the holes cut already: each is intersected, and each+ // still counts as a copy that removes no material.+ let hole_id = doc.features.iter().find(|f| f.name == "Hole").unwrap().id;+ hole_pattern(&mut doc, hole_id, 29);+ let work = counted(|| model.evaluate(&doc));+ let again = model.results.last().unwrap();+ assert!(again.error.is_none(), "{again:?}");+ // (The kernel may add a note on a retry of a boolean on faces that lie on each other.)+ assert!(again.warning.as_deref().is_some_and(|w| w.starts_with("28 of 28 cut copies remove no material")), "{again:?}");+ assert_eq!(work.miss_intersects, 28, "{work:?}");+ assert!((disc_volume(&model) - v).abs() < 1e-3 * hole);+ assert!(model.results.iter().any(|r| r.id == pattern && r.warning.is_none()));+}++#[test]+fn copies_of_a_hole_that_come_close_are_cut_one_by_one() {+ // At 8.5 mm radius, 16 copies of a 3.5 mm hole overlap their neighbours: they are not apart,+ // and each is cut on its own, as before.+ let mut doc = Document::new("crowded");+ disc_with_hole_pattern(&mut doc, 8.5, 16);+ let mut model = Model::new();+ let work = counted(|| model.evaluate(&doc));+ assert!(model.results.iter().all(|r| r.error.is_none() && r.warning.is_none()), "{:?}", model.results);+ assert_eq!((work.cut_tools, work.miss_intersects), (15, 0), "{work:?}");+ // At 9 mm they come within 0.012 mm of each other without touching: their exact shapes are+ // apart, so they are cut in one go, and all 16 holes are cut.+ let mut doc = Document::new("close");+ disc_with_hole_pattern(&mut doc, 9.0, 16);+ let mut model = Model::new();+ let work = counted(|| model.evaluate(&doc));+ assert!(model.results.iter().all(|r| r.error.is_none() && r.warning.is_none()), "{:?}", model.results);+ assert_eq!((work.cut_tools, work.miss_intersects), (1, 0), "{work:?}");+ let hole = std::f64::consts::PI * 1.75 * 1.75 * 1.5;+ let disc = std::f64::consts::PI * 2500.0 * 1.5;+ let v = disc_volume(&model);+ assert!((v - (disc - 16.0 * hole)).abs() < 1e-3 * hole, "{v}");+}++/// A ring (25 mm outside, 16 mm bore, 55 mm high) with a blind groove, 8 mm wide and 30 mm deep,+/// cut into its bore from below, in a circular pattern of ten about Z: their boxes, grown as the+/// kernel grows them, meet, their exact shapes are 1.9 mm apart. The ring's faces counted as its+/// surfaces are, and the work.+fn grooved_ring_faces() -> (usize, Counts) {+ let mut doc = Document::new("grooves");+ let cylinder = |base: Vec3, radius: &str, height: &str, operation: Operation| FeatureKind::Cylinder {+ base: point_expr(base),+ axis: Dir(Vec3::Z),+ radius: radius.into(),+ height: height.into(),+ operation,+ references: Vec::new(),+ };+ doc.add_feature(cylinder(Vec3::ZERO, "25", "55", Operation::NewBody), Some("Ring")).unwrap();+ doc.add_feature(cylinder(Vec3::new(0.0, 0.0, -1.0), "16", "57", Operation::Cut), Some("Bore")).unwrap();+ let groove = doc.add_feature(cylinder(Vec3::new(16.0, 0.0, -1.0), "4", "31", Operation::Cut), Some("Groove")).unwrap();+ hole_pattern(&mut doc, groove, 10);+ let mut model = Model::new();+ let work = counted(|| model.evaluate(&doc));+ assert!(model.results.iter().all(|r| r.error.is_none() && r.warning.is_none()), "{:?}", model.results);+ let st = model.state();+ assert_eq!(st.bodies.len(), 1);+ (kernel::measure(&st.bodies[0].body).unwrap().merged.faces, work)+}++#[test]+fn copies_that_notch_the_same_round_face_cut_at_once_leave_the_faces_of_one_by_one() {+ // The ten grooves notch the same round bore. Cut all in one go, they leave it in as many+ // faces as cutting them one after another does (#9007).+ let (patterned, work) = grooved_ring_faces();+ let cut = |a: kernel::Body, b: &kernel::Body| kernel::boolean(&a, b, kernel::BoolOp::Cut).unwrap().unwrap();+ let ring =+ cut(kernel::cylinder(Vec3::ZERO, Vec3::Z, 25.0, 55.0).unwrap(), &kernel::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, 16.0, 57.0).unwrap());+ let groove = kernel::cylinder(Vec3::new(16.0, 0.0, -1.0), Vec3::Z, 4.0, 31.0).unwrap();+ let one_by_one = (0..10).fold(ring, |ring, k| {+ let copy = kernel::transform(&groove, Vec3::ZERO, Vec3::ZERO, Vec3::Z, (36.0 * k as f64).to_radians()).unwrap();+ cut(ring, ©)+ });+ assert_eq!(patterned, kernel::measure(&one_by_one).unwrap().merged.faces);+ assert_eq!(work.cut_tools, 1, "{work:?}");+}++#[test]+fn tools_are_apart_only_when_they_neither_meet_nor_nest() {+ let rod = |x: f64, y: f64, r: f64| kernel::cylinder(Vec3::new(x, y, -100.0), Vec3::Z, r, 200.0).unwrap();+ // Long rods whose boxes, grown as the kernel grows them, meet: 0.5 mm apart.+ assert!(super::tools_clearly_apart(&[rod(0.0, 0.0, 1.0), rod(2.5, 0.0, 1.0)]));+ // Touching, crossing and nested rods are not apart.+ assert!(!super::tools_clearly_apart(&[rod(0.0, 0.0, 1.0), rod(2.0, 0.0, 1.0)]));+ assert!(!super::tools_clearly_apart(&[rod(0.0, 0.0, 1.0), rod(1.5, 0.0, 1.0)]));+ assert!(!super::tools_clearly_apart(&[rod(0.0, 0.0, 3.0), rod(0.5, 0.0, 1.0)]));+ let tube = kernel::boolean(&rod(0.0, 0.0, 5.0), &rod(0.0, 0.0, 4.0), kernel::BoolOp::Cut).unwrap().unwrap();+ assert!(!super::tools_clearly_apart(&[tube.clone(), rod(0.0, 0.0, 4.5)]));+ // A rod in the tube's bore, clear of its wall, is apart from it.+ assert!(super::tools_clearly_apart(&[tube, rod(0.0, 0.0, 3.0)]));+}