Skip to main content

brep_geometry/geometry/
regularity.rs

1//! An exact certificate that a NURBS surface is regular: its normal
2//! `N = ∂S/∂u × ∂S/∂v` vanishes nowhere and never turns back, so the sheet
3//! neither collapses nor folds over onto itself.
4//!
5//! This is a local property (the surface is an immersion): it does not
6//! certify that the sheet is embedded. A sheet that winds round and lies over
7//! itself without ever folding (an annulus traversed twice) has a regular
8//! normal everywhere and is certified. Positivity is judged to a roundoff
9//! band of 1e-13 of the coefficients' size: a fold confined to a parameter
10//! region of that order at a domain corner where the normal vanishes is
11//! indistinguishable from the tangent corner the exemption below admits.
12//!
13//! # Method
14//!
15//! The surface is cut at its interior knots into Bézier pieces (exact knot
16//! insertion). On a polynomial piece of degree `(p, q)` each component of `N`
17//! is a polynomial of degree `(2p − 1, 2q − 1)`; on a rational piece with
18//! homogeneous points `P` and weights `w`,
19//! `w⁴ (S_u × S_v) = w (w P_u × P_v + w_v P × P_u + w_u P_v × P)`, so the
20//! bracket, of degree `(3p − 1, 3q − 1)`, points the same way as `N` (the
21//! weights are positive). Either way `N` is held exactly as a grid of
22//! Bernstein coefficient vectors.
23//!
24//! A box of a piece is certified when every coefficient vector has a positive
25//! component along one reference direction (the normal at the box's centre):
26//! `N · n` is then a sum of non-negative Bernstein basis functions with
27//! positive weights, positive everywhere on the box, so `N` neither vanishes
28//! there nor reverses. A box that is not certified is halved (de Casteljau on
29//! its longer side) and its halves judged in turn; the coefficients converge
30//! to the values, so a regular surface is certified after a few levels.
31//!
32//! At the four corners of the domain the normal may vanish legitimately: where
33//! two sides meet tangentially (a disc bounded by four arcs) the corner is a
34//! parameter singularity of a regular sheet. There the corner coefficient
35//! (the normal's exact value at the corner) may be zero, and so may others
36//! beside it where the tangency is of higher order; the box is certified when
37//! no coefficient is negative, every other corner's is positive and each side
38//! of the box has a positive one, which keeps `N · n` positive everywhere in
39//! the box except at that corner.
40//!
41//! Where the interior knot lines leave the surface only C0, the normals on the
42//! two sides of the line are compared the same way: `N⁻ · N⁺` along the line
43//! is a polynomial whose coefficients must be positive (a crease that turns
44//! back by more than a right angle is a fold).
45//!
46//! # Refusals
47//!
48//! A box that cannot be certified is searched depth first for a witness, a
49//! point where the surface demonstrably fails:
50//!
51//! - [`Irregularity::Collapses`]: the normal at a box corner vanishes
52//!   against the derivatives there (`|S_u × S_v| ≤ 1e-9 |S_u| |S_v|`);
53//! - [`Irregularity::FoldsOver`]: the exact normals at two corners of a box
54//!   no larger than 1/1024 of its piece each way point into opposite half
55//!   spaces (or across a C0 knot line, the two sides' normals do);
56//! - [`Irregularity::Uncertified`]: neither a certificate nor a witness within
57//!   the subdivision budget, or an input the method does not take (an
58//!   unclamped knot vector, a non-positive weight). Never a silent pass.
59
60use crate::KnotDirection;
61use crate::{NurbsSurface, Vec3};
62
63/// Why a surface is not certified regular. Points are in the surface's own
64/// parameters.
65#[derive(Clone, Debug, PartialEq)]
66pub enum Irregularity {
67    /// The normal vanishes at `(u, v)`.
68    Collapses { u: f64, v: f64 },
69    /// The normal turns back near `(u, v)`.
70    FoldsOver { u: f64, v: f64 },
71    /// Neither certified nor refuted near `(u, v)`; `reason` says why.
72    Uncertified { u: f64, v: f64, reason: String },
73}
74
75impl std::fmt::Display for Irregularity {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        match self {
78            Self::Collapses { u, v } => write!(f, "the normal vanishes at ({u:.6}, {v:.6})"),
79            Self::FoldsOver { u, v } => write!(f, "the normal turns back near ({u:.6}, {v:.6})"),
80            Self::Uncertified { u, v, reason } => write!(f, "regularity not certified near ({u:.6}, {v:.6}): {reason}"),
81        }
82    }
83}
84
85/// What a certificate cost: Bézier pieces, boxes judged, C0 knot lines checked.
86#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
87pub struct RegularityReport {
88    pub pieces: usize,
89    pub boxes: usize,
90    pub creases: usize,
91}
92
93/// Boxes judged before a surface is reported uncertified.
94const BOX_BUDGET: usize = 400_000;
95/// Halvings of one box's side before it is reported uncertified.
96const MAX_DEPTH: u32 = 40;
97/// A box this small (fraction of its piece, each way) whose corner normals
98/// oppose is a fold.
99const WITNESS_SIZE: f64 = 1.0 / 1024.0;
100/// A corner normal this small against its piece's largest coefficient is a
101/// collapse (a domain corner's may be).
102const VANISHING: f64 = 1e-9;
103/// Roundoff margin of a positive coefficient, against the box's largest.
104const MARGIN: f64 = 1e-13;
105
106/// Certify `surface` regular (see the module notes), or name where it fails.
107pub fn certify_regular(surface: &NurbsSurface) -> Result<RegularityReport, Irregularity> {
108    let uncertified = |reason: String| Irregularity::Uncertified { u: f64::NAN, v: f64::NAN, reason };
109    let [u0, u1] = surface.domain_u().map_err(&uncertified)?;
110    let [v0, v1] = surface.domain_v().map_err(&uncertified)?;
111    let (p, q) = (surface.degree_u, surface.degree_v);
112    if p == 0 || q == 0 {
113        return Err(uncertified(format!("degree ({p}, {q}) has no normal")));
114    }
115    for (knots, degree, name) in [(&surface.knots_u, p, "u"), (&surface.knots_v, q, "v")] {
116        let n = knots.len();
117        if knots[..=degree].iter().any(|k| *k != knots[0]) || knots[n - degree - 1..].iter().any(|k| *k != knots[n - 1]) {
118            return Err(uncertified(format!("the {name} knot vector is not clamped")));
119        }
120    }
121    let rational = {
122        let w0 = surface.control_points[0][0].w;
123        surface.control_points.iter().flatten().any(|point| point.w != w0)
124    };
125    if surface.control_points.iter().flatten().any(|point| !(point.w > 0.0) || !point.w.is_finite()) {
126        return Err(uncertified("a weight is not positive".into()));
127    }
128    // Every interior knot to multiplicity = degree: the net is then the Bézier
129    // pieces' nets side by side.
130    let (breaks_u, insert_u) = breaks(&surface.knots_u, p, u0, u1);
131    let (breaks_v, insert_v) = breaks(&surface.knots_v, q, v0, v1);
132    let refined = surface
133        .refine_knots(KnotDirection::U, &insert_u)
134        .and_then(|refined| refined.refine_knots(KnotDirection::V, &insert_v))
135        .map_err(|error| uncertified(error.to_string()))?;
136    let (pieces_u, pieces_v) = (breaks_u.len() - 1, breaks_v.len() - 1);
137    if refined.control_points.len() != pieces_u * p + 1 || refined.control_points.iter().any(|row| row.len() != pieces_v * q + 1) {
138        return Err(uncertified("the refined net does not split into Bézier pieces".into()));
139    }
140    let mut report = RegularityReport::default();
141    let mut normals: Vec<Vec<Grid<Vec3>>> = Vec::with_capacity(pieces_u);
142    for a in 0..pieces_u {
143        let mut row = Vec::with_capacity(pieces_v);
144        for b in 0..pieces_v {
145            let net: Vec<Vec<crate::Vec4>> =
146                (0..=p).map(|i| refined.control_points[a * p + i][b * q..=b * q + q].to_vec()).collect();
147            let normal = piece_normal(&net, p, q, rational);
148            let piece = Piece {
149                u: [breaks_u[a], breaks_u[a + 1]],
150                v: [breaks_v[b], breaks_v[b + 1]],
151                corners: [
152                    a == 0 && b == 0,
153                    a == pieces_u - 1 && b == 0,
154                    a == 0 && b == pieces_v - 1,
155                    a == pieces_u - 1 && b == pieces_v - 1,
156                ],
157            };
158            certify_piece(surface, &normal, &piece, &mut report)?;
159            report.pieces += 1;
160            row.push(normal);
161        }
162        normals.push(row);
163    }
164    // C0 knot lines: the two sides' normals must not turn back across them.
165    let multiplicity = |knots: &[f64], value: f64| knots.iter().filter(|k| **k == value).count();
166    for a in 0..pieces_u.saturating_sub(1) {
167        if multiplicity(&surface.knots_u, breaks_u[a + 1]) < p {
168            continue;
169        }
170        for b in 0..pieces_v {
171            let (before, after) = (&normals[a][b], &normals[a + 1][b]);
172            let left: Vec<Vec3> = (0..=before.n).map(|j| before.at(before.m, j)).collect();
173            let right: Vec<Vec3> = (0..=after.n).map(|j| after.at(0, j)).collect();
174            report.creases += 1;
175            certify_crease(&left, &right, breaks_v[b], breaks_v[b + 1])
176                .map_err(|t| Irregularity::FoldsOver { u: breaks_u[a + 1], v: t })?;
177        }
178    }
179    for b in 0..pieces_v.saturating_sub(1) {
180        if multiplicity(&surface.knots_v, breaks_v[b + 1]) < q {
181            continue;
182        }
183        for a in 0..pieces_u {
184            let (before, after) = (&normals[a][b], &normals[a][b + 1]);
185            let below: Vec<Vec3> = (0..=before.m).map(|i| before.at(i, before.n)).collect();
186            let above: Vec<Vec3> = (0..=after.m).map(|i| after.at(i, 0)).collect();
187            report.creases += 1;
188            certify_crease(&below, &above, breaks_u[a], breaks_u[a + 1])
189                .map_err(|s| Irregularity::FoldsOver { u: s, v: breaks_v[b + 1] })?;
190        }
191    }
192    Ok(report)
193}
194
195/// The distinct knot values of the domain (its breakpoints) and the knots to
196/// insert so every interior one has multiplicity `degree`.
197fn breaks(knots: &[f64], degree: usize, start: f64, end: f64) -> (Vec<f64>, Vec<f64>) {
198    let mut values: Vec<f64> = Vec::new();
199    let mut insert = Vec::new();
200    for &knot in knots {
201        if knot < start || knot > end || values.last() == Some(&knot) {
202            continue;
203        }
204        values.push(knot);
205        if knot > start && knot < end {
206            let have = knots.iter().filter(|k| **k == knot).count();
207            insert.extend(std::iter::repeat(knot).take(degree.saturating_sub(have)));
208        }
209    }
210    (values, insert)
211}
212
213/// A Bézier piece's place: its parameter box and which of its corners
214/// (`(0,0)`, `(1,0)`, `(0,1)`, `(1,1)` in its own coordinates) are corners of
215/// the surface's domain.
216struct Piece {
217    u: [f64; 2],
218    v: [f64; 2],
219    corners: [bool; 4],
220}
221
222/// A tensor-product Bernstein polynomial of degree `(m, n)` on the unit square:
223/// coefficients `c[i (n + 1) + j]`.
224#[derive(Clone, Debug)]
225struct Grid<T> {
226    m: usize,
227    n: usize,
228    c: Vec<T>,
229}
230
231trait Linear: Copy {
232    fn zero() -> Self;
233    fn plus(self, other: Self) -> Self;
234    fn times(self, factor: f64) -> Self;
235}
236
237impl Linear for f64 {
238    fn zero() -> Self {
239        0.0
240    }
241    fn plus(self, other: Self) -> Self {
242        self + other
243    }
244    fn times(self, factor: f64) -> Self {
245        self * factor
246    }
247}
248
249impl Linear for Vec3 {
250    fn zero() -> Self {
251        Vec3::new(0.0, 0.0, 0.0)
252    }
253    fn plus(self, other: Self) -> Self {
254        self.add(other)
255    }
256    fn times(self, factor: f64) -> Self {
257        self.scale(factor)
258    }
259}
260
261fn binomial(n: usize, k: usize) -> f64 {
262    let k = k.min(n - k);
263    (0..k).fold(1.0, |value, i| value * (n - i) as f64 / (i + 1) as f64)
264}
265
266impl<T: Linear> Grid<T> {
267    fn at(&self, i: usize, j: usize) -> T {
268        self.c[i * (self.n + 1) + j]
269    }
270
271    /// `∂/∂u` (scaled to the unit square), degree `(m − 1, n)`.
272    fn du(&self) -> Grid<T> {
273        let (m, n) = (self.m, self.n);
274        let c = (0..m)
275            .flat_map(|i| (0..=n).map(move |j| (i, j)))
276            .map(|(i, j)| self.at(i + 1, j).plus(self.at(i, j).times(-1.0)).times(m as f64))
277            .collect();
278        Grid { m: m - 1, n, c }
279    }
280
281    /// `∂/∂v` (scaled to the unit square), degree `(m, n − 1)`.
282    fn dv(&self) -> Grid<T> {
283        let (m, n) = (self.m, self.n);
284        let c = (0..=m)
285            .flat_map(|i| (0..n).map(move |j| (i, j)))
286            .map(|(i, j)| self.at(i, j + 1).plus(self.at(i, j).times(-1.0)).times(n as f64))
287            .collect();
288        Grid { m, n: n - 1, c }
289    }
290
291    fn plus(&self, other: &Grid<T>) -> Grid<T> {
292        debug_assert!(self.m == other.m && self.n == other.n);
293        Grid { m: self.m, n: self.n, c: self.c.iter().zip(&other.c).map(|(a, b)| a.plus(*b)).collect() }
294    }
295
296    /// The two halves at `u = 1/2` (`along_u`) or `v = 1/2`, by de Casteljau.
297    fn halves(&self, along_u: bool) -> (Grid<T>, Grid<T>) {
298        let (m, n) = (self.m, self.n);
299        let mut low = self.clone();
300        let mut high = self.clone();
301        let (count, length) = if along_u { (n + 1, m + 1) } else { (m + 1, n + 1) };
302        let index = |line: usize, k: usize| if along_u { k * (n + 1) + line } else { line * (n + 1) + k };
303        let mut work = vec![T::zero(); length];
304        for line in 0..count {
305            for (k, slot) in work.iter_mut().enumerate() {
306                *slot = self.c[index(line, k)];
307            }
308            for level in 0..length {
309                low.c[index(line, level)] = work[0];
310                high.c[index(line, length - 1 - level)] = work[length - 1 - level];
311                for k in 0..length - 1 - level {
312                    work[k] = work[k].plus(work[k + 1]).times(0.5);
313                }
314            }
315        }
316        (low, high)
317    }
318
319    /// The value at `(s, t)` of the unit square, by de Casteljau.
320    fn value(&self, s: f64, t: f64) -> T {
321        let rows: Vec<T> = (0..=self.m)
322            .map(|i| casteljau(&(0..=self.n).map(|j| self.at(i, j)).collect::<Vec<_>>(), t))
323            .collect();
324        casteljau(&rows, s)
325    }
326}
327
328fn casteljau<T: Linear>(points: &[T], t: f64) -> T {
329    let mut work = points.to_vec();
330    for level in 1..work.len() {
331        for k in 0..work.len() - level {
332            work[k] = work[k].times(1.0 - t).plus(work[k + 1].times(t));
333        }
334    }
335    work[0]
336}
337
338/// The Bernstein product of two grids, combining coefficients by `combine`.
339fn product<A: Linear, B: Linear, C: Linear>(a: &Grid<A>, b: &Grid<B>, combine: impl Fn(A, B) -> C) -> Grid<C> {
340    let (m, n) = (a.m + b.m, a.n + b.n);
341    let mut c = vec![C::zero(); (m + 1) * (n + 1)];
342    for i in 0..=a.m {
343        for j in 0..=a.n {
344            for k in 0..=b.m {
345                for l in 0..=b.n {
346                    let factor = binomial(a.m, i) * binomial(b.m, k) / binomial(m, i + k) * binomial(a.n, j)
347                        * binomial(b.n, l)
348                        / binomial(n, j + l);
349                    let slot = &mut c[(i + k) * (n + 1) + j + l];
350                    *slot = slot.plus(combine(a.at(i, j), b.at(k, l)).times(factor));
351                }
352            }
353        }
354    }
355    Grid { m, n, c }
356}
357
358/// The Bernstein coefficients of a direction of the normal of the Bézier
359/// piece with homogeneous net `net` (see the module notes).
360fn piece_normal(net: &[Vec<crate::Vec4>], p: usize, q: usize, rational: bool) -> Grid<Vec3> {
361    let cells = |f: &dyn Fn(&crate::Vec4) -> Vec3| Grid {
362        m: p,
363        n: q,
364        c: net.iter().flat_map(|row| row.iter().map(f)).collect::<Vec<Vec3>>(),
365    };
366    if !rational {
367        let points = cells(&|point| Vec3::new(point.x / point.w, point.y / point.w, point.z / point.w));
368        return product(&points.du(), &points.dv(), Vec3::cross);
369    }
370    let points = cells(&|point| Vec3::new(point.x, point.y, point.z));
371    let weights = Grid { m: p, n: q, c: net.iter().flat_map(|row| row.iter().map(|point| point.w)).collect::<Vec<f64>>() };
372    let (pu, pv) = (points.du(), points.dv());
373    let first = product(&weights, &product(&pu, &pv, Vec3::cross), |w, n| n.scale(w));
374    let second = product(&weights.dv(), &product(&points, &pu, Vec3::cross), |w, n| n.scale(w));
375    let third = product(&weights.du(), &product(&pv, &points, Vec3::cross), |w, n| n.scale(w));
376    first.plus(&second).plus(&third)
377}
378
379/// One box of a piece in the piece's unit square: `[s0, s1] × [t0, t1]`.
380struct Cell {
381    normal: Grid<Vec3>,
382    s: [f64; 2],
383    t: [f64; 2],
384    depth: u32,
385}
386
387fn certify_piece(
388    surface: &NurbsSurface,
389    normal: &Grid<Vec3>,
390    piece: &Piece,
391    report: &mut RegularityReport,
392) -> Result<(), Irregularity> {
393    let scale = normal.c.iter().map(|c| c.length()).fold(0.0_f64, f64::max);
394    let at = |s: f64, t: f64| (piece.u[0] + (piece.u[1] - piece.u[0]) * s, piece.v[0] + (piece.v[1] - piece.v[0]) * t);
395    if !(scale > 0.0) || !scale.is_finite() {
396        let (u, v) = at(0.5, 0.5);
397        return Err(Irregularity::Collapses { u, v });
398    }
399    // The normal vanishes at a point when it is negligible against the
400    // derivatives there (`|S_u × S_v| ≤ 1e-9 |S_u| |S_v|`, a vanishing
401    // derivative included): the sine of their angle, not the piece's scale,
402    // so a sheet whose speed merely dips is not called collapsed.
403    let vanishes = |s: f64, t: f64| {
404        let (u, v) = at(s, t);
405        match surface.deriv1(u, v) {
406            Ok((_, su, sv)) => !(su.cross(sv).length() > VANISHING * su.length() * sv.length()),
407            Err(_) => true,
408        }
409    };
410    let mut stack = vec![Cell { normal: normal.clone(), s: [0.0, 1.0], t: [0.0, 1.0], depth: 0 }];
411    while let Some(cell) = stack.pop() {
412        report.boxes += 1;
413        let grid = &cell.normal;
414        let (m, n) = (grid.m, grid.n);
415        // Which of this box's corners are corners of the domain (the normal
416        // may vanish there).
417        let corner_index = [(0, 0), (m, 0), (0, n), (m, n)];
418        let corner_st = |k: usize| (if k % 2 == 0 { cell.s[0] } else { cell.s[1] }, if k < 2 { cell.t[0] } else { cell.t[1] });
419        let exempt = |k: usize| {
420            let (s, t) = ([cell.s[0], cell.s[1], cell.s[0], cell.s[1]][k], [cell.t[0], cell.t[0], cell.t[1], cell.t[1]][k]);
421            let piece_corner = match (s, t) {
422                (s, t) if s == 0.0 && t == 0.0 => Some(0),
423                (s, t) if s == 1.0 && t == 0.0 => Some(1),
424                (s, t) if s == 0.0 && t == 1.0 => Some(2),
425                (s, t) if s == 1.0 && t == 1.0 => Some(3),
426                _ => None,
427            };
428            piece_corner.is_some_and(|c| piece.corners[c])
429        };
430        let mut reference = grid.value(0.5, 0.5);
431        if !(reference.length() > VANISHING * scale) {
432            reference = grid.c.iter().fold(Vec3::new(0.0, 0.0, 0.0), |sum, c| sum.add(*c));
433        }
434        let largest = grid.c.iter().map(|c| c.length()).fold(0.0_f64, f64::max);
435        if reference.length() > 0.0 && largest > 0.0 {
436            let direction = reference.scale(1.0 / reference.length());
437            let margin = MARGIN * largest;
438            let dots: Vec<f64> = grid.c.iter().map(|c| c.dot(direction)).collect();
439            let certified = if dots.iter().all(|d| *d > margin) {
440                true
441            } else {
442                // A box at a vanishing domain corner: N . n >= 0 everywhere
443                // and > 0 away from that corner when no coefficient is
444                // negative, every other corner is positive and each side of
445                // the box has a positive coefficient (which is positive
446                // along that side's interior and across the box's).
447                let corner_ok = (0..4).all(|k| {
448                    let (ci, cj) = corner_index[k];
449                    dots[ci * (n + 1) + cj] > margin || (exempt(k) && vanishes(corner_st(k).0, corner_st(k).1))
450                });
451                let side_ok = |side: &dyn Fn(usize) -> Option<usize>| (0..=m.max(n)).filter_map(side).any(|index| dots[index] > margin);
452                corner_ok
453                    && dots.iter().all(|d| *d >= -margin)
454                    && side_ok(&|j| (j <= n).then_some(j))
455                    && side_ok(&|j| (j <= n).then_some(m * (n + 1) + j))
456                    && side_ok(&|i| (i <= m).then_some(i * (n + 1)))
457                    && side_ok(&|i| (i <= m).then_some(i * (n + 1) + n))
458            };
459            if certified {
460                continue;
461            }
462        }
463        // A witness at the box's corners: the exact normals there.
464        let corner_point = |k: usize| {
465            let s = if k % 2 == 0 { cell.s[0] } else { cell.s[1] };
466            let t = if k < 2 { cell.t[0] } else { cell.t[1] };
467            at(s, t)
468        };
469        let corners: Vec<(usize, Vec3)> = (0..4).filter(|&k| !exempt(k)).map(|k| (k, grid.at(corner_index[k].0, corner_index[k].1))).collect();
470        if let Some(&(k, _)) = corners.iter().find(|(k, _)| vanishes(corner_st(*k).0, corner_st(*k).1)) {
471            let (u, v) = corner_point(k);
472            return Err(Irregularity::Collapses { u, v });
473        }
474        let small = cell.s[1] - cell.s[0] <= WITNESS_SIZE && cell.t[1] - cell.t[0] <= WITNESS_SIZE;
475        if small && corners.iter().any(|(_, a)| corners.iter().any(|(_, b)| a.dot(*b) < 0.0)) {
476            let (u, v) = at(0.5 * (cell.s[0] + cell.s[1]), 0.5 * (cell.t[0] + cell.t[1]));
477            return Err(Irregularity::FoldsOver { u, v });
478        }
479        if cell.depth >= MAX_DEPTH || report.boxes >= BOX_BUDGET {
480            let (u, v) = at(0.5 * (cell.s[0] + cell.s[1]), 0.5 * (cell.t[0] + cell.t[1]));
481            let reason = if cell.depth >= MAX_DEPTH { "the subdivision reached its depth limit" } else { "the subdivision budget is spent" };
482            return Err(Irregularity::Uncertified { u, v, reason: reason.into() });
483        }
484        let along_u = cell.s[1] - cell.s[0] >= cell.t[1] - cell.t[0];
485        let (low, high) = grid.halves(along_u);
486        let (first, second) = if along_u {
487            let mid = 0.5 * (cell.s[0] + cell.s[1]);
488            (
489                Cell { normal: low, s: [cell.s[0], mid], t: cell.t, depth: cell.depth + 1 },
490                Cell { normal: high, s: [mid, cell.s[1]], t: cell.t, depth: cell.depth + 1 },
491            )
492        } else {
493            let mid = 0.5 * (cell.t[0] + cell.t[1]);
494            (
495                Cell { normal: low, s: cell.s, t: [cell.t[0], mid], depth: cell.depth + 1 },
496                Cell { normal: high, s: cell.s, t: [mid, cell.t[1]], depth: cell.depth + 1 },
497            )
498        };
499        stack.push(second);
500        stack.push(first);
501    }
502    Ok(())
503}
504
505/// `before · after > 0` along a C0 knot line whose two sides' normals have
506/// the univariate Bernstein coefficients `before` and `after` over
507/// `[start, end]`; `Err` carries where they turn back.
508fn certify_crease(before: &[Vec3], after: &[Vec3], start: f64, end: f64) -> Result<(), f64> {
509    let to_grid = |c: &[Vec3]| Grid { m: 0, n: c.len() - 1, c: c.to_vec() };
510    let dot = product(&to_grid(before), &to_grid(after), |a, b| a.dot(b));
511    let mut stack = vec![(dot, [0.0_f64, 1.0_f64], 0_u32)];
512    while let Some((grid, range, depth)) = stack.pop() {
513        let largest = grid.c.iter().map(|c| c.abs()).fold(0.0_f64, f64::max);
514        if grid.c.iter().all(|c| *c > MARGIN * largest) {
515            continue;
516        }
517        let place = |r: f64| start + (end - start) * r;
518        // the exact values at the ends
519        if let Some(r) = [(grid.c[0], range[0]), (grid.c[grid.n], range[1])].iter().find(|(c, _)| *c <= 0.0).map(|(_, r)| *r) {
520            return Err(place(r));
521        }
522        if depth >= MAX_DEPTH {
523            return Err(place(0.5 * (range[0] + range[1])));
524        }
525        let mid = 0.5 * (range[0] + range[1]);
526        let (low, high) = grid.halves(false);
527        stack.push((high, [mid, range[1]], depth + 1));
528        stack.push((low, [range[0], mid], depth + 1));
529    }
530    Ok(())
531}
532