Skip to main content

brep_geometry/geometry/
fit.rs

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