diff --git a/crates/geom/src/brep/pcurve.rs b/crates/geom/src/brep/pcurve.rs index f6e8e1e39..67fc845af 100644 --- a/crates/geom/src/brep/pcurve.rs +++ b/crates/geom/src/brep/pcurve.rs @@ -323,7 +323,7 @@ impl On { let reach = 0.25 * tol; // Interior knots: where the curve's own parameterisation is less smooth (a pcurve is no // smoother than its curve), else even. - let mut inner = breaks(record, t0, t1); + let mut inner = breaks(record, Some(curve), t0, t1); if inner.len() + 1 > MAX_SPANS / 4 { return Err(Error::TooLarge(format!("a pcurve of a curve with {} knots", inner.len()))); } @@ -499,7 +499,12 @@ impl On { /// The interior parameters where `curve` is less than twice continuously differentiable, with /// the knot multiplicity a cubic needs there: a spline's knots by their multiplicity, and the /// vertices of a polyline or an intersection curve's leader polyline (its parameter turns there). -fn breaks(curve: &Curve, t0: f64, t1: f64) -> Vec<(f64, usize)> { +/// A knot that leaves a spline only continuous by its multiplicity, where the spline's +/// derivative is the same either side (`eval`, the curve's own evaluator), is once +/// differentiable and gets a pcurve with a tangent there: two pieces fitted apart would meet at +/// an angle, sharp in (u, v) where the surface's parameters run at very different speeds (a +/// thread's flank, hundreds of mm per unit along the helix and one across it). +fn breaks(curve: &Curve, eval: Option<&CurveEval>, t0: f64, t1: f64) -> Vec<(f64, usize)> { let spline = |knots: &[f64], count: usize| -> Vec<(f64, usize)> { let degree = knots.len().saturating_sub(count + 1); let mut out: Vec<(f64, usize)> = Vec::new(); @@ -509,7 +514,15 @@ fn breaks(curve: &Curve, t0: f64, t1: f64) -> Vec<(f64, usize)> { _ => out.push((k, 1)), } } - out.into_iter().map(|(k, m)| (k, (3 - degree.saturating_sub(m).min(2)).clamp(1, 3))).collect() + out.into_iter() + .map(|(k, m)| { + let mut smooth = degree.saturating_sub(m); + if m == degree && eval.is_some_and(|e| differentiable_at(e, k)) { + smooth = 1; + } + (k, (3 - smooth.min(2)).clamp(1, 3)) + }) + .collect() }; let corners = |n: usize| (1..n.saturating_sub(1)).map(|i| (i as f64, 3)).filter(|k| k.0 > t0 && k.0 < t1).collect(); match curve { @@ -519,11 +532,23 @@ fn breaks(curve: &Curve, t0: f64, t1: f64) -> Vec<(f64, usize)> { Curve::RationalSpline { knots, homogeneous } => spline(knots, homogeneous.len()), Curve::SurfaceIntersection { leader, .. } => match &**leader { Curve::Polyline { points } => corners(points.len()), - other => breaks(other, t0, t1), + other => breaks(other, None, t0, t1), }, } } +/// Relative difference of a spline's derivatives either side of a knot within which it is +/// differentiable there (rounding of derivatives made equal). +const SAME_DERIVATIVE: f64 = 1e-9; + +/// Whether the spline `eval` has one derivative at its knot `k` (the same from either side). +fn differentiable_at(eval: &CurveEval, k: f64) -> bool { + let CurveEval::Spline(c) = eval else { return false }; + let Some((l, r)) = c.sides(k) else { return false }; + let size = l.len().max(r.len()); + size > 0.0 && (l - r).len() <= SAME_DERIVATIVE * size +} + /// Signed area in (u, v) of the loop with its uses moved by `shift` along `d`. fn area(uses: &[(Curve2, bool)], shift: &[f64], d: usize) -> f64 { let mut ring: Vec<[f64; 2]> = Vec::new(); diff --git a/crates/geom/src/brep/pcurve_tests.rs b/crates/geom/src/brep/pcurve_tests.rs index 561e91b3b..e0dca631b 100644 --- a/crates/geom/src/brep/pcurve_tests.rs +++ b/crates/geom/src/brep/pcurve_tests.rs @@ -486,6 +486,103 @@ fn intersection_curves_lie_on_both_surfaces() { } } +/// A thread flank as a screw sweep leaves it: a spline strip winding twenty-two turns of pitch 1 about +/// z, rising from radius 3 to radius 4 by half the pitch, so one turn lies 0.89 mm from the next, +/// and its v = ½ line (its rows' midpoints on its u knots, so it lies on the strip). +fn thread_flank() -> (Surface, Curve) { + helical_strip([3., 4.], 0.5, 0.5) +} + +/// A spline strip winding twenty-two turns of pitch 1 about z from radius `r[0]` (v = 0) to `r[1]` +/// (v = 1), rising by `rise` across, and its line at v = `at` (its rows' points there on its u +/// knots, so it lies on the strip). +fn helical_strip(r: [f64; 2], rise: f64, at: f64) -> (Surface, Curve) { + // Control points 7.3 to a turn (161 over 22 turns), so the knots fall at other angles on + // each turn. + const PER_TURN: f64 = 7.3; + let n = 161; + let helix = |r: f64, rise: f64| -> Vec<[f64; 3]> { + (0..n) + .map(|i| { + let a = TAU * i as f64 / PER_TURN; + [r * a.cos(), r * a.sin(), a / TAU + rise] + }) + .collect() + }; + let (inner, outer) = (helix(r[0], 0.), helix(r[1], rise)); + let mut u_knots = vec![0.; 4]; + u_knots.extend((1..n - 3).map(|k| k as f64 / (n - 3) as f64)); + u_knots.extend([1.; 4]); + let surface = Surface::Spline { + u_knots: u_knots.clone(), + v_knots: vec![0., 0., 1., 1.], + points: inner.iter().zip(&outer).map(|(a, b)| vec![*a, *b]).collect(), + }; + let middle = + Curve::Spline { knots: u_knots, points: inner.iter().zip(&outer).map(|(a, b)| [0, 1, 2].map(|k| (1. - at) * a[k] + at * b[k])).collect() }; + (surface, middle) +} + +/// Edges along a surface winding several turns (the flank's middle line, from mid-turn to +/// mid-turn, and a short run of it) get pcurves on their own turn, never the next one. +#[test] +fn edges_on_a_spline_winding_several_turns_stay_on_their_turn() { + let (surface, middle) = thread_flank(); + for interval in [[0., 1.], [0.0625, 0.9375], [0.40625, 0.4375]] { + for tol in [1e-3, 1e-6] { + let pc = &pcurves(&surface, &one(&middle, interval), tol).unwrap()[0][0]; + let e = lift_error(&surface, &middle, interval, pc); + assert!(e <= tol, "{interval:?} at {tol}: {e}"); + } + } +} + +/// A thread's root band, 0.93 of the pitch tall, its turns 0.07 mm apart: an edge along its lower +/// rim (as where the root meets a shoulder) gets a pcurve on its own turn, though the rim of the +/// turn below passes nearer some of the search's starts than its own turn does. +#[test] +fn an_edge_along_the_rim_of_a_band_winding_close_to_itself_stays_on_its_turn() { + let (surface, rim) = helical_strip([5., 5.], 0.93, 0.); + // Short edges starting every 1/64 of a turn round one turn. + for k in 0..64 { + let t0 = 0.5 + f64::from(k) / (64. * 22.); + let interval = [t0, t0 + 1. / 64.]; + let pc = &pcurves(&surface, &one(&rim, interval), 2e-4).unwrap()[0][0]; + let e = lift_error(&surface, &rim, interval, pc); + assert!(e <= 2e-4, "{interval:?}: {e}"); + } +} + +/// A curve that is smooth through a knot of full multiplicity (one smooth curve with the knot +/// inserted three times, as SMLib's intersection curves come) gets a pcurve with one tangent +/// there. Two pieces fitted apart meet at an angle in (u, v) (a tenth of a degree here, over the +/// degree SMLib's check allows on a real thread), sharp where u runs hundreds of times as fast as +/// v. +#[test] +fn a_smooth_curve_through_a_full_knot_gets_a_pcurve_with_a_tangent_there() { + let (surface, _) = thread_flank(); + let s = SurfaceEval::new(&surface).unwrap(); + // Along the flank as it winds, a third of a turn (u = t), weaving a little across it. + let [a, b] = [0.40625, 0.4234375]; + let ts: Vec = (0..=12).map(|i| a + (b - a) * i as f64 / 12.).collect(); + let v = |t: f64| 0.5 + 0.02 * (3. * TAU * (t - a) / (b - a)).sin(); + let on: Vec<[f64; 3]> = ts.iter().map(|&t| s.point([t, v(t)]).unwrap()).map(|p| [p.x, p.y, p.z]).collect(); + let c = crate::bspline::CurveN::interpolate(&ts, &on, 3).unwrap(); + let k = 0.4167; + let (mut knots, mut ctrl) = (c.knots, c.ctrl.iter().map(|p| crate::bspline::HPoint::weighted(Vec3::from(*p), 1.)).collect::>()); + for _ in 0..3 { + (knots, ctrl) = crate::bspline::insert_knot(3, &knots, &ctrl, k).unwrap(); + } + let weave = Curve::Spline { knots, points: ctrl.iter().map(|h| h.project().unwrap()).map(|p| [p.x, p.y, p.z]).collect() }; + let pc = &pcurves(&surface, &one(&weave, [a, b]), 1e-3).unwrap()[0][0]; + assert!(lift_error(&surface, &weave, [a, b], pc) <= 1e-3); + let h = 1e-7; + let (l, m, r) = (pc.eval(k - h).unwrap(), pc.eval(k).unwrap(), pc.eval(k + h).unwrap()); + let (dl, dr) = ([m[0] - l[0], m[1] - l[1]], [r[0] - m[0], r[1] - m[1]]); + let cos = (dl[0] * dr[0] + dl[1] * dr[1]) / (dl[0].hypot(dl[1]) * dr[0].hypot(dr[1])); + assert!(cos > 1. - 1e-6, "the pcurve turns by {} degrees at the knot", cos.min(1.).acos().to_degrees()); +} + /// Hostile records give errors, never a panic. #[test] fn hostile_records_give_errors() { diff --git a/crates/geom/src/tess.rs b/crates/geom/src/tess.rs index b1f6b7f7c..b5c442354 100644 --- a/crates/geom/src/tess.rs +++ b/crates/geom/src/tess.rs @@ -193,7 +193,31 @@ impl EvalCurve { if p == 0 || p > MAX_SPLINE_DEGREE || n <= p || self.knots.len() != n + p + 1 || !t.is_finite() { return None; } - let span = span_of(&self.knots, p, n, t); + self.eval_on(span_of(&self.knots, p, n, t), t) + } + + /// The first derivative at `t` from either side: on the knot spans that end and start + /// there where `t` is a knot (the polynomials either side of it), else the derivative twice. + pub fn sides(&self, t: f64) -> Option<(Vec3, Vec3)> { + let p = self.degree; + let n = self.ctrl.len(); + if p == 0 || p > MAX_SPLINE_DEGREE || n <= p || self.knots.len() != n + p + 1 || !t.is_finite() { + return None; + } + let right = span_of(&self.knots, p, n, t); + // The last non-empty span before `t`'s, when `t` is where it starts. + let left = match self.knots.get(right) { + Some(&k) if k == t => { + (p..right).rev().find(|&i| matches!((self.knots.get(i), self.knots.get(i + 1)), (Some(a), Some(b)) if a < b)).unwrap_or(right) + } + _ => right, + }; + Some((self.eval_on(left, t)?.1, self.eval_on(right, t)?.1)) + } + + /// Point and first derivative at `t` of the polynomial on knot span `span`. + fn eval_on(&self, span: usize, t: f64) -> Option<(Vec3, Vec3)> { + let p = self.degree; let ders = basis_ders(&self.knots, span, p, t)?; let (mut a, mut da) = ([0.0; 4], [0.0; 4]); for (k, (n0, n1)) in ders[0].iter().zip(&ders[1]).take(p + 1).enumerate() { diff --git a/crates/geom/src/tess/uv.rs b/crates/geom/src/tess/uv.rs index db303dd83..ab1f99a8b 100644 --- a/crates/geom/src/tess/uv.rs +++ b/crates/geom/src/tess/uv.rs @@ -170,7 +170,8 @@ fn newton(s: &EvalSurface, dom: &Domain, p: Vec3, start: [f64; 2]) -> Option<([f } /// Parameters of `p` (a point on the surface within `accept`), from `hint` when that -/// converges, else from the best starts of a grid over the surface's domain. +/// converges, else from the best starts of a grid over the surface's domain, as fine as its +/// knot spans ([`starts_along`]). pub fn project(s: &EvalSurface, dom: &Domain, p: Vec3, hint: Option<[f64; 2]>, accept: f64) -> Option<[f64; 2]> { if let EvalSurface::Plane { origin, du, dv } = s { let r = p - *origin; @@ -192,28 +193,77 @@ pub fn project(s: &EvalSurface, dom: &Domain, p: Vec3, hint: Option<[f64; 2]>, a } best = Some((uv, d)); } - let (ur, vr) = (dom.range[0]?, dom.range[1]?); - const N: usize = 16; - let mut starts: Vec<(f64, [f64; 2])> = Vec::with_capacity((N + 1) * (N + 1)); - for i in 0..=N { - for j in 0..=N { - let uv = [ur.0 + (ur.1 - ur.0) * i as f64 / N as f64, vr.0 + (vr.1 - vr.0) * j as f64 / N as f64]; - if let Some((q, _, _)) = s.derivs(uv[0], uv[1]) { - starts.push(((q - p).len2(), uv)); + let (mut us, mut vs) = (starts_along(s, 0, dom.range[0]?), starts_along(s, 1, dom.range[1]?)); + // Thin the longer list (every other start, its ends kept) until the grid fits. + while us.len().saturating_mul(vs.len()) > MAX_STARTS { + let longer = if us.len() >= vs.len() { &mut us } else { &mut vs }; + let last = longer.last().copied(); + *longer = longer.iter().step_by(2).copied().chain(last).collect(); + longer.dedup(); + } + let mut starts: Vec<(f64, [f64; 2])> = Vec::with_capacity(us.len() * vs.len()); + for &u in &us { + for &v in &vs { + if let Some((q, _, _)) = s.derivs(u, v) { + starts.push(((q - p).len2(), [u, v])); } } } starts.sort_by(|a, b| a.0.total_cmp(&b.0)); - for (_, start) in starts.iter().take(4) { + // The nearest starts first, until one converges within `accept`: where turns of a surface + // pass close to each other (a thread's root band a tenth of a millimetre from the next + // turn's), the nearest few can all lie on the wrong turn. + for (_, start) in starts.iter().take(NEWTON_STARTS) { if let Some((uv, d)) = newton(s, dom, p, *start) && best.is_none_or(|(_, bd)| d < bd) { best = Some((uv, d)); } + if accept.is_finite() && best.is_some_and(|(_, d)| d <= accept) { + break; + } } best.filter(|(_, d)| *d <= accept).map(|(uv, _)| uv) } +/// Evenly spaced starts along each direction of [`project`]'s search of the whole surface. +const EVEN_STARTS: usize = 16; +/// Starts per knot span of a direction where the surface has its own knots. +const SPAN_STARTS: usize = 2; +/// Most points of the surface the search measures. +const MAX_STARTS: usize = 1 << 14; +/// Most of them it runs Gauss–Newton from. +const NEWTON_STARTS: usize = 32; + +/// The parameters along direction `d` (over `range`) that [`project`] starts from when it has no +/// hint: even steps across the range, and where the surface has its own knots along `d` (a +/// spline's, a revolution's profile's) each span's start and points inside it, so a surface that +/// winds several turns along `d` (a thread's flank, one turn every few spans) is searched on +/// every turn and a point is never taken to the turn beside its own. +fn starts_along(s: &EvalSurface, d: usize, (a, b): (f64, f64)) -> Vec { + let knots = match s { + EvalSurface::Plane { .. } => None, + EvalSurface::Nurbs { knots, .. } => knots.get(d), + EvalSurface::Revolved { profile, swap, .. } => (usize::from(*swap) == d).then_some(&profile.knots), + }; + let (lo, hi) = (a.min(b), a.max(b)); + let mut out: Vec = (0..=EVEN_STARTS).map(|k| a + (b - a) * k as f64 / EVEN_STARTS as f64).collect(); + if let Some(knots) = knots { + let inside = knots.iter().copied().filter(|k| *k > lo && *k < hi); + let mut ends: Vec = std::iter::once(lo).chain(inside).chain(std::iter::once(hi)).collect(); + ends.dedup(); + for w in ends.windows(2).take(MAX_STARTS) { + let (Some(&k0), Some(&k1)) = (w.first(), w.get(1)) else { continue }; + out.extend((0..SPAN_STARTS).map(|j| k0 + (k1 - k0) * (j as f64 + 0.5) / SPAN_STARTS as f64)); + out.push(k0); + } + } + out.retain(|x| x.is_finite()); + out.sort_by(f64::total_cmp); + out.dedup(); + out +} + /// `x` moved by whole periods to lie within half a period of `near`. pub fn unwrap(x: f64, near: f64, period: Option) -> f64 { match period { diff --git a/crates/smlib/src/ffi/sweeps.rs b/crates/smlib/src/ffi/sweeps.rs index d92ad9af0..1d20519db 100644 --- a/crates/smlib/src/ffi/sweeps.rs +++ b/crates/smlib/src/ffi/sweeps.rs @@ -22,11 +22,27 @@ pub const SWEEP_FOLLOW: i32 = 0; pub const SWEEP_TRANSLATE: i32 = 1; /// A curve list as the C API reads it: kinds (with a NURBS curve's degree and point count) and -/// each curve's numbers. Only the calls read them, which a build without SMLib does not have. -#[cfg_attr(not(feature = "native"), allow(dead_code))] +/// each curve's numbers. +#[cfg(feature = "native")] pub struct List<'a> { - pub kinds: &'a [i64], - pub reals: &'a [f64], + kinds: &'a [i64], + reals: &'a [f64], +} + +/// Without SMLib nothing reads the list, so it carries nothing. +#[cfg(not(feature = "native"))] +pub struct List<'a>(std::marker::PhantomData<&'a ()>); + +impl<'a> List<'a> { + #[cfg(feature = "native")] + pub fn new(kinds: &'a [i64], reals: &'a [f64]) -> Self { + List { kinds, reals } + } + + #[cfg(not(feature = "native"))] + pub fn new(_: &'a [i64], _: &'a [f64]) -> Self { + List(std::marker::PhantomData) + } } #[cfg(feature = "native")] diff --git a/crates/smlib/src/sweeps.rs b/crates/smlib/src/sweeps.rs index 01790f337..ae4758765 100644 --- a/crates/smlib/src/sweeps.rs +++ b/crates/smlib/src/sweeps.rs @@ -99,7 +99,7 @@ impl List { } fn raw(&self) -> ffi::sweeps::List<'_> { - ffi::sweeps::List { kinds: &self.kinds, reals: &self.reals } + ffi::sweeps::List::new(&self.kinds, &self.reals) } }