Skip to content

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

Wave 326/509: geom: patches about a fill's centre are solved by blocks, their banded interiors eliminated onto what they share (and 3 more)

jyviko21582b66e995
diff --git a/crates/geom/src/fill.rs b/crates/geom/src/fill.rs
index 5590ec400e..71934863b8 100644
--- a/crates/geom/src/fill.rs
+++ b/crates/geom/src/fill.rs
@@ -16,7 +16,7 @@ use crate::bspline::{Dir, HPoint, NurbsSurface, Side, SplineError, SplineResult,
/// Most loop points a fill takes.
pub const MAX_LOOP_POINTS: usize = 8192;
/// Most spans of the height field in each direction.
-pub const MAX_FILL_SPANS: usize = 32;
+pub const MAX_FILL_SPANS: usize = 64;
/// How full a patch's middle may be made (`crown`): 0 the least-bending fill, positive fuller,
/// negative flatter, in fractions of the loop's size. Outside this range the value is refused.
pub const MIN_CROWN: f64 = -0.9;
@@ -89,7 +89,7 @@ pub struct LoopFill {
/// is free to turn at the rim (it is not the surface that made the rim). It does not depend
/// on the grid's directions. `λ = 10⁻⁷ ·` (fitted points) `/` (control points): just enough
/// to fix the inside, small enough not to pull the surface off the loop.
-/// - Grids of 4, 8, 16, 32 spans across the box's longer side are tried, with as many across
+/// - Grids of 4, 8, 16, 32, 64 spans across the box's longer side are tried, with as many across
/// the shorter side as keep the cells about square; a grid whose cells are under twice the
/// fitted points' largest step in a direction (cells between points would be left to the
/// energy alone) waits for denser sampling. The first grid within `tol` of every sampled
diff --git a/crates/geom/src/fill_iso.rs b/crates/geom/src/fill_iso.rs
index cfd90b6d61..6d7be3c406 100644
--- a/crates/geom/src/fill_iso.rs
+++ b/crates/geom/src/fill_iso.rs
@@ -71,7 +71,8 @@
//! 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). A
+//! patch, whose system is banded, and about a centre, whose patches' banded interiors are
+//! eliminated onto the unknowns they share, at most [`MAX_SHARED_UNKNOWNS`]). 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`]).
@@ -91,11 +92,14 @@ use crate::spline_space::{Cond, Interpolant, Space};
pub const MAX_ISO_SPANS: usize = 64;
/// Most edges of a loop.
pub const MAX_ISO_EDGES: usize = 16;
-/// Most free control points of patches about a centre (their system is solved dense: the
-/// spokes and the centre couple every patch).
-const MAX_UNKNOWN_POINTS: usize = 500;
-/// Most free control points of one patch (its system is banded: see [`Quilt::new`]).
+/// Most free control points of one solve: of one patch (its system is banded: see
+/// [`Quilt::new`]), or of the patches about a centre (each patch's interior banded, eliminated
+/// onto the unknowns the patches share: [`BlockNormal`]).
const MAX_BANDED_POINTS: usize = 6000;
+/// Most unknowns (coordinates) the patches about a centre share once their interiors are
+/// eliminated: the spokes, the centre and the points beside the spokes that rows across them
+/// couple. Their system is dense: 4000² values, 128 MB.
+const MAX_SHARED_UNKNOWNS: usize = 4000;
/// Stations per span of a side where conditions are asked and checked.
const STATIONS_PER_SPAN: usize = 6;
/// Stations per control point of a row.
@@ -562,8 +566,9 @@ fn corner_scales(edges: &[IsoEdge]) -> SplineResult<Vec<f64>> {
impl Quilt {
/// The fill's patches over the loop's sides at degree `degree` (at least) in spaces refined
/// by `extra` breaks (along u and v). One patch has a space each way, each holding the two
- /// sides that run that way; patches about a centre share one space both ways, which each
- /// spoke, a row of two patches, runs in.
+ /// sides that run that way; about a centre, the space along each spoke is the two patches'
+ /// either side of it (one's along v, the other's along u), holding the spoke and the two edge
+ /// halves it meets those patches beside.
fn new(edges: &[IsoEdge], extra: &[Vec<f64>; 2], degree: usize) -> SplineResult<Quilt> {
let n = edges.len();
let scales = corner_scales(edges)?;
@@ -613,16 +618,48 @@ impl Quilt {
for m in &middle {
curves.push(line(*m, HPoint::weighted(centre, 1.0))?);
}
- let refs: Vec<&Curve> = curves.iter().collect();
- let (space, rows) = compatible(&refs, &extra[0], degree)?;
- let c = space.count();
- let row = |r: usize| rows.get(r).cloned().ok_or_else(|| SplineError::Invalid("rows".into()));
+ // Space k runs along spoke k: it is patch k's along v (its sides edge k − 1's second half
+ // and spoke k) and patch k + 1's along u (edge k + 1's first half and spoke k), so it
+ // holds those three curves' breaks only, not every edge's.
+ let mut spaces: Vec<Space> = Vec::with_capacity(n);
+ // Each curve carried into the space it runs in: [first half, second half] per edge, and
+ // each spoke.
+ let mut first_half: Vec<Option<Vec<HPoint>>> = vec![None; n];
+ let mut second_half: Vec<Option<Vec<HPoint>>> = vec![None; n];
+ let mut spoke_rows: Vec<Vec<HPoint>> = Vec::with_capacity(n);
+ for k in 0..n {
+ let (prev, next) = ((k + n - 1) % n, (k + 1) % n);
+ let refs = [
+ curves.get(2 * prev + 1).ok_or_else(|| SplineError::Invalid("curves".into()))?,
+ curves.get(2 * next).ok_or_else(|| SplineError::Invalid("curves".into()))?,
+ curves.get(2 * n + k).ok_or_else(|| SplineError::Invalid("curves".into()))?,
+ ];
+ let (space, mut rows) = compatible(&refs, &extra[0], degree)?;
+ let spoke = rows.pop().ok_or_else(|| SplineError::Invalid("rows".into()))?;
+ let first = rows.pop().ok_or_else(|| SplineError::Invalid("rows".into()))?;
+ let second = rows.pop().ok_or_else(|| SplineError::Invalid("rows".into()))?;
+ second_half[prev] = Some(second);
+ first_half[next] = Some(first);
+ spoke_rows.push(spoke);
+ spaces.push(space);
+ }
+ let got = |v: &[Option<Vec<HPoint>>], k: usize| v.get(k).cloned().flatten().ok_or_else(|| SplineError::Invalid("rows".into()));
+ let space = |k: usize| spaces.get(k).cloned().ok_or_else(|| SplineError::Invalid("spaces".into()));
+ let spoke_row = |k: usize| spoke_rows.get(k).cloned().ok_or_else(|| SplineError::Invalid("rows".into()));
let mut patches = Vec::with_capacity(n);
for k in 0..n {
let prev = (k + n - 1) % n;
- // v = 0: edge k's first half; u = 0: edge k − 1's second half, from V_k up to M_{k−1};
- // u = 1: spoke k; v = 1: spoke k − 1, from M_{k−1} to C.
- patches.push(coons([space.clone(), space.clone()], &row(2 * k)?, &row(2 * n + prev)?, &row(2 * prev + 1)?, &row(2 * n + k)?, false)?);
+ // Along u, space k − 1: v = 0 edge k's first half, v = 1 spoke k − 1 (from M_{k−1} to
+ // C); along v, space k: u = 0 edge k − 1's second half (from V_k up to M_{k−1}),
+ // u = 1 spoke k.
+ patches.push(coons(
+ [space(prev)?, space(k)?],
+ &got(&first_half, k)?,
+ &spoke_row(prev)?,
+ &got(&second_half, prev)?,
+ &spoke_row(k)?,
+ false,
+ )?);
}
// The spokes are shared rows: their weights the same in both patches (the Coons blends
// agree on them), and so are their points once solved.
@@ -634,20 +671,21 @@ impl Quilt {
unknowns - 1
};
let centre_id = next();
- let spoke_ids: Vec<Vec<usize>> = (0..n).map(|_| (1..c - 1).map(|_| next()).collect()).collect();
+ let spoke_ids: Vec<Vec<usize>> = spaces.iter().map(|sp| (1..sp.count().saturating_sub(1)).map(|_| next()).collect()).collect();
let mut slots = Vec::with_capacity(n);
for k in 0..n {
let prev = (k + n - 1) % n;
- let mut s = vec![None; c * c];
- for j in 1..c {
- for i in 1..c {
- let id = match (i == c - 1, j == c - 1) {
+ let [cu, cv] = patches.get(k).map(Patch::counts).ok_or_else(|| SplineError::Invalid("patch".into()))?;
+ let mut s = vec![None; cu * cv];
+ for j in 1..cv {
+ for i in 1..cu {
+ let id = match (i == cu - 1, j == cv - 1) {
(true, true) => centre_id,
(true, false) => *spoke_ids.get(k).and_then(|x| x.get(j - 1)).ok_or_else(|| SplineError::Invalid("spoke".into()))?,
(false, true) => *spoke_ids.get(prev).and_then(|x| x.get(i - 1)).ok_or_else(|| SplineError::Invalid("spoke".into()))?,
(false, false) => next(),
};
- if let Some(slot) = s.get_mut(i + c * j) {
+ if let Some(slot) = s.get_mut(i + cu * j) {
*slot = Some(id);
}
}
@@ -664,10 +702,10 @@ impl Quilt {
Ok(Quilt { patches, slots, unknowns, pieces, spokes })
}
- /// Most free control points one solve takes: about a centre (`shared` spaces) the system is
- /// dense, for one patch banded.
+ /// Most free control points one solve takes, one patch or several about a centre.
fn most_unknowns(shared: bool) -> usize {
- if shared { MAX_UNKNOWN_POINTS } else { MAX_BANDED_POINTS }
+ let _ = shared;
+ MAX_BANDED_POINTS
}
/// Write the unknowns' values into every patch that holds them.
@@ -988,8 +1026,10 @@ pub fn iso_fill(
let stations = stations(edges, &quilt, &mut *across, &corners)?;
let spaces = quilt.patches.first().map(|p| p.spaces.clone()).ok_or_else(|| SplineError::Invalid("no patch".into()))?;
let shared = !quilt.spokes.is_empty();
- // Rows enough for the conditions from opposite sides not to share control points.
- let cramped = spaces.clone().map(|s| s.count() < 2 * (order + 1));
+ // Rows enough for the conditions from opposite sides not to share control points, in
+ // every patch.
+ let fewest = |d: usize| quilt.patches.iter().filter_map(|p| p.spaces.get(d).map(Space::count)).min().unwrap_or(0);
+ let cramped = [fewest(0), fewest(1)].map(|c| c < 2 * (order + 1));
if cramped.iter().any(|c| *c) && refinable(&spans, cramped, shared, quilt.unknowns) {
halve(&mut extra, &mut spans, &spaces, cramped, shared);
continue;
@@ -1032,10 +1072,19 @@ fn refinable(spans: &[usize; 2], wanted: [bool; 2], shared: bool, unknowns: usiz
spans_ok && unknowns.saturating_mul(2usize.pow(grows)) <= Quilt::most_unknowns(shared)
}
-/// Halve every span of the spaces in the `wanted` directions (both when the patches share one
-/// space): the breaks that do it added to `extra`.
+/// Halve every span of the spaces in the `wanted` directions: the breaks that do it added to
+/// `extra`. About a centre, every spoke's space takes the middles of a uniform grid as fine as
+/// the refinement has reached.
fn halve(extra: &mut [Vec<f64>; 2], spans: &mut [usize; 2], spaces: &[Space; 2], wanted: [bool; 2], shared: bool) {
- let wanted = if shared { [true; 2] } else { wanted };
+ if shared {
+ // Each spoke's space has the breaks of its own sides: every one of them gets the same
+ // further breaks, the middles of the uniform grid at the level reached so far.
+ let n = spans[0];
+ extra[0].extend((0..n).map(|i| (2 * i + 1) as f64 / (2 * n) as f64));
+ spans[0] *= 2;
+ spans[1] *= 2;
+ return;
+ }
for (((e, n), s), w) in extra.iter_mut().zip(spans.iter_mut()).zip(spaces).zip(wanted) {
if w {
e.extend(breaks(s).windows(2).map(|w| 0.5 * (w[0] + w[1])));
@@ -1157,10 +1206,10 @@ fn solve(mut quilt: Quilt, stations: &[Station], spec: &IsoSpec) -> SplineResult
let mut located: Vec<(usize, [f64; 2])> = Vec::new();
let mut report = Achieved::default();
let mut along = Along::default();
- let spoke_count = quilt.patches.first().map_or(0, |p| station_count(&p.spaces[0]));
+ let spoke_count = quilt.patches.iter().map(|p| station_count(&p.spaces[0])).max().unwrap_or(0);
let top = stations.iter().map(Station::order).max().unwrap_or(1);
- // 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));
+ // The mean span of each space of a patch.
+ let span = |p: &Patch| 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 {
@@ -1168,7 +1217,7 @@ fn solve(mut quilt: Quilt, stations: &[Station], spec: &IsoSpec) -> SplineResult
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.
- linkage_rows(&mut rows, patch, s, span.get(1 - s.side % 2).copied().unwrap_or(1.0))?;
+ linkage_rows(&mut rows, patch, s, span(patch).get(1 - s.side % 2).copied().unwrap_or(1.0))?;
}
// Across each spoke the two patches' derivatives away from it are opposed.
for &(left, right) in &quilt.spokes {
@@ -1365,7 +1414,7 @@ fn gram(s: &Space, m: usize) -> SplineResult<Vec<Vec<Vec<f64>>>> {
fn least_squares(quilt: &Quilt, rows: &[Row], energy: &[Vec<(usize, usize, f64)>]) -> SplineResult<Vec<Vec3>> {
let dim = 3 * quilt.unknowns;
let slot = |p: usize, flat: usize| quilt.slots.get(p).and_then(|s| s.get(flat)).copied().flatten();
- let mut a = Normal::new(dim, bandwidth(quilt, rows, energy));
+ let mut a = if quilt.spokes.is_empty() { Normal::new(dim, bandwidth(quilt, rows, energy)) } else { Normal::Blocks(BlockNormal::new(quilt)) };
let mut b = vec![0.0; dim];
let value = |p: usize, flat: usize| quilt.patches.get(p).and_then(|x| x.net.get(flat)).copied().unwrap_or(Vec3::ZERO);
let mut condition_trace = 0.0;
@@ -1454,6 +1503,7 @@ fn bandwidth(quilt: &Quilt, rows: &[Row], energy: &[Vec<(usize, usize, f64)>]) -
enum Normal {
Band(crate::fill::Band),
Dense(Vec<f64>, usize),
+ Blocks(BlockNormal),
}
impl Normal {
@@ -1470,6 +1520,7 @@ impl Normal {
*x += v;
}
}
+ Normal::Blocks(m) => m.add(r, s, v),
}
}
@@ -1477,10 +1528,189 @@ impl Normal {
match self {
Normal::Band(m) => m.factor_rows()?.substitute(b),
Normal::Dense(a, n) => cholesky(a, b, n),
+ Normal::Blocks(m) => m.solve(b),
}
}
}
+/// The normal equations of patches about a centre, solved by blocks: each patch's interior
+/// unknowns (coordinates of control points only that patch holds, coupled to no other patch's)
+/// form a banded block, eliminated exactly onto the shared unknowns (the spokes', the centre's,
+/// and any a row couples across patches) by their Schur complement, which is solved dense; the
+/// interiors then follow by back substitution. Entries are kept sparse until the blocks are
+/// known (callers add both halves of the symmetric matrix).
+struct BlockNormal {
+ /// Each coordinate's patch when only one patch holds its point, else `None`.
+ owner: Vec<Option<usize>>,
+ entries: std::collections::HashMap<(usize, usize), f64>,
+}
+
+impl BlockNormal {
+ fn new(quilt: &Quilt) -> BlockNormal {
+ let mut holders: Vec<Vec<usize>> = vec![Vec::new(); quilt.unknowns];
+ for (p, slots) in quilt.slots.iter().enumerate() {
+ for id in slots.iter().flatten() {
+ if let Some(h) = holders.get_mut(*id)
+ && !h.contains(&p)
+ {
+ h.push(p);
+ }
+ }
+ }
+ let owner = holders.iter().flat_map(|h| {
+ let o = if let [p] = h.as_slice() { Some(*p) } else { None };
+ [o; 3]
+ });
+ BlockNormal { owner: owner.collect(), entries: std::collections::HashMap::new() }
+ }
+
+ fn add(&mut self, r: usize, s: usize, v: f64) {
+ if v != 0.0 {
+ *self.entries.entry((r, s)).or_insert(0.0) += v;
+ }
+ }
+
+ fn solve(mut self, b: Vec<f64>) -> SplineResult<Vec<f64>> {
+ let n = b.len();
+ // A coordinate coupled to another patch's interior is shared too.
+ let coupled: Vec<usize> = self
+ .entries
+ .keys()
+ .filter(|(r, c)| matches!((self.owner.get(*r).copied().flatten(), self.owner.get(*c).copied().flatten()), (Some(a), Some(b)) if a != b))
+ .flat_map(|(r, c)| [*r, *c])
+ .collect();
+ for x in coupled {
+ if let Some(o) = self.owner.get_mut(x) {
+ *o = None;
+ }
+ }
+ let shared: Vec<usize> = (0..n).filter(|x| self.owner.get(*x).copied().flatten().is_none()).collect();
+ if shared.len() > MAX_SHARED_UNKNOWNS {
+ return Err(SplineError::TooLarge(format!(
+ "{} unknowns shared by the patches about the centre (at most {MAX_SHARED_UNKNOWNS})",
+ shared.len()
+ )));
+ }
+ let mut place = vec![usize::MAX; n];
+ for (i, x) in shared.iter().enumerate() {
+ if let Some(slot) = place.get_mut(*x) {
+ *slot = i;
+ }
+ }
+ let patches = self.owner.iter().flatten().copied().max().map_or(0, |m| m + 1);
+ let mut interior: Vec<Vec<usize>> = vec![Vec::new(); patches];
+ for (x, o) in self.owner.iter().enumerate() {
+ if let Some(p) = o
+ && let Some(list) = interior.get_mut(*p)
+ {
+ if let Some(slot) = place.get_mut(x) {
+ *slot = list.len();
+ }
+ list.push(x);
+ }
+ }
+ let m = shared.len();
+ // The shared block, and per patch its block, its coupling to the shared unknowns.
+ let mut s_mat = vec![0.0; m * m];
+ let mut blocks: Vec<std::collections::HashMap<(usize, usize), f64>> = vec![std::collections::HashMap::new(); patches];
+ let mut couple: Vec<std::collections::HashMap<(usize, usize), f64>> = vec![std::collections::HashMap::new(); patches];
+ for ((r, c), v) in std::mem::take(&mut self.entries) {
+ let (or, oc) = (self.owner.get(r).copied().flatten(), self.owner.get(c).copied().flatten());
+ let (pr, pc) = (place.get(r).copied().unwrap_or(0), place.get(c).copied().unwrap_or(0));
+ match (or, oc) {
+ (None, None) => {
+ if let Some(x) = s_mat.get_mut(pr * m + pc) {
+ *x += v;
+ }
+ }
+ (Some(p), Some(_)) => {
+ if let Some(blk) = blocks.get_mut(p) {
+ *blk.entry((pr, pc)).or_insert(0.0) += v;
+ }
+ }
+ // Interior row, shared column (the transposed entry is its mirror).
+ (Some(p), None) => {
+ if let Some(cp) = couple.get_mut(p) {
+ *cp.entry((pr, pc)).or_insert(0.0) += v;
+ }
+ }
+ (None, Some(_)) => {}
+ }
+ }
+ let mut rhs: Vec<f64> = shared.iter().map(|x| b.get(*x).copied().unwrap_or(0.0)).collect();
+ let mut solved_parts: Vec<(crate::fill::Band, Vec<f64>, Vec<(usize, Vec<f64>)>)> = Vec::with_capacity(patches);
+ for p in 0..patches {
+ let ids = interior.get(p).map(Vec::as_slice).unwrap_or(&[]);
+ let k = ids.len();
+ let blk = blocks.get(p).cloned().unwrap_or_default();
+ let bw = blk.keys().map(|(r, c)| r.abs_diff(*c)).max().unwrap_or(0);
+ let mut band = crate::fill::Band::new(k.max(1), bw);
+ for (&(r, c), &v) in &blk {
+ band.add(r, c, v);
+ }
+ if k == 0 {
+ solved_parts.push((band, Vec::new(), Vec::new()));
+ continue;
+ }
+ let band = band.factor_rows()?;
+ // g = A_kk⁻¹ b_k; per shared column j coupled to this patch, z_j = A_kk⁻¹ A_k,j.
+ let bk: Vec<f64> = ids.iter().map(|x| b.get(*x).copied().unwrap_or(0.0)).collect();
+ let g = band.substitute(bk)?;
+ let mut columns: std::collections::BTreeMap<usize, Vec<f64>> = std::collections::BTreeMap::new();
+ for (&(r, j), &v) in couple.get(p).into_iter().flatten() {
+ if let Some(cell) = columns.entry(j).or_insert_with(|| vec![0.0; k]).get_mut(r) {
+ *cell += v;
+ }
+ }
+ let mut z: Vec<(usize, Vec<f64>)> = Vec::with_capacity(columns.len());
+ for (j, col) in columns {
+ z.push((j, band.substitute(col)?));
+ }
+ // S −= A_Bk·Z, rhs −= A_Bk·g, A_Bk the transpose of the coupling.
+ let coupling = couple.get(p).cloned().unwrap_or_default();
+ let mut by_column: std::collections::BTreeMap<usize, Vec<(usize, f64)>> = std::collections::BTreeMap::new();
+ for (&(r, j), &v) in &coupling {
+ by_column.entry(j).or_default().push((r, v));
+ }
+ for (i, entries) in &by_column {
+ let dot = |w: &[f64]| entries.iter().map(|(r, v)| v * w.get(*r).copied().unwrap_or(0.0)).sum::<f64>();
+ if let Some(x) = rhs.get_mut(*i) {
+ *x -= dot(&g);
+ }
+ for (j, zj) in &z {
+ if let Some(x) = s_mat.get_mut(i * m + j) {
+ *x -= dot(zj);
+ }
+ }
+ }
+ solved_parts.push((band, g, z));
+ }
+ let xs = if m > 0 { cholesky(s_mat, rhs, m)? } else { Vec::new() };
+ let mut x = vec![0.0; n];
+ for (i, id) in shared.iter().enumerate() {
+ if let Some(slot) = x.get_mut(*id) {
+ *slot = xs.get(i).copied().unwrap_or(0.0);
+ }
+ }
+ for (p, (_, g, z)) in solved_parts.iter().enumerate() {
+ let ids = interior.get(p).map(Vec::as_slice).unwrap_or(&[]);
+ for (r, id) in ids.iter().enumerate() {
+ let mut v = g.get(r).copied().unwrap_or(0.0);
+ for (j, zj) in z {
+ v -= zj.get(r).copied().unwrap_or(0.0) * xs.get(*j).copied().unwrap_or(0.0);
+ }
+ if let Some(slot) = x.get_mut(*id) {
+ *slot = v;
+ }
+ }
+ }
+ if x.iter().any(|v| !v.is_finite()) {
+ return invalid("the patches' equations have no finite solution");
+ }
+ Ok(x)
+ }
+}
+
/// Solve the symmetric positive definite `a·x = b` (dense, `n × n`).
fn cholesky(mut a: Vec<f64>, mut b: Vec<f64>, n: usize) -> SplineResult<Vec<f64>> {
let at = |a: &[f64], r: usize, c: usize| a.get(r * n + c).copied().unwrap_or(0.0);
@@ -1648,19 +1878,37 @@ fn nearest(quilt: &Quilt, p: Vec3) -> (usize, [f64; 2]) {
(k, [u, v])
}
-/// Whether a patch folds back on itself: its normal turns against the middle's somewhere on a
-/// grid (clear of a three-sided patch's pole at u = 0, where the normal is undefined).
+/// Whether a patch folds back on itself: on a grid of its parameters, its normal reverses between
+/// neighbouring points (the surface turns back over itself), or vanishes inside it. A patch may
+/// turn its normal through more than a right angle overall (a dome meeting a tube's wall, a
+/// window round more than half a cylinder): only a reversal between neighbours is a fold. The
+/// normal may vanish at a corner (where two sides run on straight, as on a closed loop's pieces)
+/// and on a three-sided patch's pole at u = 0.
fn folds(patch: &Patch) -> bool {
- let Some(mid) = patch.normal(0.5, 0.5) else { return true };
- for i in 0..=FOLD_SAMPLES {
- if patch.pole && i == 0 {
- continue;
+ let n = FOLD_SAMPLES;
+ if patch.normal(0.5, 0.5).is_none() {
+ return true;
+ }
+ let at = |i: usize, j: usize| patch.normal(i as f64 / n as f64, j as f64 / n as f64);
+ let mut grid: Vec<Option<Vec3>> = Vec::with_capacity((n + 1) * (n + 1));
+ for i in 0..=n {
+ for j in 0..=n {
+ let normal = at(i, j);
+ let excused = (patch.pole && i == 0) || ((i == 0 || i == n) && (j == 0 || j == n));
+ if normal.is_none() && !excused {
+ return true;
+ }
+ grid.push(normal);
}
- for j in 0..=FOLD_SAMPLES {
- let (u, v) = (i as f64 / FOLD_SAMPLES as f64, j as f64 / FOLD_SAMPLES as f64);
- match patch.normal(u, v) {
- Some(n) if n.dot(mid) > 0.0 => {}
- _ => return true,
+ }
+ let get = |i: usize, j: usize| grid.get(i * (n + 1) + j).copied().flatten();
+ for i in 0..=n {
+ for j in 0..=n {
+ let Some(a) = get(i, j) else { continue };
+ for (k, l) in [(i + 1, j), (i, j + 1)] {
+ if k <= n && l <= n && get(k, l).is_some_and(|b| a.dot(b) <= 0.0) {
+ return true;
+ }
}
}
}
diff --git a/crates/kernel/src/fill_general_tests.rs b/crates/kernel/src/fill_general_tests.rs
index b0fa414f15..7fee97f5a5 100644
--- a/crates/kernel/src/fill_general_tests.rs
+++ b/crates/kernel/src/fill_general_tests.rs
@@ -164,8 +164,21 @@ fn check_face(name: &str, open: &Body, fill: &Body) -> f64 {
assert!(fill.is_surface());
assert!(fill.face_count() >= 1, "{name}: a face");
let (own, made) = (open.record(), fill.record());
+ // The same kind of curve on the same curve it is parameterised on, to rounding (SMLib makes a
+ // conic's frame and NURBS form again on a round trip, the last bit of a coordinate apart).
+ let close = |p: &[f64], q: &[f64]| p.len() == q.len() && p.iter().zip(q).all(|(x, y)| (x - y).abs() <= 1e-12 * (1.0 + x.abs().max(y.abs())));
+ let same = |c: &b::Curve, d: &b::Curve| match (c, d) {
+ (b::Curve::Spline { knots: k, points: p }, b::Curve::Spline { knots: l, points: q }) => {
+ k == l && p.len() == q.len() && p.iter().zip(q).all(|(x, y)| close(x, y))
+ }
+ (b::Curve::RationalSpline { knots: k, homogeneous: p }, b::Curve::RationalSpline { knots: l, homogeneous: q }) => {
+ k == l && p.len() == q.len() && p.iter().zip(q).all(|(x, y)| close(x, y))
+ }
+ _ => c == d,
+ };
+ let kind = |e: &b::Edge| std::mem::discriminant(&e.curve);
for e in made.edges.iter().filter(|e| e.uses.len() == 1) {
- assert!(own.edges.iter().any(|o| o.curve == e.curve), "{name}: an edge that is not the body's");
+ assert!(own.edges.iter().any(|o| kind(o) == kind(e) && same(o.parameters(), e.parameters())), "{name}: an edge that is not the body's");
}
let faces = Faces::of(fill);
let tol = face_tolerance(open);