SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Wave 55/509: kernel: spline edges on part of their curve load as that piece (and 2 more)
jyvikoad3951979414
diff --git a/crates/geom/src/bspline.rs b/crates/geom/src/bspline.rsindex 8b2cf84f86..27fa125550 100644--- a/crates/geom/src/bspline.rs+++ b/crates/geom/src/bspline.rs@@ -343,6 +343,46 @@ pub fn insert_knot(p: usize, knots: &[f64], ctrl: &[HPoint], u: f64) -> SplineReOk((nk, q))}+/// The piece of a B-spline (degree `p`, knots, homogeneous control points) on `[a, b]`, a+/// sub-interval of its domain, as a clamped B-spline of its own whose domain is exactly+/// `[a, b]`: the same points at the same parameters. Exact up to rounding: Boehm insertion of+/// `a` and `b` until each has multiplicity `p` (NURBS Book §5.3, curve splitting), then the+/// knots and control points between them.+pub fn segment(p: usize, knots: &[f64], ctrl: &[HPoint], a: f64, b: f64) -> SplineResult<(Vec<f64>, Vec<HPoint>)> {+ let n = ctrl.len();+ if n <= p || knots.len() != n + p + 1 {+ return invalid("knot and control point counts do not match the degree");+ }+ let (lo, hi) = (knots.get(p).copied().unwrap_or(f64::NAN), knots.get(n).copied().unwrap_or(f64::NAN));+ if !(lo <= a && a < b && b <= hi) {+ return invalid(format!("[{a}, {b}] is not a piece of the domain [{lo}, {hi}]"));+ }+ let (mut k, mut c) = (knots.to_vec(), ctrl.to_vec());+ for t in [a, b] {+ // At most p insertions each.+ for _ in 0..p {+ if k.iter().filter(|&&x| x == t).count() >= p {+ break;+ }+ (k, c) = insert_knot(p, &k, &c, t)?;+ }+ }+ // The curve at a (from the right) is control point j0 − p, j0 the last knot equal to a;+ // at b (from the left) control point j1 − 1, j1 the first knot equal to b.+ let j0 = k.iter().rposition(|&x| x == a).filter(|&j| j >= p).ok_or_else(|| SplineError::Invalid("segment start".into()))?;+ let j1 = k.iter().position(|&x| x == b).filter(|&j| j > j0).ok_or_else(|| SplineError::Invalid("segment end".into()))?;+ let points = c.get(j0 - p..j1).ok_or_else(|| SplineError::Invalid("segment control points".into()))?.to_vec();+ let inner = k.get(j0 + 1..j1).ok_or_else(|| SplineError::Invalid("segment knots".into()))?;+ let mut out = Vec::with_capacity(inner.len() + 2 * p + 2);+ out.extend(std::iter::repeat_n(a, p + 1));+ out.extend_from_slice(inner);+ out.extend(std::iter::repeat_n(b, p + 1));+ if out.len() != points.len() + p + 1 {+ return invalid("segment counts");+ }+ Ok((out, points))+}+/// The binomial coefficient `(n k)` (zero for `k > n`).pub(crate) fn binomial(n: usize, k: usize) -> f64 {if k > n {@@ -714,6 +754,35 @@ pub(crate) mod tests {assert_eq!(find_span(&knots, p, n, f64::NAN), None);}+ #[test]+ fn a_segment_is_the_same_curve_on_its_interval() {+ use crate::brep::{Curve, eval::CurveEval};+ let p = 3;+ let mut rng = Lcg(11);+ let ctrl: Vec<HPoint> = (0..KNOTS.len() - p - 1)+ .map(|_| HPoint::weighted(Vec3::new(rng.unit() * 10.0, rng.unit() * 10.0, rng.unit() * 10.0), 0.5 + rng.unit()))+ .collect();+ let record =+ |k: &[f64], c: &[HPoint]| Curve::RationalSpline { knots: k.to_vec(), homogeneous: c.iter().map(|h| [h.x, h.y, h.z, h.w]).collect() };+ let whole = CurveEval::new(&record(&KNOTS, &ctrl)).unwrap();+ // Inside one span, across knots (a double one included), from or to a domain end, and+ // from one existing knot to another.+ for (a, b) in [(0.1, 0.2), (0.12, 0.95), (0.0, 0.42), (0.3, 1.0), (0.3, 0.5), (0.0, 1.0)] {+ let (k, c) = segment(p, &KNOTS, &ctrl, a, b).unwrap();+ assert_eq!((k.first(), k.last()), (Some(&a), Some(&b)), "[{a}, {b}]: clamped on the interval");+ assert_eq!(k.len(), c.len() + p + 1);+ let piece = CurveEval::new(&record(&k, &c)).unwrap();+ for x in samples() {+ let t = a + (b - a) * x;+ let (q, r) = (whole.point(t).unwrap(), piece.point(t).unwrap());+ assert!(q.dist(r) < 1e-12, "[{a}, {b}] at {t}: {q:?} vs {r:?}");+ }+ }+ assert!(segment(p, &KNOTS, &ctrl, 0.5, 0.5).is_err());+ assert!(segment(p, &KNOTS, &ctrl, -0.1, 0.5).is_err());+ assert!(segment(p, &KNOTS, &ctrl, 0.2, f64::NAN).is_err());+ }+#[test]fn single_function_knot_insertion_is_exact() {let mut rng = Lcg(7);diff --git a/crates/geom/src/tess.rs b/crates/geom/src/tess.rsindex 06cb85e306..b1f6b7f7c6 100644--- a/crates/geom/src/tess.rs+++ b/crates/geom/src/tess.rs@@ -237,10 +237,23 @@ impl EvalSurface {}}- /// `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.+ /// `uv` with each parameter along which a spline closes on itself (or a revolution's+ /// profile does) moved by whole periods into the 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] {+ if let EvalSurface::Revolved { profile, swap, .. } = self {+ let d = usize::from(*swap);+ let range = (|| Some((*profile.knots.get(profile.degree)?, *profile.knots.get(profile.ctrl.len())?)))();+ let mut out = uv;+ if let (Some(r), Some(x)) = (range, out.get_mut(d))+ && !(r.0..=r.1).contains(x)+ && uv::closed_curve(profile)+ {+ *x = uv::wrap_into(*x, r);+ }+ return out;+ }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();@@ -270,6 +283,7 @@ impl EvalSurface {nurbs_derivs(*degree, knots, *count, ctrl, u, v)}EvalSurface::Revolved { profile, origin, axis, transform, swap } => {+ let [u, v] = self.wrap([u, v]);let (s, a) = if *swap { (v, u) } else { (u, v) };let (c, dc) = profile.eval(s)?;let (sin, cos) = a.sin_cos();diff --git a/crates/geom/src/tess/uv.rs b/crates/geom/src/tess/uv.rsindex 6dbb085ed4..db303dd83b 100644--- a/crates/geom/src/tess/uv.rs+++ b/crates/geom/src/tess/uv.rs@@ -6,7 +6,8 @@//! 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`]).+//! it ([`EvalSurface::derivs`]). So is a revolution along a profile closed on itself (a torus's+//! whole circle).use super::EvalSurface;use crate::Vec3;@@ -33,7 +34,10 @@ pub fn domain(s: &EvalSurface) -> Domain {}EvalSurface::Revolved { profile, swap, .. } => {let r = (|| Some((*profile.knots.get(profile.degree)?, *profile.knots.get(profile.ctrl.len())?)))();- let (a, b) = ((r, None), (Some((0.0, tau)), Some(tau)));+ // A profile closed on itself (a whole circle: a torus as another kernel writes it)+ // is periodic along the profile too.+ let along = r.filter(|_| closed_curve(profile)).map(|(a, b)| b - a).filter(|p| *p > 0.0);+ let (a, b) = ((r, along), (Some((0.0, tau)), Some(tau)));let (u, v) = if *swap { (b, a) } else { (a, b) };Domain { range: [u.0, v.0], period: [u.1, v.1] }}@@ -46,6 +50,13 @@ pub fn domain(s: &EvalSurface) -> Domain {/// come near each other does not.const CLOSED: f64 = 1e-9;+/// Whether a spline curve closes on itself: its knots clamped at both ends and its first and+/// last control points the same, weights included ([`closed`] for a curve).+pub fn closed_curve(c: &super::EvalCurve) -> bool {+ let Some(extent) = net_extent(&c.ctrl) else { return false };+ c.ctrl.len() >= 2 && clamped(c.degree, c.ctrl.len(), &c.knots) && same_point(c.ctrl.first(), c.ctrl.last(), extent)+}+/// 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]`.@@ -54,33 +65,45 @@ pub fn closed(degree: [usize; 2], knots: &[Vec<f64>; 2], count: [usize; 2], ctrlif 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 Some(extent) = net_extent(ctrl) else { return [false; 2] };+ let same = |a, b| same_point(ctrl.get(a), ctrl.get(b), extent);+ let u = clamped(degree[0], nu, &knots[0]) && (0..nv).all(|j| same(j * nu, j * nu + nu - 1));+ let v = clamped(degree[1], nv, &knots[1]) && (0..nu).all(|i| same(i, (nv - 1) * nu + i));+ [u, v]+}++fn cartesian(c: &[f64; 4]) -> Option<Vec3> {+ (c[3] != 0.0).then(|| Vec3::new(c[0] / c[3], c[1] / c[3], c[2] / c[3]))+}++/// The diagonal of a control net's box; `None` when a weight vanishes or the net is a point.+fn net_extent(ctrl: &[[f64; 4]]) -> Option<f64> {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] };+ let p = cartesian(c)?;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) {+ (extent.is_finite() && extent > 0.0).then_some(extent)+}++/// Two control points the same within [`CLOSED`] of the net's extent, weights included.+fn same_point(a: Option<&[f64; 4]>, b: Option<&[f64; 4]>, extent: f64) -> bool {+ match (a, b) {(Some(a), Some(b)) => {- matches!((cart(a), cart(b)), (Some(p), Some(q)) if p.dist(q) <= CLOSED * extent)+ matches!((cartesian(a), cartesian(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]+ }+}++/// Knots of degree `p` over `n` control points, clamped at both ends.+fn clamped(p: usize, n: usize, k: &[f64]) -> bool {+ 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)}/// `x` moved by whole periods `b − a` into `[a, b]` when it lies outside.@@ -283,6 +306,46 @@ mod tests {}}+ /// A revolution of a whole circle (a torus, the profile a rational quadratic closed on+ /// itself) is periodic along the profile too, over its knot interval; a cylinder's line+ /// profile is not.+ #[test]+ fn a_revolution_of_a_closed_profile_is_periodic_along_it() {+ let w = std::f64::consts::FRAC_1_SQRT_2;+ // The circle of radius 1 about (3, 0, 0) in the xz plane, four quarter arcs.+ let pts = [[4.0, 0.0], [4.0, 1.0], [3.0, 1.0], [2.0, 1.0], [2.0, 0.0], [2.0, -1.0], [3.0, -1.0], [4.0, -1.0], [4.0, 0.0]];+ let ctrl: Vec<[f64; 4]> = pts+ .iter()+ .enumerate()+ .map(|(i, [x, z])| {+ let wt = if i % 2 == 1 { w } else { 1.0 };+ [x * wt, 0.0, z * wt, wt]+ })+ .collect();+ let knots = vec![0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0];+ for swap in [false, true] {+ let s = EvalSurface::Revolved {+ profile: EvalCurve { degree: 2, knots: knots.clone(), ctrl: ctrl.clone() },+ origin: Vec3::ZERO,+ axis: Vec3::Z,+ transform: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]],+ swap,+ };+ let (along, around) = if swap { (1, 0) } else { (0, 1) };+ let dom = domain(&s);+ assert_eq!((dom.period[along], dom.period[around]), (Some(1.0), Some(std::f64::consts::TAU)), "swap {swap}");+ let at = |t: f64, a: f64| if swap { [a, t] } else { [t, a] };+ let wrapped = s.wrap(at(1.3, 0.4));+ assert!((wrapped[along] - 0.3).abs() < 1e-12 && wrapped[around] == 0.4, "swap {swap}: {wrapped:?}");+ assert_eq!(s.wrap(at(0.3, 7.0)), at(0.3, 7.0), "the angle is left alone");+ let (Some(p), Some(q)) = (s.derivs(at(1.3, 0.4)[0], at(1.3, 0.4)[1]), s.derivs(at(0.3, 0.4)[0], at(0.3, 0.4)[1])) else {+ panic!("evaluates")+ };+ assert!(p.0.dist(q.0) < 1e-12, "swap {swap}: {p:?} {q:?}");+ }+ assert_eq!(domain(&cylinder()).period, [None, Some(std::f64::consts::TAU)]);+ }+#[test]fn unwraps_across_the_period() {let tau = std::f64::consts::TAU;diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rsindex 5877fb3d86..f63cc99b58 100644--- a/crates/kernel/src/body.rs+++ b/crates/kernel/src/body.rs@@ -440,6 +440,13 @@ fn rephase_revolved(solid: Solid) -> Solid {faces.push(f.clone());continue;};+ // A face bounded by a seam it uses both ways goes all the way round (SMLib's+ // sphere, torus or cylinder side as one face): its wrap belongs on that seam,+ // and turning the surface would run it through the face or one of its holes.+ if uses_an_edge_twice(f) {+ faces.push(f.clone());+ continue;+ }let surf = f.surface();// The face's middle angle.let mut acc = Vec3::ZERO;@@ -494,6 +501,12 @@ fn rephase_revolved(solid: Solid) -> Solid {}}+/// Whether a face's boundary uses one edge twice (a seam).+fn uses_an_edge_twice(f: &mt::Face) -> bool {+ let mut seen = std::collections::HashSet::new();+ f.boundaries().iter().flat_map(|w| w.edge_iter()).any(|e| !seen.insert(e.id()))+}+pub(crate) fn p3(v: Vec3) -> mt::Point3 {mt::Point3::new(v.x, v.y, v.z)}@@ -674,6 +687,16 @@ impl Body {})}+ /// Like [`Body::new`], for a solid whose faces already point out of its material as+ /// recorded (another kernel's B-rep, through its schema 4 record): revolved faces turned as+ /// `new` turns them, the orientation kept. `new` orients by the volume of truck's coarse+ /// mesh, which leaves out a face it cannot mesh (SMLib's sphere bounded by its seam alone)+ /// and then turns a correct body inside out.+ #[cfg_attr(not(feature = "smlib"), allow(dead_code))]+ pub(crate) fn oriented(solid: Solid) -> Result<Body> {+ Body::new_placed(solid, false, None, false)+ }+/// Like [`Body::new`], for a solid made by placing an already-oriented body (see/// [`crate::ops::transform_matrix`]): a placement keeps the faces pointing the way they did/// unless it mirrors them, so its orientation is read from the matrix rather than mesheddiff --git a/crates/kernel/src/native.rs b/crates/kernel/src/native.rsindex 0baffb2c91..ac6da1eccb 100644--- a/crates/kernel/src/native.rs+++ b/crates/kernel/src/native.rs@@ -154,11 +154,11 @@ pub fn decode_native_body(bytes: &[u8]) -> Result<Body> {/// An SMLib body as a kernel body, through its schema 4 record: SMLib's export mapped by/// `solidcraft_smlib` (canonical order, radians, pcurves), then this adapter's decode of a/// foreign record (analytic surfaces as truck's revolutions). The body is oriented as the record-/// says; `Body::new` only measures it.+/// says (`Body::oriented`), never by meshing it.#[cfg(feature = "smlib")]pub fn body_from_smlib(brep: &solidcraft_smlib::Brep) -> Result<Body> {let record = brep.to_native().map_err(|e| KernelError::Failed(e.to_string()))?;- guard("decode SMLib B-rep", || Body::new(adapter::decode_from(record, adapter::Producer::Foreign)?))+ guard("decode SMLib B-rep", || Body::oriented(adapter::decode_from(record, adapter::Producer::Foreign)?))}fn validate_topology(saved: &SavedBody) -> Result<()> {diff --git a/crates/kernel/src/native/adapter.rs b/crates/kernel/src/native/adapter.rsindex fa2bd631b1..3caadce783 100644--- a/crates/kernel/src/native/adapter.rs+++ b/crates/kernel/src/native/adapter.rs@@ -473,8 +473,9 @@ fn save_surface(s: &mt::Surface, d: usize) -> Result<b::Surface> {}/// An edge's curve for truck, which bounds an edge by its curve's range: the record itself-/// where the interval is that range (all this adapter writes), else the piece on the interval-/// for the kinds that have one in closed form.+/// where the interval is that range (all this adapter writes), else the piece on the interval:+/// in closed form for lines and conics, cut out of a spline by knot insertion (the same points+/// at the same parameters).fn load_edge_curve(c: b::Curve, interval: [f64; 2]) -> Result<mt::Curve> {match c {b::Curve::Line { start, end } if interval != [0., 1.] => {@@ -486,10 +487,35 @@ fn load_edge_curve(c: b::Curve, interval: [f64; 2]) -> Result<mt::Curve> {b::Curve::Line { .. } => load_curve(c),c => match c.natural() {b::Natural::Range(a, z) if [a, z] == interval => load_curve(c),- _ => Err(unsupported("a spline or intersection edge on part of its curve")),+ b::Natural::Range(..) if matches!(c, b::Curve::Spline { .. } | b::Curve::RationalSpline { .. }) => {+ load_curve(spline_piece(&c, interval)?)+ }+ _ => Err(unsupported("an intersection edge on part of its curve")),},}}++/// A spline record's piece on `interval` (inside its domain), as a spline record of the same+/// kind whose domain is the interval ([`solidcraft_geom::bspline::segment`]).+fn spline_piece(c: &b::Curve, [a, z]: [f64; 2]) -> Result<b::Curve> {+ use solidcraft_geom::bspline::{HPoint, segment};+ let (knots, h): (&[f64], Vec<HPoint>) = match c {+ b::Curve::Spline { knots, points } => (knots, points.iter().map(|q| HPoint { x: q[0], y: q[1], z: q[2], w: 1.0 }).collect()),+ b::Curve::RationalSpline { knots, homogeneous } => {+ (knots, homogeneous.iter().map(|q| HPoint { x: q[0], y: q[1], z: q[2], w: q[3] }).collect())+ }+ _ => return Err(invalid("not a spline")),+ };+ let degree = knots.len().checked_sub(h.len() + 1).ok_or_else(|| invalid("spline degree"))?;+ let (knots, h) = segment(degree, knots, &h, a, z).map_err(invalid)?;+ Ok(match c {+ b::Curve::Spline { .. } => b::Curve::Spline {+ knots,+ points: h.iter().map(|q| q.project().map(|v| [v.x, v.y, v.z]).ok_or_else(|| invalid("spline piece"))).collect::<Result<_>>()?,+ },+ _ => b::Curve::RationalSpline { knots, homogeneous: h.iter().map(|q| [q.x, q.y, q.z, q.w]).collect() },+ })+}fn load_curve(c: b::Curve) -> Result<mt::Curve> {Ok(match c {b::Curve::Line { start, end } => mt::Curve::Line(mt::Line(p(start), p(end))),diff --git a/crates/kernel/src/native/adapter_tests.rs b/crates/kernel/src/native/adapter_tests.rsindex d0ca1a8e2e..505677183f 100644--- a/crates/kernel/src/native/adapter_tests.rs+++ b/crates/kernel/src/native/adapter_tests.rs@@ -9,12 +9,38 @@ fn refuses_domain_or_axis_changes_instead_of_approximating() {let plane = b::Surface::Plane { origin: [1e12; 3], u_axis: [1e-6, 0., 0.], v_axis: [0., 1., 0.] };assert!(compatible_surface(&plane).is_err());assert!(clamped(&[0., 0., 1., 1.], 2).is_ok());- // A spline edge on part of its curve would need truck to cut it: refused, not refitted.let spline = b::Curve::Spline { knots: vec![0., 0., 1., 1.], points: vec![[0.; 3], [1.; 3]] };- assert!(load_edge_curve(spline.clone(), [0., 0.5]).is_err());assert!(load_edge_curve(spline, [0., 1.]).is_ok());}+/// A spline edge on part of its curve (SMLib bounds an intersection edge on a piece of its+/// spline) loads as the piece cut out by knot insertion, not a refit: the same points at the+/// same parameters, over exactly the interval.+#[test]+fn spline_edges_on_part_of_their_curve_load_as_that_piece() {+ use mt::ParametricCurve;+ let knots = vec![0., 0., 0., 0., 0.4, 0.4, 0.7, 1., 1., 1., 1.];+ let points: Vec<[f64; 3]> = (0..7).map(|i| [f64::from(i), (f64::from(i) * 1.3).sin() * 4., f64::from(i * i) * 0.2]).collect();+ let weights = [1., 0.8, 1.3, 0.9, 1.1, 0.7, 1.];+ let rational = b::Curve::RationalSpline {+ knots: knots.clone(),+ homogeneous: points.iter().zip(weights).map(|(q, w)| [q[0] * w, q[1] * w, q[2] * w, w]).collect(),+ };+ for record in [b::Curve::Spline { knots, points }, rational] {+ let exact = solidcraft_geom::brep::eval::CurveEval::new(&record).unwrap();+ for interval in [[0.1, 0.35], [0.25, 0.9], [0., 0.4], [0.4, 1.]] {+ let piece = load_edge_curve(record.clone(), interval).unwrap();+ assert_eq!(piece.range_tuple(), (interval[0], interval[1]), "{interval:?}");+ for k in 0..=20 {+ let t = interval[0] + (interval[1] - interval[0]) * f64::from(k) / 20.;+ let (q, r) = (piece.subs(t), exact.point(t).unwrap());+ assert!((q - p([r.x, r.y, r.z])).magnitude() < 1e-12, "{interval:?} at {t}");+ }+ }+ assert!(load_edge_curve(record, [0.5, 1.2]).is_err(), "beyond the curve's domain");+ }+}+#[test]fn analytic_records_decode_as_their_mathematical_loci_and_normals() {use mt::{MetricSpace, ParametricSurface, ParametricSurface3D};@@ -281,3 +307,116 @@ fn smlib_hole_rim_fillet_decodes_with_its_volume() {let ours = crate::measure(&body).unwrap().volume;assert!((ours - smlib).abs() < 1e-3 * smlib, "decoded volume {ours}, SMLib's {smlib}");}++/// SMLib's sphere cut by a box keeps its meridian seam from pole to pole: whole beside a cap+/// cut away from it, split where the cap crosses it. Decoded, each body is oriented as its+/// record says (never by truck's coarse mesh, which leaves the seam-bounded sphere out and+/// turned one inside out), the sphere keeps its wrap on its seam and every face meshes: the+/// volume is the sphere's less the cap, within 1e-3 (it came out −V, or short by the sphere).+#[cfg(feature = "smlib")]+#[test]+fn smlib_spheres_cut_beside_or_across_their_seam_decode_with_their_volume() {+ use solidcraft_smlib::{BooleanOp, Brep as S};+ use std::f64::consts::PI;+ let (r, h) = (5., 2.);+ let exact = 4. / 3. * PI * r * r * r - PI * h * h * (3. * r - h) / 3.;+ // The seam is the meridian on +x: a cap on −x or +y leaves it whole, one on +x splits it.+ let caps =+ [("−x", [-10., -10., -10.], [h - r, 10., 10.]), ("+x", [r - h, -10., -10.], [10., 10., 10.]), ("+y", [-10., r - h, -10.], [10., 10., 10.])];+ for (name, lo, hi) in caps {+ let ball = S::make_sphere([0.; 3], r).unwrap();+ let tool = S::make_box(lo, [hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]]).unwrap();+ let cut = ball.boolean(&tool, BooleanOp::Subtract).unwrap().unwrap();+ let record = cut.to_native().unwrap();+ record.check_geometry().unwrap();+ crate::body::ORIENTED.with(|n| n.set(0));+ let body = crate::native::body_from_smlib(&cut).unwrap();+ assert_eq!(crate::body::ORIENTED.with(|n| n.get()), 0, "{name}: the decode meshed the body to orient it");+ let forward: Vec<bool> = record+ .shells+ .iter()+ .flat_map(|sh| match sh {+ b::Shell::Faces { faces, .. } => faces.iter().map(|f| f.forward).collect(),+ _ => Vec::new(),+ })+ .collect();+ let loaded: Vec<bool> = body.solid.boundaries().iter().flat_map(|sh| sh.face_iter().map(|f| f.orientation()).collect::<Vec<_>>()).collect();+ assert_eq!(loaded, forward, "{name}: the body was turned inside out");+ 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), "{name}: face {f} meshes");+ }+ let ours = crate::measure(&body).unwrap().volume;+ assert!((ours - exact).abs() < 1e-3 * exact, "{name}: decoded volume {ours}, exact {exact}");+ }+ // A bar bored into the sphere's side away from its seam: truck's turning of revolved faces+ // away from their wrap ran the wrap through the hole, and the face meshed as nothing. The+ // volume the bar takes, by midpoint rule over its disc of the chord inside the ball.+ let (c, big, y0, z0, x0, x1, rb) = ([25., 17.5, 2.5], 10., 22.5, 10., 12.5, 30., 2.5);+ let n = 400;+ let mut taken = 0.;+ for i in 0..n {+ let rho = rb * (f64::from(i) + 0.5) / f64::from(n);+ for j in 0..n {+ let t = 2. * PI * (f64::from(j) + 0.5) / f64::from(n);+ let (y, z) = (y0 + rho * t.cos(), z0 + rho * t.sin());+ let d = big * big - (y - c[1]).powi(2) - (z - c[2]).powi(2);+ if d > 0. {+ taken += ((c[0] + d.sqrt()).min(x1) - (c[0] - d.sqrt()).max(x0)).max(0.) * rho;+ }+ }+ }+ let exact = 4. / 3. * PI * big.powi(3) - taken * rb / f64::from(n) * 2. * PI / f64::from(n);+ let ball = S::make_sphere(c, big).unwrap();+ let bar = crate::cylinder(Vec3::new(x0, y0, z0), Vec3::X, rb, x1 - x0).unwrap();+ let cut = ball.boolean(&crate::native::smlib_body(&bar).unwrap(), BooleanOp::Subtract).unwrap().unwrap();+ let ours = crate::measure(&crate::native::body_from_smlib(&cut).unwrap()).unwrap().volume;+ assert!((ours - exact).abs() < 1e-3 * exact, "bored: decoded volume {ours}, exact {exact}");+}++/// SMLib's torus is one face bounded by its two seam circles, each used both ways: the display+/// plan treats the closed profile as periodic, so the torus meshes and, beside a sphere bounded+/// by its seam alone (which only the plan meshes), the body keeps both (the sphere was lost).+/// The decode never meshes the body (it took half a second, meshing a torus to orient it).+#[cfg(feature = "smlib")]+#[test]+fn smlib_torus_decodes_without_meshing_and_plans_with_a_sphere_beside_it() {+ use solidcraft_smlib::{BooleanOp, Brep as S};+ use std::f64::consts::PI;+ let ring = S::make_torus([0., 30., 15.], 7.5, 2.5).unwrap();+ let ball = S::make_sphere([2.5, 15., 7.5], 2.5).unwrap();+ let (torus, sphere) = (2. * PI * PI * 7.5 * 2.5 * 2.5, 4. / 3. * PI * 2.5 * 2.5 * 2.5);+ let both = ring.boolean(&ball, BooleanOp::Union).unwrap().unwrap();+ for (name, s, exact) in [("torus", ring, torus), ("torus and sphere", both, torus + sphere)] {+ crate::body::ORIENTED.with(|n| n.set(0));+ let body = crate::native::body_from_smlib(&s).unwrap();+ assert_eq!(crate::body::ORIENTED.with(|n| n.get()), 0, "{name}: the decode meshed the body to orient it");+ let plan = body.display_plan(0.05).unwrap_or_else(|e| panic!("{name}: {e}"));+ assert_eq!(plan.faces.len(), body.face_count(), "{name}");+ let ours = crate::measure(&body).unwrap().volume;+ assert!((ours - exact).abs() < 1e-3 * exact, "{name}: decoded volume {ours}, exact {exact}");+ }+}++/// SMLib's intersection of a block and a cylinder bounds the top disc with spline edges on+/// part of their curves: the body decodes (it was refused) with the cylinder's volume inside+/// the block, π r² h.+#[cfg(feature = "smlib")]+#[test]+fn smlib_spline_edges_on_part_of_their_curve_decode() {+ use solidcraft_smlib::BooleanOp;+ let block = crate::box_solid(Vec3::new(7.5, 15., 0.), Vec3::new(25., 32.5, 27.5)).unwrap();+ let post = crate::cylinder(Vec3::new(12.5, 20., 10.), Vec3::Z, 5., 30.).unwrap();+ let (a, c) = (crate::native::smlib_body(&block).unwrap(), crate::native::smlib_body(&post).unwrap());+ let common = a.boolean(&c, BooleanOp::Intersect).unwrap().unwrap();+ let record = common.to_native().unwrap();+ assert!(+ record.edges.iter().any(|e| matches!(e.curve.natural(), b::Natural::Range(lo, hi) if [lo, hi] != e.interval)+ && matches!(e.curve, b::Curve::Spline { .. } | b::Curve::RationalSpline { .. })),+ "a spline edge on part of its curve"+ );+ let body = crate::native::body_from_smlib(&common).unwrap();+ let exact = std::f64::consts::PI * 25. * 17.5;+ let ours = crate::measure(&body).unwrap().volume;+ assert!((ours - exact).abs() < 1e-3 * exact, "decoded volume {ours}, exact {exact}");+}diff --git a/crates/kernel/src/tess/mod.rs b/crates/kernel/src/tess/mod.rsindex a787bfea56..f22c9f3d61 100644--- a/crates/kernel/src/tess/mod.rs+++ b/crates/kernel/src/tess/mod.rs@@ -466,17 +466,22 @@ fn off_surface(rules: &size::Rules) -> f64 {(rules.extent * ON_SURFACE).max(rules.boundary_tol.unwrap_or(0.0)).max(1e-6)}-/// One face: boundary loops in 3D (shared edge nodes) to parameters and triangles.-/// `size`: the face's target side length (mm) and the surface's mean speed along u and v.-/// Whether a face of `solid` is bounded by one seam edge alone, used both ways between two-/// distinct vertices (poles): a whole sphere as one face, as SMLib writes it. Truck's mesher-/// projects both uses onto one parameter line and meshes nothing; the display plan opens the-/// loop across the period ([`open_pole_to_pole`]).+/// Whether a face of `solid` has a loop that runs along a seam edge between two distinct+/// vertices and straight back along it, the two uses one after the other (they meet at a pole):+/// a whole sphere as one face bounded by its meridian alone, as SMLib writes it, or a sphere+/// face whose meridian is split where a trim crosses it. Truck's mesher projects both uses onto+/// one parameter line and meshes nothing; the display plan opens the loop across the period+/// ([`open_pole_to_pole`]).pub(crate) fn has_pole_to_pole_seam(solid: &Solid) -> bool {solid.face_iter().any(|f| {f.boundaries().iter().any(|w| {let edges: Vec<&mt::Edge> = w.edge_iter().collect();- matches!(edges.as_slice(), [a, b] if a.id() == b.id() && a.front() != a.back())+ let n = edges.len();+ n >= 2+ && (0..n).any(|k| match (edges.get(k), edges.get((k + 1) % n)) {+ (Some(a), Some(b)) => a.id() == b.id() && a.orientation() != b.orientation() && a.front() != a.back(),+ _ => false,+ })})})}@@ -487,21 +492,24 @@ fn area2(uv: &[[f64; 2]]) -> f64 {(0..n).map(|k| uv.get(k).zip(uv.get((k + 1) % n)).map_or(0.0, |(a, b)| a[0] * b[1] - b[0] * a[1])).sum()}-/// A loop that runs from one pole to the other and back along the same parameter line (both-/// uses of a seam joined only at the poles) encloses nothing once projected: the run after the-/// second pole is moved one period along the periodic direction, which way gives the loop a-/// positive area, so the face spans the period between its two seam copies.+/// A loop through both poles that turns straight back at one of them (it runs along a seam+/// and back: a whole sphere bounded by its meridian, or a sphere face whose split meridian it+/// uses both ways) retraces that seam once projected, since the periodic parameter carries on+/// unchanged across the pole. Across a pole it may jump by any amount, so the run from the+/// second pole back to the first is moved one period along, whichever way keeps the loop+/// within one period with a positive area: the seam's two uses then lie a period apart.fn open_pole_to_pole(s: &EvalSurface, dom: &uv::Domain, l: &mut seam::Loop) {let n = l.uv.len();let poles: Vec<usize> = (0..n).filter(|&k| l.uv.get(k).is_some_and(|q| (0..2).any(|d| uv::degenerate(s, *q, d)))).collect();let [p0, p1] = poles.as_slice() else { return };- let (lo, hi) = l.uv.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), q| (a.min(q[0].min(q[1])), b.max(q[0].max(q[1]))));- let extent = (hi - lo).abs().max(1e-12);- if area2(&l.uv).abs() > 1e-9 * extent * extent {- return;- }for d in 0..2 {let Some(per) = dom.period[d] else { continue };+ let near =+ |a: Option<&[f64; 2]>, b: Option<&[f64; 2]>| a.zip(b).is_some_and(|(a, b)| (a[0] - b[0]).abs().max((a[1] - b[1]).abs()) <= 1e-9 * per);+ let turns_back = [*p0, *p1].iter().any(|&p| near(l.uv.get((p + n - 1) % n), l.uv.get((p + 1) % n)));+ if !turns_back {+ continue;+ }// Along the seam the periodic parameter is constant between the poles.let second: Vec<usize> = (0..n).filter(|k| (k > p1 || k < p0) && *k != *p0 && *k != *p1).collect();if second.is_empty() {@@ -514,7 +522,21 @@ fn open_pole_to_pole(s: &EvalSurface, dom: &uv::Domain, l: &mut seam::Loop) {q[d] += sign * per;}}- if area2(&moved) > 1e-9 * extent * extent {+ // The poles as the planner splits them: one copy at each neighbour's parameter.+ let mut ring = Vec::with_capacity(n + 2);+ for k in 0..n {+ let (Some(q), Some(a), Some(b)) = (moved.get(k), moved.get((k + n - 1) % n), moved.get((k + 1) % n)) else { continue };+ if k == *p0 || k == *p1 {+ let (mut qa, mut qb) = (*q, *q);+ qa[d] = a[d];+ qb[d] = b[d];+ ring.extend([qa, qb]);+ } else {+ ring.push(*q);+ }+ }+ let (lo, hi) = ring.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), q| (a.min(q[d]), b.max(q[d])));+ if hi - lo <= per * (1.0 + 1e-9) && area2(&ring) > 0.0 {l.uv = moved;return;}@@ -522,6 +544,8 @@ fn open_pole_to_pole(s: &EvalSurface, dom: &uv::Domain, l: &mut seam::Loop) {}}+/// One face: boundary loops in 3D (shared edge nodes) to parameters and triangles.+/// `size`: the face's target side length (mm) and the surface's mean speed along u and v.fn plan_face(fi: usize,s: &EvalSurface,