SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Wave 290/509: STEP and SMLib: no edge or vertex tolerance past the 1 mm SMLib takes (and 3 more)
jyviko5a2e050f71c7
diff --git a/crates/geom/src/brep/pcurve.rs b/crates/geom/src/brep/pcurve.rsindex 3a86d24669..cb1e3e08ef 100644--- a/crates/geom/src/brep/pcurve.rs+++ b/crates/geom/src/brep/pcurve.rs@@ -64,6 +64,10 @@ const CHECKS: usize = 16;/// How close, against the geometry's size, a closed-form pcurve must lift onto its edge to be/// taken as exact (rounding, well inside any tolerance).const EXACT: f64 = 1e-9;+/// An edge's tolerance over its largest distance from a face's surface: a pcurve is accepted+/// within half its edge's tolerance ([`pcurves_within`]), as SMLib's zone tolerance is half the+/// record's, so a tolerance that covers a gap goes past twice it.+pub const SURFACE_GAP_MARGIN: f64 = 3.0;/// For each loop of a face on `surface`, the pcurve of each of its edge uses, in order, within/// `tolerance` mm (or the use's own edge tolerance where larger) of the edge when lifted ontodiff --git a/crates/smlib/src/ffi/measure.rs b/crates/smlib/src/ffi/measure.rsindex 2761b2458f..7c90fd2d96 100644--- a/crates/smlib/src/ffi/measure.rs+++ b/crates/smlib/src/ffi/measure.rs@@ -1,4 +1,5 @@-//! `smlib_brep_mass_properties`, `smlib_brep_area` and `smlib_brep_bounds` (the fork's `capi/src/smlib_measure.cpp`), declared by+//! `smlib_brep_mass_properties`, `smlib_brep_area`, `smlib_brep_bounds` and+//! `smlib_brep_edge_face_distance` (the fork's `capi/src/smlib_measure.cpp`), declared by//! hand. Part of the FFI boundary, like its parent: called only through [`crate::measure`].#![allow(unsafe_code)]@@ -14,6 +15,7 @@ unsafe extern "C" {pub fn smlib_brep_mass_properties(brep: *const RawBrep, relative_accuracy: f64, out: *mut f64) -> i32;pub fn smlib_brep_area(brep: *const RawBrep, relative_accuracy: f64, out: *mut f64) -> i32;pub fn smlib_brep_bounds(brep: *const RawBrep, lo: *mut f64, hi: *mut f64) -> i32;+ pub fn smlib_brep_edge_face_distance(brep: *const RawBrep, edge: i64, face: i64, out: *mut f64) -> i32;}#[cfg(feature = "native")]@@ -43,6 +45,20 @@ pub fn bounds(b: &Handle) -> Result<([f64; 3], [f64; 3]), i32> {}}+#[cfg(feature = "native")]+pub fn edge_face_distance(b: &Handle, edge: i64, face: i64) -> Result<f64, i32> {+ let mut d = 0.0;+ match unsafe { smlib_brep_edge_face_distance(b.raw(), edge, face, &mut d) } {+ OK => Ok(d),+ s => Err(s),+ }+}++#[cfg(not(feature = "native"))]+pub fn edge_face_distance(_: &Handle, _: i64, _: i64) -> Result<f64, i32> {+ Err(NOT_BUILT)+}+#[cfg(not(feature = "native"))]pub fn bounds(_: &Handle) -> Result<([f64; 3], [f64; 3]), i32> {Err(NOT_BUILT)diff --git a/crates/smlib/src/flat.rs b/crates/smlib/src/flat.rsindex 62c2eb6b6a..1d28635a05 100644--- a/crates/smlib/src/flat.rs+++ b/crates/smlib/src/flat.rs@@ -104,6 +104,8 @@ pub const FACE_TORUS_MAJOR_RADIUS: i32 = 162;pub const FACE_TORUS_MINOR_RADIUS: i32 = 163;pub const EDGE_TOLERANCE: i32 = 164;pub const VERTEX_TOLERANCE: i32 = 165;+/// The largest EDGE_TOLERANCE or VERTEX_TOLERANCE import takes (smlib.h: "at most 1").+pub const MAX_TOLERANCE: f64 = 1.0;/// `SMLIB_FLAT_MAX_LEN`: no array is longer.pub const MAX_LEN: usize = 1 << 27;pub const SURFACE_NURBS: u8 = 0;diff --git a/crates/smlib/src/import.rs b/crates/smlib/src/import.rsindex bdd9b86306..516963da3a 100644--- a/crates/smlib/src/import.rs+++ b/crates/smlib/src/import.rs@@ -254,15 +254,23 @@ fn laid_out(brep: &b::Brep, trusted: bool, analytic: bool, bare: &HashSet<(u32,}a.i(flat::EDGE_VERTICES).extend([i64::from(e.vertices[0]), i64::from(e.vertices[1])]);a.r(flat::EDGE_RANGE).extend(*interval);- // Each edge's own tolerance, never below the body's.- a.r(flat::EDGE_TOLERANCE).push(e.tolerance.max(brep.tolerance));+ // Each edge's own tolerance, never below the body's, and never past what SMLib takes.+ let tolerance = e.tolerance.max(brep.tolerance);+ if !(tolerance <= flat::MAX_TOLERANCE) {+ return Err(Unsupported::NotYet("an edge tolerance over 1 mm"));+ }+ a.r(flat::EDGE_TOLERANCE).push(tolerance);}let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);for v in &brep.vertices {a.i(flat::VERTEX_POINT_TYPE).push(1);a.r3(flat::VERTEX_POSITION, v.point);- a.r(flat::VERTEX_TOLERANCE).push(v.tolerance.max(brep.tolerance));+ let tolerance = v.tolerance.max(brep.tolerance);+ if !(tolerance <= flat::MAX_TOLERANCE) {+ return Err(Unsupported::NotYet("a vertex tolerance over 1 mm"));+ }+ a.r(flat::VERTEX_TOLERANCE).push(tolerance);for k in 0..3 {lo[k] = lo[k].min(v.point[k]);hi[k] = hi[k].max(v.point[k]);diff --git a/crates/smlib/src/measure.rs b/crates/smlib/src/measure.rsindex f44d4c655a..ec470c9671 100644--- a/crates/smlib/src/measure.rs+++ b/crates/smlib/src/measure.rs@@ -1,5 +1,5 @@//! Exact mass properties from SMLib: area, volume, centroid and inertia, integrated on the exact-//! surfaces rather than a tessellation, and the exact box.+//! surfaces rather than a tessellation; the exact box; how far an edge lies from a face's surface.use crate::{Brep, Result, error, ffi};@@ -48,6 +48,17 @@ impl Brep {ffi::measure::bounds(&self.0).map_err(error)}+ /// How far edge `edge` (its curve over its interval) lies from the surface of face `face`,+ /// over that surface's own domain and not beyond it, in mm: SMLib's own edge/face gap, the+ /// one it sizes an edge's tolerance by. Indices are in the body's edge and face order (as+ /// it was imported and is exported). An edge run past its face's patch measures how far it+ /// goes; SMLib keeps such an edge whole when making its UV trim only when its zone tolerance+ /// (half the flat arrays' `EDGE_TOLERANCE`) covers this.+ pub fn edge_face_distance(&self, edge: usize, face: usize) -> Result<f64> {+ let (Ok(e), Ok(f)) = (i64::try_from(edge), i64::try_from(face)) else { return Err(error(ffi::ERR_ARG)) };+ ffi::measure::edge_face_distance(&self.0, e, f).map_err(error)+ }+/// Total area of every face, each counted once, so sheets and open shells too.pub fn area(&self, relative_accuracy: f64) -> Result<f64> {ffi::measure::area(&self.0, relative_accuracy).map_err(error)diff --git a/crates/smlib/src/pcurves.rs b/crates/smlib/src/pcurves.rsindex ca37050ffc..720d36f6b6 100644--- a/crates/smlib/src/pcurves.rs+++ b/crates/smlib/src/pcurves.rs@@ -6,7 +6,7 @@use std::collections::HashSet;-use solidcraft_geom::brep::pcurve::{TrimFace, Trims};+use solidcraft_geom::brep::pcurve::{SURFACE_GAP_MARGIN, TrimFace, Trims};use solidcraft_geom::brep::{self as b, Curve2, EdgeUseRef, Loop, OrientedEdge, OrientedFace, Region, Shell, Vertex};/// [`Trims`] by SMLib.@@ -21,8 +21,12 @@ impl Trims for SmlibTrims {fn trims(face: &TrimFace<'_>) -> Result<Vec<Vec<Curve2>>, String> {let (record, bare) = sheet(face)?;- let arrays = crate::import::arrays_with_bare_uses(&record, &bare).map_err(|e| e.to_string())?;- let body = crate::flat::Flat::from_arrays(&arrays).and_then(|f| f.import()).map_err(|e| e.to_string())?;+ let mut arrays = crate::import::arrays_with_bare_uses(&record, &bare).map_err(|e| e.to_string())?;+ let import = |a: &crate::import::Arrays| crate::flat::Flat::from_arrays(a).and_then(|f| f.import()).map_err(|e| e.to_string());+ let mut body = import(&arrays)?;+ if cover_gaps(&body, face, &bare, &mut arrays)? {+ body = import(&arrays)?;+ }let (out, order) = body.to_native_ordered().map_err(|e| e.to_string())?;let [made] = out.faces.as_slice() else { return Err(format!("SMLib made {} faces of one", out.faces.len())) };let made_uses: Vec<&OrientedEdge> = made@@ -58,6 +62,40 @@ fn trims(face: &TrimFace<'_>) -> Result<Vec<Vec<Curve2>>, String> {Ok(result)}+/// Each bare use's edge measured against the face's surface as SMLib measures it (over the+/// surface's own domain: an edge run a few um past its patch measures how far), and its+/// `EDGE_TOLERANCE` in `arrays` raised to cover that gap with [`SURFACE_GAP_MARGIN`]: SMLib keeps+/// an edge whole when making its trim only when its zone tolerance (half that) covers the gap, and+/// otherwise trims the edge back to the patch. Whether any was raised; an edge farther off than+/// SMLib's tolerances reach is refused with how far.+fn cover_gaps(body: &crate::Brep, face: &TrimFace<'_>, bare: &HashSet<(u32, u32, u32)>, arrays: &mut crate::import::Arrays) -> Result<bool, String> {+ let mut edges: Vec<usize> = Vec::new();+ for (li, l) in face.loops.iter().enumerate() {+ for (p, u) in l.iter().enumerate() {+ let (Ok(li), Ok(p)) = (u32::try_from(li), u32::try_from(p)) else { return Err("too many uses".into()) };+ if bare.contains(&(0, li, p)) && !edges.contains(&(u.edge as usize)) {+ edges.push(u.edge as usize);+ }+ }+ }+ let mut raised = false;+ for e in edges {+ let gap = body.edge_face_distance(e, 0).map_err(|e| e.to_string())?;+ let need = SURFACE_GAP_MARGIN * gap;+ let tolerances = arrays.reals.get_mut(&crate::flat::EDGE_TOLERANCE).ok_or("edge tolerances")?;+ let given = tolerances.get_mut(e).ok_or("edge reference")?;+ if need <= *given {+ continue;+ }+ if !(need <= crate::flat::MAX_TOLERANCE) {+ return Err(format!("an edge lies {gap} mm off the face's surface"));+ }+ *given = need;+ raised = true;+ }+ Ok(raised)+}+/// A pcurve SMLib made on its edge's interval `theirs`, on ours. SMLib may set an edge's end to/// a parameter of its own (a knot its vertex lies at, the end of the part on the face): where/// each end it chose is within the edge's tolerance of ours on the edge's curve, the pcurve isdiff --git a/crates/smlib/src/tests.rs b/crates/smlib/src/tests.rsindex 7054be25bd..c3251961ba 100644--- a/crates/smlib/src/tests.rs+++ b/crates/smlib/src/tests.rs@@ -109,3 +109,47 @@ fn a_pcurve_smlib_ends_within_the_edges_tolerance_is_mapped_onto_our_interval()let err = crate::pcurves::on_our_interval(pc, &edge, [0.0, 0.99]).unwrap_err();assert!(err.contains("SMLib moved an edge's interval") && err.contains("tolerance"), "{err}");}++/// An edge whose curve runs 2.5 um past its vertex and its face's patch (as Poppy Humanoid's+/// Congé19 has them), with a tolerance of 0.5 um: SMLib trims such an edge back to the patch+/// when it makes its trim, unless the edge's tolerance covers its gap. The gap is measured+/// (SMLib's own, over the patch) and covered, so the face's pcurves come back on the edge's+/// own interval, ending at the patch's corner.+#[cfg(feature = "native")]+#[test]+fn an_edge_a_few_um_past_its_patch_keeps_its_interval() {+ use solidcraft_geom::brep::pcurve::{TrimEdge, TrimFace, TrimUse, Trims};+ use solidcraft_geom::brep::{Curve, Surface};+ // S(u, v) = (10u, 10v, 2v^2), bicubic+ let g = [0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0];+ let z = [0.0, 0.0, 2.0 / 3.0, 2.0];+ let bezier = vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0];+ let points: Vec<Vec<[f64; 3]>> = (0..4).map(|i| (0..4).map(|j| [10.0 * g[i], 10.0 * g[j], z[j]]).collect()).collect();+ let surface = Surface::Spline { u_knots: bezier.clone(), v_knots: bezier.clone(), points: points.clone() };+ let past = 2.5e-3;+ let spline = |p: Vec<[f64; 3]>| Curve::Spline { knots: bezier.clone(), points: p };+ let curves = [+ spline((0..4).map(|i| [(10.0 + past) * g[i], 0.0, 0.0]).collect()),+ spline((0..4).map(|j| points[3][j]).collect()),+ spline((0..4).map(|i| points[3 - i][3]).collect()),+ spline((0..4).map(|j| points[0][3 - j]).collect()),+ ];+ let ends = [[0, 1], [1, 2], [2, 3], [3, 0]];+ let edges = (0..4)+ .map(|k| TrimEdge { curve: &curves[k], nurbs: None, interval: [0.0, 1.0], vertices: ends[k], tolerance: if k == 0 { 1e-3 } else { 1e-5 } })+ .collect();+ let face = TrimFace {+ surface: &surface,+ nurbs: None,+ domain: [[0.0, 1.0], [0.0, 1.0]],+ edges,+ vertices: vec![[0.0, 0.0, 0.0], [10.0, 0.0, 0.0], [10.0, 10.0, 2.0], [0.0, 10.0, 2.0]],+ loops: vec![(0..4).map(|k| TrimUse { edge: k, forward: true, pcurve: None }).collect()],+ tolerance: 1e-5,+ };+ let pcs = crate::pcurves::SmlibTrims.trims(&face).unwrap();+ let pc = &pcs[0][0];+ assert_eq!(pc.interval(), Some([0.0, 1.0]));+ let [u, v] = pc.eval(1.0).unwrap();+ assert!((u - 1.0).abs() < 1e-9 && v.abs() < 1e-9, "{u} {v}");+}diff --git a/crates/step/src/topology.rs b/crates/step/src/topology.rsindex bcf6eb465b..719aac904c 100644--- a/crates/step/src/topology.rs+++ b/crates/step/src/topology.rs@@ -77,20 +77,17 @@ const MAX_SPLINE_POINTS: usize = 4096;const MAX_SPLINE_DEGREE: usize = 16;/// Samples along a curve when projecting a vertex onto it.const MAX_SAMPLES: usize = 4096;-/// How far (mm) a vertex may lie from its curve before the edge is refused.-const MAX_VERTEX_GAP: f64 = 1.0;-/// How far (mm) an edge's curve may lie from a face's surface before the face is refused.-const MAX_EDGE_GAP: f64 = 1.0;+/// The largest tolerance (mm) an edge or vertex is given: SMLib takes none larger (smlib.h's+/// EDGE_TOLERANCE and VERTEX_TOLERANCE, `solidcraft_smlib::flat::MAX_TOLERANCE`). Geometry that+/// would need more is refused, with how far off it lies.+const MAX_TOLERANCE: f64 = 1.0;+/// A vertex's tolerance over its largest gap from its curves and surfaces.+const VERTEX_GAP_MARGIN: f64 = 1.5;/// Intervals an edge's curve is measured over against each face's surface it bounds.const EDGE_GAP_SAMPLES: usize = 16;/// An edge's tolerance over the largest gap measured between its pcurves and its curve, as the/// record check measures it: with margin, as a vertex's.const EDGE_GAP_MARGIN: f64 = 1.5;-/// An edge's tolerance over its largest distance from a face's surface, measured before its-/// pcurve is made: a closed-form pcurve is accepted within half its edge's tolerance-/// (`pcurve::pcurves_within`), so the tolerance goes past twice the distance.-const EDGE_SURFACE_MARGIN: f64 = 3.0;-/// A solid (or sheet) read from the file.#[derive(Clone, Debug)]pub struct Solid {@@ -441,11 +438,11 @@ impl<'b, 'a> Builder<'b, 'a> {/// A vertex `gap` mm from where its edge's curve puts it: refused if far off, else its/// tolerance covers the gap.fn raise_vertex(&mut self, v: u32, gap: f64, edge: u64) -> R<()> {- if !(gap <= MAX_VERTEX_GAP) {+ if !(VERTEX_GAP_MARGIN * gap <= MAX_TOLERANCE) {return Err(format!("edge #{edge}: a vertex lies {gap} mm off its curve"));}if let Some(x) = self.vertices.get_mut(v as usize) {- x.tolerance = x.tolerance.max(1.5 * gap);+ x.tolerance = x.tolerance.max(VERTEX_GAP_MARGIN * gap);}Ok(())}@@ -492,7 +489,7 @@ impl<'b, 'a> Builder<'b, 'a> {let Some(s) = on.project_with(&starts, p, None, f64::INFINITY).and_then(|q| on.point(q)) else { continue };gap = gap.max(s.dist(p));}- self.cover_edge(e, gap, EDGE_SURFACE_MARGIN)?;+ self.cover_edge(e, gap, pcurve::SURFACE_GAP_MARGIN)?;}}Ok(())@@ -504,7 +501,7 @@ impl<'b, 'a> Builder<'b, 'a> {if margin * gap <= x.tolerance {return Ok(());}- if !(gap <= MAX_EDGE_GAP) {+ if !(margin * gap <= MAX_TOLERANCE) {return Err(format!("an edge lies {gap} mm off the face's surface"));}x.tolerance = margin * gap;@@ -1002,10 +999,10 @@ impl<'b, 'a> Builder<'b, 'a> {{let p = v3(x.point);let gap = surface.project(p, None, f64::INFINITY).and_then(|q| surface.point(q)).map_or(f64::INFINITY, |s| s.dist(p));- if !(gap <= MAX_VERTEX_GAP) {+ if !(VERTEX_GAP_MARGIN * gap <= MAX_TOLERANCE) {return Err(format!("face #{}: a vertex loop's vertex lies {gap} mm off its surface", face.step));}- x.tolerance = x.tolerance.max(1.5 * gap);+ x.tolerance = x.tolerance.max(VERTEX_GAP_MARGIN * gap);}}}