Skip to main content

brep_geometry/geometry/
n_sided.rs

1//! N-sided filling (Golovanov §3.5): a smooth sheet of `N` four-sided patches
2//! spanning a closed loop of 3 to 6 boundary curves.
3//!
4//! # Construction
5//!
6//! Each side is cut at its parameter midpoint `M_i`. A centre point `Q` is
7//! chosen inside the loop, and a cubic *spoke* runs from every midpoint to the
8//! centre. Patch `k` is the Coons patch ([`crate::coons_with_ribbons`]) of
9//! the four curves round corner `P_k`: the second half of side `k − 1`, the
10//! first half of side `k`, and the two spokes between them. Its parameters run
11//! `u` along side `k` and `v` from side `k − 1`'s half towards the centre:
12//! `(0, 0) = P_k`, `(1, 0) = M_k`, `(1, 1) = Q`, `(0, 1) = M_{k−1}`.
13//!
14//! Every patch is given all four cross-boundary derivative fields (ribbons):
15//!
16//! - **Across a side** the ribbon is the derivative into the fill. Without a
17//!   prescribed tangent it is the linear blend of the derivatives the patch's
18//!   corners already have there. With one it stays in the plane of the side's
19//!   tangent and the prescribed direction, which is what makes the fill meet
20//!   the neighbouring face tangentially.
21//! - **Across a spoke** the two patches it divides share one tangent plane:
22//!   the ribbon of the second is `λ(v) r(v) + μ(v) S'(v)`, a combination of the
23//!   first's ribbon `r` and the spoke's own tangent `S'`. The spokes arrive at
24//!   the centre in one plane, so the patches meet there in it as well.
25//!
26//! The Coons patch interpolates the ribbons up to the corner twists, which in
27//! general disagree and of which it carries the mean. With prescribed tangent
28//! planes the disagreement across the planes at a corner P_k is geometry (the
29//! two planes turn unlike along the two sides: a vertex blend of fillets),
30//! and the mean would leave each side's derivative out of its plane along the
31//! whole half side; Gregory's direction-dependent corner twist is added
32//! instead, as a spline graded toward the corner (exact along both sides but
33//! in a span of 2⁻¹⁰ at the corner; zero with zero slope at the spokes). The
34//! joins are still not claimed to be G1. They are measured: [`NSidedReport::spoke_normal_angle`] is
35//! the worst angle between the normals of two patches across a spoke, and
36//! [`NSidedReport::tangent_normal_angle`] the worst angle between a patch's
37//! normal and the prescribed tangent plane along the sides (both as
38//! `atan2(|n × m|, n · m)`).
39//!
40//! # Re-entrant corners
41//!
42//! A corner where the loop turns away from its interior (an L shape's inner
43//! corner) cannot be a patch corner: a Coons patch whose corner angle passes
44//! 180° folds there, wherever the centre is. Such a corner becomes a spoke
45//! point instead: its two sides are taken as one side cut at the corner, the
46//! spoke leaves the corner along the bisector of its angle (or towards the
47//! centre, when that stays clear of both sides) and the patches either side
48//! of it have convex corners there. The centre is aimed at a point of the
49//! loop's kernel, the points from which all of the loop is in sight (Newell's
50//! normal fixes the plane; chords of 32 points to a side bound it): the one
51//! that leaves every patch's outline most convex, at the midpoints' mean's
52//! height (refused when none leaves them all convex). Refused by name: two re-entrant corners
53//! side by side ([`NSidedRefusal::AdjacentReentrant`]), a loop with no kernel
54//! (not star-shaped, [`NSidedRefusal::Centre`]), and a tangent fill across a
55//! re-entrant corner ([`NSidedRefusal::ReentrantTangent`]). Up to 12 sides are
56//! taken when the loop has 3 to 6 once each re-entrant corner's two sides
57//! count as one.
58//!
59//! # Rational sides
60//!
61//! The ribbon constructor is polynomial only, so a rational side (a circular
62//! arc) is replaced by the cubic interpolant of evenly spaced samples along
63//! it, as many as hold it within 1e-8 model units ([`STAND_IN_DEVIATION`]); the patch
64//! edges are then that interpolant, not the arc, and
65//! [`NSidedReport::boundary_deviation`] is the largest distance between the two
66//! measured at the quarter points between the samples; a side whose stand-in
67//! cannot be held within that bound is refused. A prescribed tangent field is
68//! sampled in the same way (only its direction is used).
69//!
70//! # Refusals
71//!
72//! Fewer than 3 or more than 6 sides (counting a re-entrant corner's two
73//! sides as one); two adjacent re-entrant corners, a loop that is not
74//! star-shaped, or a tangent fill across a re-entrant corner; a corner whose two sides miss each other
75//! by more than [`CORNER_FRACTION`] of the loop's size; a side with no length; a tangent field
76//! over a domain not its side's, or one along its side where it should cross
77//! it; and any refusal of a patch's Coons construction, verbatim.
78
79use crate::coons::compat::normalise_domain;
80use crate::coons::{coons_with_ribbons, CoonsRefusal};
81use crate::fit::interpolate_curve;
82use crate::{model_scale, NurbsCurve, NurbsSurface, Vec3, Vec4};
83
84/// Samples of a rational side or a field for its cubic stand-in, to start
85/// with; a side's sampling doubles until its stand-in is within
86/// [`STAND_IN_DEVIATION`] of it, up to [`FIT_SAMPLES_MOST`].
87const FIT_SAMPLES: usize = 257;
88const FIT_SAMPLES_MOST: usize = 16385;
89/// The absolute distance (model units) a rational side's polynomial stand-in
90/// is held within, at any size, so a pcurve of the true side on the patch
91/// stays far inside the kernel's 1e-7 pcurve floor.
92pub const STAND_IN_DEVIATION: f64 = 1e-8;
93/// Two consecutive sides meet within this fraction of the loop's size: a
94/// band relative to the loop, so it is as tight for a small corner as for a
95/// large one (the feature joins picks within the same fraction).
96pub const CORNER_FRACTION: f64 = 1e-5;
97/// A side with a knot of its own this close to its parameter midpoint (in
98/// its [0, 1]) is cut at that knot: a cut beside a knot leaves a half with a
99/// sliver span at its end (5.7e-9 on a fitted fillet rib), and a Coons patch
100/// reads its edge derivatives across that sliver, amplifying its net's
101/// rounding (a ribbon missed by 12.8 against a scale of 2.6). The knot is
102/// carried onto the midpoint by an exact reparameterisation of the side and
103/// its field together ([`knot_onto_midpoint`]).
104pub const MIDPOINT_KNOT_BAND: f64 = 1e-7;
105/// The least angle (radians, 15 degrees) the retry construction lets a spoke
106/// leave a side with a prescribed tangent at.
107const SPOKE_LEAST_LEAVE: f64 = 0.2617993877991494;
108/// The share of the field's own across component a shortened bump keeps.
109const BUMP_ACROSS_KEPT: f64 = 0.25;
110/// The reaches tried: 0.5 down by BUMP_REACH_STEP, BUMP_REACH_STEPS of them,
111/// BUMP_REACH_LEAST when none keeps the across component.
112const BUMP_REACH_STEP: f64 = 0.05;
113const BUMP_REACH_STEPS: usize = 10;
114const BUMP_REACH_LEAST: f64 = 0.05;
115/// Samples over a reach where the across component is read.
116const BUMP_REACH_SAMPLES: usize = 64;
117/// Samples along each join where its normals are compared.
118const JOIN_SAMPLES: usize = 33;
119/// `|w − 1|` below which a curve counts as polynomial.
120const POLYNOMIAL_BAND: f64 = 1e-12;
121
122/// Why an N-sided fill was refused.
123#[derive(Debug, Clone, PartialEq)]
124pub enum NSidedRefusal {
125    /// The loop has `sides` sides; 3 to 6 are filled.
126    SideCount { sides: usize },
127    /// The tangent fields are not one per side.
128    TangentCount { sides: usize, tangents: usize },
129    /// Side `side` has no length.
130    DegenerateSide { side: usize, extent: f64 },
131    /// The end of side `side` misses the next side by `gap` (band `band`).
132    CornerGap { side: usize, gap: f64, band: f64 },
133    /// Side `side`'s tangent field is over another domain than the side.
134    TangentDomain { side: usize },
135    /// Side `side`'s tangent field runs along the side at its midpoint (the
136    /// sine of its angle to the side is `sine`), so it gives no direction
137    /// across it.
138    TangentAlongSide { side: usize, sine: f64 },
139    /// The centre the spokes meet at is not a point the patches can share.
140    Centre { detail: String },
141    /// Corners `corner` and the next are both re-entrant: the side between
142    /// them would be a patch with no convex corner.
143    AdjacentReentrant { corner: usize },
144    /// A tangent fill across a loop with a re-entrant corner (`corner`).
145    ReentrantTangent { corner: usize },
146    /// Patch `patch`'s Coons construction refused.
147    Patch { patch: usize, refusal: CoonsRefusal },
148    /// Side `side` is rational and no cubic stand-in within
149    /// [`STAND_IN_DEVIATION`] was found (the best was `deviation` off).
150    StandIn { side: usize, deviation: f64 },
151    /// A curve operation failed (verbatim).
152    Geometry { detail: String },
153}
154
155impl std::fmt::Display for NSidedRefusal {
156    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157        match self {
158            Self::SideCount { sides } => write!(f, "N-sided fill: the loop has {sides} sides; 3 to 6 are filled"),
159            Self::TangentCount { sides, tangents } => {
160                write!(f, "N-sided fill: {tangents} tangent fields for {sides} sides; give one per side")
161            }
162            Self::DegenerateSide { side, extent } => {
163                write!(f, "N-sided fill: side {side} has no length (extent {extent:.3e})")
164            }
165            Self::CornerGap { side, gap, band } => write!(
166                f,
167                "N-sided fill: the end of side {side} misses the next side by {gap:.3e} (corner band {band:.3e})"
168            ),
169            Self::TangentDomain { side } => {
170                write!(f, "N-sided fill: the tangent field of side {side} is not over the side's own domain")
171            }
172            Self::TangentAlongSide { side, sine } => write!(
173                f,
174                "N-sided fill: the tangent field of side {side} runs along the side at its midpoint (sine {sine:.3e}), so it gives no direction across it"
175            ),
176            Self::Centre { detail } => write!(f, "N-sided fill: no centre point: {detail}"),
177            Self::AdjacentReentrant { corner } => write!(
178                f,
179                "N-sided fill: corners {corner} and {} are both re-entrant; the side between them has no convex corner to fill from",
180                corner + 1
181            ),
182            Self::ReentrantTangent { corner } => write!(
183                f,
184                "N-sided fill: corner {corner} is re-entrant; a tangent fill across a re-entrant corner is not built (fill in position)"
185            ),
186            Self::Patch { patch, refusal } => write!(f, "N-sided fill: patch {patch}: {refusal}"),
187            Self::StandIn { side, deviation } => write!(
188                f,
189                "N-sided fill: side {side} is rational and its best cubic stand-in is {deviation:.3e} off it (bound {STAND_IN_DEVIATION:.0e})"
190            ),
191            Self::Geometry { detail } => write!(f, "N-sided fill: {detail}"),
192        }
193    }
194}
195
196impl std::error::Error for NSidedRefusal {}
197
198fn geometry(detail: impl std::fmt::Display) -> NSidedRefusal {
199    NSidedRefusal::Geometry { detail: detail.to_string() }
200}
201
202/// What an N-sided fill built and measured.
203#[derive(Debug, Clone)]
204pub struct NSidedReport {
205    pub sides: usize,
206    /// Which sides were reversed to run head to tail from side 0.
207    pub reversed: Vec<bool>,
208    /// The worst corner gap between consecutive sides as given.
209    pub corner_gap: f64,
210    /// The corner band the gaps were admitted within.
211    pub corner_band: f64,
212    /// The centre point all patches share.
213    pub centre: Vec3,
214    /// The re-entrant corners (corner `k` is where side `k` starts), each
215    /// taken as a spoke point with its two sides whole patch edges.
216    pub reentrant_corners: Vec<usize>,
217    /// Largest distance between a rational side and its polynomial stand-in
218    /// (0 when every side is polynomial).
219    pub boundary_deviation: f64,
220    /// Worst normal angle (radians) between the two patches across a spoke.
221    pub spoke_normal_angle: f64,
222    /// Worst normal angle (radians) between a patch and the prescribed tangent
223    /// plane along the sides; `None` without tangent fields.
224    pub tangent_normal_angle: Option<f64>,
225    /// Worst corner-twist disagreement any patch carried the mean of.
226    pub twist_discrepancy: f64,
227    /// Worst cross-derivative residual of any patch against its ribbons.
228    pub cross_derivative_residual: f64,
229    /// Where each side (as given, in its own parameter) was cut at its
230    /// midpoint: its parameter midpoint, or a knot of its own within
231    /// [`MIDPOINT_KNOT_BAND`] of it; `None` for a side taken whole (one of a
232    /// re-entrant corner's two sides). A caller splitting the side's edge
233    /// for the patches cuts it here.
234    pub split_parameters: Vec<Option<f64>>,
235}
236
237/// Fill the closed loop `sides` (3 to 6 curves, in order round the loop,
238/// either way along each) with `N` four-sided patches.
239///
240/// `tangents`, when given, holds one vector-valued curve per side, over that
241/// side's own parameter domain: at each parameter, a direction ACROSS the side
242/// in the tangent plane the fill is to meet (the neighbouring face's plane);
243/// only its direction matters, and its sign does not (the fill lies on the
244/// side of the loop its interior is on). The patches come in corner order,
245/// patch `k` at the start of side `k` (after orientation).
246pub fn n_sided_fill(
247    sides: &[NurbsCurve],
248    tangents: Option<&[NurbsCurve]>,
249) -> Result<(Vec<NurbsSurface>, NSidedReport), NSidedRefusal> {
250    fill(sides, tangents, false, false)
251}
252
253/// [`n_sided_fill`] with each corner-twist bump along a side with a
254/// prescribed tangent reaching only as far as keeps the field's own across
255/// component (see `fill`): the retry for a fill whose patch folds beside a
256/// side where the two twists at its corner disagree by far more than that
257/// component.
258pub fn n_sided_fill_shortening_reach(
259    sides: &[NurbsCurve],
260    tangents: &[NurbsCurve],
261) -> Result<(Vec<NurbsSurface>, NSidedReport), NSidedRefusal> {
262    fill(sides, Some(tangents), true, false)
263}
264
265/// [`n_sided_fill_shortening_reach`] with each spoke also leaving a side with
266/// a prescribed tangent at least 15 degrees off it: the second retry, for a
267/// fill whose patches part beside a spoke that leaves nearly along its side.
268pub fn n_sided_fill_shortening_reach_spokes_off_sides(
269    sides: &[NurbsCurve],
270    tangents: &[NurbsCurve],
271) -> Result<(Vec<NurbsSurface>, NSidedReport), NSidedRefusal> {
272    fill(sides, Some(tangents), true, true)
273}
274
275/// [`n_sided_fill`] with the centre's height chosen to make the centre
276/// twists agree. The centre lies on the line from the midpoints' mean to the
277/// mean of the midpoints shot along their spokes' directions. The plain fill
278/// takes the middle of that line. Here the point is chosen where the
279/// least-squares misfit of the centre-twist system is least: a coarse scan,
280/// then golden sections. With an even number of sides that system has an
281/// exact solution only for one height, and anywhere else its misfit is a
282/// crease along the spokes. This is the fill for a set-back corner, whose
283/// six sides alternate between round sections and flat curves.
284pub fn n_sided_fill_centre_solved(
285    sides: &[NurbsCurve],
286    tangents: &[NurbsCurve],
287) -> Result<(Vec<NurbsSurface>, NSidedReport), NSidedRefusal> {
288    let misfit = |f: f64| fill_at(sides, Some(tangents), false, false, f, true).map(|(_, _, r)| r * r).unwrap_or(f64::INFINITY);
289    // A coarse scan, then parabolas through the three best points on the
290    // squared misfit (near its least, a quadratic in the height).
291    let mut seen: Vec<(f64, f64)> = (0..=15).map(|k| 0.1 * k as f64).map(|f| (f, misfit(f))).collect();
292    let Some(&(start, least)) = seen.iter().min_by(|a, b| a.1.total_cmp(&b.1)) else {
293        return fill(sides, Some(tangents), false, false);
294    };
295    if !least.is_finite() {
296        return fill(sides, Some(tangents), false, false);
297    }
298    seen.retain(|(f, _)| (f - start).abs() <= 0.1 + 1e-12);
299    let mut f = start;
300    for _ in 0..12 {
301        seen.sort_by(|a, b| a.1.total_cmp(&b.1));
302        seen.truncate(3);
303        if seen.len() < 3 {
304            break;
305        }
306        let [(a, fa), (b, fb), (c, fc)] = [seen[0], seen[1], seen[2]];
307        let num = (b - a).powi(2) * (fb - fc) - (b - c).powi(2) * (fb - fa);
308        let den = (b - a) * (fb - fc) - (b - c) * (fb - fa);
309        if !(den.abs() > 0.0) {
310            break;
311        }
312        let next = b - 0.5 * num / den;
313        let lo = seen.iter().map(|p| p.0).fold(f64::INFINITY, f64::min) - 0.1;
314        let hi = seen.iter().map(|p| p.0).fold(f64::NEG_INFINITY, f64::max) + 0.1;
315        if !(next > lo && next < hi) || seen.iter().any(|p| (p.0 - next).abs() <= 1e-12) {
316            break;
317        }
318        let value = misfit(next);
319        seen.push((next, value));
320        f = seen.iter().min_by(|x, y| x.1.total_cmp(&y.1)).map(|p| p.0).unwrap_or(f);
321    }
322    let f = seen.iter().min_by(|x, y| x.1.total_cmp(&y.1)).map(|p| p.0).unwrap_or(f);
323    fill_at(sides, Some(tangents), false, false, f, false).map(|(patches, report, _)| (patches, report.expect("a full fill reports")))
324}
325
326fn fill(
327    sides: &[NurbsCurve],
328    tangents: Option<&[NurbsCurve]>,
329    shorten_reach: bool,
330    spokes_off_sides: bool,
331) -> Result<(Vec<NurbsSurface>, NSidedReport), NSidedRefusal> {
332    fill_at(sides, tangents, shorten_reach, spokes_off_sides, 0.5, false).map(|(patches, report, _)| (patches, report.expect("a full fill reports")))
333}
334
335/// The fill with its centre `centre_at` of the way from the midpoints' mean
336/// to their shot mean (0.5: the plain fill). Also returns the misfit of its
337/// centre-twist system. With `misfit_only`, it returns once that is known,
338/// with no patches and no report.
339fn fill_at(
340    sides: &[NurbsCurve],
341    tangents: Option<&[NurbsCurve]>,
342    shorten_reach: bool,
343    spokes_off_sides: bool,
344    centre_at: f64,
345    misfit_only: bool,
346) -> Result<(Vec<NurbsSurface>, Option<NSidedReport>, f64), NSidedRefusal> {
347    let count = sides.len();
348    if !(3..=12).contains(&count) {
349        return Err(NSidedRefusal::SideCount { sides: count });
350    }
351    if let Some(fields) = tangents {
352        if fields.len() != count {
353            return Err(NSidedRefusal::TangentCount { sides: count, tangents: fields.len() });
354        }
355    }
356    let ends = |curve: &NurbsCurve| -> Result<(Vec3, Vec3), NSidedRefusal> {
357        let [t0, t1] = curve.domain().map_err(geometry)?;
358        Ok((curve.evaluate(t0).map_err(geometry)?, curve.evaluate(t1).map_err(geometry)?))
359    };
360    let mut points = Vec::new();
361    for curve in sides {
362        let (a, b) = ends(curve)?;
363        points.push(a);
364        points.push(b);
365    }
366    let scale = model_scale(points.iter().copied());
367    let band = CORNER_FRACTION * scale;
368
369    // Orient head to tail from side 0 as given; domains onto [0, 1].
370    let mut oriented: Vec<NurbsCurve> = Vec::with_capacity(count);
371    let mut fields: Vec<Option<NurbsCurve>> = Vec::with_capacity(count);
372    let mut reversed = Vec::with_capacity(count);
373    let mut corner_gap = 0.0_f64;
374    for (index, side) in sides.iter().enumerate() {
375        let (start, end) = ends(side)?;
376        if start.sub(end).length() <= band && polyline_extent(side)? <= band {
377            return Err(NSidedRefusal::DegenerateSide { side: index, extent: polyline_extent(side)? });
378        }
379        let flip = if index == 0 {
380            // side 0 sets the sense; it must still meet side 1 at its end
381            let (next_start, next_end) = ends(&sides[1])?;
382            let forward = end.sub(next_start).length().min(end.sub(next_end).length());
383            let backward = start.sub(next_start).length().min(start.sub(next_end).length());
384            backward < forward
385        } else {
386            let previous_end = ends(&oriented[index - 1])?.1;
387            start.sub(previous_end).length() > end.sub(previous_end).length()
388        };
389        let mut field = tangents.map(|all| all[index].clone());
390        if let Some(curve) = &field {
391            let [a0, a1] = side.domain().map_err(geometry)?;
392            let [b0, b1] = curve.domain().map_err(geometry)?;
393            let span = (a1 - a0).abs().max(1.0);
394            if (a0 - b0).abs() > 1e-9 * span || (a1 - b1).abs() > 1e-9 * span {
395                return Err(NSidedRefusal::TangentDomain { side: index });
396            }
397        }
398        let mut curve = side.clone();
399        if flip {
400            curve = curve.reversed().map_err(geometry)?;
401            if let Some(vector) = &field {
402                field = Some(vector.reversed().map_err(geometry)?);
403            }
404        }
405        let curve = normalise_domain(&curve).map_err(geometry)?.0;
406        let field = match field {
407            Some(vector) => Some(normalise_domain(&vector).map_err(geometry)?.0),
408            None => None,
409        };
410        if index > 0 {
411            let gap = ends(&oriented[index - 1])?.1.sub(ends(&curve)?.0).length();
412            corner_gap = corner_gap.max(gap);
413            if gap > band {
414                return Err(NSidedRefusal::CornerGap { side: index - 1, gap, band });
415            }
416        }
417        oriented.push(curve);
418        fields.push(field);
419        reversed.push(flip);
420    }
421    let closing = ends(&oriented[count - 1])?.1.sub(ends(&oriented[0])?.0).length();
422    corner_gap = corner_gap.max(closing);
423    if closing > band {
424        return Err(NSidedRefusal::CornerGap { side: count - 1, gap: closing, band });
425    }
426
427    // Polynomial stand-ins for rational sides and fields.
428    let mut boundary_deviation = 0.0_f64;
429    for (index, curve) in oriented.iter_mut().enumerate() {
430        if is_rational(curve) {
431            let (fitted, deviation) = polynomial_stand_in(curve, true)?;
432            if deviation > STAND_IN_DEVIATION {
433                return Err(NSidedRefusal::StandIn { side: index, deviation });
434            }
435            boundary_deviation = boundary_deviation.max(deviation);
436            *curve = fitted;
437        }
438    }
439    for field in fields.iter_mut().flatten() {
440        if is_rational(field) {
441            *field = polynomial_stand_in(field, false)?.0;
442        }
443    }
444
445    // Halves: A_i = side i over [0, 1/2], B_i over [1/2, 1], each on [0, 1]
446    // (both scaled alike, so A_i'(1) = B_i'(0)).
447    //
448    // A re-entrant corner (the loop turns away from its interior there) is
449    // no patch corner: a Coons patch with a corner angle past 180° folds at
450    // it, wherever the centre is. It becomes a spoke point instead: its two
451    // sides are taken as one side whose halves are the two sides whole, so
452    // the spoke leaves the corner into the interior and splits its angle
453    // between two convex patch corners. The centre is then chosen in the
454    // loop's kernel (the points that see all of it), which a loop with a
455    // re-entrant corner needs and the midpoints' mean need not lie in.
456    let (reentrant, loop_normal) = reentrant_corners_oriented(&oriented)?;
457    let mut groups: Vec<(usize, Option<usize>)> = (0..count).map(|index| (index, None)).collect();
458    let mut kernel = None;
459    if let Some(corner) = reentrant.iter().position(|is| *is) {
460        if tangents.is_some() {
461            return Err(NSidedRefusal::ReentrantTangent { corner });
462        }
463        if let Some(corner) = (0..count).find(|&k| reentrant[k] && reentrant[(k + 1) % count]) {
464            return Err(NSidedRefusal::AdjacentReentrant { corner });
465        }
466        let start = (0..count).find(|&k| !reentrant[k]).expect("no two re-entrant corners are adjacent");
467        groups.clear();
468        let mut step = 0;
469        while step < count {
470            let index = (start + step) % count;
471            if reentrant[(index + 1) % count] {
472                groups.push((index, Some((index + 1) % count)));
473                step += 2;
474            } else {
475                groups.push((index, None));
476                step += 1;
477            }
478        }
479        kernel = Some(star_kernel(&oriented, loop_normal, scale)?);
480    }
481    let count = groups.len();
482    if !(3..=6).contains(&count) {
483        return Err(NSidedRefusal::SideCount { sides: count });
484    }
485    let kinked: Vec<bool> = groups.iter().map(|(_, joined)| joined.is_some()).collect();
486    let mut first = Vec::with_capacity(count);
487    let mut second = Vec::with_capacity(count);
488    let mut split_parameters: Vec<Option<f64>> = vec![None; sides.len()];
489    // per side (in loop order) its second half's speed at the cut over its
490    // first half's: 1 at a cut at the midpoint, (1 − cut) / cut at a knot
491    let mut speed_ratio: Vec<f64> = Vec::with_capacity(groups.len());
492    for &(index, joined) in &groups {
493        match joined {
494            None => {
495                // A knot of the side's own within the band of its midpoint is
496                // carried onto the midpoint: raised to full multiplicity
497                // (exact) and each half's parameter mapped affinely, the
498                // side and its field alike, so the curve and the plane it
499                // reads at every point are unchanged and every half reads
500                // the side at 0.5 as before; the cut is then that knot.
501                // `BREP_N_SIDED_SLIVER_KNOTS`: a second knot beside the one
502                // nearest the midpoint (a fitted rib carries one within 6e-9
503                // of it) would leave a sliver span beside the cut whatever
504                // the cut; it is removed where the curve is unchanged without
505                // it (within SLIVER_KNOT_TOLERANCE of its size), side and
506                // field alike (a field with a zero pole keeps its knots).
507                if sliver_knots_on() {
508                    let size = polyline_extent(&oriented[index])?.max(f64::MIN_POSITIVE);
509                    oriented[index] = without_sliver_knots(&oriented[index], SLIVER_KNOT_TOLERANCE * size);
510                    if let Some(field) = &fields[index] {
511                        // relative to the field's smallest pole: the field's
512                        // size is arbitrary, its directions are what counts
513                        let least = field
514                            .control_points
515                            .iter()
516                            .map(|pole| (pole.x * pole.x + pole.y * pole.y + pole.z * pole.z).sqrt())
517                            .fold(f64::INFINITY, f64::min);
518                        if least.is_finite() && least > 0.0 {
519                            fields[index] = Some(without_sliver_knots(field, SLIVER_KNOT_TOLERANCE * least));
520                        }
521                    }
522                }
523                let near = oriented[index]
524                    .knots
525                    .iter()
526                    .copied()
527                    .filter(|knot| *knot > 0.0 && *knot < 1.0 && (knot - 0.5).abs() <= MIDPOINT_KNOT_BAND)
528                    .min_by(|a, b| (a - 0.5).abs().total_cmp(&(b - 0.5).abs()));
529                let cut = match near {
530                    Some(knot) if knot != 0.5 => {
531                        oriented[index] = knot_onto_midpoint(&oriented[index], knot)?;
532                        if let Some(field) = &fields[index] {
533                            fields[index] = Some(knot_onto_midpoint(field, knot)?);
534                        }
535                        knot
536                    }
537                    _ => 0.5,
538                };
539                speed_ratio.push((1.0 - cut) / cut);
540                let [t0, t1] = sides[index].domain().map_err(geometry)?;
541                split_parameters[index] = Some(if reversed[index] { t1 - cut * (t1 - t0) } else { t0 + cut * (t1 - t0) });
542                let (a, b) = oriented[index].split(0.5).map_err(geometry)?;
543                first.push(normalise_domain(&a).map_err(geometry)?.0);
544                second.push(normalise_domain(&b).map_err(geometry)?.0);
545            }
546            Some(next) => {
547                speed_ratio.push(1.0);
548                first.push(oriented[index].clone());
549                second.push(oriented[next].clone());
550            }
551        }
552    }
553    // A joined side is its first curve here (its start and, with no tangent
554    // fields, nothing else is read from it); its end is `second`'s.
555    let oriented: Vec<NurbsCurve> = groups.iter().map(|(index, _)| oriented[*index].clone()).collect();
556    let fields: Vec<Option<NurbsCurve>> = groups.iter().map(|(index, _)| fields[*index].clone()).collect();
557    let at = |curve: &NurbsCurve, t: f64| curve.evaluate(t).map_err(geometry);
558    let slope = |curve: &NurbsCurve, t: f64| curve.deriv1(t).map(|(_, d)| d).map_err(geometry);
559    let field_half = |field: &NurbsCurve, half: usize, s: f64| field.evaluate(0.5 * (s + half as f64)).map_err(geometry);
560    let end_slope = |index: usize| -> Result<Vec3, NSidedRefusal> {
561        if kinked[index] { slope(&second[index], 1.0) } else { slope(&oriented[index], 1.0) }
562    };
563
564    // Midpoints, side tangents there and the directions into the fill: in
565    // the tangent plane at the midpoint (the prescribed one, or the plane of
566    // the side and the bisector of its neighbours' directions), towards the
567    // midpoints' mean. On a regular loop that is square to the side; on a
568    // skewed one it is the way the surface's own cross curves run (a saddle's
569    // rulings, which leave a side at a slant).
570    let middle: Vec<Vec3> = first.iter().map(|half| at(half, 1.0)).collect::<Result<_, _>>()?;
571    let mean = middle.iter().fold(Vec3::new(0.0, 0.0, 0.0), |sum, point| sum.add(*point)).scale(1.0 / count as f64);
572    // With a re-entrant corner the centre is aimed at the point of the
573    // loop's kernel that leaves every patch's corners most convex, at the
574    // midpoints' mean's height above the loop's plane.
575    let mean = match &kernel {
576        Some(kernel) => {
577            let corners: Vec<Vec3> = first.iter().map(|half| at(half, 0.0)).collect::<Result<_, _>>()?;
578            kernel.best_centre(&corners, &middle, mean)?
579        }
580        None => mean,
581    };
582    let mut across = Vec::with_capacity(count);
583    for index in 0..count {
584        let along = slope(&first[index], 1.0)?;
585        let unit = along.normalized().map_err(|_| NSidedRefusal::DegenerateSide { side: index, extent: 0.0 })?;
586        let raw = match &fields[index] {
587            Some(field) => {
588                let g = field.evaluate(0.5).map_err(geometry)?;
589                let off = g.sub(unit.scale(g.dot(unit)));
590                let sine = off.length() / g.length().max(f64::MIN_POSITIVE);
591                if !(sine > 1e-6) {
592                    return Err(NSidedRefusal::TangentAlongSide { side: index, sine });
593                }
594                // the sense into the loop: towards the other sides
595                let previous = end_slope((index + count - 1) % count)?.scale(-1.0);
596                let next = slope(&oriented[(index + 1) % count], 0.0)?;
597                let inward = previous.normalized().map_err(geometry)?.add(next.normalized().map_err(geometry)?);
598                if off.dot(inward) < 0.0 { off.scale(-1.0) } else { off }
599            }
600            None if kinked[index] => {
601                // into the interior at a re-entrant corner: the bisector of
602                // its angle past 180°
603                let out = slope(&second[index], 0.0)?.normalized().map_err(geometry)?;
604                unit.sub(out)
605            }
606            None => {
607                let previous = end_slope((index + count - 1) % count)?.scale(-1.0);
608                let next = slope(&oriented[(index + 1) % count], 0.0)?;
609                let sum = previous.normalized().map_err(geometry)?.add(next.normalized().map_err(geometry)?);
610                sum.sub(unit.scale(sum.dot(unit)))
611            }
612        };
613        let square = raw.normalized().map_err(|_| NSidedRefusal::Centre {
614            detail: format!("side {index} gives no direction into the loop at its midpoint"),
615        })?;
616        let plane_normal = unit.cross(square);
617        let toward = mean.sub(middle[index]);
618        let in_plane_toward = toward.sub(plane_normal.scale(toward.dot(plane_normal)));
619        // At a re-entrant corner the spoke must leave into the interior
620        // past both sides (a convex corner each side of it).
621        let inside_both = |direction: Vec3| -> Result<bool, NSidedRefusal> {
622            if !kinked[index] {
623                return Ok(true);
624            }
625            let out = slope(&second[index], 0.0)?.normalized().map_err(geometry)?;
626            Ok(unit.cross(direction).dot(loop_normal) > 1e-3 && out.cross(direction).dot(loop_normal) > 1e-3)
627        };
628        let direction = match in_plane_toward.normalized() {
629            Ok(direction) if direction.dot(square) > 1e-3 && inside_both(direction)? => direction,
630            _ => square,
631        };
632        // `spokes_off_sides`: a spoke leaving a side with a prescribed
633        // tangent at least SPOKE_LEAST_LEAVE off the side. A spoke leaving
634        // nearly along its side (7 degrees, at a star whose rounds meet at
635        // radii 0.9 against 3) splits the plane at the midpoint between
636        // directions that hardly differ, and the two patches beside it part
637        // there by 1e-4 rad.
638        let direction = if spokes_off_sides && fields[index].is_some() && !kinked[index] {
639            let along = direction.dot(unit);
640            if along.abs() > SPOKE_LEAST_LEAVE.cos() {
641                unit.scale(along.signum() * SPOKE_LEAST_LEAVE.cos()).add(square.scale(SPOKE_LEAST_LEAVE.sin()))
642            } else {
643                direction
644            }
645        } else {
646            direction
647        };
648        across.push(direction);
649    }
650    let reach: Vec<f64> = middle.iter().map(|point| mean.sub(*point).length()).collect();
651    if reach.iter().any(|length| !(*length > band)) {
652        return Err(NSidedRefusal::Centre { detail: "a side's midpoint is at the loop's centre".into() });
653    }
654    // Two estimates of the centre that err on opposite sides of a curved
655    // fill by the same second-order amount: the midpoints' mean (on their
656    // chords, inside a dome) and each midpoint shot along its tangent `across`
657    // until it has come as far towards that mean as the mean is from it (on
658    // the tangents, outside). For a paraboloid of revolution their mean is
659    // exactly its vertex; on a plane both are the same point.
660    let mut shot = Vec3::new(0.0, 0.0, 0.0);
661    for index in 0..count {
662        let toward = mean.sub(middle[index]);
663        let unit = toward.scale(1.0 / reach[index]);
664        let pace = across[index].dot(unit);
665        if !(pace > 1e-3) {
666            return Err(NSidedRefusal::Centre {
667                detail: format!("side {index} turns away from the loop's centre at its midpoint"),
668            });
669        }
670        shot = shot.add(middle[index].add(across[index].scale(reach[index] / pace)));
671    }
672    let shot = shot.scale(1.0 / count as f64);
673    // (the plain fill's middle written as before, to the bit)
674    let centre = if centre_at == 0.5 { mean.add(shot).scale(0.5) } else { mean.add(shot.sub(mean).scale(centre_at)) };
675    let normal = (0..count)
676        .fold(Vec3::new(0.0, 0.0, 0.0), |sum, index| {
677            let along = slope(&first[index], 1.0).unwrap_or(Vec3::new(0.0, 0.0, 0.0));
678            sum.add(along.cross(across[index]).normalized().unwrap_or(Vec3::new(0.0, 0.0, 0.0)))
679        })
680        .normalized()
681        .map_err(|_| NSidedRefusal::Centre { detail: "the sides' normals cancel".into() })?;
682
683    // Spokes: cubic from M_i (leaving along `across`) to Q (arriving in the
684    // centre's tangent plane).
685    let mut spokes = Vec::with_capacity(count);
686    let mut spoke_bends = Vec::with_capacity(count);
687    for index in 0..count {
688        let toward = centre.sub(middle[index]);
689        let arrive = toward.sub(normal.scale(toward.dot(normal))).normalized().map_err(|_| NSidedRefusal::Centre {
690            detail: format!("the spoke from side {index} arrives along the centre's normal"),
691        })?;
692        let length = toward.length();
693        let poles = [
694            middle[index],
695            middle[index].add(across[index].scale(length / 3.0)),
696            centre.sub(arrive.scale(length / 3.0)),
697            centre,
698        ];
699        spoke_bends.push(poles[1].sub(poles[2].scale(2.0)).add(poles[3]).scale(6.0));
700        spokes.push(bezier(&poles)?);
701    }
702
703    // The field of derivatives into the fill along each whole side, `F_i(t)`
704    // in the halves' parameter scale: at the side's start the derivative
705    // along the side before it (reversed), at its midpoint the spoke's start,
706    // at its end the derivative along the side after it. Without a prescribed
707    // tangent it is the quadratic through those three; with one it is
708    // `a(t) g(t) + b(t) T(t)` in the prescribed plane, `(a, b)` quadratic
709    // through the three values' fits, plus each corner's misfit faded out by
710    // the midpoint. One smooth field per side gives the two patches beside a
711    // midpoint the same corner twist there.
712    let raw_value = |index: usize, t: f64| -> Result<Vec3, NSidedRefusal> {
713        let previous = (index + count - 1) % count;
714        let next = (index + 1) % count;
715        let values = [
716            slope(&second[previous], 1.0)?.scale(-1.0),
717            slope(&spokes[index], 0.0)?,
718            slope(&first[next], 0.0)?,
719        ];
720        let lagrange = [2.0 * (t - 0.5) * (t - 1.0), -4.0 * t * (t - 1.0), 2.0 * t * (t - 0.5)];
721        match &fields[index] {
722            None => Ok(values
723                .iter()
724                .zip(lagrange)
725                .fold(Vec3::new(0.0, 0.0, 0.0), |sum, (value, weight)| sum.add(value.scale(weight)))),
726            Some(field) => {
727                let along = |t: f64| slope(&oriented[index], t);
728                let mut fit = [(0.0, 0.0); 3];
729                let mut misfit = [Vec3::new(0.0, 0.0, 0.0); 3];
730                for (k, at_t) in [0.0, 0.5, 1.0].into_iter().enumerate() {
731                    let (g, d) = (field.evaluate(at_t).map_err(geometry)?, along(at_t)?);
732                    fit[k] = in_plane(values[k], g, d)?;
733                    misfit[k] = values[k].sub(g.scale(fit[k].0).add(d.scale(fit[k].1)));
734                }
735                let a = (0..3).map(|k| fit[k].0 * lagrange[k]).sum::<f64>();
736                let b = (0..3).map(|k| fit[k].1 * lagrange[k]).sum::<f64>();
737                let fade = |x: f64| if x > 0.0 { x * x } else { 0.0 };
738                Ok(field
739                    .evaluate(t)
740                    .map_err(geometry)?
741                    .scale(a)
742                    .add(along(t)?.scale(b))
743                    .add(misfit[0].scale(fade(1.0 - 2.0 * t)))
744                    .add(misfit[2].scale(fade(2.0 * t - 1.0)))
745                    .add(misfit[1].scale(1.0 - fade(1.0 - 2.0 * t) - fade(2.0 * t - 1.0))))
746            }
747        }
748    };
749    // A field's derivative in t, by second-order differences (central inside,
750    // one-sided at the ends).
751    const STEP: f64 = 1e-4;
752    let raw_slope = |index: usize, t: f64| -> Result<Vec3, NSidedRefusal> {
753        let f = |x: f64| raw_value(index, x);
754        if t <= 0.0 {
755            Ok(f(0.0)?.scale(-3.0).add(f(STEP)?.scale(4.0)).sub(f(2.0 * STEP)?).scale(0.5 / STEP))
756        } else if t >= 1.0 {
757            Ok(f(1.0)?.scale(3.0).sub(f(1.0 - STEP)?.scale(4.0)).add(f(1.0 - 2.0 * STEP)?).scale(0.5 / STEP))
758        } else {
759            Ok(f(t + STEP)?.sub(f(t - STEP)?).scale(0.5 / STEP))
760        }
761    };
762    // The corner twists. At P_k the patch has one twist from side k's field
763    // (`F_k'(0)`) and one from side k − 1's (`−F_{k−1}'(1)`); both are moved to
764    // their mean by a bump that is zero, with zero slope, at the midpoint, so
765    // the midpoint twists stay. With a prescribed tangent the bump is the
766    // move's part in the prescribed plane, carried along in the plane (`x g(t)
767    // + y T(t)`), so the field never leaves it; what remains of the twists'
768    // disagreement is their part across the plane.
769    let mut fixes: Vec<[Vec3; 2]> = vec![[Vec3::new(0.0, 0.0, 0.0); 2]; count];
770    for k in 0..count {
771        let previous = (k + count - 1) % count;
772        let (start, end) = (raw_slope(k, 0.0)?, raw_slope(previous, 1.0)?);
773        let mean = start.sub(end).scale(0.5);
774        fixes[k][0] = mean.sub(start);
775        fixes[previous][1] = mean.scale(-1.0).sub(end);
776    }
777    let mut plane_fixes: Vec<[(f64, f64); 2]> = vec![[(0.0, 0.0); 2]; count];
778    for index in 0..count {
779        if let Some(field) = &fields[index] {
780            for (end, t) in [(0usize, 0.0), (1usize, 1.0)] {
781                let (g, d) = (field.evaluate(t).map_err(geometry)?, slope(&oriented[index], t)?);
782                plane_fixes[index][end] = in_plane(fixes[index][end], g, d)?;
783            }
784        }
785    }
786    // The bump's reach from each end of a side with a prescribed tangent: half
787    // the side, or (`shorten_reach`) the longest of 0.5, 0.45, …,
788    // 0.05 over which the in-plane move leaves at least BUMP_ACROSS_KEPT of
789    // the field's own across component, in its own sense. Where the two
790    // twists at a corner disagree by far more than the field's across size
791    // (a long rib against a short one: a box corner of radii r, r and R for
792    // about 0.293 R < r < 0.35 R), the move over half the side cancels the
793    // across component and the patch folds beside the side; a shorter reach
794    // carries the same twist to the corner, keeps the plane, and stays clear
795    // of the fold. A reach that has to shorten on one side alone leaves every
796    // other side as it was.
797    let mut reaches: Vec<[f64; 2]> = vec![[0.5, 0.5]; count];
798    if shorten_reach {
799        for index in 0..count {
800            let Some(field) = &fields[index] else { continue };
801            for end in 0..2 {
802                let move_across = plane_fixes[index][end].0;
803                let sense = if end == 0 { 1.0 } else { -1.0 };
804                let mut reach = BUMP_REACH_LEAST;
805                for step in 0..BUMP_REACH_STEPS {
806                    let candidate = 0.5 - BUMP_REACH_STEP * step as f64;
807                    let mut kept = true;
808                    for j in 1..BUMP_REACH_SAMPLES {
809                        let r = candidate * j as f64 / BUMP_REACH_SAMPLES as f64;
810                        let t = if end == 0 { r } else { 1.0 - r };
811                        let (g, d) = (field.evaluate(t).map_err(geometry)?, slope(&oriented[index], t)?);
812                        let own = in_plane(raw_value(index, t)?, g, d)?.0;
813                        let shape = r * (1.0 - r / candidate) * (1.0 - r / candidate);
814                        let total = own + move_across * sense * shape;
815                        if !(total * own > 0.0 && total.abs() >= BUMP_ACROSS_KEPT * own.abs()) {
816                            kept = false;
817                            break;
818                        }
819                    }
820                    if kept {
821                        reach = candidate;
822                        break;
823                    }
824                }
825                reaches[index][end] = reach;
826            }
827        }
828    }
829    let field_value = |index: usize, t: f64| -> Result<Vec3, NSidedRefusal> {
830        // φ(0) = 0, φ'(0) = 1, φ(w) = φ'(w) = 0 for the reach w (½ unless
831        // shortened above); ψ the same at t = 1
832        let [w0, w1] = reaches[index];
833        let phi = if w0 == 0.5 {
834            if t < 0.5 { t * (1.0 - 2.0 * t) * (1.0 - 2.0 * t) } else { 0.0 }
835        } else if t < w0 {
836            t * (1.0 - t / w0) * (1.0 - t / w0)
837        } else {
838            0.0
839        };
840        let psi = if w1 == 0.5 {
841            if t > 0.5 { -(1.0 - t) * (2.0 * t - 1.0) * (2.0 * t - 1.0) } else { 0.0 }
842        } else if t > 1.0 - w1 {
843            -(1.0 - t) * (1.0 - (1.0 - t) / w1) * (1.0 - (1.0 - t) / w1)
844        } else {
845            0.0
846        };
847        let value = raw_value(index, t)?;
848        Ok(match &fields[index] {
849            None => value.add(fixes[index][0].scale(phi)).add(fixes[index][1].scale(psi)),
850            Some(field) => {
851                let (g, d) = (field.evaluate(t).map_err(geometry)?, slope(&oriented[index], t)?);
852                let [(x0, y0), (x1, y1)] = plane_fixes[index];
853                value.add(g.scale(x0 * phi + x1 * psi)).add(d.scale(y0 * phi + y1 * psi))
854            }
855        })
856    };
857    let hermite = |p0: Vec3, d0: Vec3, p1: Vec3, d1: Vec3, s: f64| {
858        let (s2, s3) = (s * s, s * s * s);
859        p0.scale(2.0 * s3 - 3.0 * s2 + 1.0)
860            .add(d0.scale(s3 - 2.0 * s2 + s))
861            .add(p1.scale(-2.0 * s3 + 3.0 * s2))
862            .add(d1.scale(s3 - s2))
863    };
864    let scalar_hermite = |p0: f64, d0: f64, p1: f64, d1: f64, s: f64| {
865        let (s2, s3) = (s * s, s * s * s);
866        p0 * (2.0 * s3 - 3.0 * s2 + 1.0) + d0 * (s3 - 2.0 * s2 + s) + p1 * (-2.0 * s3 + 3.0 * s2) + d1 * (s3 - s2)
867    };
868
869    // The centre twists. Patch k's ribbon across spoke k − 1 is
870    // `R_k = λ_k r_{k−1} + μ_k S'_{k−1}` (see below); at Q its twist from that
871    // side is `R_k'(1) = λ_k'(1) S'_{k−2}(1) + λ_k(1) w_{k−1} + μ_k'(1)
872    // S'_{k−1}(1) + μ_k(1) S''_{k−1}(1)` and from its own spoke ribbon `w_k =
873    // r_k'(1)`. The `w`, `λ'(1)` and `μ'(1)` that make the two agree round all
874    // N patches are one small linear system, solved by least squares near the
875    // plain choices (the ribbons' chords), which agree only by chance.
876    let arrive_at = |k: usize| slope(&spokes[k], 1.0);
877    let mut coefficients = Vec::with_capacity(count);
878    for k in 0..count {
879        let (previous, before) = ((k + count - 1) % count, (k + count - 2) % count);
880        coefficients.push(in_plane(arrive_at(k)?, arrive_at(before)?, arrive_at(previous)?)?);
881    }
882    let unknowns = 5 * count;
883    let mut rows: Vec<Vec<f64>> = Vec::with_capacity(3 * count);
884    let mut rhs: Vec<f64> = Vec::with_capacity(3 * count);
885    for k in 0..count {
886        let (previous, before) = ((k + count - 1) % count, (k + count - 2) % count);
887        let (lambda, mu) = coefficients[k];
888        let (sb, sp) = (arrive_at(before)?, arrive_at(previous)?);
889        let bend = spoke_bends[previous];
890        for axis in 0..3 {
891            let pick = |v: Vec3| [v.x, v.y, v.z][axis];
892            let mut row = vec![0.0; unknowns];
893            row[3 * k + axis] = 1.0;
894            row[3 * previous + axis] -= lambda;
895            row[3 * count + k] = -pick(sb);
896            row[4 * count + k] = -pick(sp);
897            rows.push(row);
898            rhs.push(mu * pick(bend));
899        }
900    }
901    let mut plain = vec![0.0; unknowns];
902    for k in 0..count {
903        let previous = (k + count - 1) % count;
904        let chord = arrive_at(previous)?.sub(slope(&first[k], 1.0)?);
905        plain[3 * k] = chord.x;
906        plain[3 * k + 1] = chord.y;
907        plain[3 * k + 2] = chord.z;
908        plain[3 * count + k] = coefficients[k].0 + 1.0;
909        plain[4 * count + k] = coefficients[k].1;
910    }
911    let mut normal_matrix = vec![vec![0.0; unknowns]; unknowns];
912    let mut normal_rhs = vec![0.0; unknowns];
913    for (row, value) in rows.iter().zip(&rhs) {
914        for i in 0..unknowns {
915            if row[i] == 0.0 {
916                continue;
917            }
918            normal_rhs[i] += row[i] * value;
919            for j in 0..unknowns {
920                normal_matrix[i][j] += row[i] * row[j];
921            }
922        }
923    }
924    let size = normal_matrix.iter().enumerate().map(|(i, row)| row[i]).fold(0.0_f64, f64::max).max(1.0);
925    let regular = 1e-10 * size;
926    for i in 0..unknowns {
927        normal_matrix[i][i] += regular;
928        normal_rhs[i] += regular * plain[i];
929    }
930    let solved = crate::solve_dense(normal_matrix, normal_rhs).map_err(geometry)?;
931    let centre_misfit = rows.iter().zip(&rhs).map(|(row, value)| (row.iter().zip(&solved).map(|(a, b)| a * b).sum::<f64>() - value).powi(2)).sum::<f64>().sqrt();
932    if misfit_only {
933        return Ok((Vec::new(), None, centre_misfit));
934    }
935    let centre_twist = |k: usize| Vec3::new(solved[3 * k], solved[3 * k + 1], solved[3 * k + 2]);
936    let lambda_slope = |k: usize| solved[3 * count + k];
937    let mu_slope = |k: usize| solved[4 * count + k];
938
939    // The spoke ribbon of each patch (dS/du on u = 1, v from M_k to Q): from
940    // the side's midpoint derivative to the previous spoke's arrival, leaving
941    // M_k with the side field's own twist and reaching Q with the solved one.
942    let mut spoke_ribbons = Vec::with_capacity(count);
943    for k in 0..count {
944        let previous = (k + count - 1) % count;
945        let start = slope(&first[k], 1.0)?;
946        let end = slope(&spokes[previous], 1.0)?;
947        let twist = raw_slope(k, 0.5)?.scale(0.5);
948        let reach_twist = centre_twist(k);
949        // on the knots of the side half the spoke's patch has across from
950        // it (second[k − 1], run from M_{k−1} to P_k: mirrored in v)
951        spoke_ribbons.push(sampled_on(|v| Ok(hermite(start, twist, end, reach_twist, v)), &interior_knots(&second[previous], true))?);
952    }
953    let mut patches = Vec::with_capacity(count);
954    let mut twist_discrepancy = 0.0_f64;
955    let mut cross_derivative_residual = 0.0_f64;
956    for k in 0..count {
957        let previous = (k + count - 1) % count;
958        let before = (k + count - 2) % count;
959        let a = &first[k];
960        let b = &second[previous];
961        let spoke = &spokes[k];
962        let back = &spokes[previous];
963        // r0 across side k's first half (dS/dv at v = 0), s along u; r3
964        // across side k − 1's second half (dS/du at u = 0), s from M_{k−1} to
965        // P_k: the two halves of the side fields.
966        let r0 = sampled_on(|s| field_value(k, 0.5 * s), &interior_knots(a, false))?;
967        let r3 = sampled_on(|s| field_value(previous, 0.5 * (s + 1.0)), &interior_knots(b, false))?;
968        let r1 = spoke_ribbons[k].clone();
969        // r2 across spoke k − 1 (dS/dv at v = 1), over the reversed spoke, s = 0
970        // at Q. In the spoke's own v = 1 − s it is λ(v) r1^{k−1}(v) +
971        // μ(v) S'_{k−1}(v): in the plane of the other patch's ribbon and the
972        // spoke, so the two patches share their tangent plane along it; −r1 at
973        // M_{k−1} with no twist of its own there, and S'_k(1) at Q.
974        let other = &spoke_ribbons[previous];
975        let target = slope(spoke, 1.0)?;
976        let _ = (target, before);
977        let (lambda, mu) = coefficients[k];
978        let (lambda_end, mu_end) = (lambda_slope(k), mu_slope(k));
979        let kink = if kinked[previous] {
980            Some((slope(&first[previous], 1.0)?, slope(&second[previous], 0.0)?))
981        } else {
982            None
983        };
984        // over the reversed spoke: the patch runs u = 1 − s along it
985        let r2 = sampled_on(|s| {
986            let v = 1.0 - s;
987            // at M_{k−1} the ribbon is the boundary's own derivative, the
988            // second half's: the first half's times their speed ratio
989            let l = scalar_hermite(-speed_ratio[previous], 0.0, lambda, lambda_end, v);
990            let m = scalar_hermite(0.0, 0.0, mu, mu_end, v);
991            let ribbon = other.evaluate(v).map_err(geometry)?.scale(l).add(slope(back, v)?.scale(m));
992            Ok(match kink {
993                // at a re-entrant corner the side leaves along `out`, not on
994                // along `into`: the ribbon meets it there and fades back to
995                // the shared-plane form with zero slope
996                Some((into, out)) => ribbon.add(into.sub(out).scale(scalar_hermite(1.0, 0.0, 0.0, 0.0, v))),
997                None => ribbon,
998            })
999        }, &interior_knots(a, true))?;
1000        let top = back.reversed().map_err(geometry)?;
1001        let top = normalise_domain(&top).map_err(geometry)?.0;
1002        let (surface, report) = coons_with_ribbons(
1003            [a.clone(), spoke.clone(), top, b.clone()],
1004            [Some(r0), Some(r1), Some(r2), Some(r3)],
1005        )
1006        .map_err(|refusal| NSidedRefusal::Patch { patch: k, refusal })?;
1007        if let Some(ribbons) = &report.ribbons {
1008            twist_discrepancy = twist_discrepancy.max(ribbons.twist_discrepancy);
1009            cross_derivative_residual = cross_derivative_residual.max(ribbons.cross_derivative_residual);
1010        }
1011        patches.push(surface);
1012    }
1013
1014    // Corner twists across the prescribed planes. Along a side with a
1015    // prescribed tangent plane the patch's derivative into the fill must stay
1016    // in that plane, and how fast the plane turns along each side fixes the
1017    // twist's component across it: at a corner the two sides ask for two
1018    // different twists wherever the two planes turn unlike (the vertex blend
1019    // of three fillets: one turns about the corner, its neighbour hardly at
1020    // all), and a patch smooth at the corner has one. The Coons patch carries
1021    // their mean, which leaves each side's derivative out of its plane by a
1022    // cubic bump `H1(u) = u (1 − u)²` times the difference, largest a third of
1023    // the way along the half side. Gregory's patch meets both with the
1024    // direction-dependent twist `(u t_v + v t_u) / (u + v)`; its term is added
1025    // here as a spline on knots graded toward the corner, exact along both
1026    // sides but in the corner's first span (2⁻¹⁰ of the patch), zero with zero
1027    // slope along the spokes, so the joins between patches are untouched.
1028    if fields.iter().any(Option::is_some) {
1029        for k in 0..count {
1030            let previous = (k + count - 1) % count;
1031            let along_v0 = fields[k].as_ref().map(|field| (&oriented[k], field));
1032            let along_u0 = fields[previous].as_ref().map(|field| (&oriented[previous], field));
1033            patches[k] = corner_twist_corrected(&patches[k], along_v0, along_u0)?;
1034        }
1035    }
1036
1037    // Measure the joins.
1038    let mut spoke_normal_angle = 0.0_f64;
1039    for k in 0..count {
1040        let next = (k + 1) % count;
1041        for index in 0..JOIN_SAMPLES {
1042            let v = index as f64 / (JOIN_SAMPLES - 1) as f64;
1043            // patch k at (1, v), patch k + 1 at (v, 1): the same point of spoke k
1044            let one = unit_normal(&patches[k], 1.0, v)?;
1045            let two = unit_normal(&patches[next], v, 1.0)?;
1046            if let (Some(one), Some(two)) = (one, two) {
1047                spoke_normal_angle = spoke_normal_angle.max(angle(one, two));
1048            }
1049        }
1050    }
1051    let tangent_normal_angle = if fields.iter().any(Option::is_some) {
1052        let mut worst = 0.0_f64;
1053        for k in 0..count {
1054            let previous = (k + count - 1) % count;
1055            for index in 0..JOIN_SAMPLES {
1056                let s = index as f64 / (JOIN_SAMPLES - 1) as f64;
1057                if let Some(field) = &fields[k] {
1058                    let plane = slope(&first[k], s)?.cross(field_half(field, 0, s)?);
1059                    if let (Some(n), Ok(m)) = (unit_normal(&patches[k], s, 0.0)?, plane.normalized()) {
1060                        worst = worst.max(line_angle(n, m));
1061                    }
1062                }
1063                if let Some(field) = &fields[previous] {
1064                    let plane = slope(&second[previous], s)?.cross(field_half(field, 1, s)?);
1065                    if let (Some(n), Ok(m)) = (unit_normal(&patches[k], 0.0, 1.0 - s)?, plane.normalized()) {
1066                        worst = worst.max(line_angle(n, m));
1067                    }
1068                }
1069            }
1070        }
1071        Some(worst)
1072    } else {
1073        None
1074    };
1075
1076    Ok((
1077        patches,
1078        Some(NSidedReport {
1079            sides: count,
1080            reversed,
1081            corner_gap,
1082            corner_band: band,
1083            centre,
1084            reentrant_corners: reentrant.iter().enumerate().filter(|(_, is)| **is).map(|(k, _)| k).collect(),
1085            boundary_deviation,
1086            spoke_normal_angle,
1087            tangent_normal_angle,
1088            twist_discrepancy,
1089            cross_derivative_residual,
1090            split_parameters,
1091        }),
1092        centre_misfit,
1093    ))
1094}
1095
1096/// Halvings toward the corner of the knots that carry the corner-twist term
1097/// (after them, spans of 1/8). Ten levels, not more: every knot of the term
1098/// is a knot of the patch it is added to, and finer spans (2⁻²⁰, spans of
1099/// 1/32) made a tangent fill of arc sides take 44 s to build into a sheet
1100/// for no reading the 1e-4 rad bar can see.
1101const GRADED_LEVELS: i32 = 10;
1102
1103/// The clamped cubic knots of the corner-twist term on [0, 1]: halving toward
1104/// the corner (0) down to 2⁻¹⁰, spans of 1/8 after. The term vanishes with
1105/// its slope at the far end (the midpoint), so it needs no grading there:
1106/// the seven knots it had toward 1 went into every patch for nothing the
1107/// 1e-4 rad bars read.
1108fn twist_knots() -> Vec<f64> {
1109    let mut interior: Vec<f64> = (4..=GRADED_LEVELS).rev().map(|level| 0.5_f64.powi(level)).collect();
1110    interior.extend((1..8).map(|k| k as f64 / 8.0));
1111    let mut knots = vec![0.0; 4];
1112    knots.extend(interior);
1113    knots.extend([1.0; 4]);
1114    knots
1115}
1116
1117/// The cubic B-spline basis functions on `knots` at `x` (all of them).
1118fn cubic_basis(knots: &[f64], x: f64) -> Vec<f64> {
1119    let n = knots.len() - 4;
1120    let x = x.clamp(knots[3], knots[n]);
1121    let span = (3..n).rev().find(|&i| knots[i] <= x).unwrap_or(3).min(n - 1);
1122    let mut values = vec![0.0; knots.len() - 1];
1123    values[span] = 1.0;
1124    for degree in 1..=3 {
1125        let mut next = vec![0.0; knots.len() - 1 - degree];
1126        for i in 0..next.len() {
1127            let mut value = 0.0;
1128            if knots[i + degree] > knots[i] {
1129                value += (x - knots[i]) / (knots[i + degree] - knots[i]) * values[i];
1130            }
1131            if knots[i + degree + 1] > knots[i + 1] {
1132                value += (knots[i + degree + 1] - x) / (knots[i + degree + 1] - knots[i + 1]) * values[i + 1];
1133            }
1134            next[i] = value;
1135        }
1136        values = next;
1137    }
1138    values.truncate(n);
1139    values
1140}
1141
1142/// `patch` with Gregory's corner-twist term added at its corner (0, 0) (see
1143/// the corner-twist notes in [`n_sided_fill`]). `along_v0` is the side and
1144/// field whose first half is the patch's `v = 0` edge (side parameter
1145/// `t = u / 2`), `along_u0` those whose second half is its `u = 0` edge
1146/// (`t = 1 − v / 2`). Along each the patch's derivative into it misses the
1147/// prescribed plane by `E(x) = (D · n) n`; that miss, fitted as a spline
1148/// on [`twist_knots`] vanishing at both ends (and in slope at the far one),
1149/// is what the term takes away. A rational patch is returned as it is.
1150fn corner_twist_corrected(
1151    patch: &NurbsSurface,
1152    along_v0: Option<(&NurbsCurve, &NurbsCurve)>,
1153    along_u0: Option<(&NurbsCurve, &NurbsCurve)>,
1154) -> Result<NurbsSurface, NSidedRefusal> {
1155    if patch.control_points.iter().flatten().any(|pole| (pole.w - 1.0).abs() > POLYNOMIAL_BAND) {
1156        return Ok(patch.clone());
1157    }
1158    let [u0, u1] = patch.domain_u().map_err(geometry)?;
1159    let [v0, v1] = patch.domain_v().map_err(geometry)?;
1160    let knots = twist_knots();
1161    let n = knots.len() - 4;
1162    let plane_normal = |side: &NurbsCurve, field: &NurbsCurve, t: f64| -> Result<Option<Vec3>, NSidedRefusal> {
1163        let tangent = side.deriv1(t).map_err(geometry)?.1;
1164        Ok(tangent.cross(field.evaluate(t).map_err(geometry)?).normalized().ok())
1165    };
1166    // the miss across the plane along an edge, as spline coefficients
1167    // e_1 .. e_{n−3} (e_0 = e_{n−2} = e_{n−1} = 0), least squares over three
1168    // points in every knot span
1169    let miss = |edge: Option<(&NurbsCurve, &NurbsCurve)>, on_v0: bool| -> Result<Vec<Vec3>, NSidedRefusal> {
1170        let zero = Vec3::new(0.0, 0.0, 0.0);
1171        let Some((side, field)) = edge else { return Ok(vec![zero; n]) };
1172        let free = n - 3;
1173        let mut matrix = vec![vec![0.0; free]; free];
1174        let mut rhs = [vec![0.0; free], vec![0.0; free], vec![0.0; free]];
1175        for span in 3..n {
1176            let (a, b) = (knots[span], knots[span + 1]);
1177            if !(b > a) {
1178                continue;
1179            }
1180            for fraction in [0.2, 0.5, 0.8] {
1181                let x = a + (b - a) * fraction;
1182                let (derivative, t) = if on_v0 {
1183                    let (_, _, sv) = patch.deriv1(u0 + (u1 - u0) * x, v0).map_err(geometry)?;
1184                    (sv.scale(v1 - v0), 0.5 * x)
1185                } else {
1186                    let (_, su, _) = patch.deriv1(u0, v0 + (v1 - v0) * x).map_err(geometry)?;
1187                    (su.scale(u1 - u0), 1.0 - 0.5 * x)
1188                };
1189                let Some(normal) = plane_normal(side, field, t)? else { continue };
1190                let value = normal.scale(derivative.dot(normal));
1191                // weight a span by its length, so the graded spans do not
1192                // swamp the fit
1193                let weight = b - a;
1194                let basis = cubic_basis(&knots, x);
1195                for i in 0..free {
1196                    let bi = basis[i + 1];
1197                    if bi == 0.0 {
1198                        continue;
1199                    }
1200                    rhs[0][i] += weight * bi * value.x;
1201                    rhs[1][i] += weight * bi * value.y;
1202                    rhs[2][i] += weight * bi * value.z;
1203                    for j in 0..free {
1204                        matrix[i][j] += weight * bi * basis[j + 1];
1205                    }
1206                }
1207            }
1208        }
1209        let size = (0..free).map(|i| matrix[i][i]).fold(0.0_f64, f64::max);
1210        for (i, row) in matrix.iter_mut().enumerate() {
1211            row[i] += 1e-14 * size;
1212        }
1213        let mut solved = Vec::with_capacity(3);
1214        for axis in &rhs {
1215            solved.push(crate::solve_dense(matrix.clone(), axis.clone()).map_err(geometry)?);
1216        }
1217        let mut out = vec![zero; n];
1218        for i in 0..free {
1219            out[i + 1] = Vec3::new(solved[0][i], solved[1][i], solved[2][i]);
1220        }
1221        Ok(out)
1222    };
1223    let (a, b) = (miss(along_v0, true)?, miss(along_u0, false)?);
1224    if a.iter().chain(&b).all(|e| e.length() == 0.0) {
1225        return Ok(patch.clone());
1226    }
1227    let term = gregory_twist_term(&knots, &a, &b, [u0, u1], [v0, v1])?;
1228    add_polynomial_surfaces(patch, &term)
1229}
1230
1231/// A bicubic spline `G` on `domain_u × domain_v` (normalised `x, y ∈ [0, 1]`,
1232/// knots `knots` each way) that is zero along all four edges, zero in slope
1233/// across the far two, and has `∂G/∂y (x, 0) = −E(x)` and
1234/// `∂G/∂x (0, y) = −F(y)` exactly but in the corner's first knot span, for
1235/// the splines `E`, `F` with coefficients `a`, `b`: Gregory's corner term
1236/// `−(E(x) W(y) x + F(y) W(x) y) / (x + y)`, `W(t) = t (1 − t)²`, its two
1237/// edge rows set exactly and its inside sampled at the Greville points.
1238fn gregory_twist_term(
1239    knots: &[f64],
1240    a: &[Vec3],
1241    b: &[Vec3],
1242    domain_u: [f64; 2],
1243    domain_v: [f64; 2],
1244) -> Result<NurbsSurface, NSidedRefusal> {
1245    let n = knots.len() - 4;
1246    // ∂/∂y at y = 0 is κ (c_1 − c_0) on a clamped cubic
1247    let kappa = 3.0 / knots[4];
1248    let greville = |i: usize| (knots[i + 1] + knots[i + 2] + knots[i + 3]) / 3.0;
1249    let spline = |coefficients: &[Vec3], x: f64| {
1250        cubic_basis(knots, x).iter().zip(coefficients).fold(Vec3::new(0.0, 0.0, 0.0), |sum, (w, c)| sum.add(c.scale(*w)))
1251    };
1252    let w = |t: f64| t * (1.0 - t) * (1.0 - t);
1253    let zero = Vec3::new(0.0, 0.0, 0.0);
1254    let mut rows = Vec::with_capacity(n);
1255    for i in 0..n {
1256        let mut row = Vec::with_capacity(n);
1257        for j in 0..n {
1258            let value = if i == 0 || j == 0 || i + 2 >= n || j + 2 >= n {
1259                zero
1260            } else if i == 1 && j == 1 {
1261                a[1].add(b[1]).scale(-0.5 / kappa)
1262            } else if j == 1 {
1263                a[i].scale(-1.0 / kappa)
1264            } else if i == 1 {
1265                b[j].scale(-1.0 / kappa)
1266            } else {
1267                let (x, y) = (greville(i), greville(j));
1268                spline(a, x).scale(w(y) * x).add(spline(b, y).scale(w(x) * y)).scale(-1.0 / (x + y))
1269            };
1270            row.push(Vec4::from_point(value, 1.0));
1271        }
1272        rows.push(row);
1273    }
1274    let map = |domain: [f64; 2]| knots.iter().map(|k| domain[0] + (domain[1] - domain[0]) * k).collect::<Vec<f64>>();
1275    NurbsSurface::new(3, 3, map(domain_u), map(domain_v), rows).map_err(geometry)
1276}
1277
1278/// The sum of two polynomial surfaces over one domain, on a common degree
1279/// and knot vector (both refined exactly).
1280fn add_polynomial_surfaces(first: &NurbsSurface, second: &NurbsSurface) -> Result<NurbsSurface, NSidedRefusal> {
1281    use crate::KnotDirection;
1282    let (pu, pv) = (first.degree_u.max(second.degree_u), first.degree_v.max(second.degree_v));
1283    let lift = |surface: &NurbsSurface| -> Result<NurbsSurface, NSidedRefusal> {
1284        let mut out = surface.clone();
1285        if out.degree_u < pu {
1286            out = out.elevate_degree(KnotDirection::U, pu).map_err(geometry)?;
1287        }
1288        if out.degree_v < pv {
1289            out = out.elevate_degree(KnotDirection::V, pv).map_err(geometry)?;
1290        }
1291        Ok(out)
1292    };
1293    let (mut a, mut b) = (lift(first)?, lift(second)?);
1294    // the knots one vector lacks against the other, with multiplicity; two
1295    // knots within the identity tolerance are one knot, as `refine_knots`
1296    // snaps them
1297    let same_knot = |a: f64, b: f64| (a - b).abs() <= crate::curve::KNOT_IDENTITY_TOL;
1298    let missing = |have: &[f64], want: &[f64]| -> Vec<f64> {
1299        let mut out = Vec::new();
1300        let mut index = 0;
1301        while index < want.len() {
1302            let value = want[index];
1303            let wanted = want.iter().filter(|k| same_knot(**k, value)).count();
1304            let held = have.iter().filter(|k| same_knot(**k, value)).count();
1305            out.extend(std::iter::repeat_n(value, wanted.saturating_sub(held)));
1306            index += wanted.max(1);
1307        }
1308        out
1309    };
1310    for direction in [KnotDirection::U, KnotDirection::V] {
1311        let (ka, kb) = match direction {
1312            KnotDirection::U => (a.knots_u.clone(), b.knots_u.clone()),
1313            KnotDirection::V => (a.knots_v.clone(), b.knots_v.clone()),
1314        };
1315        a = a.refine_knots(direction, &missing(&ka, &kb)).map_err(geometry)?;
1316        b = b.refine_knots(direction, &missing(&kb, &ka)).map_err(geometry)?;
1317    }
1318    let same = |x: &[f64], y: &[f64]| x.len() == y.len() && x.iter().zip(y).all(|(p, q)| (p - q).abs() <= 1e-9);
1319    if !same(&a.knots_u, &b.knots_u) || !same(&a.knots_v, &b.knots_v) {
1320        return Err(geometry("the corner-twist term does not share the patch's knots"));
1321    }
1322    let poles = a
1323        .control_points
1324        .iter()
1325        .zip(&b.control_points)
1326        .map(|(row_a, row_b)| {
1327            row_a.iter().zip(row_b).map(|(p, q)| Vec4 { x: p.x + q.x, y: p.y + q.y, z: p.z + q.z, w: 1.0 }).collect()
1328        })
1329        .collect();
1330    NurbsSurface::new(pu, pv, a.knots_u.clone(), a.knots_v.clone(), poles).map_err(geometry)
1331}
1332
1333/// The re-entrant corners of the loop `sides` (each over [0, 1], head to
1334/// tail; corner `k` is where side `k` starts) and the loop's normal (Newell's,
1335/// of points along every side; zero for a loop with no area, which then has
1336/// no re-entrant corner). A corner is re-entrant where the loop turns away
1337/// from its interior, `(T_in × T_out) · n < −1e-6` of the unit tangents.
1338fn reentrant_corners_oriented(sides: &[NurbsCurve]) -> Result<(Vec<bool>, Vec3), NSidedRefusal> {
1339    const PER_SIDE: usize = 16;
1340    let mut points = Vec::with_capacity(sides.len() * PER_SIDE);
1341    for side in sides {
1342        for k in 0..PER_SIDE {
1343            points.push(side.evaluate(k as f64 / PER_SIDE as f64).map_err(geometry)?);
1344        }
1345    }
1346    // about the first point (so a loop far from the origin sums no large
1347    // cancelling terms), and judged against the loop's own size (so a small
1348    // loop is not taken for one with no area)
1349    let origin = points[0];
1350    let local: Vec<Vec3> = points.iter().map(|point| point.sub(origin)).collect();
1351    let newell = (0..local.len()).fold(Vec3::new(0.0, 0.0, 0.0), |sum, k| sum.add(local[k].cross(local[(k + 1) % local.len()])));
1352    let extent = local.iter().map(|point| point.length()).fold(0.0_f64, f64::max);
1353    let length = newell.length();
1354    if !(length > 1e-12 * extent * extent) || !length.is_finite() {
1355        return Ok((vec![false; sides.len()], Vec3::new(0.0, 0.0, 0.0)));
1356    }
1357    let normal = newell.scale(1.0 / length);
1358    let count = sides.len();
1359    let mut reentrant = Vec::with_capacity(count);
1360    for k in 0..count {
1361        let into = sides[(k + count - 1) % count].deriv1(1.0).map_err(geometry)?.1.normalized();
1362        let out = sides[k].deriv1(0.0).map_err(geometry)?.1.normalized();
1363        reentrant.push(match (into, out) {
1364            (Ok(into), Ok(out)) => into.cross(out).dot(normal) < -1e-6,
1365            _ => false,
1366        });
1367    }
1368    Ok((reentrant, normal))
1369}
1370
1371/// The re-entrant corners of a loop of 3 to 12 curves given in order round
1372/// it, either way along each (corner `k` is where side `k` starts, after
1373/// orienting head to tail from side 0). A boundary fill uses it to send a
1374/// four-sided loop with a re-entrant corner to [`n_sided_fill`].
1375pub fn reentrant_corners(sides: &[NurbsCurve]) -> Result<Vec<usize>, NSidedRefusal> {
1376    if sides.len() < 3 {
1377        return Ok(Vec::new());
1378    }
1379    let ends = |curve: &NurbsCurve| -> Result<(Vec3, Vec3), NSidedRefusal> {
1380        let [t0, t1] = curve.domain().map_err(geometry)?;
1381        Ok((curve.evaluate(t0).map_err(geometry)?, curve.evaluate(t1).map_err(geometry)?))
1382    };
1383    let mut oriented: Vec<NurbsCurve> = Vec::with_capacity(sides.len());
1384    for (index, side) in sides.iter().enumerate() {
1385        let (start, end) = ends(side)?;
1386        let flip = if index == 0 {
1387            let (next_start, next_end) = ends(&sides[1])?;
1388            let forward = end.sub(next_start).length().min(end.sub(next_end).length());
1389            let backward = start.sub(next_start).length().min(start.sub(next_end).length());
1390            backward < forward
1391        } else {
1392            let previous_end = ends(&oriented[index - 1])?.1;
1393            start.sub(previous_end).length() > end.sub(previous_end).length()
1394        };
1395        let curve = if flip { side.reversed().map_err(geometry)? } else { side.clone() };
1396        oriented.push(normalise_domain(&curve).map_err(geometry)?.0);
1397    }
1398    let (reentrant, _) = reentrant_corners_oriented(&oriented)?;
1399    Ok(reentrant.iter().enumerate().filter(|(_, is)| **is).map(|(k, _)| k).collect())
1400}
1401
1402/// The kernel of a loop in its plane: the convex polygon of points that see
1403/// every point of the loop (the intersection of the half planes left of each
1404/// chord of 32 points to a side), in the frame `(e1, e2)` of the plane square
1405/// to `normal`.
1406struct Kernel {
1407    origin: Vec3,
1408    e1: Vec3,
1409    e2: Vec3,
1410    polygon: Vec<[f64; 2]>,
1411}
1412
1413impl Kernel {
1414    /// The point of the kernel, placed in the plane through `through` (so a
1415    /// point above the loop's plane keeps its height), that makes the patch
1416    /// outlines `corners[k], middle[k], Q, middle[k − 1]` most convex: the
1417    /// largest least sine of their turns, over the kernel's centroid and a
1418    /// 24 x 24 grid of its points. Refused when no point leaves every outline
1419    /// convex (the patches would fold).
1420    fn best_centre(&self, corners: &[Vec3], middle: &[Vec3], through: Vec3) -> Result<Vec3, NSidedRefusal> {
1421        let flat = |p: Vec3| [p.sub(self.origin).dot(self.e1), p.sub(self.origin).dot(self.e2)];
1422        let corners: Vec<[f64; 2]> = corners.iter().map(|p| flat(*p)).collect();
1423        let middle: Vec<[f64; 2]> = middle.iter().map(|p| flat(*p)).collect();
1424        let count = corners.len();
1425        let score = |q: [f64; 2]| {
1426            let mut least = f64::INFINITY;
1427            for k in 0..count {
1428                let outline = [corners[k], middle[k], q, middle[(k + count - 1) % count]];
1429                for index in 0..4 {
1430                    let (a, b, c) = (outline[index], outline[(index + 1) % 4], outline[(index + 2) % 4]);
1431                    let (d1, d2) = ([b[0] - a[0], b[1] - a[1]], [c[0] - b[0], c[1] - b[1]]);
1432                    let size = (d1[0].hypot(d1[1]) * d2[0].hypot(d2[1])).max(f64::MIN_POSITIVE);
1433                    least = least.min((d1[0] * d2[1] - d1[1] * d2[0]) / size);
1434                }
1435            }
1436            least
1437        };
1438        let inside = |q: [f64; 2]| {
1439            (0..self.polygon.len()).all(|k| {
1440                let (a, b) = (self.polygon[k], self.polygon[(k + 1) % self.polygon.len()]);
1441                (b[0] - a[0]) * (q[1] - a[1]) - (b[1] - a[1]) * (q[0] - a[0]) > 0.0
1442            })
1443        };
1444        let (mut low, mut high) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
1445        for point in &self.polygon {
1446            for axis in 0..2 {
1447                low[axis] = low[axis].min(point[axis]);
1448                high[axis] = high[axis].max(point[axis]);
1449            }
1450        }
1451        let mut best = (self.centroid(), score(self.centroid()));
1452        const GRID: usize = 24;
1453        for i in 1..GRID {
1454            for j in 1..GRID {
1455                let q = [
1456                    low[0] + (high[0] - low[0]) * i as f64 / GRID as f64,
1457                    low[1] + (high[1] - low[1]) * j as f64 / GRID as f64,
1458                ];
1459                if inside(q) {
1460                    let value = score(q);
1461                    if value > best.1 {
1462                        best = (q, value);
1463                    }
1464                }
1465            }
1466        }
1467        if !(best.1 > 1e-3) {
1468            return Err(NSidedRefusal::Centre {
1469                detail: "no point inside the loop leaves every patch convex round it".into(),
1470            });
1471        }
1472        let ([x, y], [x0, y0]) = (best.0, flat(through));
1473        Ok(through.add(self.e1.scale(x - x0)).add(self.e2.scale(y - y0)))
1474    }
1475
1476    /// The kernel polygon's centroid.
1477    fn centroid(&self) -> [f64; 2] {
1478        let (mut area, mut cx, mut cy) = (0.0, 0.0, 0.0);
1479        for k in 0..self.polygon.len() {
1480            let (a, b) = (self.polygon[k], self.polygon[(k + 1) % self.polygon.len()]);
1481            let cross = a[0] * b[1] - b[0] * a[1];
1482            area += cross;
1483            cx += (a[0] + b[0]) * cross;
1484            cy += (a[1] + b[1]) * cross;
1485        }
1486        [cx / (3.0 * area), cy / (3.0 * area)]
1487    }
1488}
1489
1490fn star_kernel(sides: &[NurbsCurve], normal: Vec3, scale: f64) -> Result<Kernel, NSidedRefusal> {
1491    const PER_SIDE: usize = 32;
1492    let not_star = || NSidedRefusal::Centre {
1493        detail: "the loop is not star-shaped: no point inside it sees all of its boundary".into(),
1494    };
1495    let helper = if normal.x.abs() < 0.9 { Vec3::new(1.0, 0.0, 0.0) } else { Vec3::new(0.0, 1.0, 0.0) };
1496    let e1 = helper.sub(normal.scale(helper.dot(normal))).normalized().map_err(|_| not_star())?;
1497    let e2 = normal.cross(e1);
1498    // in the plane's frame about the loop's first point, so a loop far from
1499    // the origin clips and measures without cancellation
1500    let origin = sides[0].evaluate(0.0).map_err(geometry)?;
1501    let mut points: Vec<[f64; 2]> = Vec::with_capacity(sides.len() * PER_SIDE);
1502    for side in sides {
1503        for k in 0..PER_SIDE {
1504            let point = side.evaluate(k as f64 / PER_SIDE as f64).map_err(geometry)?.sub(origin);
1505            points.push([point.dot(e1), point.dot(e2)]);
1506        }
1507    }
1508    let (mut low, mut high) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
1509    for point in &points {
1510        for axis in 0..2 {
1511            low[axis] = low[axis].min(point[axis]);
1512            high[axis] = high[axis].max(point[axis]);
1513        }
1514    }
1515    let pad = (high[0] - low[0]).max(high[1] - low[1]);
1516    let mut polygon =
1517        vec![[low[0] - pad, low[1] - pad], [high[0] + pad, low[1] - pad], [high[0] + pad, high[1] + pad], [low[0] - pad, high[1] + pad]];
1518    // keep the side of each chord the interior is on (left, the loop running
1519    // counter-clockwise about its Newell normal)
1520    for k in 0..points.len() {
1521        let (a, b) = (points[k], points[(k + 1) % points.len()]);
1522        let side = |p: [f64; 2]| (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]);
1523        let mut clipped = Vec::with_capacity(polygon.len() + 1);
1524        for index in 0..polygon.len() {
1525            let (p, q) = (polygon[index], polygon[(index + 1) % polygon.len()]);
1526            let (sp, sq) = (side(p), side(q));
1527            if sp >= 0.0 {
1528                clipped.push(p);
1529            }
1530            if (sp >= 0.0) != (sq >= 0.0) {
1531                let t = sp / (sp - sq);
1532                clipped.push([p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t]);
1533            }
1534        }
1535        polygon = clipped;
1536        if polygon.len() < 3 {
1537            return Err(not_star());
1538        }
1539    }
1540    let area = 0.5
1541        * (0..polygon.len())
1542            .map(|k| {
1543                let (a, b) = (polygon[k], polygon[(k + 1) % polygon.len()]);
1544                a[0] * b[1] - b[0] * a[1]
1545            })
1546            .sum::<f64>();
1547    if !(area > 1e-6 * scale * scale) {
1548        return Err(not_star());
1549    }
1550    Ok(Kernel { origin, e1, e2, polygon })
1551}
1552
1553/// The length of a curve's control polygon (zero only for a point).
1554fn polyline_extent(curve: &NurbsCurve) -> Result<f64, NSidedRefusal> {
1555    let points: Vec<Vec3> = curve
1556        .control_points
1557        .iter()
1558        .map(|pole| Vec3::new(pole.x / pole.w, pole.y / pole.w, pole.z / pole.w))
1559        .collect();
1560    Ok(points.windows(2).map(|pair| pair[1].sub(pair[0]).length()).sum())
1561}
1562
1563fn is_rational(curve: &NurbsCurve) -> bool {
1564    curve.control_points.iter().any(|pole| (pole.w - 1.0).abs() > POLYNOMIAL_BAND)
1565}
1566
1567/// The cubic interpolant of points of `curve` (domain [0, 1]) at their own
1568/// parameters, and its largest distance from the curve at the three quarter
1569/// points between them. The points are spread over every knot span of the
1570/// curve alike (`per` to a span, at least [`FIT_SAMPLES`] in all), so a
1571/// feature the curve has in a short span is sampled as finely as a long
1572/// span; with `adaptive` the count doubles until the distance is within
1573/// [`STAND_IN_DEVIATION`] or [`FIT_SAMPLES_MOST`] points are reached (the
1574/// distance is reported either way). A direction field (`adaptive` off)
1575/// takes the first sampling.
1576fn polynomial_stand_in(curve: &NurbsCurve, adaptive: bool) -> Result<(NurbsCurve, f64), NSidedRefusal> {
1577    let mut breaks: Vec<f64> = curve.knots.iter().copied().filter(|knot| (0.0..=1.0).contains(knot)).collect();
1578    breaks.dedup_by(|a, b| (*a - *b).abs() <= 1e-12);
1579    if breaks.first().is_none_or(|first| *first > 0.0) {
1580        breaks.insert(0, 0.0);
1581    }
1582    if breaks.last().is_none_or(|last| *last < 1.0) {
1583        breaks.push(1.0);
1584    }
1585    let spans = breaks.len() - 1;
1586    let mut per = FIT_SAMPLES.div_ceil(spans).max(4);
1587    loop {
1588        // one interpolant per knot span (an interpolant across spans of very
1589        // different lengths rings), joined end to end with a triple knot
1590        let mut parameters = Vec::with_capacity(spans * per + 1);
1591        let mut knots: Vec<f64> = Vec::new();
1592        let mut poles: Vec<Vec4> = Vec::new();
1593        for (index, pair) in breaks.windows(2).enumerate() {
1594            let local: Vec<f64> = (0..=per).map(|k| pair[0] + (pair[1] - pair[0]) * k as f64 / per as f64).collect();
1595            let points: Vec<Vec3> = local.iter().map(|t| curve.evaluate(*t)).collect::<Result<_, _>>().map_err(geometry)?;
1596            let piece = interpolate_curve(&points, 3, &local).map_err(geometry)?;
1597            let interior = &piece.knots[4..piece.knots.len() - 4];
1598            if index == 0 {
1599                knots.extend([pair[0]; 4]);
1600                poles.extend(piece.control_points.iter().copied());
1601            } else {
1602                knots.extend([pair[0]; 3]);
1603                poles.extend(piece.control_points.iter().skip(1).copied());
1604            }
1605            knots.extend(interior.iter().copied());
1606            parameters.extend(local[..per].iter().copied());
1607        }
1608        knots.extend([1.0; 4]);
1609        parameters.push(1.0);
1610        let fitted = NurbsCurve::new(3, knots, poles).map_err(geometry)?;
1611        let mut deviation = 0.0_f64;
1612        for pair in parameters.windows(2) {
1613            for fraction in [0.25, 0.5, 0.75] {
1614                let t = pair[0] + (pair[1] - pair[0]) * fraction;
1615                let gap = fitted.evaluate(t).map_err(geometry)?.sub(curve.evaluate(t).map_err(geometry)?).length();
1616                deviation = deviation.max(gap);
1617            }
1618        }
1619        if !adaptive || deviation <= STAND_IN_DEVIATION || parameters.len() >= FIT_SAMPLES_MOST {
1620            return Ok((fitted, deviation));
1621        }
1622        per *= 2;
1623    }
1624}
1625
1626/// A single Bézier curve on [0, 1] through `poles`.
1627fn bezier(poles: &[Vec3]) -> Result<NurbsCurve, NSidedRefusal> {
1628    let degree = poles.len() - 1;
1629    let mut knots = vec![0.0; degree + 1];
1630    knots.extend(std::iter::repeat_n(1.0, degree + 1));
1631    NurbsCurve::new(degree, knots, poles.iter().map(|pole| Vec4::from_point(*pole, 1.0)).collect()).map_err(geometry)
1632}
1633
1634/// The cubic interpolant over [0, 1] of the vector field `f` on the knots
1635/// of the boundary it travels with (`hint`, interior knots in the ribbon's
1636/// own parameter; the eighths when there are fewer than seven of them),
1637/// interpolating at the Greville points, with its end derivatives made `f`'s
1638/// own (rows of the interpolation in place of the second and second-to-last
1639/// Greville points). A Coons patch carries the union of its boundaries' and
1640/// ribbons' knots, so a ribbon on its boundary's knots adds none; a 33-point
1641/// ribbon added up to 31 to every patch (60 knots a direction on a fillet
1642/// star, most of a box's build in tessellating them). Read against `f` at
1643/// 513 even points and its spans' quarter points; when it misses by more
1644/// than 1e-9 of `f`'s size and by more than half again what the 33-point
1645/// ribbon ([`sampled`]) misses there, it gives way to that ribbon, as it does
1646/// for a boundary with more than 64 interior knots (its solve is dense).
1647fn sampled_on(f: impl Fn(f64) -> Result<Vec3, NSidedRefusal>, hint: &[f64]) -> Result<NurbsCurve, NSidedRefusal> {
1648    let mut interior: Vec<f64> = hint.iter().copied().filter(|knot| *knot > 1e-9 && *knot < 1.0 - 1e-9).collect();
1649    interior.sort_by(f64::total_cmp);
1650    interior.dedup_by(|a, b| (*a - *b).abs() <= 1e-9);
1651    if interior.len() < 7 {
1652        interior = (1..8).map(|k| k as f64 / 8.0).collect();
1653    }
1654    // a boundary refined past the 33-point ribbon's own size gains nothing
1655    // from its knots and would make the dense solve below its cost
1656    if interior.len() > 64 {
1657        return sampled(f);
1658    }
1659    let mut knots = vec![0.0; 4];
1660    knots.extend(interior);
1661    knots.extend([1.0; 4]);
1662    let n = knots.len() - 4;
1663    let greville: Vec<f64> = (0..n).map(|i| (knots[i + 1] + knots[i + 2] + knots[i + 3]) / 3.0).collect();
1664    // values at the Greville points but the second and the second-to-last,
1665    // whose rows carry the end derivatives instead
1666    let (start, end) = end_derivatives(&f)?;
1667    let mut matrix: Vec<Vec<f64>> = Vec::with_capacity(n);
1668    let mut rows: Vec<Vec3> = Vec::with_capacity(n);
1669    for (i, t) in greville.iter().enumerate() {
1670        if i == 1 {
1671            let c = 3.0 / (knots[4] - knots[1]);
1672            let mut row = vec![0.0; n];
1673            row[0] = -c;
1674            row[1] = c;
1675            matrix.push(row);
1676            rows.push(start);
1677        } else if i == n - 2 {
1678            let c = 3.0 / (knots[n + 2] - knots[n - 1]);
1679            let mut row = vec![0.0; n];
1680            row[n - 2] = -c;
1681            row[n - 1] = c;
1682            matrix.push(row);
1683            rows.push(end);
1684        } else {
1685            matrix.push(cubic_basis(&knots, *t));
1686            rows.push(f(*t)?);
1687        }
1688    }
1689    let mut axes = Vec::with_capacity(3);
1690    for axis in 0..3 {
1691        let rhs: Vec<f64> = rows.iter().map(|v| [v.x, v.y, v.z][axis]).collect();
1692        axes.push(crate::solve_dense(matrix.clone(), rhs).map_err(geometry)?);
1693    }
1694    let poles: Vec<Vec4> = (0..n).map(|i| Vec4::from_point(Vec3::new(axes[0][i], axes[1][i], axes[2][i]), 1.0)).collect();
1695    let curve = NurbsCurve::new(3, knots.clone(), poles).map_err(geometry)?;
1696    let values: Vec<Vec3> = greville.iter().map(|t| f(*t)).collect::<Result<_, _>>()?;
1697    // read against `f` at 513 even points and the quarter points of its
1698    // spans, and against what the 33-point ribbon misses there
1699    let size = values.iter().map(|v| v.length()).fold(0.0_f64, f64::max).max(f64::MIN_POSITIVE);
1700    let mut points: Vec<f64> = (0..=512).map(|i| i as f64 / 512.0).collect();
1701    for span in 3..n {
1702        let (a, b) = (knots[span], knots[span + 1]);
1703        if b > a {
1704            points.extend([0.25, 0.5, 0.75].map(|fraction| a + (b - a) * fraction));
1705        }
1706    }
1707    let worst = |candidate: &NurbsCurve| -> Result<f64, NSidedRefusal> {
1708        let mut worst = 0.0_f64;
1709        for t in &points {
1710            worst = worst.max(candidate.evaluate(*t).map_err(geometry)?.sub(f(*t)?).length());
1711        }
1712        Ok(worst)
1713    };
1714    let thinned = worst(&curve)?;
1715    if thinned <= 1e-9 * size {
1716        return Ok(curve);
1717    }
1718    let dense = sampled(&f)?;
1719    if thinned <= 1.5 * worst(&dense)? {
1720        Ok(curve)
1721    } else {
1722        Ok(dense)
1723    }
1724}
1725
1726/// The interior knots of `curve` (over [0, 1]), mirrored (`1 − t`) when the
1727/// ribbon runs the other way along it.
1728fn interior_knots(curve: &NurbsCurve, mirrored: bool) -> Vec<f64> {
1729    let p = curve.degree;
1730    let knots = &curve.knots[p + 1..curve.knots.len() - p - 1];
1731    knots.iter().map(|knot| if mirrored { 1.0 - knot } else { *knot }).collect()
1732}
1733
1734/// `BREP_N_SIDED_SLIVER_KNOTS` (on by default; `=0` keeps every knot): see
1735/// `without_sliver_knots`.
1736pub fn sliver_knots_on() -> bool {
1737    crate::switch!(live "BREP_N_SIDED_SLIVER_KNOTS", true)
1738}
1739
1740/// How near (in a side's [0, 1]) two knots by its midpoint leave a sliver
1741/// span between them, and how far (relative to a side's size, or to a
1742/// field's smallest pole) the curve may move when one of them is removed.
1743const SLIVER_KNOT_WINDOW: f64 = 1e-6;
1744const SLIVER_KNOT_TOLERANCE: f64 = 1e-12;
1745
1746/// `curve` (on [0, 1]) with as few simple interior knots within
1747/// SLIVER_KNOT_WINDOW of 0.5 as it can keep unchanged: each such knot is
1748/// removed where that moves the curve by at most `tolerance` (Piegl and
1749/// Tiller's single knot removal, A5.8, on the homogeneous poles), while at
1750/// least one stays; a knot that would move it more stays.
1751fn without_sliver_knots(curve: &NurbsCurve, tolerance: f64) -> NurbsCurve {
1752    let mut current = curve.clone();
1753    let mut kept: Vec<f64> = Vec::new();
1754    loop {
1755        let knots = &current.knots;
1756        // farthest from the midpoint first: the knot a fitted side carries
1757        // by its midpoint stays where another can go
1758        let mut band: Vec<usize> = (current.degree + 1..knots.len() - current.degree - 1)
1759            .filter(|&r| (knots[r] - 0.5).abs() <= SLIVER_KNOT_WINDOW && knots.iter().filter(|other| **other == knots[r]).count() == 1)
1760            .collect();
1761        band.sort_by(|&a, &b| (knots[b] - 0.5).abs().total_cmp(&(knots[a] - 0.5).abs()));
1762        if band.len() < 2 {
1763            return current;
1764        }
1765        let Some(&r) = band.iter().find(|&&r| !kept.contains(&knots[r])) else { return current };
1766        match remove_simple_knot(&current, r, tolerance) {
1767            Some(removed) => current = removed,
1768            None => kept.push(current.knots[r]),
1769        }
1770    }
1771}
1772
1773/// `curve` without its simple knot `knots[r]`, if that moves it by at most
1774/// `tolerance` (A5.8 with one removal; the check is on the homogeneous poles).
1775fn remove_simple_knot(curve: &NurbsCurve, r: usize, tolerance: f64) -> Option<NurbsCurve> {
1776    let p = curve.degree;
1777    let knots = &curve.knots;
1778    let poles = &curve.control_points;
1779    let u = knots[r];
1780    let (first, last) = (r - p, r - 1);
1781    let off = first - 1;
1782    let lerp = |a: Vec4, b: Vec4, ta: f64, tb: f64| Vec4 { x: a.x * ta + b.x * tb, y: a.y * ta + b.y * tb, z: a.z * ta + b.z * tb, w: a.w * ta + b.w * tb };
1783    let mut temp = vec![Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 }; 2 * p + 1];
1784    temp[0] = poles[off];
1785    temp[last + 1 - off] = poles[last + 1];
1786    let (mut i, mut j) = (first, last);
1787    let (mut ii, mut jj) = (1usize, last - off);
1788    while j > i {
1789        let alfi = (u - knots[i]) / (knots[i + p + 1] - knots[i]);
1790        let alfj = (u - knots[j]) / (knots[j + p + 1] - knots[j]);
1791        if !(alfi.abs() > 0.0) || !((1.0 - alfj).abs() > 0.0) {
1792            return None;
1793        }
1794        temp[ii] = lerp(poles[i], temp[ii - 1], 1.0 / alfi, -(1.0 - alfi) / alfi);
1795        temp[jj] = lerp(poles[j], temp[jj + 1], 1.0 / (1.0 - alfj), -alfj / (1.0 - alfj));
1796        i += 1;
1797        ii += 1;
1798        j -= 1;
1799        jj -= 1;
1800    }
1801    let distance = |a: Vec4, b: Vec4| ((a.x - b.x).powi(2) + (a.y - b.y).powi(2) + (a.z - b.z).powi(2) + (a.w - b.w).powi(2)).sqrt();
1802    let off_by = if j < i {
1803        distance(temp[ii - 1], temp[jj + 1])
1804    } else {
1805        let alfi = (u - knots[i]) / (knots[i + p + 1] - knots[i]);
1806        distance(poles[i], lerp(temp[ii + 1], temp[ii - 1], alfi, 1.0 - alfi))
1807    };
1808    if !(off_by <= tolerance) {
1809        return None;
1810    }
1811    let mut new_poles = poles.clone();
1812    let (mut i, mut j) = (first, last);
1813    while j > i {
1814        new_poles[i] = temp[i - off];
1815        new_poles[j] = temp[j - off];
1816        i += 1;
1817        j -= 1;
1818    }
1819    let fout = (2 * r - 1 - p) / 2;
1820    new_poles.remove(fout);
1821    let mut new_knots = knots.clone();
1822    new_knots.remove(r);
1823    NurbsCurve::new(p, new_knots, new_poles).ok()
1824}
1825
1826/// `curve` over [0, 1] with its knot `knot` carried onto 0.5: the knot
1827/// raised to full multiplicity (exact), then [0, knot] mapped onto [0, ½]
1828/// and [knot, 1] onto [½, 1]. The same points in the same order; only the
1829/// speeds of the two halves change, by `knot / ½` and `(1 − knot) / ½`.
1830fn knot_onto_midpoint(curve: &NurbsCurve, knot: f64) -> Result<NurbsCurve, NSidedRefusal> {
1831    let present = curve.knots.iter().filter(|value| **value == knot).count();
1832    let full = if present < curve.degree { curve.insert_knot(knot, curve.degree - present).map_err(geometry)? } else { curve.clone() };
1833    let knots: Vec<f64> = full
1834        .knots
1835        .iter()
1836        .map(|value| if *value <= knot { value * 0.5 / knot } else { 0.5 + (value - knot) * 0.5 / (1.0 - knot) })
1837        .collect();
1838    NurbsCurve::new(full.degree, knots, full.control_points.clone()).map_err(geometry)
1839}
1840
1841/// The cubic interpolant over [0, 1] of the vector field `f`, sampled at 33
1842/// even parameters, with its end derivatives made `f`'s own (read by
1843/// third-order one-sided differences): exact for a field of degree three or
1844/// less. A ribbon's end derivative is a corner twist of the patch it is
1845/// handed to; the interpolant's own missed it by its interpolation error,
1846/// which on a fast-turning field (a fillet star whose rounds meet at radii
1847/// 0.9 against 3) left the two patches beside a spoke's midpoint end with
1848/// twists 7e-4 apart and their normals 3.2e-4 rad apart across the spoke.
1849fn sampled(f: impl Fn(f64) -> Result<Vec3, NSidedRefusal>) -> Result<NurbsCurve, NSidedRefusal> {
1850    const SAMPLES: usize = 33;
1851    let parameters: Vec<f64> = (0..SAMPLES).map(|index| index as f64 / (SAMPLES - 1) as f64).collect();
1852    let values: Vec<Vec3> = parameters.iter().map(|t| f(*t)).collect::<Result<_, _>>()?;
1853    let curve = interpolate_curve(&values, 3, &parameters).map_err(geometry)?;
1854    with_end_derivatives(curve, &f)
1855}
1856
1857/// `f`'s derivatives at 0 and 1 by third-order one-sided differences, exact
1858/// for a cubic field.
1859fn end_derivatives(f: &impl Fn(f64) -> Result<Vec3, NSidedRefusal>) -> Result<(Vec3, Vec3), NSidedRefusal> {
1860    const STEP: f64 = 1e-4;
1861    let (first_value, last_value) = (f(0.0)?, f(1.0)?);
1862    let start = f(STEP)?
1863        .scale(18.0)
1864        .sub(f(2.0 * STEP)?.scale(9.0))
1865        .add(f(3.0 * STEP)?.scale(2.0))
1866        .sub(first_value.scale(11.0))
1867        .scale(1.0 / (6.0 * STEP));
1868    let end = last_value
1869        .scale(11.0)
1870        .sub(f(1.0 - STEP)?.scale(18.0))
1871        .add(f(1.0 - 2.0 * STEP)?.scale(9.0))
1872        .sub(f(1.0 - 3.0 * STEP)?.scale(2.0))
1873        .scale(1.0 / (6.0 * STEP));
1874    Ok((start, end))
1875}
1876
1877/// `curve` (a clamped cubic over [0, 1] interpolating `f`) with its end
1878/// derivatives made `f`'s own, read by third-order one-sided differences
1879/// (exact for a cubic field, whose interpolant they then leave as it is):
1880/// the second and second-to-last poles moved along them.
1881fn with_end_derivatives(curve: NurbsCurve, f: &impl Fn(f64) -> Result<Vec3, NSidedRefusal>) -> Result<NurbsCurve, NSidedRefusal> {
1882    let (start, end) = end_derivatives(f)?;
1883    // a clamped cubic leaves P0 along 3 (P1 - P0) / (u4 - u1) and reaches
1884    // P(n-1) along 3 (P(n-1) - P(n-2)) / (u(n+2) - u(n-1))
1885    let (degree, knots) = (curve.degree, curve.knots.clone());
1886    let mut poles = curve.control_points.clone();
1887    let n = poles.len();
1888    if degree != 3 || n < 4 || poles.iter().any(|pole| (pole.w - 1.0).abs() > POLYNOMIAL_BAND) {
1889        return Ok(curve);
1890    }
1891    let point = |pole: &Vec4| Vec3::new(pole.x, pole.y, pole.z);
1892    let first = point(&poles[0]).add(start.scale((knots[4] - knots[1]) / 3.0));
1893    let last = point(&poles[n - 1]).sub(end.scale((knots[n + 2] - knots[n - 1]) / 3.0));
1894    poles[1] = Vec4::from_point(first, 1.0);
1895    poles[n - 2] = Vec4::from_point(last, 1.0);
1896    NurbsCurve::new(degree, knots, poles).map_err(geometry)
1897}
1898
1899/// The least-squares `(λ, μ)` with `λ p + μ q` nearest `target`.
1900fn in_plane(target: Vec3, p: Vec3, q: Vec3) -> Result<(f64, f64), NSidedRefusal> {
1901    let (pp, pq, qq) = (p.dot(p), p.dot(q), q.dot(q));
1902    let (tp, tq) = (target.dot(p), target.dot(q));
1903    let determinant = pp * qq - pq * pq;
1904    if !(determinant > 1e-24 * pp * qq) || !(determinant.is_finite()) {
1905        return Err(NSidedRefusal::Centre { detail: "two directions that should span a plane are parallel".into() });
1906    }
1907    Ok(((tp * qq - tq * pq) / determinant, (tq * pp - tp * pq) / determinant))
1908}
1909
1910/// The unit normal `∂S/∂u × ∂S/∂v`, `None` where it vanishes.
1911fn unit_normal(surface: &NurbsSurface, u: f64, v: f64) -> Result<Option<Vec3>, NSidedRefusal> {
1912    let (_, su, sv) = surface.deriv1(u, v).map_err(geometry)?;
1913    let normal = su.cross(sv);
1914    if !(normal.length() > 1e-12 * su.length() * sv.length()) {
1915        return Ok(None);
1916    }
1917    Ok(normal.normalized().ok())
1918}
1919
1920/// The angle between two unit vectors, `atan2(|a × b|, a · b)`.
1921fn angle(a: Vec3, b: Vec3) -> f64 {
1922    a.cross(b).length().atan2(a.dot(b))
1923}
1924
1925/// The angle between two lines (unit vectors, sign ignored).
1926fn line_angle(a: Vec3, b: Vec3) -> f64 {
1927    a.cross(b).length().atan2(a.dot(b).abs())
1928}
1929