diff --git a/crates/geom/src/fill_iso.rs b/crates/geom/src/fill_iso.rs index 6248c3167..cfd90b6d6 100644 --- a/crates/geom/src/fill_iso.rs +++ b/crates/geom/src/fill_iso.rs @@ -37,9 +37,10 @@ //! spokes starting as straight lines to the centre, the mean of the midpoints. //! - **The inside**: with the loop's rows held, the other control points (each patch's interior, //! the spokes' and the centre, each once) minimise, by least squares, the misfit to the -//! conditions plus a vanishing multiple of the patches' thin-plate energy -//! `∫∫ |S_uu|² + 2|S_uv|² + |S_vv|²` (of the control net on the polynomial basis; it alone -//! decides a G0 fill). The conditions are those of G^n continuity in the linkage-curve +//! conditions plus a vanishing multiple of the patches' fairing energy of order n + 1, +//! `∫∫ Σ_r C(n+1, r) |∂ᵘʳ ∂ᵥⁿ⁺¹⁻ʳ S|²` (the thin plate `∫∫ |S_uu|² + 2|S_uv|² + |S_vv|²` for G0 +//! and G1, of the control net on the polynomial basis; it alone decides a G0 fill), so the +//! change of curvature the conditions ask at the edges is spread over the fill. The conditions are those of G^n continuity in the linkage-curve //! formulation ([`crate::linkage`]): at stations along an edge, the iso-parameter curve `c` //! of the fill leaving across it (σ growing into the fill) must have its height above the //! neighbour vanish to order n: @@ -51,6 +52,9 @@ //! the normal curvature (G2), its rate of change (G3) and that rate's (G4) are the //! neighbour's, in the fill's own leave direction. The right-hand side reads `c′ … c⁽ᵏ⁻¹⁾` //! from the last solution, so the rows are solved again, a few rounds; +//! - across a patch's own C0 knot lines (a side's break where it is only C0 in its +//! parameter), the derivatives either side in the ratio of the crossing sides' speeds +//! ([`knot_line_rows`]): the fill is tangent continuous there too; //! - across each spoke, the two patches' derivatives away from it opposed (`∂S_k/∂u + ∂S_{k+1}/∂v //! = 0` on the shared parameter): the patches join tangent there; //! - points the fill passes through, located on the last solution (nearest point of any patch) @@ -67,7 +71,10 @@ //! has too few rows for the conditions from opposite sides to stay apart, the spans that way are //! halved (both ways where a point is missed, a patch folds, or the patches share one space), //! up to [`MAX_ISO_SPANS`] and the free points one solve takes ([`MAX_BANDED_POINTS`] for one -//! patch, whose system is banded, [`MAX_UNKNOWN_POINTS`] about a centre, whose is dense). +//! patch, whose system is banded, [`MAX_UNKNOWN_POINTS`] about a centre, whose is dense). A +//! fill that then still misses the angle tolerance or a point, or folds, is refused; one that +//! misses only an order above G1 is the closest the finest space holds, its jumps reported +//! ([`Achieved::jumps`]). //! - **A crown** fills the middle out along the normals, on control points clear of the rows the //! conditions hold, so the loop and the conditions across it do not move. //! @@ -113,12 +120,15 @@ const CORNER_SHARE: f64 = 0.1; const FOLD_SAMPLES: usize = 24; /// How far, relative to one, the corners' weights may disagree once the edges are scaled. const WEIGHT_TOL: f64 = 1e-9; -/// Four-point Gauss–Legendre nodes and weights on `[−1, 1]` (exact to degree 7). -const GAUSS4: [(f64, f64); 4] = [ - (-0.861_136_311_594_052_6, 0.347_854_845_137_453_8), - (-0.339_981_043_584_856_3, 0.652_145_154_862_546_2), - (0.339_981_043_584_856_3, 0.652_145_154_862_546_2), - (0.861_136_311_594_052_6, 0.347_854_845_137_453_8), +/// Six-point Gauss–Legendre nodes and weights on `[−1, 1]` (exact to degree 11: the Gram +/// matrices of quintics). +const GAUSS6: [(f64, f64); 6] = [ + (-0.932_469_514_203_152, 0.171_324_492_379_170), + (-0.661_209_386_466_265, 0.360_761_573_048_139), + (-0.238_619_186_083_197, 0.467_913_934_572_691), + (0.238_619_186_083_197, 0.467_913_934_572_691), + (0.661_209_386_466_265, 0.360_761_573_048_139), + (0.932_469_514_203_152, 0.171_324_492_379_170), ]; /// One edge of the loop: a B-spline from the loop's corner before it to the one after (the @@ -381,9 +391,21 @@ impl Patch { /// rational basis `R_ij = w_ij N_i N_j / W`, by the Leibniz rule for `w_ij N_i N_j = R_ij W`: /// `R^(a,b) = (f^(a,b) − Σ_{(k,l) ≠ (0,0)} C(a,k) C(b,l) W^(k,l) R^(a−k,b−l)) / W`. fn row(&self, u: f64, v: f64, du: usize, dv: usize) -> SplineResult> { + self.row_sided(u, v, du, dv, [false; 2]) + } + + /// The basis of the space along `d` at `t`, from the left of a knot when `left`. + fn basis(&self, d: usize, t: f64, r: usize, left: bool) -> SplineResult<(usize, Vec)> { + let space = self.spaces.get(d).ok_or_else(|| SplineError::Invalid("a patch has two directions".into()))?; + if left { space.basis_left(t, r) } else { space.basis(t, r) } + } + + /// [`Patch::row`] with each direction's basis taken from the left of a knot where `left` + /// says so: the derivative of the piece ending there. + fn row_sided(&self, u: f64, v: f64, du: usize, dv: usize, left: [bool; 2]) -> SplineResult> { if !self.rational { - let (iu, bu) = self.spaces[0].basis(u, du)?; - let (iv, bv) = self.spaces[1].basis(v, dv)?; + let (iu, bu) = self.basis(0, u, du, left[0])?; + let (iv, bv) = self.basis(1, v, dv, left[1])?; let mut out = Vec::with_capacity(bu.len() * bv.len()); for (b, nv) in bv.iter().enumerate() { for (a, nu) in bu.iter().enumerate() { @@ -397,7 +419,7 @@ impl Patch { let mut first = 0; let mut out = Vec::with_capacity(top + 1); for r in 0..=top { - let (f, b) = self.spaces[d].basis(t, r)?; + let (f, b) = self.basis(d, t, r, left.get(d).copied().unwrap_or(false))?; first = f; out.push(b); } @@ -704,6 +726,7 @@ fn coons(spaces: [Space; 2], c0: &[HPoint], c1: &[HPoint], d0: &[HPoint], d1: &[ } /// One condition row: `Σ along·P = value` over its terms' control points, and its weight. +#[derive(Clone)] struct Row { terms: Vec, value: f64, @@ -742,8 +765,11 @@ struct Station { t: f64, across: Across, /// The continuity order asked here: the neighbour's, or less near a corner whose neighbours - /// do not agree to it. + /// do not agree to it ([`Asked`]): orders up to `full` at their full weight, those above it + /// up to `order` at `fade` of it. order: usize, + full: usize, + fade: f64, /// How far (radians) the edge itself leans out of the neighbour's tangent plane here: the /// fill holds the edge, so its normal can come no nearer the neighbour's than that. tilt: f64, @@ -759,6 +785,44 @@ impl Station { } } +/// What a station asks, by how near it is to corners whose neighbours agree to less (see +/// [`corner_orders`]): within [`CLASH_SHARE`] of such a corner the orders above the corner's +/// agreement (at least G1) are not asked, and over the next [`CLASH_SHARE`] they come back +/// smoothly (`fade` from 0 to 1, a smoothstep), so the fill is not strained where they start; +/// where the corner's tangent planes disagree the station is not held to the angle tolerance. +struct Asked { + asked: usize, + full: usize, + fade: f64, + held: bool, +} + +impl Asked { + /// For a station asking `asked`, at fraction `distance` of its side from each of the side's + /// two corners, whose neighbours agree to `agreement` (`None`: no cap). + fn near(asked: usize, ends: [(Option, f64); 2]) -> Asked { + let mut a = Asked { asked, full: asked, fade: 1.0, held: true }; + for (agreement, distance) in ends { + let Some(agreed) = agreement.filter(|g| *g < asked) else { continue }; + if distance >= 2.0 * CLASH_SHARE { + continue; + } + a.full = a.full.min(agreed.max(1)); + let x = ((distance - CLASH_SHARE) / CLASH_SHARE).clamp(0.0, 1.0); + a.fade = a.fade.min(x * x * (3.0 - 2.0 * x)); + if agreed == 0 && distance < CLASH_SHARE { + a.held = false; + } + } + a + } + + /// The highest order asked at all. + fn order(&self) -> usize { + if self.fade > 0.0 { self.asked } else { self.full } + } +} + /// The derivatives `[c′, c″, …, c⁽ⁿ⁾]` (n = `order`) of the linkage curve `c` leaving a station /// across its edge into the patch: the iso-parameter curve, σ growing into the patch. fn linkage(patch: &Patch, s: &Station, order: usize) -> SplineResult> { @@ -936,11 +1000,15 @@ pub fn iso_fill( if folded || report.point_deviation > spec.tol { wanted = [true; 2]; } - if !wanted.iter().any(|w| *w) { + // The tangent plane, the points and an unfolded fill are what a patch must have; the + // orders above G1 are held as tightly as the finest space allows, and reported. + let must = !folded && report.point_deviation <= spec.tol && along.angle.iter().all(|a| *a <= spec.angle_tol); + let refine = refinable(&spans, wanted, shared, quilt.unknowns); + if !wanted.iter().any(|w| *w) || (must && !refine) { let quilt = crowned(quilt, &stations, spec.crown, size)?; return finished(quilt, edges, report); } - if !refinable(&spans, wanted, shared, quilt.unknowns) { + if !refine { let jumps = report.jumps.get(2..=order).filter(|_| order >= 2).map(|j| format!(", jumps of orders 2 to {order} {j:?}")).unwrap_or_default(); let folded = if folded { ", and it folds" } else { "" }; @@ -1059,12 +1127,9 @@ fn stations( let Some(c) = c else { continue }; let t = (param - a) / (b - a); let f = (param - ea) / (eb - ea); - // What the corners near the station let it ask. let asked = c.jet.map_or(1, |j| j.order); - let near = |corner: usize, close: bool| if close { corners.get(corner).copied().unwrap_or(usize::MAX) } else { usize::MAX }; - let cap = near(k, f < CLASH_SHARE).min(near((k + 1) % n, f > 1.0 - CLASH_SHARE)); - let order = asked.min(cap.max(1)); - let clear = f > CORNER_SHARE && f < 1.0 - CORNER_SHARE && order == asked; + let ask = Asked::near(asked, [(corners.get(k).copied(), f), (corners.get((k + 1) % n).copied(), 1.0 - f)]); + let clear = f > CORNER_SHARE && f < 1.0 - CORNER_SHARE && ask.full == asked; let (uv, (du, dv, sign)) = station_on(side, t); // How fast the Coons start leaves into the leave direction: it blends the sides // across, so it leaves as fast as the opposite sides lie apart; the side's own speed @@ -1072,7 +1137,7 @@ fn stations( let along = p.eval(uv[0], uv[1], dv, du).map(|d| d.len()).unwrap_or(0.0); let speed = p.eval(uv[0], uv[1], du, dv).map(|d| (d * sign).dot(c.leave)).ok().filter(|x| *x > 0.0).unwrap_or(along); let tilt = edges.get(k).and_then(|e| e.tangent(param)).map_or(0.0, |d| d.dot(c.normal).abs().clamp(0.0, 1.0).asin()); - out.push(Station { patch, side, t, across: c, order, tilt, held: cap > 0, clear, speed }); + out.push(Station { patch, side, t, across: c, order: ask.order(), full: ask.full, fade: ask.fade, tilt, held: ask.held, clear, speed }); } } Ok(out) @@ -1087,7 +1152,8 @@ fn solve(mut quilt: Quilt, stations: &[Station], spec: &IsoSpec) -> SplineResult if quilt.unknowns > most { return Err(SplineError::TooLarge(format!("{} free control points (at most {most})", quilt.unknowns))); } - let energy: Vec> = quilt.patches.iter().map(energy).collect::>()?; + let fairing = stations.iter().map(Station::order).max().unwrap_or(1).max(1) + 1; + let energy: Vec> = quilt.patches.iter().map(|p| energy(p, fairing)).collect::>()?; let mut located: Vec<(usize, [f64; 2])> = Vec::new(); let mut report = Achieved::default(); let mut along = Along::default(); @@ -1096,8 +1162,9 @@ fn solve(mut quilt: Quilt, stations: &[Station], spec: &IsoSpec) -> SplineResult // The mean span of each space (the same in every patch). let span = quilt.patches.first().map_or([1.0; 2], |p| p.spaces.clone().map(|s| 1.0 / breaks(&s).len().saturating_sub(1).max(1) as f64)); let rounds = if top >= 2 { ROUNDS_PER_ORDER * top } else { ROUNDS }; + let smooth = knot_line_rows(&quilt, spec.angle_tol)?; for round in 0..rounds { - let mut rows: Vec = Vec::new(); + let mut rows: Vec = smooth.clone(); for s in stations { let Some(patch) = quilt.patches.get(s.patch) else { continue }; // The span across the side: of v for sides 0 and 2, of u for 1 and 3. @@ -1127,6 +1194,58 @@ fn solve(mut quilt: Quilt, stations: &[Station], spec: &IsoSpec) -> SplineResult Ok((quilt, report, along)) } +/// Rows that keep a patch tangent continuous across its own C0 knot lines (a break where a +/// side is only C0 in its parameter, such as a circle's quarter joint once in homogeneous form): +/// along the line `u = x` (or `v = x`), at stations, the derivative across it from the right is +/// the one from the left times `r`, the ratio the two sides crossing the line have there (they +/// are tangent continuous, their speeds may differ), blended linearly between them; at the sides +/// the rows hold by construction. A line where a crossing side turns a corner is left alone: no +/// surface is tangent across it there. A three-sided patch's pole takes the other side's ratio. +fn knot_line_rows(quilt: &Quilt, angle_tol: f64) -> SplineResult> { + let mut rows = Vec::new(); + for (k, patch) in quilt.patches.iter().enumerate() { + for d in 0..2 { + let (Some(space), Some(other)) = (patch.spaces.get(d), patch.spaces.get(1 - d)) else { continue }; + let count = station_count(other); + for (x, m) in interior_knots(space) { + if m < space.degree() { + continue; + } + // The point (x, t) in the patch's (u, v), and its one-sided derivatives across. + let at = |t: f64| if d == 0 { [x, t] } else { [t, x] }; + let across = |t: f64, left: bool| -> SplineResult> { + let [u, v] = at(t); + let (du, dv) = if d == 0 { (1, 0) } else { (0, 1) }; + patch.row_sided(u, v, du, dv, if d == 0 { [left, false] } else { [false, left] }) + }; + let speed = |row: &[(usize, usize, f64)]| row.iter().fold(Vec3::ZERO, |s, (i, j, c)| s + patch.at(*i, *j) * *c); + let ratio = |t: f64| -> SplineResult> { + let (a, b) = (speed(&across(t, true)?), speed(&across(t, false)?)); + let (la, lb) = (a.len(), b.len()); + if !(la > 0.0 && lb > 0.0) { + return Ok(None); + } + Ok((a.dot(b) / (la * lb) >= angle_tol.cos()).then_some(lb / la)) + }; + let ends = [ratio(0.0)?, ratio(1.0)?]; + let (r0, r1) = match ends { + [Some(a), Some(b)] => (a, b), + [Some(a), None] | [None, Some(a)] if patch.pole && d == 1 => (a, a), + _ => continue, + }; + for i in 0..count { + let t = (i as f64 + 0.5) / count as f64; + let r = r0 * (1.0 - t) + r1 * t; + let mut terms = across(t, false)?; + terms.extend(across(t, true)?.into_iter().map(|(i, j, c)| (i, j, -r * c))); + on_each_axis(&mut rows, &[(k, terms)], Vec3::ZERO, 1.0); + } + } + } + } + Ok(rows) +} + /// A station's rows (module docs), linearised about the patch as it stands: /// - G1: `n·c′ = 0`, and the weak Hermite rows `w·c′ = s`, `t·c′ = 0` in the neighbour's tangent /// plane only (`t = n × w`), so they never pull against the G1 row; @@ -1166,23 +1285,46 @@ fn linkage_rows(rows: &mut Vec, patch: &Patch, s: &Station, span: f64) -> S terms.extend(along(s.patch, cj, (t * g[0] + w * g[1]) * -1.0)); value -= g[0] * x[0] + g[1] * x[1]; } - rows.push(Row { terms, value, weight: span.powi(k as i32 - 1) }); + let fade = if k <= s.full { 1.0 } else { s.fade }; + rows.push(Row { terms, value, weight: fade * span.powi(k as i32 - 1) }); } Ok(()) } -/// A patch's thin-plate energy coefficients between its control points (flat indices), of the -/// terms `G⁽ʳ⁾ ⊗ G⁽ˢ⁾` with `(r, s)` = (2, 0), (1, 1) twice, (0, 2). -fn energy(patch: &Patch) -> SplineResult> { - let (gu, gv) = (gram(&patch.spaces[0])?, gram(&patch.spaces[1])?); - let at = |g: &[Vec>; 3], r: usize, a: usize, b: usize| g.get(r).and_then(|x| x.get(a)).and_then(|x| x.get(b)).copied().unwrap_or(0.0); +/// A patch's fairing energy for a fill asked G^n, between its control points (flat indices): the +/// thin plate (order 2) plus, for n ≥ 2, the energy of order `m = n + 1`, each scaled to unit +/// trace ([`energy_of`]). The higher order leaves the change the conditions ask (of curvature, +/// of its rate…) spread over the fill rather than squeezed into the first span along its edges; +/// the thin plate, whose null space (the planes) the loop pins, keeps the system definite where +/// the higher order's (polynomials of degree below m) is not. +fn energy(patch: &Patch, m: usize) -> SplineResult> { + let thin = energy_of(patch, 2)?; + if m <= 2 { + return Ok(thin); + } + let high = energy_of(patch, m)?; + let trace = |e: &[(usize, usize, f64)]| e.iter().filter(|(a, b, _)| a == b).map(|(_, _, x)| *x).sum::(); + let (t2, tm) = (trace(&thin), trace(&high)); + if !(t2 > 0.0 && tm > 0.0) { + return Ok(thin); + } + Ok(thin.into_iter().map(|(a, b, x)| (a, b, x / t2)).chain(high.into_iter().map(|(a, b, x)| (a, b, x / tm))).collect()) +} + +/// A patch's fairing energy of order `m` between its control points (flat indices): +/// `∫∫ Σ_r C(m, r) |∂ᵘʳ ∂ᵥᵐ⁻ʳ S|²`, the terms `G⁽ʳ⁾ ⊗ G⁽ᵐ⁻ʳ⁾` of the spaces' Gram matrices (order 2 +/// is the thin plate `∫∫ |S_uu|² + 2|S_uv|² + |S_vv|²`). +fn energy_of(patch: &Patch, m: usize) -> SplineResult> { + let (gu, gv) = (gram(&patch.spaces[0], m)?, gram(&patch.spaces[1], m)?); + let at = |g: &[Vec>], r: usize, a: usize, b: usize| g.get(r).and_then(|x| x.get(a)).and_then(|x| x.get(b)).copied().unwrap_or(0.0); + let binom = |n: usize, k: usize| (0..k).fold(1.0, |c, i| c * (n - i) as f64 / (i + 1) as f64); let [cu, cv] = patch.counts(); let mut out = Vec::new(); for j in 0..cv { for l in 0..cv { for i in 0..cu { for k in 0..cu { - let e = at(&gu, 2, i, k) * at(&gv, 0, j, l) + 2.0 * at(&gu, 1, i, k) * at(&gv, 1, j, l) + at(&gu, 0, i, k) * at(&gv, 2, j, l); + let e: f64 = (0..=m).map(|r| binom(m, r) * at(&gu, r, i, k) * at(&gv, m - r, j, l)).sum(); if e != 0.0 { out.push((i + cu * j, k + cu * l, e)); } @@ -1193,14 +1335,14 @@ fn energy(patch: &Patch) -> SplineResult> { Ok(out) } -/// The Gram matrices `∫ N_a⁽ʳ⁾ N_b⁽ʳ⁾` of a space's basis for r = 0, 1, 2 (Gauss–Legendre on +/// The Gram matrices `∫ N_a⁽ʳ⁾ N_b⁽ʳ⁾` of a space's basis for r = 0 … m (Gauss–Legendre on /// each span, exact for the degrees used). -fn gram(s: &Space) -> SplineResult<[Vec>; 3]> { +fn gram(s: &Space, m: usize) -> SplineResult>>> { let n = s.count(); - let mut g: [Vec>; 3] = std::array::from_fn(|_| vec![vec![0.0; n]; n]); + let mut g: Vec>> = vec![vec![vec![0.0; n]; n]; m + 1]; for w in breaks(s).windows(2) { let (lo, hi) = (w[0], w[1]); - for (x, wt) in GAUSS4 { + for (x, wt) in GAUSS6 { let t = 0.5 * (lo + hi) + 0.5 * (hi - lo) * x; let weight = 0.5 * (hi - lo) * wt; for (r, gr) in g.iter_mut().enumerate() { diff --git a/crates/geom/src/fill_iso_tests.rs b/crates/geom/src/fill_iso_tests.rs index dae4e871d..04ac77f6e 100644 --- a/crates/geom/src/fill_iso_tests.rs +++ b/crates/geom/src/fill_iso_tests.rs @@ -158,7 +158,7 @@ fn a_sphere_window_on_rational_arcs_holds_each_order_asked_and_not_the_next() { } if (2..4).contains(&order) { let (held, next) = (measured[order - 2], measured[order - 1]); - assert!(next > 100.0 * held.max(1e-12), "G{order} leaves order {} to the energy: {next:e} vs {held:e}", order + 1); + assert!(next > 10.0 * held.max(1e-12), "G{order} leaves order {} to the energy: {next:e} vs {held:e}", order + 1); } // Not the sphere (nothing asks for it), but a cap over the window, not a dent. assert!(off_sphere(&fill) < 0.05 * R, "G{order} near the sphere: {}", off_sphere(&fill)); diff --git a/crates/geom/src/spline_space.rs b/crates/geom/src/spline_space.rs index ecd68b612..82ac3efea 100644 --- a/crates/geom/src/spline_space.rs +++ b/crates/geom/src/spline_space.rs @@ -192,6 +192,27 @@ impl Space { Ok((first, values.collect())) } + /// [`Space::basis`] from the left of `t`: at an interior knot, the derivatives of the + /// polynomial piece that ends there (elsewhere the same as from the right). + pub fn basis_left(&self, t: f64, der: usize) -> SplineResult<(usize, Vec)> { + let [a, b] = self.domain(); + if !t.is_finite() { + return invalid("a parameter is not a finite number"); + } + let t = t.clamp(a, b); + if t <= a { + return self.basis(t, der); + } + let p = self.degree; + // The span [k_s, k_{s+1}) with k_s < t ≤ k_{s+1}. + let below = self.knots.partition_point(|&x| x < t); + let span = below.checked_sub(1).filter(|s| *s >= p).ok_or_else(|| SplineError::Invalid(format!("{t} is outside the domain")))?; + let first = span - p; + let values = + (first..=span).map(|i| self.knots.get(i..i + p + 2).map_or(0.0, |k| local_basis(k, t, Side::Left, der).get(der).copied().unwrap_or(0.0))); + Ok((first, values.collect())) + } + /// The `der`-th derivative at `t` of the spline with control values `ctrl`. pub fn eval(&self, ctrl: &[T], t: f64, der: usize) -> SplineResult { if ctrl.len() != self.count() { diff --git a/crates/kernel/src/fill_general_tests.rs b/crates/kernel/src/fill_general_tests.rs index bceb82177..870ff5a86 100644 --- a/crates/kernel/src/fill_general_tests.rs +++ b/crates/kernel/src/fill_general_tests.rs @@ -462,8 +462,6 @@ fn per_edge_continuity_and_hostile_specs() { check_face("pentagon, two edges g1/g2", &open, &fill); let bad = |spec: PatchSpec| patch_edges_report(&open, &rim, &spec).is_err(); let g1 = PatchSpec { continuity: Continuity::G1, ..PatchSpec::default() }; - assert!(bad(PatchSpec { continuity: Continuity::G3, ..g1.clone() })); - assert!(bad(PatchSpec { edges: vec![(rim[0], Continuity::G3)], ..g1.clone() })); assert!(bad(PatchSpec { edges: vec![(Vec3::new(0.0, 0.0, 40.0), Continuity::G1)], ..g1.clone() }), "an edge off the loop"); assert!(bad(PatchSpec { edges: vec![(Vec3::new(f64::NAN, 0.0, 0.0), Continuity::G1)], ..g1.clone() })); assert!(bad(PatchSpec { points: vec![Vec3::new(f64::INFINITY, 0.0, 0.0)], ..g1.clone() })); @@ -492,3 +490,89 @@ fn per_edge_continuity_and_hostile_specs() { let top = [Vec3::new(5.0, 0.0, 10.0), Vec3::new(10.0, 5.0, 10.0), Vec3::new(5.0, 10.0, 10.0), Vec3::new(0.0, 5.0, 10.0)]; assert!(patch_edges_report(&b, &top, &PatchSpec { continuity: Continuity::G1, ..PatchSpec::default() }).is_err()); } + +/// The seams between `fill` and the faces of `open` beside its edges, in the middle of each +/// edge (30 % to 70 %): per seam, the largest normal angle (degrees) and jumps of `H₂`, `H₃` and +/// `H₄` along the direction across the seam (`solidcraft_geom::linkage`), read off the two +/// faces' own surfaces: the normal curvature, its rate of change and that rate's. +fn seam_jumps(open: &Body, fill: &Body) -> Vec<[f64; 4]> { + use solidcraft_geom::linkage::surface_jet; + let (ro, rf) = (open.record(), fill.record()); + let normal = |s: &SurfaceEval, uv: [f64; 2]| { + let (_, su, sv) = s.derivs(uv[0], uv[1]).unwrap(); + su.cross(sv).normalized().unwrap() + }; + let mut out = Vec::new(); + for e in &rf.edges { + let curve = CurveEval::new(e.parameters()).unwrap(); + let [t0, t1] = e.interval; + let on_fill = SurfaceEval::new(rf.faces[e.uses[0].face as usize].parameters()).unwrap(); + // The face of `open` whose own free edge this is. + let mid = curve.point(0.5 * (t0 + t1)).unwrap(); + let near = |x: &b::Edge| { + let c = CurveEval::new(x.parameters()).unwrap(); + (0..=32).map(|k| c.point(x.interval[0] + (x.interval[1] - x.interval[0]) * k as f64 / 32.0).unwrap().dist(mid)).fold(f64::MAX, f64::min) + }; + let beside = ro.edges.iter().filter(|x| x.uses.len() == 1).min_by(|a, b| near(a).total_cmp(&near(b))).unwrap(); + let on_open = SurfaceEval::new(ro.faces[beside.uses[0].face as usize].parameters()).unwrap(); + let mut worst = [0.0f64; 4]; + for i in 0..=20 { + let (p, d) = curve.derivs(t0 + (t1 - t0) * (0.3 + 0.4 * i as f64 / 20.0)).unwrap(); + let (ua, ub) = (on_fill.project(p, None, f64::INFINITY).unwrap(), on_open.project(p, None, f64::INFINITY).unwrap()); + let na = normal(&on_fill, ua); + let nb = normal(&on_open, ub) * normal(&on_open, ub).dot(na).signum(); + let w = na.cross(d.normalized().unwrap()).normalized().unwrap(); + let (ja, jb) = (surface_jet(&on_fill, ua, na, w, 4).unwrap(), surface_jet(&on_open, ub, nb, w, 4).unwrap()); + worst[0] = worst[0].max(na.dot(nb).clamp(-1.0, 1.0).acos().to_degrees()); + for k in 2..=4 { + worst[k - 1] = worst[k - 1].max((ja.form(k, [0.0, 1.0]).unwrap() - jb.form(k, [0.0, 1.0]).unwrap()).abs()); + } + } + out.push(worst); + } + out +} + +/// A box's corner where a round of 8 up the vertical edge meets the rounds of 4 along the top +/// (one blend face rolls the top round over the vertical one); that face taken off, and the hole +/// patched G2 and G3 to the rounds and the top around it. Read off the faces themselves in the +/// middle of each seam: both meet the tangent planes and the curvature; the G3 patch also meets +/// the curvature's rate of change, which the G2 patch leaves many times larger. G3 to an edge +/// between two faces is refused. +#[test] +fn a_corner_of_three_rounds_patched_g3_holds_the_curvature_change_a_g2_patch_does_not() { + let solid = box_solid(Vec3::ZERO, Vec3::new(40.0, 40.0, 30.0)).unwrap(); + let up = crate::fillet(&solid, &[Vec3::new(40.0, 40.0, 15.0)], 8.0).unwrap(); + // The top edges and the arc between them over the vertical round: one tangent chain. + let arc = Vec3::new(32.0, 32.0, 30.0) + Vec3::new(1.0, 1.0, 0.0) * (8.0 / 2f64.sqrt()); + let rounded = crate::fillet(&up, &[Vec3::new(40.0, 20.0, 30.0), arc, Vec3::new(20.0, 40.0, 30.0)], 4.0).unwrap(); + // The blend face at the corner: the one face neither plane nor cylinder there. + let corner = Vec3::new(37.79, 36.155, 28.43); + let faces = Faces::of(&rounded); + let (k, _, _) = faces.nearest(corner); + let open = crate::remove_faces(&rounded, &[k]).unwrap(); + assert!(open.is_surface()); + let hole = [Vec3::new(34.828, 34.828, 30.0), Vec3::new(37.657, 37.657, 26.0), Vec3::new(38.828, 32.0, 28.828), Vec3::new(32.0, 38.828, 28.828)]; + let mut read = Vec::new(); + for g in [Continuity::G2, Continuity::G3] { + let name = format!("three-round corner {}", g.as_str()); + let (fill, r) = patch_edges_report(&open, &hole, &spec(g)).unwrap(); + report(&name, &r); + let seams = seam_jumps(&open, &fill); + eprintln!("{name}: jumps of the fill's report {:?}; read off the faces, per seam [angle°, H2, H3, H4] {seams:?}", r.jumps); + assert_eq!(seams.len(), 4, "{name}: four seams"); + for s in &seams { + assert!(s[0] < PATCH_ANGLE_TOL_DEG, "{name}: the tangent planes meet: {s:?}"); + assert!(s[1] < 1e-3, "{name}: the curvature meets: {s:?}"); + } + read.push(seams); + } + for (g2, g3) in read[0].iter().zip(&read[1]) { + assert!(g3[2] < 1e-2, "G3 meets the curvature change: {g3:?}"); + assert!(g2[2] > 20.0 * g3[2].max(1e-6), "G2 leaves the curvature change: {g2:?} vs G3 {g3:?}"); + } + // A closed box's top edges lie between two faces: there is no one face to meet G3. + let top = [Vec3::new(5.0, 0.0, 10.0), Vec3::new(10.0, 5.0, 10.0), Vec3::new(5.0, 10.0, 10.0), Vec3::new(0.0, 5.0, 10.0)]; + let b = box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(); + assert!(patch_edges_report(&b, &top, &spec(Continuity::G3)).is_err()); +} diff --git a/examples/clean-up/round-into-boss-wall.json b/examples/clean-up/round-into-boss-wall.json new file mode 100644 index 000000000..876962978 --- /dev/null +++ b/examples/clean-up/round-into-boss-wall.json @@ -0,0 +1,12 @@ +{ + "description": "A round along a plate's edge running into a boss wall: an 80 x 60 x 10 plate with an R12 boss through its back edge, the left part of the back edge rounded R2, then the boss's foot rounded R2 (a tangent chain up the wall and round the foot). Where the two rounds meet, the rolling ball leaves one small face between them against the wall. It is taken off (face.delete with heal false leaves the hole open, the plate a surface) and the hole patched twice from its four edges: with Curvature (g2) and, beside it, with Curvature change (g3). Both meet the rounds and the wall in tangent plane and curvature; the g3 patch also meets the curvature's rate of change in the middle of each seam (within 1e-4 /mm^2 against 1.4 to 9.6 for g2). Near the hole's corners, where the rounds themselves meet only tangent, no patch can do better than tangent. The g3 patch needs surface.patch to take g3.", + "commands": [ + {"command": "solid.box", "params": {"corner": [-40, -30, 0], "length": 80, "width": 60, "height": 10, "body_name": "Plate"}}, + {"command": "solid.cylinder", "params": {"base": [0, 26, 0], "radius": 12, "height": 30, "operation": "join", "targets": ["Plate"]}}, + {"command": "solid.fillet", "params": {"body": "Plate", "edges": [[-25, 30, 10]], "radius": 2}}, + {"command": "solid.fillet", "params": {"body": "Plate", "edges": [[-11.313708498984761, 30, 5]], "radius": 2}}, + {"command": "face.delete", "params": {"body": "Plate", "faces": [[-11.009162323954376, 30.87189136872293, 8.21538797128807]], "heal": false}}, + {"command": "surface.patch", "params": {"body": "Plate", "edges": [[-11.239, 30.199, 10.718], [-12.457, 27.798, 10.586], [-13.159, 29.381, 9.431], [-11.58, 30.31, 8.0]], "continuity": "g2", "body_name": "Patch G2"}}, + {"command": "surface.patch", "params": {"body": "Plate", "edges": [[-11.239, 30.199, 10.718], [-12.457, 27.798, 10.586], [-13.159, 29.381, 9.431], [-11.58, 30.31, 8.0]], "continuity": "g3", "body_name": "Patch G3"}} + ] +} diff --git a/examples/clean-up/three-round-corner.json b/examples/clean-up/three-round-corner.json new file mode 100644 index 000000000..fbbb95861 --- /dev/null +++ b/examples/clean-up/three-round-corner.json @@ -0,0 +1,11 @@ +{ + "description": "A corner where three rounds meet: a 40 x 40 x 30 box with its vertical edge rounded R8, then its two top edges and the arc between them over that round rounded R4 (one tangent chain). The top round rolls over the vertical one in one blend face at the corner, which meets its neighbours tangent but jumps in curvature. It is taken off (face.delete with heal false) and the hole patched from its four edges with Curvature (g2) and, beside it, with Curvature change (g3). Both meet the rounds and the top in tangent plane and curvature; the g3 patch also meets the curvature's rate of change in the middle of each seam (below 1e-4 /mm^2, against 0.27 to 0.63 for g2). The g3 patch needs surface.patch to take g3.", + "commands": [ + {"command": "solid.box", "params": {"corner": [0, 0, 0], "length": 40, "width": 40, "height": 30, "body_name": "Plate"}}, + {"command": "solid.fillet", "params": {"body": "Plate", "edges": [[40, 40, 15]], "radius": 8}}, + {"command": "solid.fillet", "params": {"body": "Plate", "edges": [[40, 20, 30], [20, 40, 30]], "radius": 4}}, + {"command": "face.delete", "params": {"body": "Plate", "faces": [[37.79, 36.155, 28.43]], "heal": false}}, + {"command": "surface.patch", "params": {"body": "Plate", "edges": [[34.828, 34.828, 30.0], [37.657, 37.657, 26.0], [38.828, 32.0, 28.828], [32.0, 38.828, 28.828]], "continuity": "g2", "body_name": "Patch G2"}}, + {"command": "surface.patch", "params": {"body": "Plate", "edges": [[34.828, 34.828, 30.0], [37.657, 37.657, 26.0], [38.828, 32.0, 28.828], [32.0, 38.828, 28.828]], "continuity": "g3", "body_name": "Patch G3"}} + ] +}