SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Fix lens-profile cuts into revolved quarter spheres (#2791)
fkirill5bed5196c735
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex daceaaf472..844db5037f 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -325,6 +325,7 @@ mod primitive_points;mod rim_cut;mod robustness;mod robustness_goldens;+mod sphere_lens;mod spiral_join;mod step_import_options;mod xz_plane;diff --git a/crates/engine/src/tests/sphere_lens.rs b/crates/engine/src/tests/sphere_lens.rsnew file mode 100644index 0000000000..de06a19a9f--- /dev/null+++ b/crates/engine/src/tests/sphere_lens.rs@@ -0,0 +1,37 @@+//! #2750: a negative extrude of the overlap between a circle and a dome outline.+use super::*;++#[test]+fn negative_lens_extrude_cuts_a_partial_sphere_and_reopens() {+ let mut s = Session::default();+ let plane = json!({"origin":[0,0,0],"x_dir":[1,0,0],"y_dir":[0,0,1]});+ run(&mut s, "sketch.create", json!({"name":"DomeProfile","plane":plane}));+ run(&mut s, "sketch.arc.three_point", json!({"start":[25,0],"through":[0,25],"end":[-25,0]}));+ run(&mut s, "sketch.line", json!({"points":[[-25,0],[25,0]]}));+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "solid.revolve", json!({"sketch":"DomeProfile","axis":"x","angle":"90 deg","body_name":"Dome"}));+ // The same outline a face-attached sketch projects, and the intersecting circle.+ run(&mut s, "sketch.create", json!({"name":"CutProfile","plane":{"origin":[0,0,0],"x_dir":[-1,0,0],"y_dir":[0,0,1]}}));+ run(&mut s, "sketch.arc.three_point", json!({"start":[25,0],"through":[0,25],"end":[-25,0]}));+ run(&mut s, "sketch.line", json!({"points":[[-25,0],[25,0]]}));+ run(&mut s, "sketch.circle.center", json!({"center":[0,20],"radius":15}));+ run(&mut s, "sketch.finish", json!({}));+ run(+ &mut s,+ "solid.extrude",+ json!({"sketch":"CutProfile","profiles":[{"point":[0,15]}],"direction":"positive","distance":"-30 mm","operation":"cut"}),+ );+ let check = |s: &mut Session| {+ assert!((volume(s) - 8810.08973246).abs() < 2.);+ let state = s.model.state();+ assert_eq!(state.bodies.len(), 1);+ let body = &state.bodies[0].body;+ assert!(body.validity().is_empty(), "{:?}", body.validity());+ assert!(solidcraft_kernel::measure(body).unwrap().bbox.max.z < 20.01, "no lid across the opening");+ assert!(body.contains(Vec3::new(0., -10., 2.)));+ assert!(!body.contains(Vec3::new(0., -10., 15.)));+ };+ check(&mut s);+ let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap());+ check(&mut reopened);+}diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rsindex 0555849959..4ea1228fba 100644--- a/crates/kernel/src/lib.rs+++ b/crates/kernel/src/lib.rs@@ -113,6 +113,7 @@ mod record;mod seam_faces;mod sew;mod smooth_edges;+mod sphere_lens;mod spline_conv;mod splitface;mod step;diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rsindex 4194412c1b..10e7fc4814 100644--- a/crates/kernel/src/ops.rs+++ b/crates/kernel/src/ops.rs@@ -1196,6 +1196,18 @@ fn boolean_whole_with_refinement(a: &Body, b: &Body, op: BoolOp, refine: bool) -return Ok(Some(body));}}+ // A lens cut from a sphere's projected outline carries a redundant cylinder+ // tangent to the sphere (#2750). Remove it only after proving that it+ // encloses the entire target, keeping the other wall and both caps exact.+ if attempt == 1 && op == BoolOp::Cut {+ let (lens, diagnostics) = capture_boolean_diagnostics(|| crate::sphere_lens::cut(a, b, &boolean_whole));+ if let Some(Ok(result)) = lens+ && result.as_ref().is_none_or(|body| check(body).0)+ {+ merge(diagnostics);+ return Ok(result);+ }+ }// A whole turn of a cylinder or cone bounded by one wire along its seam (as STEP files// write them) can't be divided by a loop lying inside it, and the tries below end in a// nudged tool, or fail: the same boolean with such faces in two halves, which is exact.diff --git a/crates/kernel/src/sphere_lens.rs b/crates/kernel/src/sphere_lens.rsnew file mode 100644index 0000000000..05eda9638e--- /dev/null+++ b/crates/kernel/src/sphere_lens.rs@@ -0,0 +1,187 @@+//! A lens extruded from a sphere's projected outline (#2750). One of its two+//! cylinders encloses the whole target and only touches the sphere. Removing that+//! redundant constraint gives the same cut without a tangent intersection.++use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3};++use crate::boolean_record as recorded;+use crate::history::Change;+use crate::{Body, BoolOp, FaceSource, FaceSurface, Result, face_surface};++/// Maximum signed height of a line or circular arc, including interior extrema.+fn height(segment: Seg2, plane: Plane, cap: Plane) -> Option<f64> {+ let at = |p| cap.height(plane.to_world(p));+ let ends = at(segment.start()).max(at(segment.end()));+ match segment {+ Seg2::Line { .. } => Some(ends),+ Seg2::Arc { center, radius, .. } => {+ let n = cap.normal();+ let direction = Vec2::new(n.dot(plane.x), n.dot(plane.y));+ let probe = center + direction.normalized().unwrap_or(Vec2::X) * radius;+ Some(ends.max(at(segment.point_at(segment.closest_param(probe)))))+ }+ _ => None,+ }+}++/// Recognize a quarter ball by its complete boundary: one spherical face, two+/// perpendicular semicircular caps sharing their diameter, each cap inside the+/// other's outward halfspace. The opposite cap orientation (three quarters of a+/// ball) is refused. Whole-span curve certificates prove the caps, not samples.+fn enclosing_ball(body: &Body, tol: f64) -> Option<(Vec3, f64, Vec<Plane>)> {+ if body.is_mesh() || body.shell_count() != 1 || body.face_count() != 3 {+ return None;+ }+ let surfaces = (0..3).map(|i| face_surface(body, i)).collect::<Option<Vec<_>>>()?;+ let (sphere, center, radius) = surfaces.iter().enumerate().find_map(|(i, surface)| match *surface {+ FaceSurface::Sphere { center, radius } => Some((i, center, radius)),+ _ => None,+ })?;+ let spherical = body.solid.face_iter().nth(sphere)?;+ if spherical.boundaries().len() != 1 || spherical.edge_iter().count() != 2 {+ return None;+ }+ let sphere_edges: std::collections::HashSet<_> = spherical.edge_iter().map(|e| e.id()).collect();+ let caps: Vec<_> = surfaces+ .iter()+ .filter_map(|surface| match *surface {+ FaceSurface::Plane { normal, point } => Plane::from_normal(point, normal),+ _ => None,+ })+ .collect();+ let (cap0, cap1) = (*caps.first()?, *caps.get(1)?);+ if caps.len() != 2 || cap0.normal().dot(cap1.normal()).abs() > 1e-9 || cap0.height(center).abs() > tol || cap1.height(center).abs() > tol {+ return None;+ }+ let mut work = 2_000_000usize;+ let mut diameters = Vec::new();+ for (i, face) in body.solid.face_iter().enumerate() {+ if i == sphere {+ continue;+ }+ let FaceSurface::Plane { normal, point } = *surfaces.get(i)? else { return None };+ let plane = Plane::from_normal(point, normal)?;+ if face.boundaries().len() != 1 || face.edge_iter().count() != 2 {+ return None;+ }+ let c = plane.to_local(center);+ let mut arc = 0.;+ let mut lines = 0;+ for edge in face.edge_iter() {+ if plane.height(crate::body::from_p3(edge.front().point())).abs() > tol+ || plane.height(crate::body::from_p3(edge.back().point())).abs() > tol+ {+ return None;+ }+ for segment in crate::prism_curve::segment(&edge, &plane, tol, &mut work)? {+ match segment {+ Seg2::Line { a, b } if (a + b - c * 2.).len() <= tol && (a.dist(c) - radius).abs() <= tol => {+ diameters.push(edge.id());+ lines += 1;+ }+ Seg2::Arc { center: q, radius: r, sweep, .. } if q.dist(c) + (r - radius).abs() <= tol && sphere_edges.contains(&edge.id()) => {+ arc += sweep.abs();+ }+ _ => return None,+ }+ if height(segment, plane, cap0)? > tol || height(segment, plane, cap1)? > tol {+ return None;+ }+ }+ }+ if lines != 1 || (arc - std::f64::consts::PI).abs() > 1e-8 {+ return None;+ }+ }+ if diameters.len() != 2 || diameters.first()? != diameters.get(1)? {+ return None;+ }+ Some((center, radius, caps))+}++/// Replace only a construction-certified, convex two-circle lens. Its cutting cylinder stays exact; a cap moves+/// only into a halfspace proved to be outside the target. The added tool material is outside the ball.+fn relaxed_tool(a: &Body, b: &Body) -> Option<Body> {+ if b.is_mesh() || b.shell_count() != 1 || b.face_count() != 4 {+ return None;+ }+ let tol = (a.size().max(b.size()) * 1e-9).max(1e-8);+ let sources = b.face_sources()?;+ let (region, plane) = sources.iter().find_map(|source| match source {+ Some(FaceSource::ExtrudeCap { high: true, region, plane }) => Some((region, *plane)),+ _ => None,+ })?;+ let bottom = sources.iter().find_map(|source| match source {+ Some(FaceSource::ExtrudeCap { high: false, region: r, plane }) if r == region => Some(*plane),+ _ => None,+ })?;+ if !region.holes.is_empty() || region.outer.segs.len() != 2 || !region.outer.is_closed(tol) {+ return None;+ }+ let circles: Vec<(Vec2, f64)> = region+ .outer+ .segs+ .iter()+ .map(|s| match *s {+ Seg2::Arc { center, radius, sweep, .. } if sweep > 0.0 && sweep <= std::f64::consts::PI + 1e-9 => Some((center, radius)),+ _ => None,+ })+ .collect::<Option<_>>()?;+ let ((c0, r0), (c1, r1)) = (*circles.first()?, *circles.get(1)?);+ let distance = c0.dist(c1);+ if distance <= (r0 - r1).abs() + tol || distance >= r0 + r1 - tol {+ return None;+ }+ let (center, radius, caps) = enclosing_ball(a, tol)?;+ let projected = plane.to_local(center);+ let redundant = circles.iter().position(|(c, r)| projected.dist(*c) + radius <= *r + tol)?;+ let (c, r) = *circles.get(1 - redundant)?;+ let height = plane.height(bottom.origin);+ if !height.is_finite() || height >= -tol || plane.normal().dot(bottom.normal()) > -1.0 + 1e-9 {+ return None;+ }+ // The proven quarter ball lies behind each cap. Extend a coincident tool+ // end outward into that empty halfspace; this avoids the generic nudge's+ // paper-thin lid across the opening, without moving the cutting cylinder.+ let on_cap = |end: Plane| caps.iter().any(|cap| cap.normal().dot(end.normal()) > 1.0 - 1e-9 && cap.height(end.origin).abs() <= tol);+ let (low, high) = (on_cap(bottom), on_cap(plane));+ if !low && !high {+ return None;+ }+ let margin = (a.size().max(b.size()) * 0.01).max(1e-5);+ let lo = height - if low { margin } else { 0. };+ let hi = if high { margin } else { 0. };+ let mut tool =+ crate::extrude(&plane, &[Region2 { outer: Loop2::circle_from(c, r, crate::build::SEAM_ANGLE), holes: vec![] }], lo, hi).ok()?.pop()?;+ // Each rebuilt surface names its original tool face. Extended portions never+ // meet the target, so every face used in the cut still lies in that input face.+ let mut faces = Vec::new();+ for i in 0..tool.face_count() {+ let surface = face_surface(&tool, i)?;+ let original = (0..b.face_count()).find(|j| match (surface, face_surface(b, *j)) {+ (FaceSurface::Plane { normal: n, .. }, Some(FaceSurface::Plane { normal: m, .. })) => n.dot(m) > 1.0 - 1e-9,+ (FaceSurface::Cylinder { origin: p, axis: n, radius: r }, Some(FaceSurface::Cylinder { origin: q, axis: m, radius: s })) => {+ n.dot(m).abs() > 1.0 - 1e-9 && (p - q).cross(n).len() + (r - s).abs() <= tol+ }+ _ => false,+ })?;+ faces.push(crate::record::from_face(0, original, Change::Modified));+ }+ let history = crate::record::from_faces(&tool.solid, 1, faces);+ tool = tool.with_checked_history(Some(history), &crate::record::counts(&[b]));+ Some(tool)+}++pub(crate) fn cut(a: &Body, b: &Body, run: &dyn Fn(&Body, &Body, BoolOp) -> Result<Option<Body>>) -> Option<Result<Option<Body>>> {+ let tool = crate::guard("sphere lens tool", || Ok(relaxed_tool(a, b))).ok()??;+ let result = run(a, &tool, BoolOp::Cut).ok()?;+ crate::boolean_guard::check_retry(a, b, BoolOp::Cut, result.as_ref()).ok()?;+ Some(Ok(result.map(|body| {+ let history = recorded::through(&body, 1, tool.history());+ body.with_checked_history(history, &crate::record::counts(&[a, b]))+ })))+}++#[cfg(test)]+#[path = "sphere_lens_tests.rs"]+mod tests;diff --git a/crates/kernel/src/sphere_lens_tests.rs b/crates/kernel/src/sphere_lens_tests.rsnew file mode 100644index 0000000000..b46be3e8f2--- /dev/null+++ b/crates/kernel/src/sphere_lens_tests.rs@@ -0,0 +1,73 @@+use super::*;+use std::f64::consts::{FRAC_PI_2, PI};++fn dome() -> Body {+ let profile = Region2 {+ outer: Loop2 {+ segs: vec![+ Seg2::Arc { center: Vec2::ZERO, radius: 25., start: 0., sweep: PI },+ Seg2::Line { a: Vec2::new(-25., 0.), b: Vec2::new(25., 0.) },+ ],+ },+ holes: vec![],+ };+ let plane = Plane { origin: Vec3::ZERO, x: Vec3::X, y: Vec3::Z };+ crate::revolve_whole(&plane, &[profile], Vec2::ZERO, Vec2::X, FRAC_PI_2).unwrap().pop().unwrap()+}++fn lens(enclosing_radius: f64) -> Region2 {+ crate::planar_regions_boolean(+ &[Region2 { outer: Loop2::circle(Vec2::ZERO, enclosing_radius), holes: vec![] }],+ &[Region2 { outer: Loop2::circle(Vec2::new(0., 20.), 15.), holes: vec![] }],+ BoolOp::Intersect,+ 1e-7,+ )+ .unwrap()+ .pop()+ .unwrap()+}++fn tool(region: Region2, depth: f64) -> Body {+ let plane = Plane { origin: Vec3::ZERO, x: Vec3::X, y: Vec3::Z };+ crate::extrude(&plane, &[region], 0., depth).unwrap().pop().unwrap()+}++#[test]+fn projected_spherical_outline_does_not_block_a_lens_cut() {+ let target = dome();+ let cutter = tool(lens(25.), 30.);+ let (result, diagnostics) = crate::capture_boolean_diagnostics(|| crate::boolean(&target, &cutter, BoolOp::Cut));+ let result = result.unwrap().unwrap();+ assert!(diagnostics.events.iter().all(|event| !event.strategy.alters_result()), "{diagnostics:?}");+ assert!(result.validity().is_empty(), "{:?}", result.validity());+ assert_eq!(result.lumps().unwrap().len(), 1);+ // Integrating the half-disc cross-section left by the offset bore gives+ // 8810.08973246 mm³ (R=25, bore radius=15, bore centre z=20).+ let measured = crate::measure(&result).unwrap();+ assert!((measured.volume - 8810.08973246).abs() < 2., "{measured:?}");+ assert!(measured.bbox.max.z < 20.01, "no thin lid may remain above the cut: {measured:?}");+ assert!(result.contains(Vec3::new(0., -10., 2.)));+ assert!(!result.contains(Vec3::new(0., -10., 15.)));+ assert_eq!(measured.merged.face_types.get("cylinder"), Some(&1));+ let history = result.history().expect("the retry composes the tool's face history");+ history.check(&result, &[&target, &cutter]).unwrap();+ assert!(history.faces.iter().all(|f| !f.origins.is_empty()));+}++#[test]+fn only_an_enclosing_wall_can_be_removed_and_cap_depth_stays_exact() {+ let target = dome();+ assert!(relaxed_tool(&target, &tool(lens(24.), 30.)).is_none(), "a cylinder inside the sphere removes real material");+ let rectangle =+ Region2 { outer: Loop2::polygon(&[Vec2::new(-4., 5.), Vec2::new(4., 5.), Vec2::new(4., 15.), Vec2::new(-4., 15.)]), holes: vec![] };+ assert!(relaxed_tool(&target, &tool(rectangle, 30.)).is_none());+ let cutter = tool(lens(25.), 7.);+ let relaxed = relaxed_tool(&target, &cutter).unwrap();+ let bounds = crate::measure(&relaxed).unwrap().bbox;+ assert!((bounds.min.y + 7.).abs() < 1e-6 && bounds.max.y > 0., "only the end outside the quarter ball is extended: {bounds:?}");+ let cut = crate::boolean(&target, &cutter, BoolOp::Cut).unwrap().unwrap();+ assert!(cut.contains(Vec3::new(0., -8., 15.)), "material past the pocket floor stays");+ assert!(!cut.contains(Vec3::new(0., -6., 15.)), "the shallow pocket removes material up to its floor");+ let box_target = crate::box_solid(Vec3::new(-25., -25., 0.), Vec3::new(25., 0., 25.)).unwrap();+ assert!(relaxed_tool(&box_target, &cutter).is_none());+}