SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Wave 336/509: kernel: two planar supports are one when SMLib would call them coincident (and 3 more)
jyvikoae5294529824
diff --git a/crates/engine/src/cmd/sketch_project.rs b/crates/engine/src/cmd/sketch_project.rsindex c0e16df1f8..feaebfeccf 100644--- a/crates/engine/src/cmd/sketch_project.rs+++ b/crates/engine/src/cmd/sketch_project.rs@@ -270,6 +270,9 @@ fn add_link_unless_present(// The link is the edge that was picked, not whichever is nearest the picked point later.let edge_name = solidcraft_doc::project::resolved_edge_name(&st, &r);let link = sk.add_link_with_wires(kind, r.source, &r.geom, &r.wires)?;+ // The wires' exact curves, as a refresh of the link gives them (an included edge's record+ // curve): a link made now is the one its sketch would resolve.+ sk.set_link_wire_curves(&link, &r.exact)?;if let Some(l) = sk.links.iter_mut().find(|l| l.id == link) {l.face_name = name;l.edge_name = edge_name;diff --git a/crates/engine/src/cmd/sketch_project_tests.rs b/crates/engine/src/cmd/sketch_project_tests.rsindex 0f5a9e451e..0ba5016f79 100644--- a/crates/engine/src/cmd/sketch_project_tests.rs+++ b/crates/engine/src/cmd/sketch_project_tests.rs@@ -452,10 +452,11 @@ fn tilted_circles_project_to_exact_ellipses_and_splines_stay_splines() {run(&mut s, "sketch.create", json!({"plane": "XY", "offset": -10}));// The base circle (centred at the origin) seen from above.let r = run(&mut s, "sketch.project", json!({"refs": [{"edge": [0, 5, 0]}]}));- // One seam half: exact conics (rational quadratic arcs).+ // The rim is one closed circle edge: an exact ellipse, x semi-axis 5·cos 45° (the tilt), y 5.let si = inspect(&mut s);let c = si["curves"].as_array().unwrap().iter().find(|c| c["id"] == r["links"][0]["curves"][0]).unwrap().clone();- assert_eq!(c["type"], "conic", "{c}");+ assert_eq!(c["type"], "ellipse", "{c}");+ assert!((c["minor_radius"].as_f64().unwrap() - 5.0 * std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-9, "{c}");let st = s.model.state();let sk = &st.sketch(s.active_sketch.unwrap()).unwrap().sketch;for ci in sk.link_curves(r["links"][0]["link"].as_str().unwrap()) {@@ -465,7 +466,7 @@ fn tilted_circles_project_to_exact_ellipses_and_splines_stay_splines() {assert!((e - 1.0).abs() < 1e-9, "{q:?}");}}- // The whole face (both halves of its rim, plus its seam) gives the full ellipse.+ // The whole face (its rim, plus its seam) gives the full ellipse.let r = run(&mut s, "sketch.project", json!({"refs": [{"face": [0, 0, 0]}]}));let si = inspect(&mut s);let types: Vec<String> = r["links"][0]["curves"]@@ -812,6 +813,21 @@ fn intersect_curves(steps: &[(&str, Value)], plane: Value) -> std::result::ResulOk(linked_curves(&inspect(&mut s)))}+/// The lines among `curves` as an outline: each line's ends rounded and the lower first, the lines+/// sorted. A section's chains are walked from either end (the mesh's triangle order picks which),+/// so a line's direction says nothing about the cut.+fn outline(curves: &[Value]) -> Vec<[f64; 4]> {+ let mut ends: Vec<[f64; 4]> = line_ends(curves)+ .into_iter()+ .map(|e| {+ let e = e.map(f64::round);+ if [e[2], e[3]] < [e[0], e[1]] { [e[2], e[3], e[0], e[1]] } else { e }+ })+ .collect();+ ends.sort_by(|a, b| a.partial_cmp(b).unwrap());+ ends+}+fn line_ends(curves: &[Value]) -> Vec<[f64; 4]> {let at = |c: &Value, k: &str, i: usize| c[k][i].as_f64().unwrap_or(f64::NAN);curves@@ -827,10 +843,8 @@ fn line_ends(curves: &[Value]) -> Vec<[f64; 4]> {fn intersect_keeps_its_exact_cuts() {let block = [("solid.box", json!({"length": 40, "width": 30, "height": 20}))];for offset in [10, 0] {- let mut ends = line_ends(&intersect_curves(&block, json!({"plane": "XY", "offset": offset})).unwrap());- ends.iter_mut().for_each(|e| *e = e.map(|v| v.round()));- ends.sort_by(|a, b| a.partial_cmp(b).unwrap());- assert_eq!(ends, vec![[0.0, 0.0, 40.0, 0.0], [0.0, 30.0, 0.0, 0.0], [40.0, 0.0, 40.0, 30.0], [40.0, 30.0, 0.0, 30.0]], "offset {offset}");+ let ends = outline(&intersect_curves(&block, json!({"plane": "XY", "offset": offset})).unwrap());+ assert_eq!(ends, vec![[0.0, 0.0, 0.0, 30.0], [0.0, 0.0, 40.0, 0.0], [0.0, 30.0, 40.0, 30.0], [40.0, 0.0, 40.0, 30.0]], "offset {offset}");}for (steps, plane, radius) in [(vec![("solid.cylinder", json!({"base": [0, 0, 0], "radius": 7, "height": 30}))], json!({"plane": "XY", "offset": 12}), 7.0),@@ -870,8 +884,6 @@ fn intersect_crosses_a_curved_face_on_the_surface() {#[test]fn intersect_on_a_top_face_gives_its_outline() {let block = [("solid.box", json!({"length": 40, "width": 30, "height": 20}))];- let mut ends = line_ends(&intersect_curves(&block, json!({"plane": "XY", "offset": 20})).unwrap());- ends.iter_mut().for_each(|e| *e = e.map(|v| v.round()));- ends.sort_by(|a, b| a.partial_cmp(b).unwrap());- assert_eq!(ends, vec![[0.0, 0.0, 40.0, 0.0], [0.0, 30.0, 0.0, 0.0], [40.0, 0.0, 40.0, 30.0], [40.0, 30.0, 0.0, 30.0]]);+ let ends = outline(&intersect_curves(&block, json!({"plane": "XY", "offset": 20})).unwrap());+ assert_eq!(ends, vec![[0.0, 0.0, 0.0, 30.0], [0.0, 0.0, 40.0, 0.0], [0.0, 30.0, 40.0, 30.0], [40.0, 0.0, 40.0, 30.0]]);}diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rsindex 053368f669..eff7ee3db9 100644--- a/crates/kernel/src/ops.rs+++ b/crates/kernel/src/ops.rs@@ -21,9 +21,18 @@ pub enum BoolOp {/// everything or an intersection of disjoint bodies. A result SMLib's check refuses is an error.////// The result carries its exact history ([`Body::history`]) over the operands `[a, b]`, from-/// SMLib's own tags, or none where a body's order cannot be matched to SMLib's.+/// SMLib's own tags, or none where a body's order cannot be matched to SMLib's. A cut by a tool+/// apart from the body is the body itself (its faces and edges kept), and their intersection empty.pub fn boolean(a: &Body, b: &Body, op: BoolOp) -> Result<Option<Body>> {crate::profile::timed(crate::profile::Kind::Boolean, "boolean", || {+ // A tool apart from the body (their exact boxes, grown by the tolerances, do not meet)+ // leaves a cut the body itself and an intersection nothing, with no intersection work.+ if matches!(op, BoolOp::Cut | BoolOp::Intersect) && apart(a, b)? {+ return Ok(match op {+ BoolOp::Cut => Some(crate::boolean_record::operand(a, 0, &crate::record::counts(&[a, b]))),+ _ => None,+ });+ }let r = guard("SMLib boolean", || crate::smlib_boolean::smlib_boolean(a, b, op));with_operand_roles(a, b, op, r)})@@ -44,6 +53,16 @@ pub fn union_all(bodies: &[&Body]) -> Result<Body> {})}+/// Whether B-rep bodies `a` and `b` are apart: their exact boxes, each grown by twice its+/// record's tolerance (as [`union_apart`] takes them), do not meet.+fn apart(a: &Body, b: &Body) -> Result<bool> {+ if a.is_mesh() || b.is_mesh() {+ return Ok(false);+ }+ let grown = |x: &Body| x.exact_bounds().map(|bb| bb.inflated(2.0 * x.record().tolerance));+ Ok(!grown(a)?.meets(&grown(b)?))+}+/// A boolean's result with what its operands' faces stood for carried over: regularization/// protection and the planar construction and shell roles on supports it kept.fn with_operand_roles(a: &Body, b: &Body, op: BoolOp, r: Result<Option<Body>>) -> Result<Option<Body>> {diff --git a/crates/kernel/src/planar_regularize.rs b/crates/kernel/src/planar_regularize.rsindex 6d5a8cc466..5f263c0c3a 100644--- a/crates/kernel/src/planar_regularize.rs+++ b/crates/kernel/src/planar_regularize.rs@@ -41,13 +41,14 @@ impl Body {return Ok(None);}let actual = super::planar_sources::actual_planes(&self)?;+ let at = super::planar_sources::Resolution::of(&self);let valid: Vec<_> = actual.iter().zip(sources).map(|(actual, s)| {s.as_ref().and_then(super::planar_sources::certified_plane)- .filter(|p| actual.is_some_and(|actual| super::planar_sources::same_support(p, &actual)))+ .filter(|p| actual.is_some_and(|actual| super::planar_sources::same_support(p, &actual, at)))}).collect();let record = self.record();diff --git a/crates/kernel/src/planar_sources.rs b/crates/kernel/src/planar_sources.rsindex ad0ee3249c..51ed1f83a0 100644--- a/crates/kernel/src/planar_sources.rs+++ b/crates/kernel/src/planar_sources.rs@@ -40,23 +40,48 @@ pub(super) fn actual_planes(body: &Body) -> Result<Vec<Option<Plane>>> {.collect())}-/// How far apart the normals' x components of two planes `same_support` accepts can be, with-/// room to spare: their unit normals are within about 1e-12 of each other.-const NORMAL_WINDOW: f64 = 1e-9;+/// The resolution two planar supports are compared at: SMLib's own, by which it calls two planes+/// coincident (SmPlane::CoincidenceCheck): a distance within the body's intersection tolerance+/// (the record's `tolerance`, SMLib's XSectTol3d) and normals within the angle that tolerance+/// makes across the body (`tolerance / size`; SMLib takes the plane's own extent, the body's is+/// at least as large, so this is no looser), never finer than rounding. Faces SMLib rebuilt+/// through a boolean lie within it of the plane they were made on (a cut cap at z = 10 came back+/// 2.1e-11 off and 1.4e-12 rad turned), not within a few ulps of it.+#[derive(Clone, Copy, Debug)]+pub(super) struct Resolution {+ linear: f64,+ angular: f64,+}++impl Resolution {+ pub(super) fn of(body: &Body) -> Self {+ let tolerance = body.record().tolerance;+ let size = body.size();+ let rounding = 4096. * f64::EPSILON;+ let linear = if tolerance.is_finite() && tolerance > 0. { tolerance } else { 0. };+ let angular = if size.is_finite() && size > 0. { linear / size } else { 0. };+ Resolution { linear: linear.max(rounding * (1. + size.max(0.))), angular: angular.max(rounding) }+ }+}-/// The entries of `sorted` (ordered by their plane's normal x) whose normal x is within-/// [`NORMAL_WINDOW`] of `nx`: the only ones `same_support` can accept for a plane with that normal.-fn normal_window<T>(sorted: &[T], plane: impl Fn(&T) -> &Plane, nx: f64) -> &[T] {- let first = sorted.partition_point(|t| plane(t).normal().x < nx - NORMAL_WINDOW);- let last = sorted.partition_point(|t| plane(t).normal().x <= nx + NORMAL_WINDOW);+/// The entries of `sorted` (ordered by their plane's normal x) whose normal x is within the+/// resolution's angle of `nx` (and rounding): the only ones `same_support` can accept for a plane+/// with that normal.+fn normal_window<T>(sorted: &[T], plane: impl Fn(&T) -> &Plane, nx: f64, at: Resolution) -> &[T] {+ let window = 2. * at.angular + 1e-12;+ let first = sorted.partition_point(|t| plane(t).normal().x < nx - window);+ let last = sorted.partition_point(|t| plane(t).normal().x <= nx + window);sorted.get(first..last.max(first)).unwrap_or_default()}-pub(super) fn same_support(a: &Plane, b: &Plane) -> bool {- let error = 4096. * f64::EPSILON * (1. + a.origin.len() + b.origin.len());- a.normal().cross(b.normal()).len() <= 4096. * f64::EPSILON- && a.normal().dot(b.normal()) > 0.- && (a.origin - b.origin).dot(a.normal()).abs() <= error+/// Whether `a` and `b` are one oriented plane at resolution `at`: normals the same way within its+/// angle, each origin within its distance of the other plane.+pub(super) fn same_support(a: &Plane, b: &Plane, at: Resolution) -> bool {+ let (na, nb) = (a.normal(), b.normal());+ na.cross(nb).len() <= at.angular+ && na.dot(nb) > 0.+ && (b.origin - a.origin).dot(na).abs() <= at.linear+ && (a.origin - b.origin).dot(nb).abs() <= at.linear}fn base_plane(source: &FaceSource, actual: &Plane) -> Option<Plane> {@@ -195,6 +220,7 @@ impl Body {if open.len() > 256 {return Ok(self);}+ let at = Resolution::of(&self);let opening_tolerance = if shell.is_some() { inputs.iter().map(|input| input.size()).fold(0., f64::max) * 1e-4 + 1e-6 } else { 0. };let mapped = guard("exact planar support lineage", || {let mut competing = Vec::new();@@ -226,7 +252,7 @@ impl Body {unknown_supports.push(actual);continue;};- if !same_support(&plane, &actual) || (shell.is_some() && open.iter().any(|p| actual.height(*p).abs() <= opening_tolerance)) {+ if !same_support(&plane, &actual, at) || (shell.is_some() && open.iter().any(|p| actual.height(*p).abs() <= opening_tolerance)) {unknown_supports.push(actual);continue;}@@ -254,16 +280,16 @@ impl Body {if let Some(actual) = actual {let mut blocked = false;let nx = actual.normal().x;- for plane in normal_window(&unknown_supports, |p| p, nx) {+ for plane in normal_window(&unknown_supports, |p| p, nx, at) {work = work.checked_sub(1).ok_or_else(|| KernelError::Invalid("unknown planar source comparison budget exceeded".into()))?;- if same_support(plane, &actual) {+ if same_support(plane, &actual, at) {blocked = true;break;}}- for plane in normal_window(&competing, |p| p, nx) {+ for plane in normal_window(&competing, |p| p, nx, at) {work = work.checked_sub(1).ok_or_else(|| KernelError::Invalid("planar tool comparison budget exceeded".into()))?;- if same_support(plane, &actual) {+ if same_support(plane, &actual, at) {blocked = true;break;}@@ -286,9 +312,9 @@ impl Body {continue;}let mut chosen: Option<(Plane, &FaceSource, bool, usize)> = None;- for (plane, source, inner, cost) in normal_window(&candidates, |c| &c.0, nx) {+ for (plane, source, inner, cost) in normal_window(&candidates, |c| &c.0, nx, at) {work = work.checked_sub(1).ok_or_else(|| KernelError::Invalid("planar source comparison budget exceeded".into()))?;- if same_support(plane, &actual) {+ if same_support(plane, &actual, at) {if let Some((previous_plane, previous_source, previous_inner, _)) = chosen {let Some(remaining) = identity_bytes.checked_sub(*cost) else {chosen = None;@@ -444,7 +470,9 @@ mod tests {.map(|(i, p)| {let p = (*p)?;let find = |of: &Body, ps: &[Option<Plane>]| {- ps.iter().position(|q| q.is_some_and(|q| same_support(&q, &p))).and_then(|i| of.face_sources()?[i].clone())+ ps.iter()+ .position(|q| q.is_some_and(|q| same_support(&q, &p, Resolution::of(&combined))))+ .and_then(|i| of.face_sources()?[i].clone())};let in_a = face_points(&combined, i).iter().all(|q| q.x <= a_right + 1e-9);if in_a {@@ -496,7 +524,7 @@ mod tests {if matches!(s, Some(FaceSource::ExtrudeSide { coalesced: true, plane: None, .. })) {assert!(cup.face_plane(i).is_none(), "loss witness is not source authority");} else if s.is_some() {- assert!(same_support(&cup.face_plane(i).unwrap(), &cup.planar_face(i).unwrap()));+ assert!(same_support(&cup.face_plane(i).unwrap(), &cup.planar_face(i).unwrap(), Resolution::of(&cup)));}}let moved = transform_matrix(&cup, [[0., 1., 0., 0.], [-1., 0., 0., 0.], [0., 0., 1., 0.], [100., 200., 300., 1.]]).unwrap();