Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Wave 28/509: brep: splines closed on themselves are periodic for pcurves and tessellation (and 3 more)

jyvikoe9315767238e
diff --git a/crates/geom/src/brep.rs b/crates/geom/src/brep.rs
index b5f59d2ccb..d81dd31ea2 100644
--- a/crates/geom/src/brep.rs
+++ b/crates/geom/src/brep.rs
@@ -85,9 +85,11 @@ pub struct Face {
/// The modelled rectangle in surface parameters, `[[u0, u1], [v0, v1]]`, inside the
/// surface's natural domain and around every loop.
pub domain: [[f64; 2]; 2],
- /// `loops[0]` is the outer loop, the rest inner. Loops are stored relative to the surface's
- /// natural normal, whatever side a shell uses: seen from that normal, the outer loop runs
- /// counter-clockwise and inner loops clockwise.
+ /// One outer loop and any inner ones, in the producer's order (truck lists some holes
+ /// first; SMLib's import puts the outer loop first, as SMLib requires). Loops are stored
+ /// relative to the surface's natural normal, whatever side a shell uses: seen from that
+ /// normal, the outer loop runs counter-clockwise and inner loops clockwise, which is what
+ /// tells them apart. The first loop is an edge loop.
pub loops: Vec<Loop>,
}
diff --git a/crates/geom/src/brep/geometry.rs b/crates/geom/src/brep/geometry.rs
index 71fc35cc65..247099ea29 100644
--- a/crates/geom/src/brep/geometry.rs
+++ b/crates/geom/src/brep/geometry.rs
@@ -2,11 +2,13 @@
//! assumes when it builds topology from the records without checking them itself. Each edge's
//! curve meets its vertices at its interval's ends; each oriented edge's pcurve, lifted through
//! its face's surface, lies on the edge's curve at the interval's ends and middle, and continues
-//! the use before it without jumping a period; each vertex loop's vertex lies on its surface.
+//! the use before it without jumping a period; each edge loop's pcurves enclose (u, v) area,
+//! one loop of each face counter-clockwise about the natural normal (the outer) and the rest
+//! clockwise; each vertex loop's vertex lies on its surface.
//!
//! A spot check, not a certificate: a fixed number of evaluations per record (three points of
-//! each edge, three of each use, one projection per vertex loop), so the work is linear in the
-//! item budget [`Brep::validate`] caps. Every distance is held to the record's own tolerance:
+//! each edge, [`AREA_SAMPLES`] of each use, one projection per vertex loop), so the work is
+//! linear in the item budget [`Brep::validate`] caps. Every distance is held to the record's own tolerance:
//! an edge's for its pcurves, an edge's and its vertex's together where they meet, a vertex's on
//! its surface. A point that cannot be evaluated is an error, never a panic.
use super::eval::{CurveEval, SurfaceEval};
@@ -24,6 +26,8 @@ pub enum Record {
Use { face: u32, r#loop: u32, position: u32 },
/// `faces[face].loops[loop]`, a vertex loop.
VertexLoop { face: u32, r#loop: u32 },
+ /// `faces[face].loops[loop]`, an edge loop.
+ Loop { face: u32, r#loop: u32 },
}
impl std::fmt::Display for Record {
@@ -32,7 +36,7 @@ impl std::fmt::Display for Record {
Record::Edge(e) => write!(f, "edge {e}"),
Record::Face(i) => write!(f, "face {i}"),
Record::Use { face, r#loop, position } => write!(f, "face {face} loop {loop} use {position}"),
- Record::VertexLoop { face, r#loop } => write!(f, "face {face} loop {loop}"),
+ Record::VertexLoop { face, r#loop } | Record::Loop { face, r#loop } => write!(f, "face {face} loop {loop}"),
}
}
}
@@ -47,6 +51,15 @@ pub enum Problem {
/// another period.
#[error("pcurve starts {gap} from the end of the use before it, on another period (period {period})")]
Period { gap: f64, period: f64 },
+ /// An edge loop's pcurves enclose no (u, v) area, within rounding of the loop's size: its
+ /// face has no surface to it (a seam's two uses on one parameter line).
+ #[error("loop encloses no (u, v) area (signed area {area})")]
+ Empty { area: f64 },
+ /// An edge loop runs the wrong way round in (u, v), seen from the surface's natural normal:
+ /// no loop of the face runs counter-clockwise (`outer`: the largest runs clockwise), or a
+ /// second one does (an inner loop, the smaller of them).
+ #[error("{} loop runs {} in (u, v) (signed area {area})", if *outer { "outer" } else { "inner" }, if *outer { "clockwise" } else { "counter-clockwise" })]
+ Turn { outer: bool, area: f64 },
/// A point of the record cannot be evaluated (an unsupported kind, a non-finite value).
#[error("{0}")]
Unevaluable(String),
@@ -76,6 +89,11 @@ fn within(record: Record, what: &'static str, gap: f64, tolerance: f64) -> Resul
if gap <= tolerance { Ok(()) } else { Err(Mismatch { record, problem: Problem::Off { what, gap, tolerance } }) }
}
+/// Points of each use's pcurve that its loop's (u, v) area is taken over.
+pub const AREA_SAMPLES: usize = 16;
+/// Signed area this small against the square of the loop's (u, v) extent is none.
+const EMPTY_AREA: f64 = 1e-9;
+
const PCURVE_POINTS: [&str; 3] =
["pcurve start lifts off its edge's curve", "pcurve middle lifts off its edge's curve", "pcurve end lifts off its edge's curve"];
@@ -106,6 +124,8 @@ impl Brep {
let face = index(fi);
let surface = SurfaceEval::new(&f.surface).map_err(|err| unevaluable(Record::Face(face), err))?;
let period = surface.domain().period;
+ // Each edge loop's signed (u, v) area.
+ let mut areas: Vec<(u32, f64)> = Vec::with_capacity(f.loops.len());
for (li, l) in f.loops.iter().enumerate() {
let r#loop = index(li);
match l {
@@ -152,10 +172,52 @@ impl Brep {
}
}
}
+ // The signed area the loop encloses (positive for the outer loop). Where
+ // uses meet at a pole the ring runs straight along the pole's line.
+ let at = Record::Loop { face, r#loop };
+ let mut ring: Vec<[f64; 2]> = Vec::with_capacity(edges.len().saturating_mul(AREA_SAMPLES));
+ for u in edges {
+ let [t0, t1] = self.edges.get(u.edge as usize).ok_or_else(|| unevaluable(at, "edge reference"))?.interval;
+ for k in 0..AREA_SAMPLES {
+ let f = k as f64 / AREA_SAMPLES as f64;
+ let t = if u.forward { t0 + (t1 - t0) * f } else { t1 - (t1 - t0) * f };
+ ring.push(u.pcurve.eval(t).ok_or_else(|| unevaluable(at, format!("the pcurve has no point at {t}")))?);
+ }
+ }
+ let area = signed_area(&ring);
+ let extent = (0..2)
+ .map(|d| {
+ let (lo, hi) = ring.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), q| (a.min(q[d]), b.max(q[d])));
+ hi - lo
+ })
+ .fold(0.0, f64::max);
+ if !(area.abs() > EMPTY_AREA * extent * extent) {
+ return Err(Mismatch { record: at, problem: Problem::Empty { area } });
+ }
+ areas.push((r#loop, area));
}
}
}
+ // One loop runs counter-clockwise, the outer; every other one clockwise. Which is
+ // which comes from the areas, not the loops' order: the truck adapter writes a face's
+ // wires in truck's order, which need not put the outer one first.
+ let by_size = |a: &(u32, f64), b: &(u32, f64)| a.1.abs().total_cmp(&b.1.abs());
+ let ccw: Vec<(u32, f64)> = areas.iter().copied().filter(|a| a.1 > 0.0).collect();
+ let wrong = match ccw.len() {
+ 0 => areas.into_iter().max_by(by_size).map(|(l, area)| (l, true, area)),
+ 1 => None,
+ _ => ccw.into_iter().min_by(by_size).map(|(l, area)| (l, false, area)),
+ };
+ if let Some((r#loop, outer, area)) = wrong {
+ return Err(Mismatch { record: Record::Loop { face, r#loop }, problem: Problem::Turn { outer, area } });
+ }
}
Ok(())
}
}
+
+/// Signed area of a closed polygon in (u, v): positive counter-clockwise.
+fn signed_area(ring: &[[f64; 2]]) -> f64 {
+ let n = ring.len();
+ 0.5 * (0..n).filter_map(|i| Some((ring.get(i)?, ring.get((i + 1) % n)?))).map(|(p, q)| p[0] * q[1] - q[0] * p[1]).sum::<f64>()
+}
diff --git a/crates/geom/src/brep/pcurve.rs b/crates/geom/src/brep/pcurve.rs
index d6912301fb..ec03c7154c 100644
--- a/crates/geom/src/brep/pcurve.rs
+++ b/crates/geom/src/brep/pcurve.rs
@@ -13,9 +13,10 @@
//!
//! Periodic parameters are unwrapped along each curve, and each loop's uses are moved by whole
//! periods so every use starts where the one before it ends: a seam edge used twice gets two
-//! pcurves a period apart. At a pole the parameter along the collapsed direction is undefined;
-//! there it is taken from the nearest sample where it is defined, so a pcurve runs straight into
-//! the pole, and where two uses meet at a pole the loop runs along the pole's line.
+//! pcurves a period apart. A spline closed on itself in a direction is periodic there, one knot
+//! interval per period ([`uv`]). At a pole the parameter along the collapsed direction is
+//! undefined; there it is taken from the nearest sample where it is defined, so a pcurve runs
+//! straight into the pole, and where two uses meet at a pole the loop runs along the pole's line.
use super::eval::{CurveEval, SurfaceEval};
use super::{Budget, Curve, Curve2, Surface, curve, curve_natural, interval, surface};
use crate::Vec3;
@@ -646,4 +647,4 @@ fn move_by(c: &mut Curve2, d: usize, by: f64) {
#[cfg(test)]
#[path = "pcurve_tests.rs"]
-mod tests;
+pub(super) mod tests;
diff --git a/crates/geom/src/brep/pcurve_tests.rs b/crates/geom/src/brep/pcurve_tests.rs
index 4b934daef9..c696bdf709 100644
--- a/crates/geom/src/brep/pcurve_tests.rs
+++ b/crates/geom/src/brep/pcurve_tests.rs
@@ -321,6 +321,117 @@ fn a_torus_bounded_by_its_seams_spans_both_periods() {
}
}
+/// A surface of revolution about +z as a rational spline closed in u, as SMLib writes a fillet
+/// ring round a hole's rim and STEP a NURBS cylinder: u the nine-point rational quadratic
+/// circle on [0, 1] (first and last rows the same), v the profile's `[radius, height, weight]`
+/// points on `v_knots`.
+pub(crate) fn closed_ring(profile: &[[f64; 3]], v_knots: &[f64]) -> Surface {
+ let w = std::f64::consts::FRAC_1_SQRT_2;
+ let around = [[1., 0., 1.], [1., 1., w], [0., 1., 1.], [-1., 1., w], [-1., 0., 1.], [-1., -1., w], [0., -1., 1.], [1., -1., w], [1., 0., 1.]];
+ let homogeneous = around
+ .iter()
+ .map(|&[cx, cy, wu]| {
+ profile
+ .iter()
+ .map(|&[r, z, wv]| {
+ let wt = wu * wv;
+ [r * cx * wt, r * cy * wt, z * wt, wt]
+ })
+ .collect()
+ })
+ .collect();
+ Surface::RationalSpline { u_knots: vec![0., 0., 0., 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1., 1., 1.], v_knots: v_knots.to_vec(), homogeneous }
+}
+
+/// The pcurves of a loop on a spline closed in u (period 1): each lifts within `tol`, the
+/// seam's two uses (`seam`: their positions) lie one period apart, the loop closes (in v alone
+/// where it meets a pole) and turns counter-clockwise once around the whole (u, v) box, all in
+/// the base period.
+fn closes_around_the_box(surface: &Surface, l: &[EdgeUse<'_>], seam: [usize; 2], pole: Option<usize>, tol: f64, what: &str) {
+ let pcs = &pcurves(surface, &[l.to_vec()], tol).unwrap_or_else(|e| panic!("{what}: {e}"))[0];
+ for (u, pc) in l.iter().zip(pcs) {
+ assert!(lift_error(surface, u.curve, u.interval, pc) <= tol, "{what}: lifts");
+ }
+ let iv = l[seam[0]].interval;
+ let mid = 0.5 * (iv[0] + iv[1]);
+ let (a, b) = (pcs[seam[0]].eval(mid).unwrap(), pcs[seam[1]].eval(mid).unwrap());
+ assert!(((a[0] - b[0]).abs() - 1.).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9, "{what}: seam uses a period apart: {a:?} {b:?}");
+ let (ends, area) = walk(l, pcs);
+ let n = l.len();
+ for k in 0..n {
+ let (end, start) = (ends[k].1, ends[(k + 1) % n].0);
+ let free_u = pole == Some((k + 1) % n);
+ assert!((free_u || (end[0] - start[0]).abs() < 1e-9) && (end[1] - start[1]).abs() < 1e-9, "{what}: closes at {k}: {end:?} {start:?}");
+ }
+ // At a pole `walk` cuts the corner (it joins each use's 16th sample to the next use's
+ // start, across the pole's line): a sliver of the box less.
+ let least = if pole.is_some() { 0.9 } else { 1. - 1e-6 };
+ assert!(area >= least && area < 1. + 1e-6, "{what}: counter-clockwise around the box: {area}");
+ for pc in pcs {
+ let (Curve2::Spline { knots, .. } | Curve2::RationalSpline { knots, .. }) = pc;
+ for k in 0..=32 {
+ let t = knots[0] + (knots[knots.len() - 1] - knots[0]) * k as f64 / 32.;
+ let q = pc.eval(t).unwrap();
+ assert!((-1e-9..=1. + 1e-9).contains(&q[0]), "{what}: base period: {q:?}");
+ }
+ }
+}
+
+/// Splines closed on themselves in u (their first and last control rows the same) are periodic
+/// there, one knot interval per period: a ring of a torus bounded by two circles and a seam used
+/// twice (SMLib's fillet round a hole's rim), a NURBS cylinder, and a NURBS dome whose seam runs
+/// into its pole. Each seam's uses come out a period apart, never both on u = 0.
+#[test]
+fn a_seam_on_a_spline_closed_in_u_gets_pcurves_a_period_apart() {
+ let w = std::f64::consts::FRAC_1_SQRT_2;
+ let full = [0., TAU];
+ let (big, small) = (5., 1.);
+ // The torus band: the tube's quarter from its outer equator (v = 0) to its top (v = 1).
+ let band = closed_ring(&[[big + small, 0., 1.], [big + small, small, w], [big, small, 1.]], &[0., 0., 0., 1., 1., 1.]);
+ let outer = Curve::Circle { frame: about_z([0.; 3], false), radius: big + small };
+ let top = Curve::Circle { frame: about_z([0., 0., small], false), radius: big };
+ let quarter = Curve::Circle { frame: frame([big, 0., 0.], [1., 0., 0.], [0., 0., 1.]), radius: small };
+ let l = vec![
+ EdgeUse { edge: 0, curve: &outer, interval: full, forward: true },
+ EdgeUse { edge: 1, curve: &quarter, interval: [0., FRAC_PI_2], forward: true },
+ EdgeUse { edge: 2, curve: &top, interval: full, forward: false },
+ EdgeUse { edge: 1, curve: &quarter, interval: [0., FRAC_PI_2], forward: false },
+ ];
+ for tol in [1e-4, 1e-7] {
+ closes_around_the_box(&band, &l, [1, 3], None, tol, &format!("torus band, tol {tol}"));
+ }
+ // The cylinder: radius 3 from z = 0 (v = 0) to z = 4 (v = 1), its seam a line.
+ let cylinder = closed_ring(&[[3., 0., 1.], [3., 4., 1.]], &[0., 0., 1., 1.]);
+ let (low, high) =
+ (Curve::Circle { frame: about_z([0.; 3], false), radius: 3. }, Curve::Circle { frame: about_z([0., 0., 4.], false), radius: 3. });
+ let line = Curve::Line { start: [3., 0., 0.], end: [3., 0., 4.] };
+ let l = vec![
+ EdgeUse { edge: 0, curve: &low, interval: full, forward: true },
+ EdgeUse { edge: 1, curve: &line, interval: [0., 1.], forward: true },
+ EdgeUse { edge: 2, curve: &high, interval: full, forward: false },
+ EdgeUse { edge: 1, curve: &line, interval: [0., 1.], forward: false },
+ ];
+ closes_around_the_box(&cylinder, &l, [1, 3], None, 1e-7, "cylinder");
+ // The dome: radius 6 from its equator (v = 0) to its pole (v = 1), the seam a meridian.
+ let dome = closed_ring(&[[6., 0., 1.], [6., 6., w], [0., 6., 1.]], &[0., 0., 0., 1., 1., 1.]);
+ let equator = Curve::Circle { frame: about_z([0.; 3], false), radius: 6. };
+ let meridian = Curve::Circle { frame: frame([0.; 3], [1., 0., 0.], [0., 0., 1.]), radius: 6. };
+ let l = vec![
+ EdgeUse { edge: 0, curve: &equator, interval: full, forward: true },
+ EdgeUse { edge: 1, curve: &meridian, interval: [0., FRAC_PI_2], forward: true },
+ EdgeUse { edge: 1, curve: &meridian, interval: [0., FRAC_PI_2], forward: false },
+ ];
+ closes_around_the_box(&dome, &l, [1, 2], Some(2), 1e-7, "dome");
+ // A spline whose ends merely come near each other stays open: no period, so the seam's
+ // second use cannot be moved and the loop does not close around the box.
+ let Surface::RationalSpline { u_knots, v_knots, homogeneous } = &cylinder else { panic!("a rational spline") };
+ let mut open = homogeneous.clone();
+ open[8][0][1] += 1e-3;
+ let open = Surface::RationalSpline { u_knots: u_knots.clone(), v_knots: v_knots.clone(), homogeneous: open };
+ assert_eq!(SurfaceEval::new(&open).unwrap().domain().period, [None, None]);
+ assert_eq!(SurfaceEval::new(&cylinder).unwrap().domain().period, [Some(1.), None]);
+}
+
/// An intersection record evaluates to the point of both surfaces in the leader's normal
/// plane, and its pcurves on either surface fit.
#[test]
diff --git a/crates/geom/src/brep/tests.rs b/crates/geom/src/brep/tests.rs
index fc8ad6a865..b4c71fc897 100644
--- a/crates/geom/src/brep/tests.rs
+++ b/crates/geom/src/brep/tests.rs
@@ -160,6 +160,60 @@ fn tube() -> Brep {
fit_pcurves(&mut b);
b
}
+/// One face on `surface` bounded by one loop of `uses` (edge index, forward), each edge's
+/// pcurves fitted, as an open sheet.
+fn one_face(surface: Surface, domain: [[f64; 2]; 2], edges: Vec<(Curve, [f64; 2], [u32; 2])>, vertices: &[[f64; 3]], uses: &[(u32, bool)]) -> Brep {
+ let mut b = Brep {
+ version: VERSION,
+ tolerance: 1e-7,
+ regions: vec![infinite(vec![0])],
+ shells: vec![Shell::Faces { faces: vec![OrientedFace { face: 0, forward: true }], wires: vec![] }],
+ faces: vec![Face {
+ surface,
+ domain,
+ loops: vec![Loop::Edges { edges: uses.iter().map(|&(edge, forward)| OrientedEdge { edge, forward, pcurve: segment(0., 1.) }).collect() }],
+ }],
+ edges: edges.into_iter().map(|(curve, interval, vertices)| Edge { curve, interval, vertices, tolerance: 1e-7, uses: vec![] }).collect(),
+ vertices: vertices.iter().map(|&point| Vertex { point, tolerance: 1e-7 }).collect(),
+ };
+ list_uses(&mut b);
+ fit_pcurves(&mut b);
+ b
+}
+/// A ring of a torus as a rational spline closed in u (first and last control rows the same),
+/// as SMLib writes the fillet round a hole's rim: bounded by its two circles and the tube's
+/// quarter at u = 0, a seam used twice.
+fn closed_band() -> Brep {
+ let w = std::f64::consts::FRAC_1_SQRT_2;
+ let (big, small) = (5., 1.);
+ let surface = pcurve::tests::closed_ring(&[[big + small, 0., 1.], [big + small, small, w], [big, small, 1.]], &[0., 0., 0., 1., 1., 1.]);
+ let about = |z: f64| Frame { origin: [0., 0., z], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] };
+ let quarter = Curve::Circle { frame: Frame { origin: [big, 0., 0.], x_axis: [1., 0., 0.], y_axis: [0., 0., 1.] }, radius: small };
+ one_face(
+ surface,
+ [[0., 1.], [0., 1.]],
+ vec![
+ (Curve::Circle { frame: about(0.), radius: big + small }, [0., TAU], [0, 0]),
+ (quarter, [0., FRAC_PI_2], [0, 1]),
+ (Curve::Circle { frame: about(small), radius: big }, [0., TAU], [1, 1]),
+ ],
+ &[[big + small, 0., 0.], [big, 0., small]],
+ &[(0, true), (1, true), (2, false), (1, false)],
+ )
+}
+/// A whole sphere bounded by one meridian from pole to pole, used twice: a closed shell.
+fn ball() -> Brep {
+ let meridian = Curve::Circle { frame: Frame { origin: [1., 2., 3.], x_axis: [1., 0., 0.], y_axis: [0., 0., 1.] }, radius: 2. };
+ let mut b = one_face(
+ Surface::Sphere { frame: a_frame(), radius: 2. },
+ [[0., TAU], [-FRAC_PI_2, FRAC_PI_2]],
+ vec![(meridian, [-FRAC_PI_2, FRAC_PI_2], [0, 1])],
+ &[[1., 2., 1.], [1., 2., 5.]],
+ &[(0, true), (0, false)],
+ );
+ b.regions.push(Region { shells: vec![0], void: false });
+ b
+}
/// The sheet with a vertex loop inside it, a wire shell and a vertex shell beside it.
fn sheet_with_lower_forms() -> Brep {
let mut b = sheet();
@@ -182,7 +236,15 @@ fn sheet_with_lower_forms() -> Brep {
#[test]
fn every_form_validates_and_round_trips_without_a_kernel() {
- for (name, body) in [("sheet", sheet()), ("closed", tetra()), ("void", hollow()), ("seam", tube()), ("lower forms", sheet_with_lower_forms())] {
+ for (name, body) in [
+ ("sheet", sheet()),
+ ("closed", tetra()),
+ ("void", hollow()),
+ ("seam", tube()),
+ ("seam on a closed spline", closed_band()),
+ ("seam from pole to pole", ball()),
+ ("lower forms", sheet_with_lower_forms()),
+ ] {
body.validate().unwrap_or_else(|e| panic!("{name}: {e}"));
body.check_geometry().unwrap_or_else(|e| panic!("{name}: {e}"));
let bytes = serde_json::to_vec(&body).unwrap();
@@ -470,6 +532,49 @@ fn geometric_defects_are_refused_by_record() {
b.vertices[6].point[2] = 0.01;
b
}),
+ (
+ "seam uses of a closed spline on one line",
+ Record::Use { face: 0, r#loop: 0, position: 1 },
+ Box::new(|p: &Problem| *p == Problem::Period { gap: 1., period: 1. }),
+ {
+ let mut b = closed_band();
+ shift(pcurve_of(&mut b, 0, 1), [-1., 0.]);
+ b
+ },
+ ),
+ (
+ "seam from pole to pole on one line",
+ Record::Loop { face: 0, r#loop: 0 },
+ Box::new(|p: &Problem| {
+ matches!(p, Problem::Empty { area } if area.abs() < 1e-9) && p.to_string().starts_with("loop encloses no (u, v) area (signed area ")
+ }),
+ {
+ let mut b = ball();
+ let mid = |b: &mut Brep, k: usize| pcurve_of(b, 0, k).eval(0.).unwrap()[0];
+ let by = mid(&mut b, 0) - mid(&mut b, 1);
+ assert!((by.abs() - TAU).abs() < 1e-9, "a period apart: {by}");
+ shift(pcurve_of(&mut b, 0, 1), [by, 0.]);
+ b
+ },
+ ),
+ (
+ "outer loop clockwise",
+ Record::Loop { face: 0, r#loop: 0 },
+ Box::new(|p: &Problem| {
+ matches!(p, Problem::Turn { outer: true, area } if (*area + 1.).abs() < 1e-12)
+ && p.to_string() == "outer loop runs clockwise in (u, v) (signed area -1)"
+ }),
+ {
+ // The plane's axes swapped turn its natural normal over: the loop, unchanged in
+ // space, runs clockwise about it.
+ let mut b = sheet();
+ if let Surface::Plane { u_axis, v_axis, .. } = &mut b.faces[0].surface {
+ std::mem::swap(u_axis, v_axis);
+ }
+ fit_pcurves(&mut b);
+ b
+ },
+ ),
];
for (name, record, problem, body) in cases {
body.validate().unwrap_or_else(|e| panic!("{name}: structurally valid: {e}"));
diff --git a/crates/geom/src/tess.rs b/crates/geom/src/tess.rs
index eaf31117d5..06cb85e306 100644
--- a/crates/geom/src/tess.rs
+++ b/crates/geom/src/tess.rs
@@ -237,26 +237,37 @@ impl EvalSurface {
}
}
- /// Point and first partial derivatives.
+ /// `uv` with each parameter along which a spline closes on itself moved by whole periods
+ /// into the spline's active knot interval (unchanged inside it, and for any other surface):
+ /// the parameters both evaluators take for a point of a closed spline found a period away.
+ pub fn wrap(&self, uv: [f64; 2]) -> [f64; 2] {
+ let EvalSurface::Nurbs { degree, knots, count, ctrl, .. } = self else { return uv };
+ let range = |d: usize| Some((*knots.get(d)?.get(*degree.get(d)?)?, *knots.get(d)?.get(*count.get(d)?)?));
+ let outside: Vec<usize> = (0..2).filter(|&d| range(d).is_some_and(|(a, b)| !(a..=b).contains(&uv[d]))).collect();
+ if outside.is_empty() {
+ return uv;
+ }
+ let shut = uv::closed(*degree, knots, *count, ctrl);
+ let mut out = uv;
+ for d in outside {
+ if let (true, Some(r)) = (shut[d], range(d)) {
+ out[d] = uv::wrap_into(uv[d], r);
+ }
+ }
+ out
+ }
+
+ /// Point and first partial derivatives (a closed spline's parameters wrapped into its
+ /// active interval first, [`EvalSurface::wrap`]).
pub fn derivs(&self, u: f64, v: f64) -> Option<(Vec3, Vec3, Vec3)> {
if !(u.is_finite() && v.is_finite()) {
return None;
}
match self {
EvalSurface::Plane { origin, du, dv } => Some((*origin + *du * u + *dv * v, *du, *dv)),
- EvalSurface::Nurbs { degree, knots, count, ctrl, closed } => {
- // The knot range of direction `d`: the parameters the surface is defined over.
- let range = |d: usize| -> Option<(f64, f64)> {
- let k = knots.get(d)?;
- Some((*k.get(*degree.get(d)?)?, *k.get(*count.get(d)?)?))
- };
- // A direction the surface joins itself along repeats, so a parameter outside the
- // range is moved by whole ranges back into it. Any other direction is left alone.
- let wrap = |d: usize, t: f64| match range(d) {
- Some((a, b)) if closed.get(d).copied().unwrap_or(false) && b > a && !(a..=b).contains(&t) => a + (t - a).rem_euclid(b - a),
- _ => t,
- };
- nurbs_derivs(*degree, knots, *count, ctrl, wrap(0, u), wrap(1, v))
+ EvalSurface::Nurbs { degree, knots, count, ctrl, .. } => {
+ let [u, v] = self.wrap([u, v]);
+ nurbs_derivs(*degree, knots, *count, ctrl, u, v)
}
EvalSurface::Revolved { profile, origin, axis, transform, swap } => {
let (s, a) = if *swap { (v, u) } else { (u, v) };
diff --git a/crates/geom/src/tess/uv.rs b/crates/geom/src/tess/uv.rs
index 41254bdce3..6dbb085ed4 100644
--- a/crates/geom/src/tess/uv.rs
+++ b/crates/geom/src/tess/uv.rs
@@ -1,6 +1,12 @@
//! Parameters of points on an [`EvalSurface`], on the evaluator's own surface form: a
//! surface's parameter box and periods, the parameters of a point on it (closed form on a plane,
//! damped Gauss–Newton elsewhere), unwrapping across a period, and its poles.
+//!
+//! A spline that closes on itself along a direction (its first and last control rows coincide,
+//! weights included, and its knots are clamped there: a NURBS cylinder, a fillet ring round a
+//! hole's rim) is periodic along it, one active knot interval per period: the record stays as it
+//! is, and parameters outside the interval are evaluated a whole number of periods back inside
+//! it ([`EvalSurface::derivs`]).
use super::EvalSurface;
use crate::Vec3;
@@ -18,9 +24,12 @@ pub fn domain(s: &EvalSurface) -> Domain {
let tau = std::f64::consts::TAU;
match s {
EvalSurface::Plane { .. } => Domain { range: [None, None], period: [None, None] },
- EvalSurface::Nurbs { degree, knots, count, .. } => {
+ EvalSurface::Nurbs { degree, knots, count, ctrl } => {
let r = |d: usize| Some((*knots[d].get(degree[d])?, *knots[d].get(count[d])?));
- Domain { range: [r(0), r(1)], period: [None, None] }
+ let range = [r(0), r(1)];
+ let shut = closed(*degree, knots, *count, ctrl);
+ let period = [0, 1].map(|d| range[d].filter(|_| shut[d]).map(|(a, b)| b - a).filter(|p| *p > 0.0));
+ Domain { range, period }
}
EvalSurface::Revolved { profile, swap, .. } => {
let r = (|| Some((*profile.knots.get(profile.degree)?, *profile.knots.get(profile.ctrl.len())?)))();
@@ -31,6 +40,59 @@ pub fn domain(s: &EvalSurface) -> Domain {
}
}
+/// Relative closeness of a spline's first and last control rows that makes it closed: control
+/// points within this fraction of the control net's extent, weights within this fraction of
+/// their size. Rows written as one (a producer's exact copy) pass; a surface whose ends merely
+/// come near each other does not.
+const CLOSED: f64 = 1e-9;
+
+/// Whether the tensor spline closes on itself along each direction: its knots clamped at both
+/// ends of that direction (so its boundary rows are its edges) and its first and last control
+/// rows the same points with the same weights. Control point `(i, j)` is `ctrl[j·count[0] + i]`.
+pub fn closed(degree: [usize; 2], knots: &[Vec<f64>; 2], count: [usize; 2], ctrl: &[[f64; 4]]) -> [bool; 2] {
+ let [nu, nv] = count;
+ if nu.checked_mul(nv) != Some(ctrl.len()) || nu < 2 || nv < 2 {
+ return [false; 2];
+ }
+ let cart = |c: &[f64; 4]| (c[3] != 0.0).then(|| Vec3::new(c[0] / c[3], c[1] / c[3], c[2] / c[3]));
+ let (mut lo, mut hi) =
+ (Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY));
+ for c in ctrl {
+ let Some(p) = cart(c) else { return [false; 2] };
+ lo = Vec3::new(lo.x.min(p.x), lo.y.min(p.y), lo.z.min(p.z));
+ hi = Vec3::new(hi.x.max(p.x), hi.y.max(p.y), hi.z.max(p.z));
+ }
+ let extent = hi.dist(lo);
+ if !(extent.is_finite() && extent > 0.0) {
+ return [false; 2];
+ }
+ let same = |a: Option<&[f64; 4]>, b: Option<&[f64; 4]>| match (a, b) {
+ (Some(a), Some(b)) => {
+ matches!((cart(a), cart(b)), (Some(p), Some(q)) if p.dist(q) <= CLOSED * extent)
+ && (a[3] - b[3]).abs() <= CLOSED * a[3].abs().max(b[3].abs())
+ }
+ _ => false,
+ };
+ let clamped = |d: usize| {
+ let (p, n, k) = (degree[d], count[d], &knots[d]);
+ let ends = |r: std::ops::RangeInclusive<usize>| k.get(r).is_some_and(|s| s.windows(2).all(|w| w.first() == w.get(1)));
+ k.len() == n + p + 1 && ends(0..=p) && ends(n..=n + p)
+ };
+ let u = clamped(0) && (0..nv).all(|j| same(ctrl.get(j * nu), ctrl.get(j * nu + nu - 1)));
+ let v = clamped(1) && (0..nu).all(|i| same(ctrl.get(i), ctrl.get((nv - 1) * nu + i)));
+ [u, v]
+}
+
+/// `x` moved by whole periods `b − a` into `[a, b]` when it lies outside.
+pub(crate) fn wrap_into(x: f64, (a, b): (f64, f64)) -> f64 {
+ let period = b - a;
+ if (a..=b).contains(&x) || !(period > 0.0) {
+ return x;
+ }
+ let w = x - ((x - a) / period).floor() * period;
+ w.clamp(a, b)
+}
+
impl Domain {
pub fn clamp(&self, uv: [f64; 2]) -> [f64; 2] {
let mut out = uv;
@@ -175,6 +237,52 @@ mod tests {
assert!(project(&s, &dom, Vec3::new(5.0, 0.0, 1.0), None, 1e-3).is_none());
}
+ /// A quadratic spline round a square in u (first and last columns the same), straight
+ /// up in v, `last` moving its last u column.
+ fn ring(last: [f64; 4], u_knots: Vec<f64>) -> EvalSurface {
+ let around =
+ [[2.0, 0.0, 0.0, 1.0], [2.0, 2.0, 0.0, 1.0], [-2.0, 2.0, 0.0, 1.0], [-2.0, -2.0, 0.0, 1.0], [2.0, -2.0, 0.0, 1.0], [2.0, 0.0, 0.0, 1.0]];
+ let mut ctrl = Vec::new();
+ for z in [0.0, 3.0] {
+ for (i, c) in around.iter().enumerate() {
+ let c = if i == around.len() - 1 { [c[0] + last[0], c[1] + last[1], c[2] + last[2], c[3] + last[3]] } else { *c };
+ ctrl.push([c[0] * c[3], c[1] * c[3], (c[2] + z) * c[3], c[3]]);
+ }
+ }
+ EvalSurface::Nurbs { degree: [2, 1], knots: [u_knots, vec![0.0, 0.0, 1.0, 1.0]], count: [6, 2], ctrl }
+ }
+
+ #[test]
+ fn a_spline_closed_on_itself_is_periodic_over_its_knot_interval() {
+ let clamped = || vec![0.0, 0.0, 0.0, 0.25, 0.5, 0.75, 1.0, 1.0, 1.0];
+ let s = ring([0.0; 4], clamped());
+ let EvalSurface::Nurbs { degree, knots, count, ctrl } = &s else { panic!("a spline") };
+ assert_eq!(closed(*degree, knots, *count, ctrl), [true, false]);
+ assert_eq!(domain(&s).period, [Some(1.0), None]);
+ // A period away is the same point; inside the interval nothing moves.
+ for (u, inside) in [(1.25, 0.25), (-0.25, 0.75), (3.6, 0.6)] {
+ let (Some(a), Some(b)) = (s.derivs(u, 0.4), s.derivs(inside, 0.4)) else { panic!("evaluates") };
+ assert!(a.0.dist(b.0) < 1e-12 && a.1.dist(b.1) < 1e-12, "{u}: {a:?} {b:?}");
+ }
+ assert_eq!(s.wrap([1.0, 0.5]), [1.0, 0.5]);
+ assert_eq!(s.wrap([1.25, 2.0]), [0.25, 2.0]);
+ // Projection finds a point near the seam from either side.
+ let p = s.derivs(0.02, 0.5).map(|d| d.0).unwrap_or(Vec3::ZERO);
+ let dom = domain(&s);
+ let Some(q) = project(&s, &dom, p, Some([0.98, 0.5]), 1e-9) else { panic!("projects") };
+ assert!((unwrap(q[0], 0.98, dom.period[0]) - 1.02).abs() < 1e-9, "{q:?}");
+ // Ends that only come near each other, a weight that differs, or unclamped knots: open,
+ // and evaluated past the interval as before (the end span continued).
+ for (what, open) in [
+ ("ends apart", ring([0.0, 1e-6, 0.0, 0.0], clamped())),
+ ("weights differ", ring([0.0, 0.0, 0.0, 1e-6], clamped())),
+ ("unclamped", ring([0.0; 4], vec![-0.5, -0.25, 0.0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5])),
+ ] {
+ assert_eq!(domain(&open).period, [None, None], "{what}");
+ assert_eq!(open.wrap([1.25, 0.5]), [1.25, 0.5], "{what}");
+ }
+ }
+
#[test]
fn unwraps_across_the_period() {
let tau = std::f64::consts::TAU;
diff --git a/crates/kernel/examples/smlib_booleans.rs b/crates/kernel/examples/smlib_booleans.rs
index b214fc06c4..c44e7bf99a 100644
--- a/crates/kernel/examples/smlib_booleans.rs
+++ b/crates/kernel/examples/smlib_booleans.rs
@@ -46,6 +46,7 @@ mod run {
use solidcraft_geom::brep::history::{Change, EdgeOrigin, History};
use solidcraft_kernel::fuzz::{Shape, boolean_shapes};
use solidcraft_kernel::{BoolOp, boolean, measure};
+ use solidcraft_smlib::MEASURE_ACCURACY;
use solidcraft_smlib::history::Order;
const OPS: [BoolOp; 3] = [BoolOp::Union, BoolOp::Intersect, BoolOp::Cut];
@@ -155,7 +156,7 @@ mod run {
Ok(None) => o.empty = true,
Ok(Some(r)) => {
let counts = r.counts().map_err(|e| e.to_string());
- let volume = r.volume(1e-6).map_err(|e| e.to_string());
+ let volume = r.mass_properties(MEASURE_ACCURACY).map(|m| m.volume).map_err(|e| e.to_string());
let history = r
.history()
.map_err(|e| e.to_string())
@@ -178,16 +179,11 @@ mod run {
/// starts from, through their schema 4 records imported into SMLib (`smlib_body`), so both
/// kernels get the same input whatever the axis. Spheres and tori are SMLib's own primitives
/// (about +Z, like truck's): the import doesn't take truck's revolved surfaces yet. The
- /// boolean arrives with the operation shims (smlib_ops.cpp); until then it answers "not
- /// supported yet" and the report counts the case as not run on SMLib.
+ /// boolean is SMLib's own (`Brep::boolean`, through smlib_ops.cpp).
mod side {
use solidcraft_kernel::BoolOp;
use solidcraft_kernel::fuzz::Shape;
- use solidcraft_smlib::Brep;
-
- fn not_yet(what: &str) -> String {
- format!("not supported yet: {what} through the SMLib C API")
- }
+ use solidcraft_smlib::{BooleanOp, Brep};
pub fn shape(s: &Shape) -> Result<Brep, String> {
match s {
@@ -200,12 +196,13 @@ mod run {
}
/// `a op b`; `None` when the result is empty.
- pub fn boolean(_a: &Brep, _b: &Brep, op: BoolOp) -> Result<Option<Brep>, String> {
- Err(not_yet(match op {
- BoolOp::Union => "union",
- BoolOp::Intersect => "intersection",
- BoolOp::Cut => "cut",
- }))
+ pub fn boolean(a: &Brep, b: &Brep, op: BoolOp) -> Result<Option<Brep>, String> {
+ let op = match op {
+ BoolOp::Union => BooleanOp::Union,
+ BoolOp::Intersect => BooleanOp::Intersect,
+ BoolOp::Cut => BooleanOp::Subtract,
+ };
+ a.boolean(b, op).map_err(|e| e.to_string())
}
}
diff --git a/crates/kernel/src/native/adapter_tests.rs b/crates/kernel/src/native/adapter_tests.rs
index 0dbd1bc527..d0ca1a8e2e 100644
--- a/crates/kernel/src/native/adapter_tests.rs
+++ b/crates/kernel/src/native/adapter_tests.rs
@@ -251,3 +251,33 @@ fn smlib_primitives_decode_with_their_volume_and_orientation() {
);
}
}
+
+/// SMLib's fillet round a hole's rim is a rational spline closed on itself in u, bounded by its
+/// seam used twice: the seam's pcurves lie a period apart, so the face meshes and the decoded
+/// body has SMLib's volume (both seam uses on u = 0 left the face empty, 149 mm³ short).
+#[cfg(feature = "smlib")]
+#[test]
+fn smlib_hole_rim_fillet_decodes_with_its_volume() {
+ use solidcraft_smlib::{BooleanOp, Brep as S};
+ let block = S::make_box([0.; 3], [20.; 3]).unwrap();
+ let pin = S::make_cylinder([10., 10., -1.], 4., 22.).unwrap();
+ let holed = block.boolean(&pin, BooleanOp::Subtract).unwrap().unwrap();
+ let rim = holed.fillet(&[[10., 14., 20.]], 0.1, 1.).unwrap();
+ let record = rim.to_native().unwrap();
+ assert!(
+ record
+ .faces
+ .iter()
+ .any(|f| matches!(&f.surface, b::Surface::RationalSpline { homogeneous, .. } if homogeneous.first() == homogeneous.last())),
+ "the fillet is a spline closed in u"
+ );
+ record.check_geometry().unwrap();
+ let body = crate::native::body_from_smlib(&rim).unwrap();
+ let mesh = body.tessellate(0.02).unwrap();
+ for f in 0..body.face_count() {
+ assert!(mesh.tri_face.iter().any(|&t| t as usize == f), "face {f} meshes");
+ }
+ let smlib = rim.mass_properties(solidcraft_smlib::MEASURE_ACCURACY).unwrap().volume;
+ let ours = crate::measure(&body).unwrap().volume;
+ assert!((ours - smlib).abs() < 1e-3 * smlib, "decoded volume {ours}, SMLib's {smlib}");
+}
diff --git a/crates/kernel/src/tess/mod.rs b/crates/kernel/src/tess/mod.rs
index 93a7b573c8..a787bfea56 100644
--- a/crates/kernel/src/tess/mod.rs
+++ b/crates/kernel/src/tess/mod.rs
@@ -737,6 +737,10 @@ fn plan_face(
}
let mut all = uvs;
all.extend(extra);
+ // Both evaluators take a closed spline's parameters inside its active interval.
+ for q in &mut all {
+ *q = s.wrap(*q);
+ }
Ok(FacePlan { face: u32::try_from(fi).unwrap_or(u32::MAX), surface: None, uv: all, fixed, normals: Vec::new(), flip: false, triangles })
}
diff --git a/docs/native-brep.md b/docs/native-brep.md
index ebadb064ce..911e8130d7 100644
--- a/docs/native-brep.md
+++ b/docs/native-brep.md
@@ -52,8 +52,11 @@ shells with opposite `forward`. `forward` means the face's normal in that shell
its surface's natural normal, ∂S/∂u × ∂S/∂v. In a closed shell, normals point out
of the material.
-**Loops.** A face's first loop is its outer loop and is an edge loop. A vertex
-loop (a pole, a collapsed boundary) is only ever an inner loop. Loops are stored
+**Loops.** A face has one outer loop and any number of inner ones, in the
+producer's order: truck lists some holes before the outer loop, and an SMLib
+import puts the outer loop first, as SMLib requires. The first loop is an edge
+loop. A vertex loop (a pole, a collapsed boundary) is only ever an inner loop.
+Orientation tells outer from inner. Loops are stored
relative to the surface's natural normal, whichever side a shell uses: seen from
that normal, the outer loop runs counter-clockwise and inner loops clockwise.
This lets one face sit in two shells without contradicting itself. An edge loop
@@ -82,7 +85,7 @@ paint and persistent names. The same holds for edges and vertices.
1. Regions: the infinite region, then bounded regions in the producer's order.
2. Shells and faces in order of first appearance, walking regions → shells →
oriented faces.
-3. Edges in order of first appearance, walking faces → loops (outer first) →
+3. Edges in order of first appearance, walking faces → loops (in stored order) →
oriented edges, then wire edges walking shells. A face whose first oriented
face is reversed is walked backwards: each of its loops from its last
oriented edge to its first. That is how a reversed face is traversed.
@@ -158,7 +161,12 @@ max, whatever the oriented edge's direction. Its interval must equal the edge's
within 10⁻⁹ of the interval's magnitude (at least 1), room for a linear remap's
rounding. A seam edge has two uses on one face, each with its own pcurve, a
period apart. On a periodic surface a loop's pcurves are unwrapped, so each one
-starts where the one before it ends.
+starts where the one before it ends. A spline surface that closes on itself in a
+direction (knots clamped there, first and last control rows the same points with
+the same weights, within 10⁻⁹ of the control net's extent) is periodic in it for
+pcurves and tessellation, one active knot interval per period: a seam on it has
+its two uses an interval apart. The record is unchanged; a parameter outside the
+interval is evaluated a whole number of periods back inside it.
Pcurves are SolidCraft's own, never a kernel's internal parameter space:
`brep::pcurve::pcurves` computes them from a face's surface record and each
@@ -196,8 +204,11 @@ ends (within the edge's and the vertex's tolerances together); every oriented
edge's pcurve, lifted through its face's surface, lies on the edge's curve at the
interval's ends and middle (within the edge's) and starts on the same period as
the use before it ends, except along a direction that collapses at a pole; every
-vertex loop's vertex lies on its face's surface (within the vertex's). It makes a
-fixed number of evaluations per record, so its work is linear in the item
+edge loop's pcurves enclose (u, v) area (more than 10⁻⁹ of the square of the
+loop's extent), and exactly one loop of each face, the outer, runs
+counter-clockwise about the natural normal, the rest clockwise (told apart by
+their areas, not their order); every vertex loop's vertex lies on its face's
+surface (within the vertex's). It makes a fixed number of evaluations per record, so its work is linear in the item
budget, and a point it cannot evaluate is an error naming the record. It is not
a certificate either: between the points it checks, an edge may still leave its
surface. The truck adapter runs it before building topology, which truck does