Skip to main content

brep_kernel/geometry/
fit.rs

1use crate::{DiagnosticSeverity, KernelDiagnostics, KernelStage, KnotVector, NurbsCurve, Vec3, Vec4};
2
3pub fn solve_dense(mut matrix: Vec<Vec<f64>>, mut rhs: Vec<f64>) -> Result<Vec<f64>, String> {
4    let count = rhs.len();
5    if count == 0 || matrix.len() != count || matrix.iter().any(|row| row.len() != count) {
6        return Err("solve_dense: matrix must be square and match RHS".into());
7    }
8    let scale = matrix
9        .iter()
10        .flatten()
11        .fold(0.0_f64, |maximum, value| maximum.max(value.abs()));
12    if scale == 0.0 {
13        return Err("solve_dense: singular matrix".into());
14    }
15    for column in 0..count {
16        let pivot = (column..count)
17            .max_by(|&a, &b| matrix[a][column].abs().total_cmp(&matrix[b][column].abs()))
18            .unwrap();
19        if matrix[pivot][column].abs() <= 1e-13 * scale {
20            return Err("solve_dense: singular matrix".into());
21        }
22        matrix.swap(column, pivot);
23        rhs.swap(column, pivot);
24        let diagonal = matrix[column][column];
25        for row in column + 1..count {
26            let factor = matrix[row][column] / diagonal;
27            matrix[row][column] = 0.0;
28            for entry in column + 1..count {
29                matrix[row][entry] -= factor * matrix[column][entry];
30            }
31            rhs[row] -= factor * rhs[column];
32        }
33    }
34    let mut result = vec![0.0; count];
35    for row in (0..count).rev() {
36        let remainder: f64 = (row + 1..count)
37            .map(|column| matrix[row][column] * result[column])
38            .sum();
39        result[row] = (rhs[row] - remainder) / matrix[row][row];
40    }
41    Ok(result)
42}
43
44/// `solve_dense` for fixed-size systems on the stack — identical pivoting and
45/// thresholds, no allocation. `count <= N` solves the leading `count`-sized
46/// block (for callers that shrink the system by fixing parameters).
47pub fn solve_small<const N: usize>(
48    mut matrix: [[f64; N]; N],
49    mut rhs: [f64; N],
50    count: usize,
51) -> Result<[f64; N], String> {
52    if count == 0 || count > N {
53        return Err("solve_small: invalid system size".into());
54    }
55    let scale = matrix
56        .iter()
57        .take(count)
58        .flat_map(|row| row.iter().take(count))
59        .fold(0.0_f64, |maximum, value| maximum.max(value.abs()));
60    if scale == 0.0 {
61        return Err("solve_small: singular matrix".into());
62    }
63    for column in 0..count {
64        let pivot = (column..count)
65            .max_by(|&a, &b| matrix[a][column].abs().total_cmp(&matrix[b][column].abs()))
66            .unwrap();
67        if matrix[pivot][column].abs() <= 1e-13 * scale {
68            return Err("solve_small: singular matrix".into());
69        }
70        matrix.swap(column, pivot);
71        rhs.swap(column, pivot);
72        let diagonal = matrix[column][column];
73        for row in column + 1..count {
74            let factor = matrix[row][column] / diagonal;
75            matrix[row][column] = 0.0;
76            for entry in column + 1..count {
77                matrix[row][entry] -= factor * matrix[column][entry];
78            }
79            rhs[row] -= factor * rhs[column];
80        }
81    }
82    let mut result = [0.0; N];
83    for row in (0..count).rev() {
84        let remainder: f64 = (row + 1..count)
85            .map(|column| matrix[row][column] * result[column])
86            .sum();
87        result[row] = (rhs[row] - remainder) / matrix[row][row];
88    }
89    Ok(result)
90}
91
92/// Solve a B-spline interpolation (collocation) system. The collocation matrix
93/// `N_j(τ_i)` produced by the knot-averaging schemes below is banded with
94/// half-bandwidth ≤ `degree` (Schoenberg–Whitney) and totally positive, so a
95/// no-pivot BANDED elimination is O(n·degree²) — vs the O(n³) of the general
96/// dense solver — and is numerically identical to it on these systems.
97///
98/// The banded result is accepted only when its in-band residual is tiny;
99/// otherwise (a pathological / near-singular system) it falls back to the
100/// partial-pivoting dense solver. This keeps large STEP-import pcurve fits
101/// (which push `n` toward ~500) from turning each solve into a ~500³ blowup.
102pub fn solve_collocation(
103    matrix: &[Vec<f64>],
104    rhs: &[f64],
105    degree: usize,
106) -> Result<Vec<f64>, String> {
107    let count = rhs.len();
108    let bandwidth = degree.max(1).min(count.saturating_sub(1).max(1));
109    if let Ok(solution) = solve_banded(matrix, rhs, bandwidth) {
110        let scale = rhs
111            .iter()
112            .fold(0.0_f64, |maximum, value| maximum.max(value.abs()));
113        let tolerance = 1e-9 * scale.max(1.0);
114        let mut residual = 0.0_f64;
115        for row in 0..count {
116            let lo = row.saturating_sub(bandwidth);
117            let hi = (row + bandwidth).min(count - 1);
118            let mut accumulated = 0.0;
119            for col in lo..=hi {
120                accumulated += matrix[row][col] * solution[col];
121            }
122            residual = residual.max((accumulated - rhs[row]).abs());
123        }
124        if residual <= tolerance {
125            return Ok(solution);
126        }
127    }
128    solve_dense(matrix.to_vec(), rhs.to_vec())
129}
130
131/// A collocation matrix held as its band only: row `r` stores columns
132/// `r - bandwidth ..= r + bandwidth`, the entries [`solve_banded`]'s no-pivot
133/// elimination can read or fill. [`solve_collocation`] on a dense
134/// `(n+1)²` matrix allocates and copies O(n²) per axis for an O(n·degree²)
135/// solve; at the 2000-station ceiling of the pcurve fitters that dominated
136/// the solve (28 s of an 81 s `abc_00000011` import, 4051 builds, measured
137/// 2026-09-26). [`solve_collocation_banded`] performs the SAME operations in
138/// the same order on the same entries, so its result is bit-identical.
139pub(crate) struct CollocationBand {
140    count: usize,
141    bandwidth: usize,
142    data: Vec<f64>,
143}
144
145impl CollocationBand {
146    /// Zeroed, for `count` rows at [`solve_collocation`]'s bandwidth for
147    /// `degree`.
148    pub(crate) fn new(count: usize, degree: usize) -> Self {
149        let bandwidth = degree.max(1).min(count.saturating_sub(1).max(1));
150        CollocationBand { count, bandwidth, data: vec![0.0; count * (2 * bandwidth + 1)] }
151    }
152
153    fn slot(&self, row: usize, column: usize) -> Option<usize> {
154        let offset = column as isize - row as isize + self.bandwidth as isize;
155        (offset >= 0 && offset <= 2 * self.bandwidth as isize)
156            .then(|| row * (2 * self.bandwidth + 1) + offset as usize)
157    }
158
159    /// Store an entry; `false` when it lies outside the band (the caller then
160    /// solves densely, as [`solve_collocation`] would after its banded check).
161    pub(crate) fn set(&mut self, row: usize, column: usize, value: f64) -> bool {
162        match self.slot(row, column) {
163            Some(index) => {
164                self.data[index] = value;
165                true
166            }
167            None => value == 0.0,
168        }
169    }
170
171    fn get(&self, row: usize, column: usize) -> f64 {
172        self.slot(row, column).map_or(0.0, |index| self.data[index])
173    }
174
175    fn to_dense(&self) -> Vec<Vec<f64>> {
176        (0..self.count)
177            .map(|row| (0..self.count).map(|column| self.get(row, column)).collect())
178            .collect()
179    }
180}
181
182/// [`solve_collocation`] on a [`CollocationBand`]: the banded elimination with
183/// its in-band residual check, and the dense partial-pivoting fallback
184/// (materialised only then). Bit-identical to [`solve_collocation`] on the
185/// dense form of the same matrix.
186pub(crate) fn solve_collocation_banded(band: &CollocationBand, rhs: &[f64]) -> Result<Vec<f64>, String> {
187    let count = rhs.len();
188    if count == 0 || band.count != count {
189        return Err("solve_banded: matrix must be square and match RHS".into());
190    }
191    let bandwidth = band.bandwidth;
192    if let Ok(solution) = solve_band_storage(band, rhs) {
193        let scale = rhs
194            .iter()
195            .fold(0.0_f64, |maximum, value| maximum.max(value.abs()));
196        let tolerance = 1e-9 * scale.max(1.0);
197        let mut residual = 0.0_f64;
198        for row in 0..count {
199            let lo = row.saturating_sub(bandwidth);
200            let hi = (row + bandwidth).min(count - 1);
201            let mut accumulated = 0.0;
202            for col in lo..=hi {
203                accumulated += band.get(row, col) * solution[col];
204            }
205            residual = residual.max((accumulated - rhs[row]).abs());
206        }
207        if residual <= tolerance {
208            return Ok(solution);
209        }
210    }
211    solve_dense(band.to_dense(), rhs.to_vec())
212}
213
214fn solve_band_storage(band: &CollocationBand, rhs: &[f64]) -> Result<Vec<f64>, String> {
215    let count = rhs.len();
216    let bandwidth = band.bandwidth;
217    let width = 2 * bandwidth + 1;
218    let mut matrix = band.data.clone();
219    let mut rhs = rhs.to_vec();
220    // Row `r`, column `c` lives at `r * width + (c + bandwidth - r)`.
221    let at = |row: usize, column: usize| row * width + column + bandwidth - row;
222    for column in 0..count {
223        let pivot = matrix[at(column, column)];
224        if pivot.abs() <= 1e-300 {
225            return Err("solve_banded: singular matrix".into());
226        }
227        let maximum_row = (column + bandwidth).min(count - 1);
228        for row in column + 1..=maximum_row {
229            let factor = matrix[at(row, column)] / pivot;
230            if factor == 0.0 {
231                continue;
232            }
233            let maximum_column = (column + bandwidth).min(count - 1);
234            for entry in column..=maximum_column {
235                matrix[at(row, entry)] -= factor * matrix[at(column, entry)];
236            }
237            rhs[row] -= factor * rhs[column];
238        }
239    }
240    let mut result = vec![0.0; count];
241    for row in (0..count).rev() {
242        let mut value = rhs[row];
243        let maximum_column = (row + bandwidth).min(count - 1);
244        for column in row + 1..=maximum_column {
245            value -= matrix[at(row, column)] * result[column];
246        }
247        if matrix[at(row, row)].abs() <= 1e-300 {
248            return Err("solve_banded: singular matrix".into());
249        }
250        result[row] = value / matrix[at(row, row)];
251    }
252    Ok(result)
253}
254
255pub fn solve_banded(
256    matrix: &[Vec<f64>],
257    rhs: &[f64],
258    bandwidth: usize,
259) -> Result<Vec<f64>, String> {
260    let count = rhs.len();
261    if count == 0 || matrix.len() != count || matrix.iter().any(|row| row.len() != count) {
262        return Err("solve_banded: matrix must be square and match RHS".into());
263    }
264    let mut matrix = matrix.to_vec();
265    let mut rhs = rhs.to_vec();
266    for column in 0..count {
267        let pivot = matrix[column][column];
268        if pivot.abs() <= 1e-300 {
269            return Err("solve_banded: singular matrix".into());
270        }
271        let maximum_row = (column + bandwidth).min(count - 1);
272        for row in column + 1..=maximum_row {
273            let factor = matrix[row][column] / pivot;
274            if factor == 0.0 {
275                continue;
276            }
277            let maximum_column = (column + bandwidth).min(count - 1);
278            for entry in column..=maximum_column {
279                matrix[row][entry] -= factor * matrix[column][entry];
280            }
281            rhs[row] -= factor * rhs[column];
282        }
283    }
284    let mut result = vec![0.0; count];
285    for row in (0..count).rev() {
286        let mut value = rhs[row];
287        let maximum_column = (row + bandwidth).min(count - 1);
288        for column in row + 1..=maximum_column {
289            value -= matrix[row][column] * result[column];
290        }
291        if matrix[row][row].abs() <= 1e-300 {
292            return Err("solve_banded: singular matrix".into());
293        }
294        result[row] = value / matrix[row][row];
295    }
296    Ok(result)
297}
298
299/// Global B-spline interpolation (The NURBS Book A9.1), matching the
300/// reference implementation's supplied-parameter path.
301/// Interpolate HOMOGENEOUS points (Vec4, rational data) at the given
302/// parameters with the same averaged-knot scheme as `interpolate_curve`.
303/// Parameters must start at 0 and end at 1. Rows fitted with identical
304/// parameters share knots — the contract the blend-surface rows rely on.
305pub fn interpolate_homogeneous(
306    points: &[Vec4],
307    degree: usize,
308    parameters: &[f64],
309) -> Result<NurbsCurve, String> {
310    if points.len() < 2 || parameters.len() != points.len() {
311        return Err(
312            "interpolate_homogeneous: points and parameters must have matching length >= 2".into(),
313        );
314    }
315    if parameters.windows(2).any(|pair| pair[1] <= pair[0]) {
316        return Err("interpolate_homogeneous: parameters must be strictly increasing".into());
317    }
318    let n = points.len() - 1;
319    let degree = degree.min(n);
320    let m = n + degree + 1;
321    let mut knots = vec![0.0; m + 1];
322    for knot in &mut knots[m - degree..=m] {
323        *knot = 1.0;
324    }
325    for j in 1..=n.saturating_sub(degree) {
326        knots[j + degree] = parameters[j..j + degree].iter().sum::<f64>() / degree as f64;
327    }
328    let knot_vector = KnotVector::new(knots.clone(), degree)?;
329    let mut matrix = vec![vec![0.0; n + 1]; n + 1];
330    for (row, &parameter) in parameters.iter().enumerate() {
331        let span = knot_vector.find_span(parameter);
332        let basis = knot_vector.basis_functions(span, parameter);
333        for (offset, value) in basis.into_iter().enumerate() {
334            matrix[row][span - degree + offset] = value;
335        }
336    }
337    let solve_axis = |axis: fn(&Vec4) -> f64| {
338        solve_collocation(
339            &matrix,
340            &points.iter().map(axis).collect::<Vec<_>>(),
341            degree,
342        )
343    };
344    let xs = solve_axis(|point| point.x)?;
345    let ys = solve_axis(|point| point.y)?;
346    let zs = solve_axis(|point| point.z)?;
347    let ws = solve_axis(|point| point.w)?;
348    NurbsCurve::new(
349        degree,
350        knots,
351        (0..=n)
352            .map(|index| Vec4 {
353                x: xs[index],
354                y: ys[index],
355                z: zs[index],
356                w: ws[index],
357            })
358            .collect(),
359    )
360}
361
362/// Global B-spline interpolation (The NURBS Book A9.1) through `points` at the
363/// supplied strictly increasing `parameters`.
364///
365/// The result is CLAMPED over exactly `[parameters[0], parameters[n]]` — the
366/// caller's own parameter interval, not a normalized `[0, 1]`. A9.1's end knots
367/// are `ū_0` and `ū_n`; hardcoding `0.0`/`1.0` there is only correct when the
368/// caller already normalized, and silently emits a knot vector that DESCENDS at
369/// the clamp when it did not (STEP import's `reconcile_edges_onto_surfaces`
370/// re-fits an edge over its own domain — on ABC 00000290 that is `[1.0,
371/// 1.2499]`, producing interior knots up to 1.234 followed by the four 1.0 end
372/// knots, i.e. a 0.234 descent that `validate_knots` rightly rejected). Since
373/// the averaged interior knots always lie strictly between `parameters[0]` and
374/// `parameters[n]`, taking the ends from the parameters makes the vector valid
375/// for ANY strictly increasing input, and is bit-identical for the already-
376/// normalized callers.
377pub fn interpolate_curve(
378    points: &[Vec3],
379    degree: usize,
380    parameters: &[f64],
381) -> Result<NurbsCurve, String> {
382    if points.len() < 2 || parameters.len() != points.len() {
383        return Err(
384            "interpolate_curve: points and parameters must have matching length >= 2".into(),
385        );
386    }
387    if parameters.windows(2).any(|pair| pair[1] <= pair[0]) {
388        return Err("interpolate_curve: parameters must be strictly increasing".into());
389    }
390    let n = points.len() - 1;
391    let degree = degree.min(n);
392    let m = n + degree + 1;
393    let mut knots = vec![parameters[0]; m + 1];
394    for knot in &mut knots[m - degree..=m] {
395        *knot = parameters[n];
396    }
397    for j in 1..=n.saturating_sub(degree) {
398        knots[j + degree] = parameters[j..j + degree].iter().sum::<f64>() / degree as f64;
399    }
400    let knot_vector = KnotVector::new(knots.clone(), degree)?;
401    // The band alone ([`CollocationBand`]); the dense matrix only when a basis
402    // value falls outside it, which the dense banded solve could not use either.
403    let mut band = CollocationBand::new(n + 1, degree);
404    let mut dense: Option<Vec<Vec<f64>>> = None;
405    for (row, &parameter) in parameters.iter().enumerate() {
406        let span = knot_vector.find_span(parameter);
407        let basis = knot_vector.basis_functions(span, parameter);
408        for (offset, value) in basis.into_iter().enumerate() {
409            let column = span - degree + offset;
410            if !band.set(row, column, value) {
411                dense.get_or_insert_with(|| band.to_dense())[row][column] = value;
412            } else if let Some(dense) = dense.as_mut() {
413                dense[row][column] = value;
414            }
415        }
416    }
417    let solve_axis = |axis: fn(Vec3) -> f64| {
418        let rhs = points.iter().copied().map(axis).collect::<Vec<_>>();
419        match &dense {
420            Some(matrix) => solve_collocation(matrix, &rhs, degree),
421            None => solve_collocation_banded(&band, &rhs),
422        }
423    };
424    let xs = solve_axis(|point| point.x)?;
425    let ys = solve_axis(|point| point.y)?;
426    let zs = solve_axis(|point| point.z)?;
427    NurbsCurve::new(
428        degree,
429        knots,
430        (0..=n)
431            .map(|index| Vec4::from_point(Vec3::new(xs[index], ys[index], zs[index]), 1.0))
432            .collect(),
433    )
434}
435
436/// Cubic interpolation with PRESCRIBED end derivatives (Piegl–Tiller §9.2.2):
437/// n+1 points plus two tangent rows give n+3 clamped control points. The
438/// derivative conditions use the exact clamped end forms
439/// C'(t0) = p/(u_{p+1}−t0)·(Q1−Q0) and C'(t1) = p/(t1−u_{m−p−1})·(Qn−Qn−1),
440/// so the requested tangents are reproduced exactly — the §5.8 loft tangency
441/// building block.
442pub fn interpolate_curve_with_end_tangents(
443    points: &[Vec3],
444    parameters: &[f64],
445    start_tangent: Vec3,
446    end_tangent: Vec3,
447) -> Result<NurbsCurve, String> {
448    if points.len() < 2 || parameters.len() != points.len() {
449        return Err(
450            "interpolate_curve_with_end_tangents: points and parameters must match, >= 2".into(),
451        );
452    }
453    if parameters.windows(2).any(|pair| pair[1] <= pair[0]) {
454        return Err("interpolate_curve_with_end_tangents: parameters must increase".into());
455    }
456    let degree = 3usize;
457    let n = points.len() - 1;
458    let control_count = n + 3;
459    let t0 = parameters[0];
460    let t1 = parameters[n];
461    // Clamped knots with n−1 interior values averaged over parameter runs
462    // (the tangent rows consume the two extra controls).
463    let mut knots = vec![t0; degree + 1];
464    for j in 0..n.saturating_sub(1) {
465        let window = &parameters[j + 1..(j + degree).min(n) + 1];
466        knots.push(window.iter().sum::<f64>() / window.len() as f64);
467    }
468    knots.extend(std::iter::repeat(t1).take(degree + 1));
469    if knots.len() != control_count + degree + 1 {
470        return Err(format!(
471            "interpolate_curve_with_end_tangents: internal knot count {} for {} controls",
472            knots.len(),
473            control_count
474        ));
475    }
476    let knot_vector = KnotVector::new(knots.clone(), degree)?;
477    let mut matrix = vec![vec![0.0; control_count]; control_count];
478    let mut rhs_points = vec![Vec3::default(); control_count];
479    // Row 0: C(t0) = P0; row 1: start tangent; rows 2..=n: interior + end
480    // interpolation; row n+1... reorganized: standard layout is
481    // [P0, T0, P1..Pn-1, T1, Pn].
482    matrix[0][0] = 1.0;
483    rhs_points[0] = points[0];
484    let start_span = knots[degree + 1] - t0;
485    matrix[1][0] = -(degree as f64) / start_span;
486    matrix[1][1] = (degree as f64) / start_span;
487    rhs_points[1] = start_tangent;
488    for (index, &parameter) in parameters.iter().enumerate().take(n).skip(1) {
489        let row = index + 1;
490        let span = knot_vector.find_span(parameter);
491        let basis = knot_vector.basis_functions(span, parameter);
492        for (offset, value) in basis.into_iter().enumerate() {
493            matrix[row][span - degree + offset] = value;
494        }
495        rhs_points[row] = points[index];
496    }
497    let end_span = t1 - knots[control_count - 1];
498    matrix[control_count - 2][control_count - 2] = -(degree as f64) / end_span;
499    matrix[control_count - 2][control_count - 1] = (degree as f64) / end_span;
500    rhs_points[control_count - 2] = end_tangent;
501    matrix[control_count - 1][control_count - 1] = 1.0;
502    rhs_points[control_count - 1] = points[n];
503    let solve_axis = |axis: fn(Vec3) -> f64| {
504        solve_dense(
505            matrix.clone(),
506            rhs_points.iter().copied().map(axis).collect::<Vec<_>>(),
507        )
508    };
509    let xs = solve_axis(|point| point.x)?;
510    let ys = solve_axis(|point| point.y)?;
511    let zs = solve_axis(|point| point.z)?;
512    NurbsCurve::new(
513        degree,
514        knots,
515        (0..control_count)
516            .map(|index| Vec4::from_point(Vec3::new(xs[index], ys[index], zs[index]), 1.0))
517            .collect(),
518    )
519}
520
521pub fn interpolate_curve_thinned(
522    points: &[Vec3],
523    degree: usize,
524    maximum_points: usize,
525) -> Result<NurbsCurve, String> {
526    if maximum_points < 2 {
527        return Err("interpolate_curve_thinned: maximum point count must be at least 2".into());
528    }
529    if points.len() <= maximum_points {
530        let parameters = chord_parameters(points);
531        return interpolate_curve(points, degree, &parameters);
532    }
533    let step = (points.len() - 1) as f64 / (maximum_points - 1) as f64;
534    let thinned = (0..maximum_points)
535        .map(|index| points[(index as f64 * step).round() as usize])
536        .collect::<Vec<_>>();
537    let parameters = chord_parameters(&thinned);
538    interpolate_curve(&thinned, degree, &parameters)
539}
540
541fn chord_parameters(points: &[Vec3]) -> Vec<f64> {
542    if points.len() < 2 {
543        return vec![0.0; points.len()];
544    }
545    let mut parameters = vec![0.0; points.len()];
546    for index in 1..points.len() {
547        parameters[index] = parameters[index - 1] + points[index].sub(points[index - 1]).length();
548    }
549    let length = parameters[points.len() - 1];
550    if length <= 1e-15 {
551        for (index, parameter) in parameters.iter_mut().enumerate() {
552            *parameter = index as f64 / (points.len() - 1) as f64;
553        }
554    } else {
555        for parameter in &mut parameters {
556            *parameter /= length;
557        }
558    }
559    parameters
560}
561
562/// Douglas–Peucker against `tolerance`, as INDICES into `points`.
563///
564/// The indices are what a FIT needs: they carry the correspondence between an
565/// interpolation station and the input station it came from, and that
566/// correspondence is what lets [`fit_polyline`] measure its own result against
567/// the input points BETWEEN its stations without a global projection per point.
568/// [`simplify_polyline`] is a thin wrapper over this; the arithmetic is
569/// unchanged.
570pub fn simplify_polyline_indices(points: &[Vec3], tolerance: f64) -> Vec<usize> {
571    if points.len() <= 2 {
572        return (0..points.len()).collect();
573    }
574    let mut keep = vec![false; points.len()];
575    keep[0] = true;
576    keep[points.len() - 1] = true;
577    let mut stack = vec![(0usize, points.len() - 1)];
578    while let Some((start, end)) = stack.pop() {
579        if end - start < 2 {
580            continue;
581        }
582        let a = points[start];
583        let direction = points[end].sub(a);
584        let length_squared = direction.length_squared().max(1e-300);
585        let mut worst = None;
586        let mut worst_distance = tolerance;
587        for (index, point) in points.iter().enumerate().take(end).skip(start + 1) {
588            let fraction = point.sub(a).dot(direction) / length_squared;
589            let fraction = fraction.clamp(0.0, 1.0);
590            let distance = point.sub(a.add(direction.scale(fraction))).length();
591            if distance > worst_distance {
592                worst_distance = distance;
593                worst = Some(index);
594            }
595        }
596        if let Some(index) = worst {
597            keep[index] = true;
598            stack.push((start, index));
599            stack.push((index, end));
600        }
601    }
602    keep.into_iter()
603        .enumerate()
604        .filter_map(|(index, keep)| keep.then_some(index))
605        .collect()
606}
607
608pub fn simplify_polyline(points: &[Vec3], tolerance: f64) -> Vec<Vec3> {
609    simplify_polyline_indices(points, tolerance)
610        .into_iter()
611        .map(|index| points[index])
612        .collect()
613}
614
615pub fn interpolate_curve_local(
616    points: &[Vec3],
617    parameters: &[f64],
618    tension: f64,
619) -> Result<NurbsCurve, String> {
620    if points.len() != parameters.len() || points.len() < 2 {
621        return Err(
622            "interpolate_curve_local: points and parameters must have matching length >= 2".into(),
623        );
624    }
625    if points.len() == 2 {
626        return interpolate_curve(points, 1, parameters);
627    }
628    let count = points.len();
629    let mut tangents = vec![Vec3::default(); count];
630    tangents[0] = points[1]
631        .sub(points[0])
632        .scale(1.0 / (parameters[1] - parameters[0]));
633    tangents[count - 1] = points[count - 1]
634        .sub(points[count - 2])
635        .scale(1.0 / (parameters[count - 1] - parameters[count - 2]));
636    for index in 1..count - 1 {
637        let previous_interval = parameters[index] - parameters[index - 1];
638        let next_interval = parameters[index + 1] - parameters[index];
639        let total = previous_interval + next_interval;
640        let previous_secant = points[index]
641            .sub(points[index - 1])
642            .scale(1.0 / previous_interval);
643        let next_secant = points[index + 1]
644            .sub(points[index])
645            .scale(1.0 / next_interval);
646        let mut tangent =
647            points[index - 1]
648                .scale(-next_interval / (previous_interval * total))
649                .add(points[index].scale(
650                    (next_interval - previous_interval) / (previous_interval * next_interval),
651                ))
652                .add(points[index + 1].scale(previous_interval / (next_interval * total)));
653        if previous_secant.dot(next_secant) <= 0.0
654            || tangent.dot(previous_secant) <= 0.0
655            || tangent.dot(next_secant) <= 0.0
656        {
657            tangent = Vec3::default();
658        } else {
659            let maximum = 3.0 * previous_secant.length().min(next_secant.length());
660            if tangent.length() > maximum {
661                tangent = tangent.normalized()?.scale(maximum);
662            }
663        }
664        tangents[index] = tangent;
665    }
666    if tension != 1.0 {
667        for tangent in &mut tangents {
668            *tangent = tangent.scale(tension);
669        }
670    }
671    let mut control_points = vec![Vec4::from_point(points[0], 1.0)];
672    for index in 0..count - 1 {
673        let interval = parameters[index + 1] - parameters[index];
674        control_points.extend([
675            Vec4::from_point(
676                points[index].add(tangents[index].scale(interval / 3.0)),
677                1.0,
678            ),
679            Vec4::from_point(
680                points[index + 1].sub(tangents[index + 1].scale(interval / 3.0)),
681                1.0,
682            ),
683            Vec4::from_point(points[index + 1], 1.0),
684        ]);
685    }
686    let mut knots = vec![parameters[0]; 4];
687    for parameter in &parameters[1..count - 1] {
688        knots.extend([*parameter; 3]);
689    }
690    knots.extend([parameters[count - 1]; 4]);
691    NurbsCurve::new(3, knots, control_points)
692}
693
694/// How far past the caller's own station budget the ladder may climb.
695///
696/// The budget a caller passes is its declaration of what it can afford
697/// DOWNSTREAM, and downstream cost is not linear in a section curve's span
698/// count: measured on the torus×torus singular pair, 4x the stations (80 → 320)
699/// took one imprint from 1.4 s to over 200 s, because every pcurve fit on the
700/// section then needs more samples than `MAX_PCURVE_SAMPLES` allows and takes
701/// the raised pass, 400 times over. So the ladder may DOUBLE the caller's
702/// budget and no more. With the input's own band as the floor
703/// ([`PolylineFitReport::floor`]) that meets 275 of the 282 fits in the case
704/// population; the other 7 are all `offset_shell` sections that stop at 192
705/// stations holding 2.33e-7 to 3.42e-6, and they REPORT it
706/// ([`PolylineFitExit::StationCeiling`]) instead of widening to it. Meeting every
707/// bar is not this bound's job — capping the cost of the ones it cannot at 2x
708/// what the caller chose, rather than at an absolute this module invented, is.
709const LADDER_BUDGET_FACTOR: usize = 2;
710
711/// Absolute station ceiling, whatever the caller's budget.
712///
713/// The ladder doubles the interpolation budget from what the caller asked for
714/// while the MEASUREMENT says the curve misses its tolerance, and stops here —
715/// or at the input's own station count, whichever comes first.
716///
717/// 1024 is a COST cap, not a geometric one. As SHIPPED it is a BACKSTOP that
718/// nothing in the corpus reaches, because [`LADDER_BUDGET_FACTOR`] binds first
719/// for every caller here (80 → 160 for the imprint driver, 96 → 192 for
720/// `offset_shell`). The reading below is the ladder let OFF that bound, kept
721/// because it is what the ceiling exists for. Measured over the 55-row case
722/// population: 282 fits, 21 of which miss at the caller's own budget; 16 of
723/// those reach their tolerance inside the ladder, and 5 do not — three at this
724/// ceiling with 3,070 control points and two stalled at 2,302 — every one of
725/// them an `offset_shell` section on the LOCAL interpolation lane, which
726/// converges at h² and cannot reach 1e-7 on a curved section at any station
727/// count this input offers. The lane is the fix there, not the ceiling; raising
728/// the ceiling buys accuracy in the fourth significant figure and pays for it
729/// in control points on every consumer downstream. A fit that stops here
730/// reports [`PolylineFitExit::StationCeiling`] with the deviation it actually
731/// holds, the way a pcurve fit reports its sample ceiling.
732pub const MAX_FIT_STATIONS: usize = 1024;
733
734/// Newton steps spent per point when the measurement locates the curve's
735/// nearest point to an input station. Three is enough on a seed that is already
736/// inside the right span (the seed comes from the station correspondence, not
737/// from a search), and the best iterate is kept, so a non-convergent step can
738/// only cost time.
739const MEASURE_NEWTON_STEPS: usize = 3;
740
741/// Fractions of every station span the measurement probes BETWEEN the input's
742/// own stations — the same three the pcurve refinement probes (`probe_residual`
743/// in `geometry/pcurve.rs`), and for the same reason: an interpolant that
744/// passes exactly through every station it was built from can still bulge in
745/// between, and that bulge is what becomes topology.
746const MEASURE_SPAN_FRACTIONS: [f64; 3] = [0.25, 0.5, 0.75];
747
748/// A rung must beat the one below it by this factor to be worth the next
749/// doubling. Global cubic interpolation improves 16x per doubling and the local
750/// lane 4x, so anything above 0.9 says the input — not the station count — is
751/// what binds, and the ladder stops with [`PolylineFitExit::Stalled`].
752const STALL_FACTOR: f64 = 0.9;
753
754/// What a polyline fit ACHIEVED, returned beside the curve so a budget exit can
755/// never be mistaken for a met tolerance.
756///
757/// [`fit_polyline`] is handed a tolerance by every caller that fits a marched
758/// section. Until 2026-09-13 that tolerance only ever reached
759/// [`simplify_polyline`] and the conditioning floor — the INPUT side — and the
760/// returned curve was never compared against it, while `maximum_points`
761/// DECIMATED the input before interpolation. A cap on the number of
762/// interpolation points is not a tolerance: on the 5,925-point marched base
763/// circle of an offset apex cone the delivered rim sagged 2.179e-3 against a
764/// requested 1e-7, four orders, silently, and the shell's volume read 4.23e-7
765/// relative where its analytically recognized sibling read 2.40e-11.
766///
767/// This report is a MEASUREMENT taken at a construction, not a band. Nothing
768/// may read `deviation` as the acceptance tolerance of the curve it describes;
769/// its consumers are the [`PolylineFitLedger`] (operation diagnostics) and the
770/// ladder's own stopping decision.
771#[derive(Clone, Copy, Debug, PartialEq)]
772pub struct PolylineFitReport {
773    /// Largest distance from an input point to the returned curve, over every
774    /// point of the input run. THE acceptance measurement: the points the
775    /// decimation dropped are the ones that read it.
776    pub deviation: f64,
777    /// Root mean square of the same sample set.
778    pub rms: f64,
779    /// Largest distance from the curve to the input POLYLINE, sampled between
780    /// the fit's own stations. Reported, never compared against the tolerance:
781    /// see [`measure_polyline_fit`] — its floor is the input's chord sag.
782    pub between_stations: f64,
783    /// The deviation the caller asked for.
784    pub tolerance: f64,
785    /// The deviation the ladder actually chased: `tolerance.max(dropped_band)`.
786    ///
787    /// A fit cannot demonstrate fidelity finer than its own INPUT's band. The
788    /// conditioning that produced the station pool drops points up to
789    /// `dropped_band` from the polyline through the survivors, so a curve that
790    /// reproduces the pool to 1e-8 while the pool stands 3.75e-7 from the input
791    /// is not a 1e-8 curve — it is a 3.75e-7 curve with an expensive interior.
792    /// Refining past the band buys control points and nothing else, and control
793    /// points are not free: the imprint's cost in a section curve's span count
794    /// is superlinear (measured on the torus×torus singular pair, where 4x the
795    /// stations cost two orders of magnitude of `process_curve` time).
796    pub floor: f64,
797    /// Interpolation stations in the returned curve.
798    pub stations: usize,
799    /// Control points in the returned curve — what the fit costs downstream.
800    pub controls: usize,
801    /// Points in the input run.
802    pub input_points: usize,
803    /// Stations the input offers after [`simplify_polyline`] and conditioning:
804    /// the ceiling the ladder can climb to on this input.
805    pub pool_points: usize,
806    /// Largest distance from an input point DROPPED by the simplification to
807    /// the polyline through the stations that survived it — the part of
808    /// `deviation` no interpolation can remove, since those points are not
809    /// stations any more. The analogue of [`crate::PcurveFitReport::off_surface`]:
810    /// a value near `tolerance` says the input's own band explains the
811    /// residual. Zero when the simplification dropped nothing.
812    pub dropped_band: f64,
813    /// Rungs the ladder spent. One means rung zero met the tolerance, or
814    /// nothing was refined.
815    pub rungs: usize,
816    /// Whether the returned curve came from the LOCAL interpolation lane. Not
817    /// always the lane the caller asked for: a ladder that ends unmet is
818    /// re-run in the other lane and the better MEASURED result is returned
819    /// (see [`fit_polyline`]).
820    pub local_lane: bool,
821    /// Whether that is the other lane — the caller's own ladder could not meet
822    /// the tolerance and this one measured better.
823    pub lane_switched: bool,
824    /// Why the ladder stopped.
825    pub exit: PolylineFitExit,
826}
827
828impl PolylineFitReport {
829    /// Whether the returned curve reaches the floor the fit chased — the
830    /// caller's tolerance, or the input's own band where that is coarser (see
831    /// [`PolylineFitReport::floor`]).
832    pub fn met_tolerance(&self) -> bool {
833        self.deviation <= self.floor
834    }
835
836    /// Whether the caller's own tolerance was reached, band or no band.
837    pub fn met_requested_tolerance(&self) -> bool {
838        self.deviation <= self.tolerance
839    }
840
841    /// Whether every station the input offers is an interpolation station — in
842    /// which case `deviation` is the interpolation SOLVE's residual and not a
843    /// statement about the curve between the input's samples.
844    ///
845    /// This matters for reading a met tolerance honestly. A fit has no oracle
846    /// but its input: on the exact-circle bench the pool-exhausted rung reads
847    /// 8.9e-16 in both lanes while the curves are 5.61e-7 (local) and 2.36e-13
848    /// (global) from the true circle. So a saturated `Converged` says "this
849    /// curve reproduces every point the marcher produced", which is the most a
850    /// fit can claim — not "this curve is within the tolerance of the section".
851    pub fn saturated(&self) -> bool {
852        self.stations >= self.pool_points
853    }
854}
855
856/// Why a polyline fit's refinement stopped. Only
857/// [`PolylineFitExit::Converged`] means the tolerance was met; every other
858/// variant is a BUDGET exit whose deviation was measured on the curve actually
859/// returned.
860#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
861pub enum PolylineFitExit {
862    /// A measured rung came in at or under the tolerance.
863    Converged,
864    /// [`MAX_FIT_STATIONS`] bound with the tolerance unmet and the input still
865    /// holding stations the ladder never used.
866    StationCeiling,
867    /// Every station the input offers is an interpolation station and the
868    /// tolerance is still unmet. More points cannot help; a different lane, a
869    /// finer march or a looser bar can.
870    InputExhausted,
871    /// A doubling failed to improve the deviation by [`STALL_FACTOR`], so the
872    /// input rather than the station count is what binds. The better of the two
873    /// curves is returned.
874    Stalled,
875    /// No refinement was attempted: [`fit_polyline_at`] fits exactly one rung,
876    /// and `BREP_POLYLINE_FIT_REFINE=0` makes [`fit_polyline`] do the same.
877    Unrefined,
878}
879
880#[derive(Clone, Debug)]
881pub struct PolylineFit {
882    pub curve: NurbsCurve,
883    pub parameters: Vec<f64>,
884    pub kept: Vec<Vec3>,
885    /// What this fit achieved against the tolerance it was given.
886    pub report: PolylineFitReport,
887}
888
889/// The interpolation stations a fit is ENTITLED to on this input: the points
890/// [`simplify_polyline`] keeps at `tolerance`, conditioned against
891/// near-duplicates (a station a fraction of a step from its neighbour, or from
892/// either end, rings the interpolant). Indices into `points`, ascending.
893///
894/// The decimation to a point BUDGET is deliberately not here
895/// ([`decimate_stations`]): the ladder lifts the budget and never the pool, so
896/// this runs once per fit however many rungs it takes.
897/// The station pool a full refit of `points` would interpolate from: the
898/// existing [`station_pool`], exposed unchanged for the section refiner's
899/// debug trace, which compares it against the seeded refit's forced seeds.
900pub(crate) fn polyline_station_pool(points: &[Vec3], tolerance: f64) -> Vec<usize> {
901    station_pool(points, tolerance)
902}
903
904fn station_pool(points: &[Vec3], tolerance: f64) -> Vec<usize> {
905    let simplified = simplify_polyline_indices(points, tolerance);
906    if simplified.len() > 2 {
907        let total: f64 = simplified
908            .windows(2)
909            .map(|pair| points[pair[1]].sub(points[pair[0]]).length())
910            .sum();
911        let floor = (tolerance * 0.01).max(total * 1e-4);
912        let first = points[simplified[0]];
913        let last = points[simplified[simplified.len() - 1]];
914        let mut conditioned = vec![simplified[0]];
915        for index in &simplified[1..simplified.len() - 1] {
916            let point = points[*index];
917            if point.sub(first).length() > floor
918                && point.sub(last).length() > floor
919                && point.sub(points[*conditioned.last().unwrap()]).length() > floor
920            {
921                conditioned.push(*index);
922            }
923        }
924        conditioned.push(simplified[simplified.len() - 1]);
925        conditioned
926    } else {
927        let mut distinct: Vec<usize> = Vec::new();
928        for index in simplified {
929            if distinct.last().is_none_or(|previous: &usize| {
930                points[index].sub(points[*previous]).length() > tolerance * 0.01
931            }) {
932                distinct.push(index);
933            }
934        }
935        distinct
936    }
937}
938
939/// `maximum_points` stations spread evenly over the pool, both ends kept.
940fn decimate_stations(pool: &[usize], maximum_points: usize) -> Vec<usize> {
941    if pool.len() <= maximum_points {
942        return pool.to_vec();
943    }
944    let step = (pool.len() - 1) as f64 / (maximum_points - 1) as f64;
945    (0..maximum_points)
946        .map(|index| pool[(index as f64 * step).round() as usize])
947        .collect()
948}
949
950/// Normalized chord-length parameters for `stations`, or `None` when they span
951/// no length at all.
952fn station_parameters(points: &[Vec3], stations: &[usize]) -> Option<Vec<f64>> {
953    let total: f64 = stations
954        .windows(2)
955        .map(|pair| points[pair[1]].sub(points[pair[0]]).length())
956        .sum();
957    if total <= 0.0 {
958        return None;
959    }
960    let mut parameters = vec![0.0; stations.len()];
961    let mut accumulated = 0.0;
962    for index in 1..stations.len() {
963        accumulated += points[stations[index]]
964            .sub(points[stations[index - 1]])
965            .length();
966        parameters[index] = accumulated / total;
967    }
968    *parameters.last_mut().unwrap() = 1.0;
969    Some(parameters)
970}
971
972fn distance_to_segment(point: Vec3, from: Vec3, to: Vec3) -> f64 {
973    let direction = to.sub(from);
974    let length_squared = direction.length_squared();
975    if length_squared <= 0.0 {
976        return point.sub(from).length();
977    }
978    let fraction = (point.sub(from).dot(direction) / length_squared).clamp(0.0, 1.0);
979    point.sub(from.add(direction.scale(fraction))).length()
980}
981
982/// Distance from `point` to `curve`, minimized inside `[lower, upper]` from a
983/// seed that is already in the right span.
984///
985/// NOT [`crate::project_point_to_curve`]: that one sweeps `4.max(degree + 2)`
986/// samples of EVERY span before its Newton — 1,700 evaluations on a
987/// 286-control fit, per query, where this is a fixed four — and it stops
988/// refining at a 1e-7 residual, which is exactly the bar this measurement has
989/// to resolve.
990fn distance_to_curve_near(
991    curve: &NurbsCurve,
992    point: Vec3,
993    seed: f64,
994    lower: f64,
995    upper: f64,
996) -> Result<f64, String> {
997    let mut parameter = seed.clamp(lower, upper);
998    let mut best = f64::INFINITY;
999    for _ in 0..MEASURE_NEWTON_STEPS {
1000        let derivatives = curve.derivatives_small(parameter, 2)?;
1001        let residual = derivatives[0].sub(point);
1002        best = best.min(residual.length_squared());
1003        let slope = derivatives[1].dot(residual);
1004        let curvature = derivatives[2].dot(residual) + derivatives[1].length_squared();
1005        if curvature.abs() <= f64::MIN_POSITIVE {
1006            break;
1007        }
1008        let next = (parameter - slope / curvature).clamp(lower, upper);
1009        if next == parameter {
1010            break;
1011        }
1012        parameter = next;
1013    }
1014    let residual = curve.evaluate(parameter)?.sub(point).length_squared();
1015    Ok(best.min(residual).sqrt())
1016}
1017
1018/// Deviation of `curve` from the input run: `(max, rms, between_stations)`.
1019///
1020/// `max` and `rms` are taken AT the input's own stations — the distance from
1021/// every input point to the curve. That is the acceptance measurement, and it
1022/// is the one the decimation defeats: a curve interpolating 96 of 5,925 marched
1023/// points reproduces those 96 exactly and misses the other 5,829 by however far
1024/// the interpolant sags, 2.179e-3 on the apex cone's base circle.
1025///
1026/// `between_stations` is the same curve sampled at [`MEASURE_SPAN_FRACTIONS`] of
1027/// every station span and measured against the input POLYLINE. It is reported
1028/// and deliberately NOT compared against the tolerance, because its floor is
1029/// the input's own sampling: a polyline through exact samples of a circle of
1030/// radius R taken every h cuts the corner by h²/(8R), so the perfect curve —
1031/// the circle itself — reads 9.6e-7 against a 7.2e-3-step march of a
1032/// radius-6.798 section. Measuring acceptance against chords would make the
1033/// bar unreachable for being right. What it does catch is a curve that wanders
1034/// between the points it was given by much MORE than that sag.
1035///
1036/// `stations` are indices into `points` and `parameters` their curve
1037/// parameters, so every query starts from a seed inside the right span and
1038/// nothing here searches the whole curve.
1039fn measure_polyline_fit(
1040    curve: &NurbsCurve,
1041    points: &[Vec3],
1042    stations: &[usize],
1043    parameters: &[f64],
1044    arc: &[f64],
1045) -> Result<(f64, f64, f64), String> {
1046    let mut worst = 0.0_f64;
1047    let mut sum_squares = 0.0_f64;
1048    let mut samples = 0usize;
1049    let mut between = 0.0_f64;
1050    let last = stations.len() - 1;
1051    for span in 0..last {
1052        let (from, to) = (stations[span], stations[span + 1]);
1053        let (t0, t1) = (parameters[span], parameters[span + 1]);
1054        // One span each side, so a station's nearest point may sit past its own
1055        // span's end without the bracket cutting the minimization short.
1056        let lower = parameters[span.saturating_sub(1)];
1057        let upper = parameters[(span + 2).min(last)];
1058        // AT the input's stations: every input point of this span, the left end
1059        // included (the right end belongs to the next span, and the very last
1060        // one is taken after the loop).
1061        let length = arc[to] - arc[from];
1062        for index in from..to {
1063            let seed = if length > 0.0 {
1064                t0 + (t1 - t0) * (arc[index] - arc[from]) / length
1065            } else {
1066                t0
1067            };
1068            let distance = distance_to_curve_near(curve, points[index], seed, lower, upper)?;
1069            worst = worst.max(distance);
1070            sum_squares += distance * distance;
1071            samples += 1;
1072        }
1073        // BETWEEN them: the curve's own span samples against the input run, in
1074        // the index window this span covers, widened by one segment each side.
1075        let window_start = from.saturating_sub(1);
1076        let window_end = (to + 1).min(points.len() - 1);
1077        for fraction in MEASURE_SPAN_FRACTIONS {
1078            let sample = curve.evaluate(t0 + (t1 - t0) * fraction)?;
1079            let mut nearest = f64::INFINITY;
1080            for index in window_start..window_end {
1081                nearest = nearest.min(distance_to_segment(
1082                    sample,
1083                    points[index],
1084                    points[index + 1],
1085                ));
1086            }
1087            if nearest.is_finite() {
1088                between = between.max(nearest);
1089            }
1090        }
1091    }
1092    let distance = distance_to_curve_near(
1093        curve,
1094        points[stations[last]],
1095        parameters[last],
1096        parameters[last.saturating_sub(1)],
1097        parameters[last],
1098    )?;
1099    worst = worst.max(distance);
1100    sum_squares += distance * distance;
1101    samples += 1;
1102    let rms = (sum_squares / samples as f64).sqrt();
1103    Ok((worst, rms, between))
1104}
1105
1106/// Largest distance from an input point the simplification DROPPED to the
1107/// polyline through the stations that survived — the input-side floor under
1108/// every rung of the ladder. See [`PolylineFitReport::dropped_band`].
1109fn dropped_band(points: &[Vec3], pool: &[usize]) -> f64 {
1110    let mut worst = 0.0_f64;
1111    for span in 0..pool.len() - 1 {
1112        let (from, to) = (pool[span], pool[span + 1]);
1113        for index in from + 1..to {
1114            worst = worst.max(distance_to_segment(
1115                points[index],
1116                points[from],
1117                points[to],
1118            ));
1119        }
1120    }
1121    worst
1122}
1123
1124/// Cumulative chord length of `points`, in the input's own order.
1125fn cumulative_chord(points: &[Vec3]) -> Vec<f64> {
1126    let mut arc = vec![0.0; points.len()];
1127    for index in 1..points.len() {
1128        arc[index] = arc[index - 1] + points[index].sub(points[index - 1]).length();
1129    }
1130    arc
1131}
1132
1133/// ONE rung: interpolate `stations` and measure the result against the input.
1134fn fit_rung(
1135    points: &[Vec3],
1136    pool: &[usize],
1137    arc: &[f64],
1138    maximum_points: usize,
1139    local_interpolation: bool,
1140    degree: usize,
1141) -> Result<(NurbsCurve, Vec<usize>, Vec<f64>, f64, f64, f64), String> {
1142    let stations = decimate_stations(pool, maximum_points);
1143    fit_station_set(points, stations, arc, local_interpolation, degree)
1144}
1145
1146fn fit_station_set(
1147    points: &[Vec3],
1148    stations: Vec<usize>,
1149    arc: &[f64],
1150    local_interpolation: bool,
1151    degree: usize,
1152) -> Result<(NurbsCurve, Vec<usize>, Vec<f64>, f64, f64, f64), String> {
1153    let parameters = station_parameters(points, &stations)
1154        .ok_or_else(|| "fit_polyline: degenerate polyline".to_string())?;
1155    let kept = stations.iter().map(|index| points[*index]).collect::<Vec<_>>();
1156    // A run that closes on itself is fitted PERIODICALLY on the global lane:
1157    // an open interpolant errs most at its ends, and a closed run's ends are
1158    // the march's origin, not a feature of the curve.
1159    let closed = kept.len() > degree + 1
1160        && kept[0].sub(kept[kept.len() - 1]).length() <= 1e-12 * (1.0 + kept[0].length());
1161    let curve = if local_interpolation {
1162        interpolate_curve_local(&kept, &parameters, 1.0)?
1163    } else if closed
1164        && degree > 3
1165        && degree % 2 == 1
1166        && std::env::var("BREP_SECTION_FIT_PERIODIC").as_deref() != Ok("0")
1167    {
1168        interpolate_curve_closed_of_degree(&kept[..kept.len() - 1], &parameters, degree)?
1169    } else {
1170        interpolate_curve(&kept, degree.min(kept.len() - 1), &parameters)?
1171    };
1172    let (deviation, rms, between) =
1173        measure_polyline_fit(&curve, points, &stations, &parameters, arc)?;
1174    Ok((curve, stations, parameters, deviation, rms, between))
1175}
1176
1177/// Fit ONE rung at the given station budget and measure it — no refinement.
1178///
1179/// This is [`fit_polyline`] before the ladder: the bench that pins the fit's
1180/// convergence orders drives it directly, because the ladder by design does
1181/// NOT return a 96-station curve when 96 stations miss the tolerance. Its
1182/// report always exits [`PolylineFitExit::Unrefined`] when the tolerance is
1183/// unmet.
1184pub fn fit_polyline_at(
1185    points: &[Vec3],
1186    tolerance: f64,
1187    maximum_points: usize,
1188    local_interpolation: bool,
1189) -> Result<PolylineFit, String> {
1190    let fit = fit_polyline_inner(points, tolerance, maximum_points, local_interpolation, false, 3)?;
1191    record_polyline_fit(&fit.report);
1192    Ok(fit)
1193}
1194
1195/// Interpolate a curve through a polyline and REFINE it until the curve itself
1196/// is within `tolerance` of that polyline.
1197///
1198/// `tolerance` is the deviation the RESULT must reach; `maximum_points` is
1199/// where the station ladder STARTS, not where it ends. Rung zero is exactly
1200/// the fit this routine returned before the ladder existed — same
1201/// simplification, same conditioning, same decimation, same parameters — so a
1202/// section that already met its tolerance returns the identical curve, to the
1203/// bit. Only a MEASURED miss spends anything: the budget doubles, each rung is
1204/// measured, and the best is kept, up to [`MAX_FIT_STATIONS`] or the input's
1205/// own station count.
1206///
1207/// Where it cannot get there it says so, in [`PolylineFit::report`], rather
1208/// than returning silently — the interpolant becomes a trim boundary and every
1209/// mass property downstream is read off it, so "within a step of the marched
1210/// points" is not good enough. This is the same contract
1211/// [`offset::fold_locus::fit_locus_pcurve`] already keeps for a traced locus
1212/// and [`crate::PcurveFitReport`] for a pcurve.
1213///
1214/// THE LANE IS ALSO MEASURED. `local_interpolation` is the lane the ladder
1215/// STARTS in, not the lane that is returned: where the caller's own ladder ends
1216/// unmet, the other lane's ladder is run on the same input and the better
1217/// MEASURED result is returned. Neither lane wins in general and the two fail
1218/// differently — measured on the exact-circle bench and the kink bench below:
1219///
1220/// * on a SMOOTH section the global cubic converges at h⁴ and the local lane at
1221///   h², so at the 96 stations `offset_shell` asks for the local lane delivers
1222///   286 control points 2.179e-3 from the input and the global one delivers 96
1223///   at 3.700e-6 — 589x better with a third of the controls, and the local lane
1224///   cannot reach 1e-7 there at any station count;
1225/// * at a KINK — a rim through a corner — the local lane's monotonicity limiter
1226///   holds the corner where the global cubic rings across it: 8.377e-2 against
1227///   4.095e-1 at the same 32 stations, 4.9x.
1228///
1229/// So the flag is a caller's PREFERENCE — which ladder is paid for first — and
1230/// never a decision about which curve is delivered. `offset_shell` asks for the
1231/// global lane since 2026-09-13 because its sections are mostly smooth and the
1232/// global rungs are three times cheaper per station; its corner sections reach
1233/// the local lane through this fallback instead. This is the
1234/// same shape as `degenerate_apex_frustum`'s branch selection in
1235/// `geometry/analytic_surface/intersect.rs`: a deterministic choice between two
1236/// constructions on their measured error, never a tolerance, and it can only
1237/// return the more accurate of the two.
1238///
1239/// Escape hatch: `BREP_POLYLINE_FIT_REFINE=0` fits rung zero alone, for
1240/// bisecting a moved number against the pre-ladder tree.
1241///
1242/// [`offset::fold_locus::fit_locus_pcurve`]: crate::offset
1243pub fn fit_polyline(
1244    points: &[Vec3],
1245    tolerance: f64,
1246    maximum_points: usize,
1247    local_interpolation: bool,
1248) -> Result<PolylineFit, String> {
1249    fit_polyline_of_degree(points, tolerance, maximum_points, local_interpolation, 3)
1250}
1251
1252/// [`fit_polyline`] with the GLOBAL lane's interpolation degree chosen by the
1253/// caller (the local lane is cubic Hermite whatever is asked). A marched
1254/// section's stations lie on both carriers to the march's residual, and a
1255/// degree-`p` interpolant through them errs by O(h^(p+1)) between stations: on
1256/// `BadBoolean`'s sphere×bore rim at its own 135 stations the cubic sits
1257/// 2.5e-7 off a carrier with a mean signed bias of −1.2e-8, the quintic 8.5e-9
1258/// and +6e-11 — the SAME stations, knots and control-point count, so nothing
1259/// downstream that samples per knot pays for it (2026-09-27).
1260pub fn fit_polyline_of_degree(
1261    points: &[Vec3],
1262    tolerance: f64,
1263    maximum_points: usize,
1264    local_interpolation: bool,
1265    degree: usize,
1266) -> Result<PolylineFit, String> {
1267    fit_polyline_of_degree_with_recovery(points, tolerance, maximum_points, local_interpolation, degree)
1268        .map(|(fit, _)| fit)
1269}
1270
1271/// Internal provenance for the SSI caller: recovering fidelity to the march
1272/// points does not establish accuracy between them against the carriers.
1273/// Keep this out of the public fit/report API.
1274pub(crate) fn fit_polyline_of_degree_with_recovery(
1275    points: &[Vec3],
1276    tolerance: f64,
1277    maximum_points: usize,
1278    local_interpolation: bool,
1279    degree: usize,
1280) -> Result<(PolylineFit, bool), String> {
1281    let refine = std::env::var("BREP_POLYLINE_FIT_REFINE").as_deref() != Ok("0");
1282    let asked = fit_polyline_inner(points, tolerance, maximum_points, local_interpolation, refine, degree)?;
1283    if asked.report.met_tolerance() || !refine {
1284        record_polyline_fit(&asked.report);
1285        return Ok((asked, false));
1286    }
1287    let mut other =
1288        fit_polyline_inner(points, tolerance, maximum_points, !local_interpolation, refine, degree)?;
1289    let spent = asked.report.rungs + other.report.rungs;
1290    let mut best = if other.report.deviation < asked.report.deviation {
1291        other.report.lane_switched = true;
1292        other
1293    } else {
1294        asked
1295    };
1296    // Uniform decimation can spend its whole budget away from a short,
1297    // highly curved part of the run. Retry a missed fit by adding the worst
1298    // eligible station per span, within the same station ceiling. Only a
1299    // measured converged fit replaces the already available fallback.
1300    let mut spent = spent;
1301    let mut recovered = false;
1302    if !best.report.met_tolerance() {
1303        let (adaptive, rounds) = fit_polyline_adaptive(points, tolerance, maximum_points, degree)?;
1304        spent += rounds;
1305        if let Some(mut adaptive) = adaptive {
1306            adaptive.report.lane_switched = local_interpolation;
1307            best = adaptive;
1308            recovered = true;
1309        }
1310    }
1311    // Include discarded attempts in the work ledger.
1312    best.report.rungs = spent;
1313    record_polyline_fit(&best.report);
1314    Ok((best, recovered))
1315}
1316
1317/// Redistribute the existing station budget after both uniform ladders miss.
1318/// Measurements still include every input point, not just eligible stations.
1319/// This proves fidelity to the sampled run, not accuracy between march points.
1320fn fit_polyline_adaptive(
1321    points: &[Vec3],
1322    tolerance: f64,
1323    maximum_points: usize,
1324    degree: usize,
1325) -> Result<(Option<PolylineFit>, usize), String> {
1326    let pool = station_pool(points, tolerance);
1327    let arc = cumulative_chord(points);
1328    let band = dropped_band(points, &pool);
1329    let floor = tolerance.max(band);
1330    let budget = maximum_points.max(2);
1331    let ceiling = pool.len().min(MAX_FIT_STATIONS)
1332        .min(budget.saturating_mul(LADDER_BUDGET_FACTOR)).max(budget);
1333    let mut stations = decimate_stations(&pool, budget);
1334    // Limit work independently of the station ceiling. A difficult run keeps
1335    // the existing measured fallback when this recovery does not converge.
1336    for round in 0..=8 {
1337        let Ok((curve, current, parameters, deviation, rms, between)) =
1338            fit_station_set(points, stations, &arc, false, degree)
1339        else { return Ok((None, round + 1)); };
1340        stations = current;
1341        if deviation <= floor {
1342            let report = PolylineFitReport {
1343                deviation, rms, between_stations: between, tolerance, floor,
1344                stations: stations.len(), controls: curve.control_points.len(),
1345                input_points: points.len(), pool_points: pool.len(), dropped_band: band,
1346                rungs: round + 1, local_lane: false, lane_switched: false,
1347                exit: PolylineFitExit::Converged,
1348            };
1349            return Ok((Some(PolylineFit {
1350                curve, parameters, kept: stations.iter().map(|&i| points[i]).collect(), report,
1351            }), round + 1));
1352        }
1353        if stations.len() >= ceiling || round == 8 { return Ok((None, round + 1)); }
1354        let mut candidates = Vec::new();
1355        for span in 0..stations.len() - 1 {
1356            let (from, to) = (stations[span], stations[span + 1]);
1357            let (t0, t1) = (parameters[span], parameters[span + 1]);
1358            let lower = parameters[span.saturating_sub(1)];
1359            let upper = parameters[(span + 2).min(stations.len() - 1)];
1360            let mut candidate: Option<(usize, f64)> = None;
1361            for &index in pool.iter().filter(|&&i| i > from && i < to) {
1362                let length = arc[to] - arc[from];
1363                let seed = if length > 0.0 {
1364                    t0 + (t1 - t0) * (arc[index] - arc[from]) / length
1365                } else { t0 };
1366                let error = distance_to_curve_near(&curve, points[index], seed, lower, upper)?;
1367                if candidate.is_none_or(|(_, previous)| error > previous) {
1368                    candidate = Some((index, error));
1369                }
1370            }
1371            if let Some((index, error)) = candidate {
1372                if error > floor { candidates.push((index, error)); }
1373            }
1374        }
1375        candidates.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
1376        let added = candidates.len().min(16).min(ceiling - stations.len());
1377        if added == 0 { return Ok((None, round + 1)); }
1378        stations.extend(candidates.iter().take(added).map(|&(index, _)| index));
1379        stations.sort_unstable();
1380    }
1381    unreachable!("the bounded refinement returns on its last round")
1382}
1383
1384/// The section refiner's refit (`csg/imprint/driver.rs`): every SEED station is
1385/// kept, and the set grows only where the fit is measured to miss.
1386///
1387/// The refiner inserts true intersection points into a run whose standing fit
1388/// kept only some of the run's stations. Refitting the whole run from its own
1389/// count interpolates every march station the standing fit had dropped as well;
1390/// on the skew-cylinder loop that took 160 kept stations to 519 (consistent with
1391/// ~122 inserts if the old refit kept every run point; the inserts themselves were
1392/// not counted). Here `seeds` (indices into `points`, any order) are the stations
1393/// the standing fit kept plus every inserted point, the bend witnesses, and the
1394/// run's two ends are added. AN ACCEPTED seeded fit interpolates every one of
1395/// them; the fallback below is the original full refit with its own pool and its
1396/// own conditioning, which may not. The set then grows exactly as
1397/// [`fit_polyline_adaptive`] grows its stations: the worst eligible pool station
1398/// of each span measured over the floor, at most 16 a round, at most 9 rounds.
1399/// It never passes the ceiling [`fit_polyline_inner`] derives for `full_budget`,
1400/// and it stands only when its deviation, measured over every input point,
1401/// meets the same floor (the tolerance, or the input's dropped band where
1402/// coarser).
1403///
1404/// Otherwise the result is EXACTLY `fit_polyline_of_degree(points, tolerance,
1405/// full_budget, local_interpolation, degree)`, the full-run refit the refiner
1406/// made before, both recovery lanes included. That covers every seeded
1407/// measurement that errs or reads non-finite (deviation, floor or a span's
1408/// error). So a seeded fit can stand only where it meets the same floor, and
1409/// every other section keeps the old curve, to the bit, or the old call's own
1410/// error.
1411/// How [`fit_polyline_seeded_with_path`] produced its fit: the seeded set
1412/// accepted at the floor, or the original full refit, and why. Returned on
1413/// every call (not a trace switch), so callers and controls can rely on it.
1414#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1415pub(crate) enum SeededPath {
1416    /// The seeded set met the floor after `rounds` fits.
1417    Accepted { rounds: usize },
1418    /// The result IS `fit_polyline_of_degree` at the full budget.
1419    Fallback(SeededFallback),
1420}
1421
1422/// Why a seeded refit fell back to the original full refit.
1423#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1424pub(crate) enum SeededFallback {
1425    NonFiniteInput,
1426    Degenerate,
1427    RefineDisabled,
1428    PoolTooSmall,
1429    NonFiniteBandOrArc,
1430    NonFiniteFloor,
1431    SeedsOverCeiling,
1432    /// A forced station is not in the pool `station_pool` builds for the full
1433    /// refit (simplified or conditioned away): the seeded set cannot respect
1434    /// the pool contract, so the attempt is declined.
1435    SeedsOutsideStationPool,
1436    StationSetFailed,
1437    NonFiniteFitReading,
1438    SpanUnreadable,
1439    CeilingReached,
1440    RoundsSpent,
1441    NothingToAdd,
1442    /// The accepted candidate's curve could not be evaluated, finite, at its
1443    /// own domain ends: the endpoint readings do not exist, so it is declined.
1444    EndpointUnreadable,
1445    /// A tight witness that is ALREADY a station reads over its tight
1446    /// tolerance at its own interpolation parameter: no station can be added
1447    /// to fix it, so the candidate is declined.
1448    TightStationOverTolerance,
1449}
1450
1451/// What one representative candidate call spent, for cost accounting apart
1452/// from the fallback's own report (whose bits must stay the full refit's).
1453#[derive(Clone, Copy, Debug, Default, PartialEq)]
1454pub(crate) struct RepresentativeCost {
1455    /// Pool representatives the candidate STARTED from (previous kept
1456    /// stations that are pool members, plus both run ends); every other point
1457    /// of the run, raw inserts included, is a witness, never forced.
1458    pub(crate) representatives: usize,
1459    /// Witnesses: every point of the run.
1460    pub(crate) witnesses: usize,
1461    /// `fit_station_set` interpolations the candidate made (at most 9).
1462    pub(crate) candidate_fits: usize,
1463    /// Whether the original full refit was then called (a fallback).
1464    pub(crate) full_refit: bool,
1465    /// MEASURED, not an acceptance condition (2026-10-04 clarification): on an
1466    /// accepted candidate, the distance of its curve evaluated at its own
1467    /// domain start and end from the run's first and last points. The
1468    /// existing constructors do not guarantee raw bit equality there (a
1469    /// periodic solve interpolates the distinct stations and reaches the seam
1470    /// by knot insertion), so no bit condition is imposed; the endpoint
1471    /// stations keep their indices and order, and both ends are witnesses of
1472    /// the all-run deviation like every other point. NaN when not accepted.
1473    pub(crate) start_offset: f64,
1474    pub(crate) end_offset: f64,
1475}
1476
1477/// TRACE ONLY: the near-duplicate floor `station_pool` conditions its pool
1478/// with, max(1% of the tolerance, 1e-4 of the simplified run's length), or 1%
1479/// of the tolerance for a run that simplifies to two points. It MIRRORS
1480/// `station_pool`'s expression (which is not edited); private controls pin it
1481/// against `station_pool`'s own conditioning. Production decisions use
1482/// `station_pool` membership itself, never this mirror.
1483pub(crate) fn polyline_station_pool_floor(points: &[Vec3], tolerance: f64) -> f64 {
1484    let simplified = simplify_polyline_indices(points, tolerance);
1485    if simplified.len() > 2 {
1486        let total: f64 = simplified.windows(2).map(|pair| points[pair[1]].sub(points[pair[0]]).length()).sum();
1487        (tolerance * 0.01).max(total * 1e-4)
1488    } else {
1489        tolerance * 0.01
1490    }
1491}
1492
1493pub(crate) fn fit_polyline_seeded_with_path(
1494    points: &[Vec3],
1495    seeds: &[usize],
1496    tolerance: f64,
1497    full_budget: usize,
1498    local_interpolation: bool,
1499    degree: usize,
1500) -> Result<(PolylineFit, SeededPath), String> {
1501    let full_refit = |reason: SeededFallback| {
1502        fit_polyline_of_degree(points, tolerance, full_budget, local_interpolation, degree)
1503            .map(|fit| (fit, SeededPath::Fallback(reason)))
1504    };
1505    // Inspect unreadable inputs before max/reductions can hide a NaN.
1506    if !tolerance.is_finite() || points.iter().any(|p| !p.x.is_finite() || !p.y.is_finite() || !p.z.is_finite()) {
1507        return full_refit(SeededFallback::NonFiniteInput);
1508    }
1509    if points.len() < 3 {
1510        return full_refit(SeededFallback::Degenerate);
1511    }
1512    if std::env::var("BREP_POLYLINE_FIT_REFINE").as_deref() == Ok("0") {
1513        return full_refit(SeededFallback::RefineDisabled);
1514    }
1515    let pool = station_pool(points, tolerance);
1516    if pool.len() < 2 {
1517        return full_refit(SeededFallback::PoolTooSmall);
1518    }
1519    let arc = cumulative_chord(points);
1520    let band = dropped_band(points, &pool);
1521    if !band.is_finite() || arc.iter().any(|value| !value.is_finite()) {
1522        return full_refit(SeededFallback::NonFiniteBandOrArc);
1523    }
1524    let floor = tolerance.max(band);
1525    if !floor.is_finite() {
1526        return full_refit(SeededFallback::NonFiniteFloor);
1527    }
1528    // The ceiling `fit_polyline_inner` derives for the same budget: the seeded
1529    // set may grow to it and never past it.
1530    let budget = full_budget.max(2);
1531    let ceiling = pool
1532        .len()
1533        .min(MAX_FIT_STATIONS)
1534        .min(budget.saturating_mul(LADDER_BUDGET_FACTOR))
1535        .max(budget);
1536    let mut stations = seeds
1537        .iter()
1538        .copied()
1539        .filter(|&index| index < points.len())
1540        .chain([0, points.len() - 1])
1541        .collect::<Vec<_>>();
1542    stations.sort_unstable();
1543    stations.dedup();
1544    if stations.len() > ceiling {
1545        return full_refit(SeededFallback::SeedsOverCeiling);
1546    }
1547    // ELIGIBILITY: THE ORIGINAL STATION-POOL CONTRACT. The full refit
1548    // interpolates `pool`, i.e. `station_pool`'s own simplification and
1549    // near-duplicate conditioning of this run. Every forced station must be
1550    // a member of that pool. If one is not (simplified or conditioned away),
1551    // the seeded set cannot respect the contract, and the attempt is DECLINED
1552    // to the identical full refit. Seeds are never dropped or moved, and no
1553    // new threshold is read: membership is `station_pool`'s own answer.
1554    // Measured on the helmet's 2036x3009 section (2026-10-04, 42f031ae6): an
1555    // accepted seeded fit with one seed outside the pool met its polyline
1556    // floor at 6.373e-8 while its carrier mid-span rang to 1.945e-4. That
1557    // seed is an insert SIMPLIFIED away (traced on c47bedc2a: insert
1558    // simplified 1, conditioned 0), not conditioned. The round's closest
1559    // seed pair (station-insert, 8.585e-8, same 59 seeds) sits under the
1560    // 4.881e-7 near-duplicate floor, but no seed was conditioned out; which
1561    // seeds that pair joins is not traced. On the bend control the declined
1562    // insert is the other case, conditioned out against a non-seed run point.
1563    // Membership covers both.
1564    if stations.iter().any(|index| pool.binary_search(index).is_err()) {
1565        return full_refit(SeededFallback::SeedsOutsideStationPool);
1566    }
1567    for round in 0..=8 {
1568        let Ok((curve, current, parameters, deviation, rms, between)) =
1569            fit_station_set(points, stations, &arc, local_interpolation, degree)
1570        else {
1571            return full_refit(SeededFallback::StationSetFailed);
1572        };
1573        stations = current;
1574        if !deviation.is_finite() || !rms.is_finite() || !between.is_finite() {
1575            return full_refit(SeededFallback::NonFiniteFitReading);
1576        }
1577        if deviation <= floor {
1578            let report = PolylineFitReport {
1579                deviation,
1580                rms,
1581                between_stations: between,
1582                tolerance,
1583                floor,
1584                stations: stations.len(),
1585                controls: curve.control_points.len(),
1586                input_points: points.len(),
1587                pool_points: pool.len(),
1588                dropped_band: band,
1589                rungs: round + 1,
1590                local_lane: local_interpolation,
1591                lane_switched: false,
1592                exit: PolylineFitExit::Converged,
1593            };
1594            record_polyline_fit(&report);
1595            let kept = stations.iter().map(|&index| points[index]).collect();
1596            return Ok((PolylineFit { curve, parameters, kept, report }, SeededPath::Accepted { rounds: round + 1 }));
1597        }
1598        if stations.len() >= ceiling {
1599            return full_refit(SeededFallback::CeilingReached);
1600        }
1601        if round == 8 {
1602            return full_refit(SeededFallback::RoundsSpent);
1603        }
1604        let mut candidates = Vec::new();
1605        for span in 0..stations.len() - 1 {
1606            let (from, to) = (stations[span], stations[span + 1]);
1607            let (t0, t1) = (parameters[span], parameters[span + 1]);
1608            let lower = parameters[span.saturating_sub(1)];
1609            let upper = parameters[(span + 2).min(stations.len() - 1)];
1610            let mut candidate: Option<(usize, f64)> = None;
1611            for &index in pool.iter().filter(|&&i| i > from && i < to) {
1612                let length = arc[to] - arc[from];
1613                let seed = if length > 0.0 { t0 + (t1 - t0) * (arc[index] - arc[from]) / length } else { t0 };
1614                // A span this entry cannot read sends the section to the
1615                // original refit; the shared measurement itself is unchanged.
1616                let Ok(error) = distance_to_curve_near(&curve, points[index], seed, lower, upper) else {
1617                    return full_refit(SeededFallback::SpanUnreadable);
1618                };
1619                if !error.is_finite() {
1620                    return full_refit(SeededFallback::SpanUnreadable);
1621                }
1622                if candidate.is_none_or(|(_, previous)| error > previous) {
1623                    candidate = Some((index, error));
1624                }
1625            }
1626            if let Some((index, error)) = candidate {
1627                if error > floor {
1628                    candidates.push((index, error));
1629                }
1630            }
1631        }
1632        candidates.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
1633        let added = candidates.len().min(16).min(ceiling - stations.len());
1634        if added == 0 {
1635            return full_refit(SeededFallback::NothingToAdd);
1636        }
1637        stations.extend(candidates.iter().take(added).map(|&(index, _)| index));
1638        stations.sort_unstable();
1639    }
1640    // Every pass of the loop above returns; this is the same fallback, named.
1641    full_refit(SeededFallback::RoundsSpent)
1642}
1643
1644/// REFINER-SPECIFIC candidate (2026-10-04, design review of 8f8c17368): the
1645/// seeded refit's contract with forced membership replaced by REPRESENTATIVES.
1646/// `seeds` (the previous fit's kept stations) that are members of
1647/// `station_pool(points, tolerance)` start the set, with both ends; seeds the
1648/// pool does not keep, and every refiner insert, are NOT forced as stations.
1649/// Instead EVERY point of `points` is a fidelity witness: the candidate is
1650/// accepted only when the interpolant's deviation over all of them (the same
1651/// `measure_polyline_fit` reading the full refit takes) is within `tolerance`
1652/// itself, NOT within max(tolerance, dropped_band). The chord band a
1653/// simplified or conditioned pool leaves is a property of the polyline
1654/// through the pool, not inherited uncertainty of points that lie on the
1655/// carriers; it is reported as `dropped_band` and never used as the bar here.
1656/// Growth is the existing rule: per span, the pool member farthest from the
1657/// curve, if over `tolerance`, at most 16 per round, 9 rounds, the same
1658/// ceiling. The caller enables this only for a run whose every ORIGINAL
1659/// point lies on both carriers. Anything that fails (unreadable, ceiling,
1660/// rounds, nothing a pool member can add while a witness is still over)
1661/// returns the identical `fit_polyline_of_degree(points, tolerance,
1662/// full_budget, local_interpolation, degree)`.
1663pub(crate) fn fit_polyline_representatives_with_path(
1664    points: &[Vec3],
1665    seeds: &[usize],
1666    tolerance: f64,
1667    full_budget: usize,
1668    local_interpolation: bool,
1669    degree: usize,
1670) -> Result<(PolylineFit, SeededPath, RepresentativeCost), String> {
1671    fit_polyline_representatives_with_witnesses(points, seeds, &[], tolerance, tolerance, full_budget, local_interpolation, degree)
1672}
1673
1674/// [`fit_polyline_representatives_with_path`] with TIGHT witnesses (root
1675/// ruling, 2026-10-04): `tight` indices of `points` (the refiner's own
1676/// inserted true-carrier points) must lie within `tight_tolerance` of the
1677/// curve (the refiner's existing carrier floor), while every other point is
1678/// held to `tolerance` as before. Measured on e90c30c94's bend: round 2's
1679/// inserts were already within 1e-7 of round 1's 63-station curve, so the
1680/// candidate added nothing, the carrier worst stayed 1.762e-8 against the
1681/// 1e-8 floor, and the bounded retry ended on the full refit. A tight
1682/// witness over its tolerance is REPRESENTED: the pool member nearest it (by
1683/// arc) inside its span becomes a station; if its span has none to add, the
1684/// candidate declines to the identical full refit (NothingToAdd). Inserts are
1685/// never forced as stations and no original point is held tighter. With
1686/// `tight` empty this is exactly the original candidate.
1687#[allow(clippy::too_many_arguments)]
1688pub(crate) fn fit_polyline_representatives_with_witnesses(
1689    points: &[Vec3],
1690    seeds: &[usize],
1691    tight: &[usize],
1692    tight_tolerance: f64,
1693    tolerance: f64,
1694    full_budget: usize,
1695    local_interpolation: bool,
1696    degree: usize,
1697) -> Result<(PolylineFit, SeededPath, RepresentativeCost), String> {
1698    let mut cost = RepresentativeCost { witnesses: points.len(), start_offset: f64::NAN, end_offset: f64::NAN, ..RepresentativeCost::default() };
1699    let full_refit = |reason: SeededFallback, mut cost: RepresentativeCost| {
1700        cost.full_refit = true;
1701        fit_polyline_of_degree(points, tolerance, full_budget, local_interpolation, degree)
1702            .map(|fit| (fit, SeededPath::Fallback(reason), cost))
1703    };
1704    if !tolerance.is_finite()
1705        || !tight_tolerance.is_finite()
1706        || points.iter().any(|p| !p.x.is_finite() || !p.y.is_finite() || !p.z.is_finite())
1707    {
1708        return full_refit(SeededFallback::NonFiniteInput, cost);
1709    }
1710    if points.len() < 3 {
1711        return full_refit(SeededFallback::Degenerate, cost);
1712    }
1713    if std::env::var("BREP_POLYLINE_FIT_REFINE").as_deref() == Ok("0") {
1714        return full_refit(SeededFallback::RefineDisabled, cost);
1715    }
1716    let mut tight: Vec<usize> = tight.iter().copied().filter(|&index| index < points.len()).collect();
1717    tight.sort_unstable();
1718    tight.dedup();
1719    let pool = station_pool(points, tolerance);
1720    if pool.len() < 2 || pool[0] != 0 || pool[pool.len() - 1] != points.len() - 1 {
1721        return full_refit(SeededFallback::PoolTooSmall, cost);
1722    }
1723    let arc = cumulative_chord(points);
1724    let band = dropped_band(points, &pool);
1725    if !band.is_finite() || arc.iter().any(|value| !value.is_finite()) {
1726        return full_refit(SeededFallback::NonFiniteBandOrArc, cost);
1727    }
1728    let budget = full_budget.max(2);
1729    let ceiling = pool
1730        .len()
1731        .min(MAX_FIT_STATIONS)
1732        .min(budget.saturating_mul(LADDER_BUDGET_FACTOR))
1733        .max(budget);
1734    let mut stations = seeds
1735        .iter()
1736        .copied()
1737        .filter(|index| pool.binary_search(index).is_ok())
1738        .chain([0, points.len() - 1])
1739        .collect::<Vec<_>>();
1740    stations.sort_unstable();
1741    stations.dedup();
1742    cost.representatives = stations.len();
1743    if stations.len() > ceiling {
1744        return full_refit(SeededFallback::SeedsOverCeiling, cost);
1745    }
1746    for round in 0..=8 {
1747        cost.candidate_fits += 1;
1748        let Ok((curve, current, parameters, deviation, rms, between)) =
1749            fit_station_set(points, stations, &arc, local_interpolation, degree)
1750        else {
1751            return full_refit(SeededFallback::StationSetFailed, cost);
1752        };
1753        stations = current;
1754        if !deviation.is_finite() || !rms.is_finite() || !between.is_finite() {
1755            return full_refit(SeededFallback::NonFiniteFitReading, cost);
1756        }
1757        // Every tight witness against the curve, near its own span (the same
1758        // bracketed reader the growth below uses). Any unreadable read declines.
1759        let mut tight_over: Vec<usize> = Vec::new();
1760        for &index in &tight {
1761            let span = match stations.binary_search(&index) {
1762                Ok(position) => {
1763                    // A station is interpolated, but finite precision is not a
1764                    // proof: read it at its own interpolation parameter.
1765                    let distance = curve.evaluate(parameters[position]).map(|p| p.sub(points[index]).length());
1766                    match distance {
1767                        Ok(distance) if distance.is_finite() => {
1768                            if distance > tight_tolerance {
1769                                return full_refit(SeededFallback::TightStationOverTolerance, cost);
1770                            }
1771                        }
1772                        _ => return full_refit(SeededFallback::SpanUnreadable, cost),
1773                    }
1774                    continue;
1775                }
1776                // Both run ends are always stations; an index outside the
1777                // stations' range cannot occur, and is read as unreadable.
1778                Err(at) if at == 0 || at >= stations.len() => return full_refit(SeededFallback::SpanUnreadable, cost),
1779                Err(at) => at - 1,
1780            };
1781            let (from, to) = (stations[span], stations[span + 1]);
1782            let (t0, t1) = (parameters[span], parameters[span + 1]);
1783            let length = arc[to] - arc[from];
1784            let seed = if length > 0.0 { t0 + (t1 - t0) * (arc[index] - arc[from]) / length } else { t0 };
1785            let lower = parameters[span.saturating_sub(1)];
1786            let upper = parameters[(span + 2).min(stations.len() - 1)];
1787            let Ok(error) = distance_to_curve_near(&curve, points[index], seed, lower, upper) else {
1788                return full_refit(SeededFallback::SpanUnreadable, cost);
1789            };
1790            if !error.is_finite() {
1791                return full_refit(SeededFallback::SpanUnreadable, cost);
1792            }
1793            if error > tight_tolerance {
1794                tight_over.push(index);
1795            }
1796        }
1797        if deviation <= tolerance && tight_over.is_empty() {
1798            // The curve at its own domain ends, read and recorded against the
1799            // run's first and last points (the same reading the controls take
1800            // on the full refit). Unreadable ends decline; the offsets are
1801            // reported, not judged by a new bit condition.
1802            let ends = curve
1803                .domain()
1804                .and_then(|[t0, t1]| Ok((curve.evaluate(t0)?, curve.evaluate(t1)?)));
1805            let Ok((start, end)) = ends else {
1806                return full_refit(SeededFallback::EndpointUnreadable, cost);
1807            };
1808            cost.start_offset = start.sub(points[0]).length();
1809            cost.end_offset = end.sub(points[points.len() - 1]).length();
1810            if !(cost.start_offset.is_finite() && cost.end_offset.is_finite()) {
1811                cost.start_offset = f64::NAN;
1812                cost.end_offset = f64::NAN;
1813                return full_refit(SeededFallback::EndpointUnreadable, cost);
1814            }
1815            let report = PolylineFitReport {
1816                deviation,
1817                rms,
1818                between_stations: between,
1819                tolerance,
1820                floor: tolerance,
1821                stations: stations.len(),
1822                controls: curve.control_points.len(),
1823                input_points: points.len(),
1824                pool_points: pool.len(),
1825                dropped_band: band,
1826                rungs: round + 1,
1827                local_lane: local_interpolation,
1828                lane_switched: false,
1829                exit: PolylineFitExit::Converged,
1830            };
1831            record_polyline_fit(&report);
1832            let kept = stations.iter().map(|&index| points[index]).collect();
1833            return Ok((PolylineFit { curve, parameters, kept, report }, SeededPath::Accepted { rounds: round + 1 }, cost));
1834        }
1835        if stations.len() >= ceiling {
1836            return full_refit(SeededFallback::CeilingReached, cost);
1837        }
1838        if round == 8 {
1839            return full_refit(SeededFallback::RoundsSpent, cost);
1840        }
1841        let mut candidates = Vec::new();
1842        for span in 0..stations.len() - 1 {
1843            let (from, to) = (stations[span], stations[span + 1]);
1844            let (t0, t1) = (parameters[span], parameters[span + 1]);
1845            let lower = parameters[span.saturating_sub(1)];
1846            let upper = parameters[(span + 2).min(stations.len() - 1)];
1847            let mut candidate: Option<(usize, f64)> = None;
1848            for &index in pool.iter().filter(|&&i| i > from && i < to) {
1849                let length = arc[to] - arc[from];
1850                let seed = if length > 0.0 { t0 + (t1 - t0) * (arc[index] - arc[from]) / length } else { t0 };
1851                let Ok(error) = distance_to_curve_near(&curve, points[index], seed, lower, upper) else {
1852                    return full_refit(SeededFallback::SpanUnreadable, cost);
1853                };
1854                if !error.is_finite() {
1855                    return full_refit(SeededFallback::SpanUnreadable, cost);
1856                }
1857                if candidate.is_none_or(|(_, previous)| error > previous) {
1858                    candidate = Some((index, error));
1859                }
1860            }
1861            if let Some((index, error)) = candidate {
1862                if error > tolerance {
1863                    candidates.push((index, error));
1864                }
1865            }
1866        }
1867        // A tight witness over its tolerance is represented by the pool member
1868        // nearest it by arc inside its span (not already chosen), if any.
1869        for &index in &tight_over {
1870            let at = stations.binary_search(&index).unwrap_err();
1871            let (from, to) = (stations[at - 1], stations[at]);
1872            let nearest = pool
1873                .iter()
1874                .copied()
1875                .filter(|&member| member > from && member < to)
1876                .min_by(|&a, &b| (arc[a] - arc[index]).abs().total_cmp(&(arc[b] - arc[index]).abs()).then_with(|| a.cmp(&b)));
1877            if let Some(member) = nearest {
1878                // Already an ordinary candidate: raise it to the tight priority
1879                // so the first 16 cannot pass it over.
1880                match candidates.iter_mut().find(|(chosen, _)| *chosen == member) {
1881                    Some(entry) => entry.1 = f64::INFINITY,
1882                    None => candidates.push((member, f64::INFINITY)),
1883                }
1884            }
1885        }
1886        candidates.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
1887        let added = candidates.len().min(16).min(ceiling - stations.len());
1888        if added == 0 {
1889            // A witness is still over its tolerance and no pool member in any
1890            // span can represent it: decline, never force the raw point.
1891            return full_refit(SeededFallback::NothingToAdd, cost);
1892        }
1893        stations.extend(candidates.iter().take(added).map(|&(index, _)| index));
1894        stations.sort_unstable();
1895    }
1896    full_refit(SeededFallback::RoundsSpent, cost)
1897}
1898
1899
1900fn fit_polyline_inner(
1901    points: &[Vec3],
1902    tolerance: f64,
1903    maximum_points: usize,
1904    local_interpolation: bool,
1905    refine: bool,
1906    degree: usize,
1907) -> Result<PolylineFit, String> {
1908    let pool = station_pool(points, tolerance);
1909    if pool.len() < 2 {
1910        return Err("fit_polyline: degenerate polyline".into());
1911    }
1912    let arc = cumulative_chord(points);
1913    let band = dropped_band(points, &pool);
1914    let floor = tolerance.max(band);
1915    let mut budget = maximum_points.max(2);
1916    let ceiling = pool
1917        .len()
1918        .min(MAX_FIT_STATIONS)
1919        .min(budget.saturating_mul(LADDER_BUDGET_FACTOR))
1920        .max(budget);
1921    let (mut curve, mut stations, mut parameters, mut deviation, mut rms, mut between) =
1922        fit_rung(points, &pool, &arc, budget, local_interpolation, degree)?;
1923    let mut rungs = 1usize;
1924    let mut exit = if deviation <= floor {
1925        PolylineFitExit::Converged
1926    } else {
1927        PolylineFitExit::Unrefined
1928    };
1929    while refine && deviation > floor {
1930        if budget >= ceiling {
1931            exit = if ceiling >= pool.len() {
1932                PolylineFitExit::InputExhausted
1933            } else {
1934                PolylineFitExit::StationCeiling
1935            };
1936            break;
1937        }
1938        budget = (budget * 2).min(ceiling);
1939        let rung = fit_rung(points, &pool, &arc, budget, local_interpolation, degree)?;
1940        rungs += 1;
1941        if rung.3 >= deviation * STALL_FACTOR {
1942            if rung.3 < deviation {
1943                (curve, stations, parameters, deviation, rms, between) = rung;
1944            }
1945            // A rung can stall INSIDE the tolerance — it bought little because
1946            // there was little left to buy. The exit names what the curve is,
1947            // so `met_tolerance()` and `exit` can never disagree.
1948            exit = if deviation <= floor {
1949                PolylineFitExit::Converged
1950            } else {
1951                PolylineFitExit::Stalled
1952            };
1953            break;
1954        }
1955        (curve, stations, parameters, deviation, rms, between) = rung;
1956        if deviation <= floor {
1957            exit = PolylineFitExit::Converged;
1958        }
1959    }
1960    let report = PolylineFitReport {
1961        deviation,
1962        rms,
1963        between_stations: between,
1964        tolerance,
1965        floor,
1966        stations: stations.len(),
1967        controls: curve.control_points.len(),
1968        input_points: points.len(),
1969        pool_points: pool.len(),
1970        dropped_band: band,
1971        rungs,
1972        local_lane: local_interpolation,
1973        lane_switched: false,
1974        exit,
1975    };
1976    Ok(PolylineFit {
1977        curve,
1978        parameters,
1979        kept: stations.iter().map(|index| points[*index]).collect(),
1980        report,
1981    })
1982}
1983
1984/// Per-operation tally of polyline fits and how many missed their tolerance.
1985///
1986/// The same shape, and for the same reason, as [`crate::PcurveFitLedger`]:
1987/// [`fit_polyline`] is called from the imprint driver and from the offset
1988/// reintersection, neither of which has a diagnostics record to write into. An
1989/// operation that returns [`KernelDiagnostics`] opens a [`PolylineFitScope`];
1990/// every fit made on that thread while the scope is open is tallied here, and
1991/// closing it hands the tally back for [`PolylineFitLedger::report_into`].
1992/// Scopes nest — closing a child folds it into its parent — and a scope DROPPED
1993/// without being closed is discarded, so a refused boolean attempt does not
1994/// leave its fits on the caller's tally. With no scope open, recording is a
1995/// no-op.
1996#[derive(Clone, Copy, Debug, Default, PartialEq)]
1997pub struct PolylineFitLedger {
1998    /// Fits recorded, met ones included.
1999    pub fits: u64,
2000    /// Fits whose returned curve did not reach its tolerance.
2001    pub unmet: u64,
2002    /// Unmet fits that stopped at [`MAX_FIT_STATIONS`].
2003    pub station_ceiling: u64,
2004    /// Unmet fits that had already used every station the input offers.
2005    pub input_exhausted: u64,
2006    /// Unmet fits whose last doubling bought nothing.
2007    pub stalled: u64,
2008    /// Unmet fits that never refined (a single-rung fit, or the escape hatch).
2009    pub unrefined: u64,
2010    /// Fits that spent more than one rung, met or not.
2011    pub refined: u64,
2012    /// Fits that met their tolerance only with every station the input offers —
2013    /// a SATURATED reading (see [`PolylineFitReport::saturated`]).
2014    pub met_at_pool: u64,
2015    /// Fits returned from the lane the caller did NOT ask for, because the
2016    /// caller's own ladder ended unmet and the other lane measured better.
2017    pub lane_switched: u64,
2018    /// Extra rungs spent over every fit — what the ladder cost.
2019    pub extra_rungs: u64,
2020    /// Largest deviation among the unmet fits; zero when there are none.
2021    pub worst_unmet_deviation: f64,
2022    /// Largest [`PolylineFitReport::dropped_band`] over every fit.
2023    pub worst_dropped_band: f64,
2024}
2025
2026impl PolylineFitLedger {
2027    fn record(&mut self, report: &PolylineFitReport) {
2028        self.fits += 1;
2029        self.extra_rungs += (report.rungs - 1) as u64;
2030        if report.rungs > 1 {
2031            self.refined += 1;
2032        }
2033        self.worst_dropped_band = self.worst_dropped_band.max(report.dropped_band);
2034        if report.lane_switched {
2035            self.lane_switched += 1;
2036        }
2037        if report.met_tolerance() {
2038            if report.saturated() {
2039                self.met_at_pool += 1;
2040            }
2041            return;
2042        }
2043        self.unmet += 1;
2044        match report.exit {
2045            PolylineFitExit::Converged => {}
2046            PolylineFitExit::StationCeiling => self.station_ceiling += 1,
2047            PolylineFitExit::InputExhausted => self.input_exhausted += 1,
2048            PolylineFitExit::Stalled => self.stalled += 1,
2049            PolylineFitExit::Unrefined => self.unrefined += 1,
2050        }
2051        self.worst_unmet_deviation = self.worst_unmet_deviation.max(report.deviation);
2052    }
2053
2054    fn fold(&mut self, child: &PolylineFitLedger) {
2055        self.fits += child.fits;
2056        self.unmet += child.unmet;
2057        self.station_ceiling += child.station_ceiling;
2058        self.input_exhausted += child.input_exhausted;
2059        self.stalled += child.stalled;
2060        self.unrefined += child.unrefined;
2061        self.refined += child.refined;
2062        self.met_at_pool += child.met_at_pool;
2063        self.lane_switched += child.lane_switched;
2064        self.extra_rungs += child.extra_rungs;
2065        self.worst_unmet_deviation = self.worst_unmet_deviation.max(child.worst_unmet_deviation);
2066        self.worst_dropped_band = self.worst_dropped_band.max(child.worst_dropped_band);
2067    }
2068
2069    /// Write the tally into an operation's diagnostics: the `fit.polyline.*`
2070    /// counters always, plus one `fit.polyline.unmet_tolerance` event at
2071    /// [`DiagnosticSeverity::Degraded`] when any fit missed its tolerance.
2072    /// Degraded, not Error: the curve is still the kernel's best interpolant of
2073    /// the points it was given and the solid stays shippable, but it no longer
2074    /// claims the accuracy the caller asked for.
2075    pub fn report_into(&self, diagnostics: &mut KernelDiagnostics) {
2076        diagnostics.count_n("fit.polyline.fits", self.fits);
2077        diagnostics.count_n("fit.polyline.unmet_tolerance", self.unmet);
2078        diagnostics.count_n("fit.polyline.exit.station_ceiling", self.station_ceiling);
2079        diagnostics.count_n("fit.polyline.exit.input_exhausted", self.input_exhausted);
2080        diagnostics.count_n("fit.polyline.exit.stalled", self.stalled);
2081        diagnostics.count_n("fit.polyline.exit.unrefined", self.unrefined);
2082        diagnostics.count_n("fit.polyline.refined", self.refined);
2083        diagnostics.count_n("fit.polyline.met_at_pool", self.met_at_pool);
2084        diagnostics.count_n("fit.polyline.lane_switched", self.lane_switched);
2085        diagnostics.count_n("fit.polyline.extra_rungs", self.extra_rungs);
2086        diagnostics.measure_max("fit.polyline.worst_unmet_deviation", self.worst_unmet_deviation);
2087        diagnostics.measure_max("fit.polyline.worst_dropped_band", self.worst_dropped_band);
2088        if self.unmet > 0 {
2089            diagnostics.event(
2090                DiagnosticSeverity::Degraded,
2091                KernelStage::Intersect,
2092                "fit.polyline.unmet_tolerance",
2093                format!(
2094                    "{} of {} polyline fits did not reach the tolerance they were given \
2095                     (station ceiling {}, input exhausted {}, stalled {}, unrefined {}); \
2096                     worst deviation {:.3e}; the simplification's own band reaches {:.3e}",
2097                    self.unmet,
2098                    self.fits,
2099                    self.station_ceiling,
2100                    self.input_exhausted,
2101                    self.stalled,
2102                    self.unrefined,
2103                    self.worst_unmet_deviation,
2104                    self.worst_dropped_band,
2105                ),
2106            );
2107        }
2108    }
2109}
2110
2111thread_local! {
2112    /// The open [`PolylineFitScope`]s on this thread, innermost last.
2113    static POLYLINE_FIT_SCOPES: std::cell::RefCell<Vec<PolylineFitLedger>> =
2114        const { std::cell::RefCell::new(Vec::new()) };
2115}
2116
2117/// An open tally of the polyline fits made on this thread — see
2118/// [`PolylineFitLedger`]. Open it where an operation starts, [`close`] it where
2119/// the operation returns its diagnostics; a `?` that unwinds past it drops the
2120/// tally.
2121///
2122/// [`close`]: PolylineFitScope::close
2123pub struct PolylineFitScope {
2124    /// Not `Send`: the scope must close on the thread that opened it.
2125    _thread_bound: std::marker::PhantomData<*const ()>,
2126}
2127
2128impl PolylineFitScope {
2129    pub fn open() -> Self {
2130        POLYLINE_FIT_SCOPES.with(|scopes| scopes.borrow_mut().push(PolylineFitLedger::default()));
2131        Self {
2132            _thread_bound: std::marker::PhantomData,
2133        }
2134    }
2135
2136    /// Take the tally, folding it into the enclosing scope if there is one.
2137    pub fn close(self) -> PolylineFitLedger {
2138        let ledger = POLYLINE_FIT_SCOPES.with(|scopes| {
2139            let mut scopes = scopes.borrow_mut();
2140            let ledger = scopes.pop().unwrap_or_default();
2141            if let Some(parent) = scopes.last_mut() {
2142                parent.fold(&ledger);
2143            }
2144            ledger
2145        });
2146        std::mem::forget(self);
2147        ledger
2148    }
2149}
2150
2151impl Drop for PolylineFitScope {
2152    fn drop(&mut self) {
2153        POLYLINE_FIT_SCOPES.with(|scopes| {
2154            scopes.borrow_mut().pop();
2155        });
2156    }
2157}
2158
2159fn record_polyline_fit(report: &PolylineFitReport) {
2160    // Per-fit trace for the fit bench and the lane census, the way
2161    // `BREP_DEBUG_PCURVE_FIT` traces a pcurve fit.
2162    if std::env::var_os("BREP_DEBUG_POLYLINE_FIT").is_some() {
2163        eprintln!("POLYLINE-FIT {report:?}");
2164    }
2165    POLYLINE_FIT_SCOPES.with(|scopes| {
2166        if let Some(open) = scopes.borrow_mut().last_mut() {
2167            open.record(report);
2168        }
2169    });
2170}
2171
2172
2173
2174/// Cox–de Boor basis over a RAW (possibly unclamped) knot array — the local
2175/// helper the periodic interpolation needs; `KnotVector` validation rightly
2176/// rejects unclamped arrays, so this stays private to the fit module.
2177fn raw_basis(knots: &[f64], degree: usize, span: usize, parameter: f64) -> Vec<f64> {
2178    let mut basis = vec![0.0; degree + 1];
2179    let mut left = vec![0.0; degree + 1];
2180    let mut right = vec![0.0; degree + 1];
2181    basis[0] = 1.0;
2182    for j in 1..=degree {
2183        left[j] = parameter - knots[span + 1 - j];
2184        right[j] = knots[span + j] - parameter;
2185        let mut saved = 0.0;
2186        for r in 0..j {
2187            let denominator = right[r + 1] + left[j - r];
2188            let temp = if denominator.abs() > 0.0 {
2189                basis[r] / denominator
2190            } else {
2191                0.0
2192            };
2193            basis[r] = saved + right[r + 1] * temp;
2194            saved = left[j - r] * temp;
2195        }
2196        basis[j] = saved;
2197    }
2198    basis
2199}
2200
2201/// Boehm single-knot insertion on raw arrays (degree fixed by caller).
2202fn raw_insert_knot(knots: &mut Vec<f64>, controls: &mut Vec<Vec3>, degree: usize, parameter: f64) {
2203    // span: last index with knots[span] <= parameter, clamped to the valid
2204    // control range (the textbook find_span clamp — inserting at the domain
2205    // end otherwise indexes one past the control array).
2206    let span = knots
2207        .iter()
2208        .rposition(|&knot| knot <= parameter + 1e-14)
2209        .unwrap()
2210        .min(controls.len() - 1);
2211    let mut fresh = Vec::with_capacity(controls.len() + 1);
2212    fresh.extend_from_slice(&controls[..=span - degree]);
2213    for i in span - degree + 1..=span {
2214        let denominator = knots[i + degree] - knots[i];
2215        let alpha = if denominator.abs() > 0.0 {
2216            (parameter - knots[i]) / denominator
2217        } else {
2218            0.0
2219        };
2220        fresh.push(
2221            controls[i - 1]
2222                .scale(1.0 - alpha)
2223                .add(controls[i].scale(alpha)),
2224        );
2225    }
2226    fresh.extend_from_slice(&controls[span..]);
2227    *controls = fresh;
2228    knots.insert(span + 1, parameter);
2229}
2230
2231/// EXACT closed (periodic) cubic interpolation. `points` are the S >= 4
2232/// distinct stations (first NOT repeated); `parameters` has S+1 strictly
2233/// increasing values whose last entry closes the period. The cyclic
2234/// collocation system is solved densely (S is small for lofts), and the
2235/// periodic B-spline is re-expressed in CLAMPED form by Boehm-inserting the
2236/// domain ends to full multiplicity — the representation every kernel
2237/// consumer expects — so the seam is C² by construction, not by welding.
2238pub fn interpolate_curve_closed(points: &[Vec3], parameters: &[f64]) -> Result<NurbsCurve, String> {
2239    interpolate_curve_closed_of_degree(points, parameters, 3)
2240}
2241
2242/// [`interpolate_curve_closed`] at an odd `degree` (3 or 5): the cyclic knot
2243/// line carries `degree` knots either side of the period, and interpolating at
2244/// the knots is well posed for an odd degree. A closed marched section fitted
2245/// OPEN errs most at its ends — the march's origin, where the loop was cut —
2246/// and that end error is what the periodic fit removes (2026-09-27).
2247pub fn interpolate_curve_closed_of_degree(
2248    points: &[Vec3],
2249    parameters: &[f64],
2250    degree: usize,
2251) -> Result<NurbsCurve, String> {
2252    if degree % 2 == 0 || degree < 3 {
2253        return Err("interpolate_curve_closed: the degree must be odd and at least 3".into());
2254    }
2255    let station_count = points.len();
2256    if station_count < degree + 1 {
2257        return Err("interpolate_curve_closed: need more stations than the degree".into());
2258    }
2259    if parameters.len() != station_count + 1 {
2260        return Err(
2261            "interpolate_curve_closed: parameters must have one more entry than points".into(),
2262        );
2263    }
2264    if parameters.windows(2).any(|pair| pair[1] <= pair[0]) {
2265        return Err("interpolate_curve_closed: parameters must increase".into());
2266    }
2267    let period = parameters[station_count] - parameters[0];
2268    // Cyclic knot line u_j = t_{j mod S} + floor(j/S)·T for j in −p..S+p,
2269    // stored with offset p (the degree): raw[k] = u_{k−p}.
2270    let cyclic = |j: i64| -> f64 {
2271        let s = station_count as i64;
2272        let wrap = j.div_euclid(s);
2273        parameters[j.rem_euclid(s) as usize] + wrap as f64 * period
2274    };
2275    let raw_knots: Vec<f64> = (-(degree as i64)..=(station_count as i64 + degree as i64)).map(cyclic).collect();
2276    // Collocation: row i evaluates the cubic basis at t_i; the span in the
2277    // raw array is the one containing t_i (raw index i+p == u_i).
2278    let mut matrix = vec![vec![0.0; station_count]; station_count];
2279    for i in 0..station_count {
2280        let span = i + degree;
2281        let basis = raw_basis(&raw_knots, degree, span, parameters[i]);
2282        for (offset, value) in basis.iter().enumerate() {
2283            // Control j = span − degree + offset in unclamped indexing, i.e.
2284            // cyclic control (i + offset − p) mod S.
2285            let index = (i as i64 + offset as i64 - degree as i64).rem_euclid(station_count as i64) as usize;
2286            matrix[i][index] += value;
2287        }
2288    }
2289    let solve_axis = |axis: fn(Vec3) -> f64| {
2290        solve_dense(
2291            matrix.clone(),
2292            points.iter().copied().map(axis).collect::<Vec<_>>(),
2293        )
2294    };
2295    let xs = solve_axis(|point| point.x)?;
2296    let ys = solve_axis(|point| point.y)?;
2297    let zs = solve_axis(|point| point.z)?;
2298    let cyclic_controls: Vec<Vec3> = (0..station_count)
2299        .map(|index| Vec3::new(xs[index], ys[index], zs[index]))
2300        .collect();
2301    // Window covering [t_0, t_S]: controls D_{−p..S−1} cyclically.
2302    let mut window_controls: Vec<Vec3> = (-(degree as i64)..(station_count as i64))
2303        .map(|j| cyclic_controls[j.rem_euclid(station_count as i64) as usize])
2304        .collect();
2305    let mut window_knots = raw_knots.clone();
2306    // Clamp both domain ends to full multiplicity (degree insertions each —
2307    // the ends currently sit at multiplicity 1).
2308    for _ in 0..degree {
2309        raw_insert_knot(
2310            &mut window_knots,
2311            &mut window_controls,
2312            degree,
2313            parameters[0],
2314        );
2315    }
2316    for _ in 0..degree {
2317        raw_insert_knot(
2318            &mut window_knots,
2319            &mut window_controls,
2320            degree,
2321            parameters[station_count],
2322        );
2323    }
2324    // Slice out the clamped sub-curve over [t_0, t_S]: knots from the first
2325    // occurrence of t_0 through the last of t_S, controls aligned so that
2326    // control k pairs with knot span k..k+degree+1.
2327    let first = window_knots
2328        .iter()
2329        .position(|&knot| (knot - parameters[0]).abs() < 1e-12)
2330        .ok_or("interpolate_curve_closed: clamp lost the start knot")?;
2331    let last = window_knots
2332        .iter()
2333        .rposition(|&knot| (knot - parameters[station_count]).abs() < 1e-12)
2334        .ok_or("interpolate_curve_closed: clamp lost the end knot")?;
2335    let clamped_knots: Vec<f64> = window_knots[first..=last].to_vec();
2336    let control_count = clamped_knots.len() - degree - 1;
2337    let clamped_controls: Vec<Vec4> = window_controls[first..first + control_count]
2338        .iter()
2339        .map(|point| Vec4::from_point(*point, 1.0))
2340        .collect();
2341    NurbsCurve::new(degree, clamped_knots, clamped_controls)
2342}
2343