Skip to main content

brep_geometry/geometry/
curve.rs

1pub use crate::Vec3;
2use serde::{Deserialize, Serialize};
3
4const EPS: f64 = crate::tolerance::FP_FLOOR;
5
6/// Knot IDENTITY tolerance (parameter-space): two knot parameters within this
7/// absolute band are treated as the SAME knot for snapping — insert_knot,
8/// `NurbsCurve::split`, monotonicity and clamp checks.  This is the single
9/// source for the "absolute 1e-9 knot tolerance" that `split` enforces and
10/// that imprint's trim guards mirror.  Distinct in PURPOSE (not just value)
11/// from [`KNOT_DEDUP_EPS`]; the two are deliberately NOT unified.
12pub const KNOT_IDENTITY_TOL: f64 = 1e-9;
13
14/// Numerical knot DEDUP epsilon (parameter-space): the tighter floor used when
15/// *counting distinct* knots (SSI/CSI `interior_knot_count`) or comparing whole
16/// knot vectors for exact reconstruction (analytic surface recognition).  This
17/// answers "are these two knot floats the same value?", NOT "are these the same
18/// knot for snapping?" — so it stays at 1e-12 and must NOT be unified with the
19/// looser [`KNOT_IDENTITY_TOL`].
20///
21/// Comparand: the absolute difference of two knot values of ONE knot vector,
22/// and a knot's distance from either end of the active domain
23/// (`knots[degree]`, `knots[len − 1 − degree]`), in that curve's parameter
24/// units. Two knots within it count as one, and a knot within it of an end is
25/// not interior. The containment lanes' per-pcurve sample count
26/// (`crate::trim_sample_count`) counts interior knots this way.
27pub const KNOT_DEDUP_EPS: f64 = 1e-12;
28
29/// Count distinct knots strictly inside a valid knot vector's active domain.
30/// Multiplicities and values within [`KNOT_DEDUP_EPS`] of the domain ends are
31/// ignored. Used to choose sampling density for intersections and containment.
32pub fn interior_knot_count(knots: &[f64], degree: usize) -> usize {
33    distinct_interior_knots(knots, degree).count()
34}
35
36fn distinct_interior_knots(knots: &[f64], degree: usize) -> impl Iterator<Item = f64> + '_ {
37    let start = knots[degree];
38    let end = knots[knots.len() - 1 - degree];
39    let mut previous = None;
40    knots.iter().copied().filter(move |&knot| {
41        if knot <= start + KNOT_DEDUP_EPS || knot >= end - KNOT_DEDUP_EPS {
42            return false;
43        }
44        if previous.is_none_or(|value: f64| (value - knot).abs() > KNOT_DEDUP_EPS) {
45            previous = Some(knot);
46            true
47        } else {
48            false
49        }
50    })
51}
52
53#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
54pub struct Vec4 {
55    pub x: f64,
56    pub y: f64,
57    pub z: f64,
58    pub w: f64,
59}
60
61/// Construct a line in the parameter plane (z = 0).
62pub fn parameter_line(u0: f64, v0: f64, u1: f64, v1: f64) -> Result<NurbsCurve, String> {
63    make_line(Vec3::new(u0, v0, 0.0), Vec3::new(u1, v1, 0.0))
64}
65
66/// Project a curve onto plane axes while preserving its knots and rational weights.
67pub fn curve_to_plane_parameters(
68    curve: &NurbsCurve,
69    origin: Vec3,
70    x_axis: Vec3,
71    y_axis: Vec3,
72) -> Result<NurbsCurve, String> {
73    NurbsCurve::new(
74        curve.degree,
75        curve.knots.clone(),
76        curve
77            .control_points
78            .iter()
79            .map(|point| {
80                let euclidean = Vec3::new(point.x / point.w, point.y / point.w, point.z / point.w);
81                let delta = euclidean.sub(origin);
82                Vec4 {
83                    x: delta.dot(x_axis) * point.w,
84                    y: delta.dot(y_axis) * point.w,
85                    z: 0.0,
86                    w: point.w,
87                }
88            })
89            .collect(),
90    )
91}
92
93impl Vec4 {
94    pub fn from_point(point: Vec3, weight: f64) -> Self {
95        Self {
96            x: point.x * weight,
97            y: point.y * weight,
98            z: point.z * weight,
99            w: weight,
100        }
101    }
102
103    pub fn add(self, rhs: Self) -> Self {
104        Self {
105            x: self.x + rhs.x,
106            y: self.y + rhs.y,
107            z: self.z + rhs.z,
108            w: self.w + rhs.w,
109        }
110    }
111
112    pub fn scale(self, factor: f64) -> Self {
113        Self {
114            x: self.x * factor,
115            y: self.y * factor,
116            z: self.z * factor,
117            w: self.w * factor,
118        }
119    }
120
121    pub fn point(self) -> Result<Vec3, String> {
122        if self.w.abs() <= EPS {
123            return Err("cannot project a homogeneous point with zero weight".into());
124        }
125        Ok(Vec3::new(self.x / self.w, self.y / self.w, self.z / self.w))
126    }
127}
128
129/// Public stack capacity used by prepared readers and optional algorithms.
130/// Keep this bound stable: those algorithms may use different arithmetic.
131pub const MAX_STACK_DEGREE: usize = 7;
132pub const MAX_STACK_ORDER: usize = MAX_STACK_DEGREE + 1;
133
134// The scalar surface evaluator also carries degree-nine screw walls. Its
135// larger scratch must not enable other algorithms or resize public fields.
136pub(crate) const EVALUATOR_STACK_DEGREE: usize = 9;
137pub(crate) const EVALUATOR_STACK_ORDER: usize = EVALUATOR_STACK_DEGREE + 1;
138
139/// `BREP_DEBUG_KNOTS=1` diagnostic for a rejected knot vector: dumps the whole
140/// vector (plus a backtrace) to stderr and appends it to the returned message,
141/// so a knot failure buried behind a `Result` that a caller only prints —
142/// STEP import's `first_error`, say — still names the offending construction
143/// site. Off by default; the message stays byte-identical without the var.
144fn knot_reject(reason: &str, knots: &[f64], degree: usize) -> String {
145    if std::env::var("BREP_DEBUG_KNOTS").is_err() {
146        return reason.to_string();
147    }
148    let mut worst_descent = f64::NEG_INFINITY;
149    let mut worst_index = 0usize;
150    for (index, pair) in knots.windows(2).enumerate() {
151        let descent = pair[0] - pair[1];
152        if descent > worst_descent {
153            worst_descent = descent;
154            worst_index = index;
155        }
156    }
157    let detail = format!(
158        "{reason} [degree={degree} count={} worst_descent={worst_descent:.6e} at index \
159         {worst_index} knots={knots:?}]",
160        knots.len()
161    );
162    eprintln!(
163        "KNOT-REJECT {detail}\n{}",
164        std::backtrace::Backtrace::force_capture()
165    );
166    detail
167}
168
169/// Validation shared by `KnotVector::new` and the lazily-validated
170/// curve/surface types. Must stay the single source of truth so cached
171/// validation and eager validation reject exactly the same inputs.
172pub fn validate_knots(knots: &[f64], degree: usize) -> Result<(), String> {
173    if degree < 1 {
174        return Err("KnotVector: degree must be >= 1".into());
175    }
176    if knots.len() < 2 * (degree + 1) {
177        return Err(format!(
178            "KnotVector: need at least {} knots for degree {}, got {}",
179            2 * (degree + 1),
180            degree,
181            knots.len()
182        ));
183    }
184    if knots.iter().any(|value| !value.is_finite()) {
185        return Err("KnotVector: knots must be finite".into());
186    }
187    if knots
188        .windows(2)
189        .any(|pair| pair[1] < pair[0] - KNOT_IDENTITY_TOL)
190    {
191        return Err(knot_reject(
192            "KnotVector: knots must be non-decreasing",
193            knots,
194            degree,
195        ));
196    }
197    let first = knots[0];
198    let last = knots[knots.len() - 1];
199    for index in 0..=degree {
200        if (knots[index] - first).abs() > KNOT_IDENTITY_TOL {
201            return Err(knot_reject(
202                "KnotVector: expected clamped start",
203                knots,
204                degree,
205            ));
206        }
207        if (knots[knots.len() - 1 - index] - last).abs() > KNOT_IDENTITY_TOL {
208            return Err(knot_reject("KnotVector: expected clamped end", knots, degree));
209        }
210    }
211    if last - first <= KNOT_IDENTITY_TOL {
212        return Err(knot_reject(
213            "KnotVector: degenerate parameter range",
214            knots,
215            degree,
216        ));
217    }
218    Ok(())
219}
220
221pub fn knot_domain(knots: &[f64], degree: usize) -> [f64; 2] {
222    [knots[degree], knots[knots.len() - 1 - degree]]
223}
224
225pub fn knot_clamp(knots: &[f64], degree: usize, parameter: f64) -> f64 {
226    let [start, end] = knot_domain(knots, degree);
227    parameter.clamp(start, end)
228}
229
230pub fn knot_find_span(knots: &[f64], degree: usize, parameter: f64) -> usize {
231    let parameter = knot_clamp(knots, degree, parameter);
232    let n = knots.len() - degree - 2;
233    if parameter >= knots[n + 1] {
234        // At/after the domain end.  A properly clamped vector has the end knot
235        // at multiplicity exactly `degree + 1`, so span `n` is the last
236        // non-empty interval.  An over-clamped end (a vendor exporter can emit
237        // multiplicity > degree + 1, e.g. two coincident knot VALUES) leaves
238        // span `n` pointing at a zero-width interval whose basis functions are
239        // all zero.  Walk back to the last interval that actually has width.
240        let mut span = n;
241        while span > degree && knots[span] >= knots[span + 1] {
242            span -= 1;
243        }
244        return span;
245    }
246    if parameter <= knots[degree] {
247        // At/before the domain start — the mirror of the case above.  For a
248        // properly clamped start (multiplicity degree + 1) this returns
249        // `degree`; for an over-clamped start it advances past the extra
250        // coincident knots to the first non-empty interval so evaluation never
251        // lands on a zero-width span (which would yield an all-zero,
252        // zero-weight homogeneous point).
253        let mut span = degree;
254        while span < n && knots[span + 1] <= parameter {
255            span += 1;
256        }
257        return span;
258    }
259    let mut low = degree;
260    let mut high = n + 1;
261    let mut middle = (low + high) / 2;
262    while parameter < knots[middle] || parameter >= knots[middle + 1] {
263        if parameter < knots[middle] {
264            high = middle;
265        } else {
266            low = middle;
267        }
268        middle = (low + high) / 2;
269    }
270    middle
271}
272
273/// Cox–de Boor basis functions into a caller-provided stack array.
274/// Requires `degree <= MAX_STACK_DEGREE`; entries `0..=degree` are written.
275#[inline]
276pub fn basis_functions_into(
277    knots: &[f64], degree: usize, span: usize, parameter: f64,
278    basis: &mut [f64; MAX_STACK_ORDER],
279) {
280    debug_assert!(degree <= MAX_STACK_DEGREE);
281    basis_functions_wide(knots, degree, span, parameter, basis);
282}
283
284/// Internal surface scratch, including ninth-degree screw walls.
285pub(crate) fn basis_functions_wide<const WIDTH: usize>(
286    knots: &[f64],
287    degree: usize,
288    span: usize,
289    parameter: f64,
290    basis: &mut [f64; WIDTH],
291) {
292    debug_assert!(degree <= EVALUATOR_STACK_DEGREE);
293    debug_assert!(degree < WIDTH);
294    // Common carrier degrees (1..=5, 8 and 9) run the same
295    // recurrence with the degree and the scratch size fixed at compile time:
296    // the same operations in the same order on the same operands, so the same
297    // bits, without the full-width scratch fill and runtime loop bounds.
298    // Degrees 0, 6 and 7 retain the public eight-wide scratch.
299    match degree {
300        1 => basis_functions_scratch::<2>(knots, 1, span, parameter, basis),
301        2 => basis_functions_scratch::<3>(knots, 2, span, parameter, basis),
302        3 => basis_functions_scratch::<4>(knots, 3, span, parameter, basis),
303        4 => basis_functions_scratch::<5>(knots, 4, span, parameter, basis),
304        5 => basis_functions_scratch::<6>(knots, 5, span, parameter, basis),
305        8 => basis_functions_scratch::<9>(knots, 8, span, parameter, basis),
306        9 => basis_functions_scratch::<10>(knots, 9, span, parameter, basis),
307        _ => basis_functions_scratch::<MAX_STACK_ORDER>(knots, degree, span, parameter, basis),
308    }
309}
310
311/// [`basis_functions_into`]'s body with `left`/`right` scratch of `ORDER`
312/// entries (`degree < ORDER`). The recurrence reads only entries `..=degree`
313/// of either, so the scratch width changes no value.
314#[inline(always)]
315fn basis_functions_scratch<const ORDER: usize>(
316    knots: &[f64],
317    degree: usize,
318    span: usize,
319    parameter: f64,
320    basis: &mut [f64],
321) {
322    debug_assert!(degree < ORDER);
323    let mut left = [0.0f64; ORDER];
324    let mut right = [0.0f64; ORDER];
325    basis_functions_raw_into(knots, degree, span, parameter, EPS, basis, &mut left, &mut right);
326}
327
328/// Basis derivatives (The NURBS Book A2.3) into caller-provided stack rows.
329/// Writes rows `0..=min(derivative_count, degree)` of `out`; rows above the
330/// degree keep whatever the caller initialized them to (callers zero-fill,
331/// matching the heap implementation's zero rows). Requires
332/// `degree <= MAX_STACK_DEGREE` and `out.len() > derivative_count`.
333#[inline]
334pub fn basis_derivatives_into(
335    knots: &[f64], degree: usize, span: usize, parameter: f64,
336    derivative_count: usize, out: &mut [[f64; MAX_STACK_ORDER]],
337) {
338    debug_assert!(degree <= MAX_STACK_DEGREE);
339    basis_derivatives_wide(knots, degree, span, parameter, derivative_count, out);
340}
341
342/// Internal surface scratch, with the public helper's arithmetic.
343pub(crate) fn basis_derivatives_wide<const WIDTH: usize>(
344    knots: &[f64],
345    degree: usize,
346    span: usize,
347    parameter: f64,
348    derivative_count: usize,
349    out: &mut [[f64; WIDTH]],
350) {
351    debug_assert!(degree <= EVALUATOR_STACK_DEGREE);
352    debug_assert!(degree < WIDTH);
353    debug_assert!(out.len() > derivative_count);
354    // A value-only request needs only the current basis column. A2.2 uses
355    // the same scalar recurrence as A2.3's zeroth row, without its square
356    // derivative scratch table or the final column copy.
357    if derivative_count == 0 {
358        basis_functions_wide(knots, degree, span, parameter, &mut out[0]);
359        return;
360    }
361    // The degree is already fixed below, but A2.3's inner k loop still
362    // receives a runtime derivative count. Fix the common counts too,
363    // without changing the recurrence or the higher-order fallback.
364    if switch!("BREP_BASIS_DERIVATIVE_COUNT_FIXED", true) {
365        match derivative_count {
366            0 => return basis_derivatives_count_fixed::<0, WIDTH>(knots, degree, span, parameter, out),
367            1 => return basis_derivatives_count_fixed::<1, WIDTH>(knots, degree, span, parameter, out),
368            2 => return basis_derivatives_count_fixed::<2, WIDTH>(knots, degree, span, parameter, out),
369            _ => {}
370        }
371    }
372    // Degrees 1..=5, 8 and 9 with degree and scratch size fixed at compile
373    // time (see `basis_functions_into`): the same operations in the same
374    // order, so the same bits; `ndu`, `left`, `right` and `a` shrink from
375    // full-width to `degree + 1`-wide and the loop bounds fold.
376    match degree {
377        1 => basis_derivatives_scratch::<2, WIDTH>(knots, 1, span, parameter, derivative_count, out),
378        2 => basis_derivatives_scratch::<3, WIDTH>(knots, 2, span, parameter, derivative_count, out),
379        3 => basis_derivatives_scratch::<4, WIDTH>(knots, 3, span, parameter, derivative_count, out),
380        4 => basis_derivatives_scratch::<5, WIDTH>(knots, 4, span, parameter, derivative_count, out),
381        5 => basis_derivatives_scratch::<6, WIDTH>(knots, 5, span, parameter, derivative_count, out),
382        8 => basis_derivatives_scratch::<9, WIDTH>(knots, 8, span, parameter, derivative_count, out),
383        9 => basis_derivatives_scratch::<10, WIDTH>(knots, 9, span, parameter, derivative_count, out),
384        _ => basis_derivatives_scratch::<MAX_STACK_ORDER, WIDTH>(knots, degree, span, parameter, derivative_count, out),
385    }
386}
387
388#[inline(always)]
389fn basis_derivatives_count_fixed<const COUNT: usize, const WIDTH: usize>(
390    knots: &[f64], degree: usize, span: usize, parameter: f64,
391    out: &mut [[f64; WIDTH]],
392) {
393    match degree {
394        1 => basis_derivatives_scratch::<2, WIDTH>(knots, 1, span, parameter, COUNT, out),
395        2 => basis_derivatives_scratch::<3, WIDTH>(knots, 2, span, parameter, COUNT, out),
396        3 => basis_derivatives_scratch::<4, WIDTH>(knots, 3, span, parameter, COUNT, out),
397        4 => basis_derivatives_scratch::<5, WIDTH>(knots, 4, span, parameter, COUNT, out),
398        5 => basis_derivatives_scratch::<6, WIDTH>(knots, 5, span, parameter, COUNT, out),
399        8 => basis_derivatives_scratch::<9, WIDTH>(knots, 8, span, parameter, COUNT, out),
400        9 => basis_derivatives_scratch::<10, WIDTH>(knots, 9, span, parameter, COUNT, out),
401        _ => basis_derivatives_scratch::<MAX_STACK_ORDER, WIDTH>(knots, degree, span, parameter, COUNT, out),
402    }
403}
404
405/// [`basis_derivatives_into`]'s body (The NURBS Book A2.3) with every scratch
406/// array `ORDER` wide (`degree < ORDER`). The recurrence reads scratch entries
407/// `..=degree` only, and the per-order zero fill of `a[s2]` is kept (its
408/// unwritten entries are read as zero by the next order), so the width
409/// changes no value.
410#[inline(always)]
411fn basis_derivatives_scratch<const ORDER: usize, const WIDTH: usize>(
412    knots: &[f64],
413    degree: usize,
414    span: usize,
415    parameter: f64,
416    derivative_count: usize,
417    out: &mut [[f64; WIDTH]],
418) {
419        let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::BASIS);
420    debug_assert!(degree < ORDER);
421    let p = degree;
422    let n = derivative_count.min(p);
423    let mut ndu = [[0.0f64; ORDER]; ORDER];
424    let mut left = [0.0f64; ORDER];
425    let mut right = [0.0f64; ORDER];
426    ndu[0][0] = 1.0;
427
428    for j in 1..=p {
429        left[j] = parameter - knots[span + 1 - j];
430        right[j] = knots[span + j] - parameter;
431        let mut saved = 0.0;
432        for r in 0..j {
433            ndu[j][r] = right[r + 1] + left[j - r];
434            let temporary = if ndu[j][r].abs() <= EPS {
435                0.0
436            } else {
437                ndu[r][j - 1] / ndu[j][r]
438            };
439            ndu[r][j] = saved + right[r + 1] * temporary;
440            saved = left[j - r] * temporary;
441        }
442        ndu[j][j] = saved;
443    }
444
445    for j in 0..=p {
446        out[0][j] = ndu[j][p];
447    }
448    let mut a = [[0.0f64; ORDER]; 2];
449    for r in 0..=p {
450        let mut s1 = 0;
451        let mut s2 = 1;
452        a[0][0] = 1.0;
453        for k in 1..=n {
454            a[s2] = [0.0; ORDER];
455            let mut value = 0.0;
456            let rk = r as isize - k as isize;
457            let pk = p - k;
458            if r >= k {
459                let denominator = ndu[pk + 1][rk as usize];
460                a[s2][0] = a[s1][0] / denominator;
461                value = a[s2][0] * ndu[rk as usize][pk];
462            }
463            let j1 = if rk >= -1 { 1 } else { (-rk) as usize };
464            let j2 = if r <= pk + 1 { k - 1 } else { p - r };
465            if j1 <= j2 {
466                for j in j1..=j2 {
467                    let index = (rk + j as isize) as usize;
468                    a[s2][j] = (a[s1][j] - a[s1][j - 1]) / ndu[pk + 1][index];
469                    value += a[s2][j] * ndu[index][pk];
470                }
471            }
472            if r <= pk {
473                a[s2][k] = -a[s1][k - 1] / ndu[pk + 1][r];
474                value += a[s2][k] * ndu[r][pk];
475            }
476            out[k][r] = value;
477            std::mem::swap(&mut s1, &mut s2);
478        }
479    }
480    let mut factor = p as f64;
481    for k in 1..=n {
482        for value in out[k][..=p].iter_mut() {
483            *value *= factor;
484        }
485        factor *= (p - k) as f64;
486    }
487}
488
489#[derive(Clone, Debug, Deserialize, Serialize)]
490pub struct KnotVector {
491    pub knots: Vec<f64>,
492    pub degree: usize,
493}
494
495/// Distinct interior knots, excluding endpoint neighborhoods within `1e-12`.
496pub fn interior_knots(knots: &[f64], degree: usize) -> Vec<f64> {
497    distinct_interior_knots(knots, degree).collect()
498}
499
500impl KnotVector {
501    pub fn new(knots: Vec<f64>, degree: usize) -> Result<Self, String> {
502        validate_knots(&knots, degree)?;
503        Ok(Self { knots, degree })
504    }
505
506    pub fn control_point_count(&self) -> usize {
507        self.knots.len() - self.degree - 1
508    }
509
510    pub fn domain(&self) -> [f64; 2] {
511        [
512            self.knots[self.degree],
513            self.knots[self.knots.len() - 1 - self.degree],
514        ]
515    }
516
517    pub fn clamp_param(&self, parameter: f64) -> f64 {
518        knot_clamp(&self.knots, self.degree, parameter)
519    }
520
521    pub fn find_span(&self, parameter: f64) -> usize {
522        knot_find_span(&self.knots, self.degree, parameter)
523    }
524
525    pub fn basis_functions(&self, span: usize, parameter: f64) -> Vec<f64> {
526        let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::BASIS);
527        if self.degree <= MAX_STACK_DEGREE {
528            let mut basis = [0.0f64; MAX_STACK_ORDER];
529            basis_functions_into(&self.knots, self.degree, span, parameter, &mut basis);
530            return basis[..=self.degree].to_vec();
531        }
532        basis_functions_raw(&self.knots, self.degree, span, parameter, EPS)
533    }
534
535    pub fn basis_derivatives(
536        &self,
537        span: usize,
538        parameter: f64,
539        derivative_count: usize,
540    ) -> Vec<Vec<f64>> {
541        let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::BASIS);
542        if self.degree <= MAX_STACK_DEGREE && derivative_count <= MAX_STACK_DEGREE {
543            let mut rows = [[0.0f64; MAX_STACK_ORDER]; MAX_STACK_ORDER];
544            basis_derivatives_into(
545                &self.knots,
546                self.degree,
547                span,
548                parameter,
549                derivative_count,
550                &mut rows[..=derivative_count],
551            );
552            return rows[..=derivative_count]
553                .iter()
554                .map(|row| row[..=self.degree].to_vec())
555                .collect();
556        }
557        let p = self.degree;
558        let n = derivative_count.min(p);
559        let mut ndu = vec![vec![0.0; p + 1]; p + 1];
560        let mut left = vec![0.0; p + 1];
561        let mut right = vec![0.0; p + 1];
562        ndu[0][0] = 1.0;
563
564        for j in 1..=p {
565            left[j] = parameter - self.knots[span + 1 - j];
566            right[j] = self.knots[span + j] - parameter;
567            let mut saved = 0.0;
568            for r in 0..j {
569                ndu[j][r] = right[r + 1] + left[j - r];
570                let temporary = if ndu[j][r].abs() <= EPS {
571                    0.0
572                } else {
573                    ndu[r][j - 1] / ndu[j][r]
574                };
575                ndu[r][j] = saved + right[r + 1] * temporary;
576                saved = left[j - r] * temporary;
577            }
578            ndu[j][j] = saved;
579        }
580
581        let mut derivatives = vec![vec![0.0; p + 1]; derivative_count + 1];
582        for j in 0..=p {
583            derivatives[0][j] = ndu[j][p];
584        }
585        let mut a = vec![vec![0.0; p + 1]; 2];
586        for r in 0..=p {
587            let mut s1 = 0;
588            let mut s2 = 1;
589            a[0][0] = 1.0;
590            for k in 1..=n {
591                a[s2].fill(0.0);
592                let mut value = 0.0;
593                let rk = r as isize - k as isize;
594                let pk = p - k;
595                if r >= k {
596                    let denominator = ndu[pk + 1][rk as usize];
597                    a[s2][0] = a[s1][0] / denominator;
598                    value = a[s2][0] * ndu[rk as usize][pk];
599                }
600                let j1 = if rk >= -1 { 1 } else { (-rk) as usize };
601                let j2 = if r <= pk + 1 { k - 1 } else { p - r };
602                if j1 <= j2 {
603                    for j in j1..=j2 {
604                        let index = (rk + j as isize) as usize;
605                        a[s2][j] = (a[s1][j] - a[s1][j - 1]) / ndu[pk + 1][index];
606                        value += a[s2][j] * ndu[index][pk];
607                    }
608                }
609                if r <= pk {
610                    a[s2][k] = -a[s1][k - 1] / ndu[pk + 1][r];
611                    value += a[s2][k] * ndu[r][pk];
612                }
613                derivatives[k][r] = value;
614                std::mem::swap(&mut s1, &mut s2);
615            }
616        }
617        let mut factor = p as f64;
618        for (k, row) in derivatives.iter_mut().enumerate().take(n + 1).skip(1) {
619            for value in row {
620                *value *= factor;
621            }
622            factor *= (p - k) as f64;
623        }
624        derivatives
625    }
626}
627
628/// A rational B-spline curve.
629///
630/// **Invariant: an in-place edit of the public fields must keep the curve
631/// valid.** The curve caches that it passed validation (finite values,
632/// positive weights, a clamped knot vector with a positive domain), and
633/// `Clone` copies that flag; nothing re-checks a field edited in place. Prefer
634/// building a new value with [`NurbsCurve::new`].
635#[derive(Clone, Debug, Deserialize, Serialize)]
636pub struct NurbsCurve {
637    pub degree: usize,
638    pub knots: Vec<f64>,
639    pub control_points: Vec<Vec4>,
640    /// One-time validation cache. Deserialized curves (which bypass `new`)
641    /// run the full `new`-equivalent checks on first geometric use instead of
642    /// re-validating the knot vector on every evaluation.
643    #[serde(skip, default)]
644    validated: std::cell::Cell<bool>,
645}
646
647impl NurbsCurve {
648    /// Whether the one-time validation has run. For the boolean's
649    /// operand-state instrument (`BREP_DEBUG_OPERAND_STATE`).
650    pub fn is_validated(&self) -> bool {
651        self.validated.get()
652    }
653
654    /// Sets the validation cache: for the operand-state instrument only.
655    pub fn set_validated(&mut self, validated: bool) {
656        self.validated = std::cell::Cell::new(validated);
657    }
658
659    pub fn new(degree: usize, knots: Vec<f64>, control_points: Vec<Vec4>) -> Result<Self, String> {
660        let curve = Self {
661            degree,
662            knots,
663            control_points,
664            validated: std::cell::Cell::new(false),
665        };
666        curve.ensure_valid()?;
667        Ok(curve)
668    }
669
670    /// The full construction-time checks, run at most once per instance.
671    fn ensure_valid(&self) -> Result<(), String> {
672        if self.validated.get() {
673            return Ok(());
674        }
675        validate_knots(&self.knots, self.degree)?;
676        let expected = self.knots.len() - self.degree - 1;
677        if self.control_points.len() != expected {
678            return Err(format!(
679                "NurbsCurve: knot vector implies {} control points, got {}",
680                expected,
681                self.control_points.len()
682            ));
683        }
684        if self.control_points.iter().any(|point| {
685            point.w <= EPS
686                || ![point.x, point.y, point.z, point.w]
687                    .iter()
688                    .all(|value| value.is_finite())
689        }) {
690            return Err("NurbsCurve: control points must be finite with positive weights".into());
691        }
692        self.validated.set(true);
693        Ok(())
694    }
695
696    fn knot_vector(&self) -> Result<KnotVector, String> {
697        KnotVector::new(self.knots.clone(), self.degree)
698    }
699
700    pub fn domain(&self) -> Result<[f64; 2], String> {
701        self.ensure_valid()?;
702        Ok(knot_domain(&self.knots, self.degree))
703    }
704
705    #[cfg_attr(feature = "profile-wall", track_caller)]
706    pub fn evaluate_homogeneous(&self, parameter: f64) -> Result<Vec4, String> {
707        let _reader = crate::reader_profile::Point::open(crate::reader_profile::CURVE, std::panic::Location::caller());
708    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::POINT);
709        if crate::switch!("BREP_CURVE_POINT_FIXED", true) {
710            match self.degree {
711                1 => return self.evaluate_homogeneous_fixed::<1, 2>(parameter),
712                2 => return self.evaluate_homogeneous_fixed::<2, 3>(parameter),
713                3 => return self.evaluate_homogeneous_fixed::<3, 4>(parameter),
714                _ => {}
715            }
716        }
717        self.ensure_valid()?;
718        let span = knot_find_span(&self.knots, self.degree, parameter);
719        let parameter = knot_clamp(&self.knots, self.degree, parameter);
720        let mut point = Vec4 {
721            x: 0.0,
722            y: 0.0,
723            z: 0.0,
724            w: 0.0,
725        };
726        if self.degree <= MAX_STACK_DEGREE {
727            let mut basis = [0.0f64; MAX_STACK_ORDER];
728            basis_functions_into(&self.knots, self.degree, span, parameter, &mut basis);
729            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
730            for (index, value) in basis[..=self.degree].iter().enumerate() {
731                point = point.add(self.control_points[span - self.degree + index].scale(*value));
732            }
733        } else {
734            let knot_vector = self.knot_vector()?;
735            let basis = knot_vector.basis_functions(span, parameter);
736            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
737            for (index, value) in basis.iter().enumerate() {
738                point = point.add(self.control_points[span - self.degree + index].scale(*value));
739            }
740        }
741        Ok(point)
742    }
743
744    // Same Cox–de Boor recurrence and accumulation order as the general
745    // reader, with the common degrees and scratch widths known at compile time.
746    fn evaluate_homogeneous_fixed<const DEGREE: usize, const ORDER: usize>(&self, parameter: f64) -> Result<Vec4, String> {
747        self.ensure_valid()?;
748        let span = knot_find_span(&self.knots, DEGREE, parameter);
749        let parameter = knot_clamp(&self.knots, DEGREE, parameter);
750        let mut basis = [0.0f64; ORDER];
751        let mut left = [0.0f64; ORDER];
752        let mut right = [0.0f64; ORDER];
753        {
754            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::BASIS);
755            basis[0] = 1.0;
756            for j in 1..=DEGREE {
757                left[j] = parameter - self.knots[span + 1 - j];
758                right[j] = self.knots[span + j] - parameter;
759                let mut saved = 0.0;
760                for r in 0..j {
761                    let denominator = right[r + 1] + left[j - r];
762                    let temporary = if denominator.abs() <= EPS { 0.0 } else { basis[r] / denominator };
763                    basis[r] = saved + right[r + 1] * temporary;
764                    saved = left[j - r] * temporary;
765                }
766                basis[j] = saved;
767            }
768        }
769        let mut point = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
770        let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
771        for (index, value) in basis.iter().enumerate() {
772            point = point.add(self.control_points[span - DEGREE + index].scale(*value));
773        }
774        Ok(point)
775    }
776
777    #[cfg_attr(feature = "profile-wall", track_caller)]
778    pub fn evaluate(&self, parameter: f64) -> Result<Vec3, String> {
779        let _reader = crate::reader_profile::Point::open(crate::reader_profile::CURVE, std::panic::Location::caller());
780    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::POINT);
781        self.evaluate_homogeneous(parameter)?.point()
782    }
783
784    /// The straight segment this curve traces, as `(start, end)`, or `None`
785    /// when it genuinely bends.
786    ///
787    /// What a direct-edit heal actually needs to know about an edge is
788    /// *geometric* — "is this a straight segment I may rebuild between two
789    /// re-solved corners?" — but it used to be answered by the
790    /// *representation* `degree == 1 && control_points.len() == 2`. That
791    /// answer is wrong for a line that carries an interior knot, which is what
792    /// an offset shell or a boolean leaves behind when it splits a box edge and
793    /// rejoins the pieces: the same line, three control points, and every heal
794    /// that asked the representation question called it "curved".
795    ///
796    /// Weights are strictly positive (`ensure_valid`), so every point of the
797    /// curve is a convex combination of its control points and the curve is a
798    /// straight segment **iff** those control points are collinear — for any
799    /// degree, not just degree 1. Monotone projections onto the chord are
800    /// required too, so a polyline that doubles back along its own line (it
801    /// covers the segment but does not parameterise it) is not mistaken for
802    /// one.
803    pub fn straight_segment(&self, tolerance: f64) -> Option<(Vec3, Vec3)> {
804        self.ensure_valid().ok()?;
805        let points = self
806            .control_points
807            .iter()
808            .map(|point| point.point().ok())
809            .collect::<Option<Vec<Vec3>>>()?;
810        let start = *points.first()?;
811        let end = *points.last()?;
812        let chord = end.sub(start);
813        let length = chord.length();
814        if length <= tolerance {
815            return None;
816        }
817        let direction = chord.scale(1.0 / length);
818        let mut reached = 0.0f64;
819        for point in &points {
820            let offset = point.sub(start);
821            let axial = offset.dot(direction);
822            if offset.sub(direction.scale(axial)).length() > tolerance {
823                return None; // off the chord — the curve genuinely bends
824            }
825            if axial < reached - tolerance {
826                return None; // collinear, but the polygon doubles back
827            }
828            reached = reached.max(axial);
829        }
830        Some((start, end))
831    }
832
833    /// Value beyond the domain (Golovanov §2.15): every curve must answer
834    /// out-of-domain queries because intersection and projection
835    /// algorithms probe there.  Closed curves wrap the parameter
836    /// cyclically; open curves extend linearly along the end tangent.
837    #[cfg_attr(feature = "profile-wall", track_caller)]
838    pub fn evaluate_extended(&self, parameter: f64) -> Result<Vec3, String> {
839        let _reader = crate::reader_profile::Point::open(crate::reader_profile::CURVE, std::panic::Location::caller());
840    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::POINT);
841        Ok(self.derivatives_extended(parameter, 0)?[0])
842    }
843
844    /// Derivatives beyond the domain (§2.15).  The open-end extension is
845    /// linear: the first derivative is the boundary tangent and higher
846    /// derivatives vanish.
847    pub fn derivatives_extended(
848        &self,
849        parameter: f64,
850        derivative_count: usize,
851    ) -> Result<Vec<Vec3>, String> {
852        let [start, end] = self.domain()?;
853        if parameter >= start && parameter <= end {
854            return self.derivatives(parameter, derivative_count);
855        }
856        let period = end - start;
857        if period > 0.0 {
858            let closed =
859                self.evaluate(start)?.sub(self.evaluate(end)?).length() <= 1e-9 * (1.0 + period);
860            if closed {
861                let wrapped = start + (parameter - start).rem_euclid(period);
862                return self.derivatives(wrapped, derivative_count);
863            }
864        }
865        let boundary = if parameter < start { start } else { end };
866        let base = self.derivatives(boundary, derivative_count.max(1))?;
867        let mut result = Vec::with_capacity(derivative_count + 1);
868        result.push(base[0].add(base[1].scale(parameter - boundary)));
869        if derivative_count >= 1 {
870            result.push(base[1]);
871        }
872        for _ in 2..=derivative_count {
873            result.push(Vec3::default());
874        }
875        Ok(result)
876    }
877
878    pub fn derivatives(
879        &self,
880        parameter: f64,
881        derivative_count: usize,
882    ) -> Result<Vec<Vec3>, String> {
883        if derivative_count <= 2 && small_curve_derivatives_enabled() {
884            return Ok(self.derivatives_small(parameter, derivative_count)?[..=derivative_count].to_vec());
885        }
886        self.ensure_valid()?;
887        let parameter = knot_clamp(&self.knots, self.degree, parameter);
888        let span = knot_find_span(&self.knots, self.degree, parameter);
889        let calculated_count = derivative_count.min(self.degree);
890        let mut homogeneous: Vec<Vec4> = Vec::with_capacity(calculated_count + 1);
891        if self.degree <= MAX_STACK_DEGREE {
892            let mut rows = [[0.0f64; MAX_STACK_ORDER]; MAX_STACK_ORDER];
893            basis_derivatives_into(
894                &self.knots,
895                self.degree,
896                span,
897                parameter,
898                calculated_count,
899                &mut rows[..=calculated_count],
900            );
901            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
902            for row in rows.iter().take(calculated_count + 1) {
903                let mut point = Vec4 {
904                    x: 0.0,
905                    y: 0.0,
906                    z: 0.0,
907                    w: 0.0,
908                };
909                for (index, value) in row.iter().enumerate().take(self.degree + 1) {
910                    point =
911                        point.add(self.control_points[span - self.degree + index].scale(*value));
912                }
913                homogeneous.push(point);
914            }
915        } else {
916            let knot_vector = self.knot_vector()?;
917            let basis = knot_vector.basis_derivatives(span, parameter, calculated_count);
918            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
919            for row in basis.iter().take(calculated_count + 1) {
920                let mut point = Vec4 {
921                    x: 0.0,
922                    y: 0.0,
923                    z: 0.0,
924                    w: 0.0,
925                };
926                for (index, value) in row.iter().enumerate().take(self.degree + 1) {
927                    point =
928                        point.add(self.control_points[span - self.degree + index].scale(*value));
929                }
930                homogeneous.push(point);
931            }
932        }
933
934        let mut result: Vec<Vec3> = Vec::with_capacity(derivative_count + 1);
935        for k in 0..=calculated_count {
936            let mut value = Vec3::new(homogeneous[k].x, homogeneous[k].y, homogeneous[k].z);
937            for i in 1..=k {
938                value = value.sub(result[k - i].scale(binomial(k, i) * homogeneous[i].w));
939            }
940            result.push(value.scale(1.0 / homogeneous[0].w));
941        }
942        result.resize(derivative_count + 1, Vec3::default());
943        Ok(result)
944    }
945
946    /// The curve's unit TANGENT at `parameter`, read as the one-sided limit
947    /// when the first derivative vanishes there.
948    ///
949    /// This is what `derivatives(t, 1)?[1].normalized()?` should always have
950    /// been. That shape refuses on a curve class that is not exotic at all —
951    /// any Hermite segment whose end tangent is the zero vector, of which an
952    /// INVOLUTE flank is the standard source (speed `r_base * t`, so a profile
953    /// sampled from the base circle outwards carries an exactly zero tangent at
954    /// its start, one per flank per tooth). The direction of travel is still
955    /// defined there, as the limit from inside the range, and
956    /// [`Self::stationary_tangent_rescue`] reads it.
957    ///
958    /// Pass the range the CALLER owns — an edge's `[t0, t1]`, not the curve's
959    /// domain, where the two differ (an `EdgeRecord` keeps the whole curve and
960    /// records the sub-range it uses), so the probe never reads geometry
961    /// outside the caller's own span.
962    ///
963    /// The error names the parameter and the range it probed, because the only
964    /// curve that reaches it is stationary EVERYWHERE the range allows, and the
965    /// caller's own identifier is the half this function cannot supply.
966    ///
967    /// Escape hatch for tamper-verification: `BREP_CUSP_TANGENT_RESCUE=0`
968    /// restores the bare `normalized()` refusal, the same hatch the imprint
969    /// driver's seed loop carries.
970    pub fn unit_tangent(
971        &self,
972        parameter: f64,
973        range_start: f64,
974        range_end: f64,
975    ) -> Result<Vec3, String> {
976        let derivative = self.derivatives(parameter, 1)?[1];
977        self.tangent_or_one_sided_limit(derivative, parameter, range_start, range_end)
978    }
979
980    /// The point and unit tangent that `derivatives_extended(parameter, 1)`
981    /// reads, with the tangent taken as [`Self::unit_tangent`] takes it.
982    ///
983    /// The blend march reads its section plane — the point and the edge's
984    /// unit tangent — through the EXTENDED evaluation at every station,
985    /// overshoot stations past the edge's ends included, and `unit_tangent`
986    /// cannot stand in for that read: it evaluates `derivatives`, which CLAMPS
987    /// a parameter outside the domain, where `derivatives_extended` WRAPS it on
988    /// a closed curve. A closed rim's overshoot station would read a different
989    /// tangent. This is the same one evaluation the march always made, so a
990    /// non-zero derivative returns the vector `derivatives[1].normalized()`
991    /// returned, to the bit, at no extra cost.
992    ///
993    /// Where the derivative vanishes, the one-sided limit is read at the
994    /// parameter the extended evaluation actually took its derivative from —
995    /// the parameter itself inside the domain, the wrapped one on a closed
996    /// curve, the boundary past an open end, where the extension's direction
997    /// IS the boundary's one-sided limit. The caller's range is widened to
998    /// contain that parameter, because an overshoot station reads outside the
999    /// caller's span on purpose; the ladder still probes from the side the
1000    /// range lies on.
1001    pub fn point_and_unit_tangent_extended(
1002        &self,
1003        parameter: f64,
1004        range_start: f64,
1005        range_end: f64,
1006    ) -> Result<(Vec3, Vec3), String> {
1007        let derivatives = self.derivatives_extended(parameter, 1)?;
1008        if let Ok(tangent) = derivatives[1].normalized() {
1009            return Ok((derivatives[0], tangent));
1010        }
1011        let read_at = self.extended_read_parameter(parameter)?;
1012        let low = range_start.min(range_end).min(read_at);
1013        let high = range_start.max(range_end).max(read_at);
1014        let tangent = self.tangent_or_one_sided_limit(derivatives[1], read_at, low, high)?;
1015        Ok((derivatives[0], tangent))
1016    }
1017
1018    /// The in-domain parameter whose derivatives `derivatives_extended` reads
1019    /// for `parameter`: itself inside the domain, wrapped on a closed curve,
1020    /// the nearer boundary past an open end. Mirrors that function's three
1021    /// cases; only the zero-derivative lane of
1022    /// [`Self::point_and_unit_tangent_extended`] pays for it.
1023    fn extended_read_parameter(&self, parameter: f64) -> Result<f64, String> {
1024        let [start, end] = self.domain()?;
1025        if parameter >= start && parameter <= end {
1026            return Ok(parameter);
1027        }
1028        if self.extension_wraps(start, end)? {
1029            return Ok(start + (parameter - start).rem_euclid(end - start));
1030        }
1031        Ok(if parameter < start { start } else { end })
1032    }
1033
1034    /// `derivatives_extended`'s closed test: a curve whose ends meet WRAPS an
1035    /// out-of-domain parameter instead of extending it.
1036    fn extension_wraps(&self, start: f64, end: f64) -> Result<bool, String> {
1037        let period = end - start;
1038        Ok(period > 0.0
1039            && self.evaluate(start)?.sub(self.evaluate(end)?).length() <= 1e-9 * (1.0 + period))
1040    }
1041
1042    /// The open end `parameter` lies past, when the first derivative VANISHES
1043    /// there — the one case in which `derivatives_extended`'s point does not
1044    /// move with its parameter: past an open end it returns
1045    /// `P(end) + C'(end)·(t − end)`, which is `P(end)` for every `t` when
1046    /// `C'(end) = 0`. `None` inside the domain, on a closed curve (which wraps
1047    /// onto the real curve), and past an end whose derivative is regular.
1048    ///
1049    /// The zero test is [`Self::point_and_unit_tangent_extended`]'s own: the
1050    /// derivative has no unit vector. A caller that extends past such an end
1051    /// supplies the SPEED the parameterization does not; the direction is the
1052    /// one-sided limit that function already reads there.
1053    pub fn stationary_open_end(&self, parameter: f64) -> Result<Option<f64>, String> {
1054        let [start, end] = self.domain()?;
1055        if parameter >= start && parameter <= end {
1056            return Ok(None);
1057        }
1058        let boundary = if parameter < start { start } else { end };
1059        if self.derivatives(boundary, 1)?[1].normalized().is_ok()
1060            || self.extension_wraps(start, end)?
1061        {
1062            return Ok(None);
1063        }
1064        Ok(Some(boundary))
1065    }
1066
1067    /// `derivative`, normalized — or, where it vanishes, the one-sided limit
1068    /// from inside `[range_start, range_end]` at `parameter`, or the named
1069    /// refusal. The one failure lane [`Self::unit_tangent`] and
1070    /// [`Self::point_and_unit_tangent_extended`] share.
1071    fn tangent_or_one_sided_limit(
1072        &self,
1073        derivative: Vec3,
1074        parameter: f64,
1075        range_start: f64,
1076        range_end: f64,
1077    ) -> Result<Vec3, String> {
1078        let error = match derivative.normalized() {
1079            Ok(tangent) => return Ok(tangent),
1080            Err(error) => error,
1081        };
1082        if std::env::var("BREP_CUSP_TANGENT_RESCUE").as_deref() == Ok("0") {
1083            return Err(error);
1084        }
1085        self.stationary_tangent_rescue(parameter, range_start, range_end)
1086            .ok_or_else(|| {
1087                format!(
1088                    "curve tangent: the first derivative vanishes at t = {parameter} and \
1089                     everywhere in [{range_start}, {range_end}] the probe can reach, so this \
1090                     curve has no direction of travel to report"
1091                )
1092            })
1093    }
1094
1095    /// The unit tangent just inside `[range_start, range_end]`, for a
1096    /// `parameter` where the first derivative VANISHES.
1097    ///
1098    /// A curve can be stationary at a parameter where the curve itself is
1099    /// perfectly well behaved, and the direction of travel is then still
1100    /// defined as the one-sided limit. The standard case is a cubic Bezier
1101    /// whose first two control points coincide — the shape a Hermite segment
1102    /// takes when its end tangent is the zero vector — and an INVOLUTE is the
1103    /// standard source of one: the involute's speed is `r_base * t`, so a gear
1104    /// flank sampled from the base circle outwards starts with an exactly zero
1105    /// tangent and every tooth profile carries one per flank. The 2026-09-14
1106    /// herringbone report is that shape: a hit landing exactly on the cusp
1107    /// parameter made `derivatives(t, 1)[1].normalized()` fail and killed the
1108    /// whole union.
1109    ///
1110    /// The range bounds the probe — pass an edge's own `[t0, t1]` and the
1111    /// rescue never reads the curve outside the span the caller owns. The
1112    /// ladder walks OUTWARDS, and it starts at 1e-6 of the span rather than at
1113    /// the smallest representable step: the rescued direction is a ONE-SIDED
1114    /// limit, so a nearer probe truncates less, but the derivative at a
1115    /// stationary point is a CANCELLING sum that shrinks with the step while
1116    /// its rounding error does not — at 1e-9 of the span the involute cusp
1117    /// below reads its own limit direction only to 1e-6, worse than at 1e-6 of
1118    /// the span. Later rungs exist for a higher-order stationary point, whose
1119    /// derivative is still under the zero-length floor at the first. `None`
1120    /// means the curve is stationary everywhere the range allows, where no
1121    /// direction exists to report at all.
1122    pub fn stationary_tangent_rescue(
1123        &self,
1124        parameter: f64,
1125        range_start: f64,
1126        range_end: f64,
1127    ) -> Option<Vec3> {
1128        let low = range_start.min(range_end);
1129        let high = range_start.max(range_end);
1130        let span = high - low;
1131        if !(span > 0.0) {
1132            return None;
1133        }
1134        for scale in [1e-6, 1e-4, 1e-2, 1e-1] {
1135            let step = span * scale;
1136            for probe in [parameter + step, parameter - step] {
1137                if probe < low || probe > high {
1138                    continue;
1139                }
1140                if let Some(unit) = self
1141                    .derivatives(probe, 1)
1142                    .ok()
1143                    .and_then(|derivatives| derivatives[1].normalized().ok())
1144                {
1145                    return Some(unit);
1146                }
1147            }
1148        }
1149        None
1150    }
1151
1152    /// Allocation-free twin of [`Self::derivatives`] for the hot
1153    /// `derivative_count <= 2` path.
1154    ///
1155    /// Byte-for-byte faithful copy of the arithmetic in [`Self::derivatives`]:
1156    /// identical basis evaluation, identical summation order, and the identical
1157    /// rational de-homogenization recurrence. Only the storage differs — a
1158    /// fixed-size `[Vec4; 3]` / `[Vec3; 3]` on the stack instead of the heap
1159    /// `Vec`s. Entries beyond `derivative_count.min(degree)` stay
1160    /// `Vec3::default()`, exactly as the heap version's trailing `resize` leaves
1161    /// them.
1162    pub fn derivatives_small(
1163        &self,
1164        parameter: f64,
1165        derivative_count: usize,
1166    ) -> Result<[Vec3; 3], String> {
1167        debug_assert!(derivative_count <= 2);
1168        self.ensure_valid()?;
1169        let parameter = knot_clamp(&self.knots, self.degree, parameter);
1170        let span = knot_find_span(&self.knots, self.degree, parameter);
1171        let calculated_count = derivative_count.min(self.degree);
1172        let zero = Vec4 {
1173            x: 0.0,
1174            y: 0.0,
1175            z: 0.0,
1176            w: 0.0,
1177        };
1178        let mut homogeneous = [zero; 3];
1179        if self.degree <= MAX_STACK_DEGREE {
1180            // Rows `..=calculated_count` (at most three) are the only ones
1181            // written or read; the eight-row fill was pure cost.
1182            let mut rows = [[0.0f64; MAX_STACK_ORDER]; 3];
1183            basis_derivatives_into(
1184                &self.knots,
1185                self.degree,
1186                span,
1187                parameter,
1188                calculated_count,
1189                &mut rows[..=calculated_count],
1190            );
1191            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
1192            for (k, row) in rows.iter().take(calculated_count + 1).enumerate() {
1193                let mut point = zero;
1194                for (index, value) in row.iter().enumerate().take(self.degree + 1) {
1195                    point =
1196                        point.add(self.control_points[span - self.degree + index].scale(*value));
1197                }
1198                homogeneous[k] = point;
1199            }
1200        } else {
1201            let knot_vector = self.knot_vector()?;
1202            let basis = knot_vector.basis_derivatives(span, parameter, calculated_count);
1203            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
1204            for (k, row) in basis.iter().take(calculated_count + 1).enumerate() {
1205                let mut point = zero;
1206                for (index, value) in row.iter().enumerate().take(self.degree + 1) {
1207                    point =
1208                        point.add(self.control_points[span - self.degree + index].scale(*value));
1209                }
1210                homogeneous[k] = point;
1211            }
1212        }
1213
1214        let mut result = [Vec3::default(); 3];
1215        for k in 0..=calculated_count {
1216            let mut value = Vec3::new(homogeneous[k].x, homogeneous[k].y, homogeneous[k].z);
1217            for i in 1..=k {
1218                value = value.sub(result[k - i].scale(binomial(k, i) * homogeneous[i].w));
1219            }
1220            result[k] = value.scale(1.0 / homogeneous[0].w);
1221        }
1222        Ok(result)
1223    }
1224
1225    /// First derivative with the low degree and recurrence width fixed at
1226    /// compile time. Accumulation and rational conversion keep the ordinary
1227    /// reader's operation order.
1228    fn deriv1_fixed<const DEGREE: usize, const ORDER: usize>(&self, parameter: f64) -> Result<(Vec3, Vec3), String> {
1229        self.ensure_valid()?;
1230        let parameter = knot_clamp(&self.knots, DEGREE, parameter);
1231        let span = knot_find_span(&self.knots, DEGREE, parameter);
1232        let mut rows = [[0.0; MAX_STACK_ORDER]; 2];
1233        basis_derivatives_scratch::<ORDER, MAX_STACK_ORDER>(&self.knots, DEGREE, span, parameter, 1, &mut rows);
1234        let zero = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
1235        let mut homogeneous = [zero; 2];
1236        let reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
1237        for k in 0..2 {
1238            let mut point = zero;
1239            for index in 0..=DEGREE {
1240                point = point.add(self.control_points[span - DEGREE + index].scale(rows[k][index]));
1241            }
1242            homogeneous[k] = point;
1243        }
1244        drop(reader_part);
1245        let inverse = 1.0 / homogeneous[0].w;
1246        let point = Vec3::new(homogeneous[0].x, homogeneous[0].y, homogeneous[0].z).scale(inverse);
1247        let tangent = Vec3::new(homogeneous[1].x, homogeneous[1].y, homogeneous[1].z)
1248            .sub(point.scale(1.0 * homogeneous[1].w)).scale(inverse);
1249        Ok((point, tangent))
1250    }
1251
1252    /// Point and first derivative `(C, C')` with zero heap allocation.
1253    /// Bit-identical to `derivatives(t, 1)` at indices `[0]` and `[1]`.
1254    #[inline]
1255    pub fn deriv1(&self, parameter: f64) -> Result<(Vec3, Vec3), String> {
1256        if switch!("BREP_CURVE_DERIV1_FIXED", true) {
1257            match self.degree {
1258                1 => return self.deriv1_fixed::<1, 2>(parameter),
1259                2 => return self.deriv1_fixed::<2, 3>(parameter),
1260                3 => return self.deriv1_fixed::<3, 4>(parameter),
1261                _ => {}
1262            }
1263        }
1264        let d = self.derivatives_small(parameter, 1)?;
1265        Ok((d[0], d[1]))
1266    }
1267
1268    pub fn reversed(&self) -> Result<Self, String> {
1269        let start = self.knots[0];
1270        let end = self.knots[self.knots.len() - 1];
1271        let knots = self
1272            .knots
1273            .iter()
1274            .rev()
1275            .map(|knot| start + end - knot)
1276            .collect();
1277        let control_points = self.control_points.iter().rev().copied().collect();
1278        Self::new(self.degree, knots, control_points)
1279    }
1280
1281    pub fn insert_knot(&self, parameter: f64, requested: usize) -> Result<Self, String> {
1282        let knot_vector = self.knot_vector()?;
1283        let degree = self.degree;
1284        let parameter = knot_vector.clamp_param(parameter);
1285        // A parameter within knot tolerance of an existing knot must BE
1286        // that knot: counting it as a multiplicity while find_span places
1287        // it in the span below (parameter infinitesimally smaller) makes
1288        // the Boehm index bookkeeping inconsistent and corrupts the net.
1289        let parameter = self
1290            .knots
1291            .iter()
1292            .copied()
1293            .find(|knot| (knot - parameter).abs() <= KNOT_IDENTITY_TOL)
1294            .unwrap_or(parameter);
1295        let multiplicity = self
1296            .knots
1297            .iter()
1298            .filter(|knot| (**knot - parameter).abs() <= KNOT_IDENTITY_TOL)
1299            .count();
1300        let insertion_count = requested.min(degree.saturating_sub(multiplicity));
1301        if insertion_count == 0 {
1302            return Ok(self.clone());
1303        }
1304        let span = knot_vector.find_span(parameter);
1305        let last_control = self.control_points.len() - 1;
1306        let mut knots = Vec::with_capacity(self.knots.len() + insertion_count);
1307        knots.extend_from_slice(&self.knots[..=span]);
1308        knots.extend(std::iter::repeat_n(parameter, insertion_count));
1309        knots.extend_from_slice(&self.knots[span + 1..]);
1310
1311        let mut output = vec![
1312            Vec4 {
1313                x: 0.0,
1314                y: 0.0,
1315                z: 0.0,
1316                w: 1.0,
1317            };
1318            last_control + 1 + insertion_count
1319        ];
1320        output[..=span - degree].copy_from_slice(&self.control_points[..=span - degree]);
1321        for index in span - multiplicity..=last_control {
1322            output[index + insertion_count] = self.control_points[index];
1323        }
1324        let mut affected = vec![
1325            Vec4 {
1326                x: 0.0,
1327                y: 0.0,
1328                z: 0.0,
1329                w: 1.0,
1330            };
1331            degree + 1
1332        ];
1333        affected[..=degree - multiplicity]
1334            .copy_from_slice(&self.control_points[span - degree..=span - multiplicity]);
1335        let mut left = 0;
1336        for insertion in 1..=insertion_count {
1337            left = span - degree + insertion;
1338            for index in 0..=degree - insertion - multiplicity {
1339                let denominator = self.knots[index + span + 1] - self.knots[left + index];
1340                let alpha = (parameter - self.knots[left + index]) / denominator;
1341                affected[index] = affected[index + 1]
1342                    .scale(alpha)
1343                    .add(affected[index].scale(1.0 - alpha));
1344            }
1345            output[left] = affected[0];
1346            output[span + insertion_count - insertion - multiplicity] =
1347                affected[degree - insertion - multiplicity];
1348        }
1349        for index in left + 1..span - multiplicity {
1350            output[index] = affected[index - left];
1351        }
1352        Self::new(degree, knots, output)
1353    }
1354
1355    pub fn split(&self, parameter: f64) -> Result<(Self, Self), String> {
1356        let [start, end] = self.domain()?;
1357        if parameter <= start + KNOT_IDENTITY_TOL || parameter >= end - KNOT_IDENTITY_TOL {
1358            return Err(format!(
1359                "NurbsCurve.split: parameter {parameter} must be strictly inside domain [{start}, {end}]"
1360            ));
1361        }
1362        // Snap onto a coincident knot so multiplicity and span agree (see
1363        // insert_knot).
1364        let parameter = self
1365            .knots
1366            .iter()
1367            .copied()
1368            .find(|knot| (knot - parameter).abs() <= KNOT_IDENTITY_TOL)
1369            .unwrap_or(parameter);
1370        let multiplicity = self
1371            .knots
1372            .iter()
1373            .filter(|knot| (**knot - parameter).abs() <= KNOT_IDENTITY_TOL)
1374            .count();
1375        let refined = self.insert_knot(parameter, self.degree.saturating_sub(multiplicity))?;
1376        let first = refined
1377            .knots
1378            .iter()
1379            .position(|knot| (*knot - parameter).abs() <= KNOT_IDENTITY_TOL)
1380            .ok_or_else(|| "NurbsCurve.split: inserted knot not found".to_string())?;
1381        let mut left_knots = refined.knots[..first + self.degree].to_vec();
1382        left_knots.push(parameter);
1383        let left_points = refined.control_points[..first].to_vec();
1384        let mut right_knots = vec![parameter; self.degree + 1];
1385        right_knots.extend_from_slice(&refined.knots[first + self.degree..]);
1386        let right_points = refined.control_points[first - 1..].to_vec();
1387        Ok((
1388            Self::new(self.degree, left_knots, left_points)?,
1389            Self::new(self.degree, right_knots, right_points)?,
1390        ))
1391    }
1392}
1393
1394pub fn make_line(start: Vec3, end: Vec3) -> Result<NurbsCurve, String> {
1395    NurbsCurve::new(
1396        1,
1397        vec![0.0, 0.0, 1.0, 1.0],
1398        vec![Vec4::from_point(start, 1.0), Vec4::from_point(end, 1.0)],
1399    )
1400}
1401
1402pub fn make_arc(
1403    center: Vec3,
1404    x_axis: Vec3,
1405    y_axis: Vec3,
1406    radius: f64,
1407    start_angle: f64,
1408    end_angle: f64,
1409) -> Result<NurbsCurve, String> {
1410    if radius <= EPS {
1411        return Err("makeArc: radius must be positive".into());
1412    }
1413    let x_axis = x_axis.normalized()?;
1414    let y_axis = y_axis.normalized()?;
1415    if x_axis.dot(y_axis).abs() > 1e-9 {
1416        return Err("makeArc: xAxis and yAxis must be orthogonal".into());
1417    }
1418    let mut theta = end_angle - start_angle;
1419    if theta <= EPS {
1420        return Err("makeArc: endAngle must exceed startAngle".into());
1421    }
1422    if theta > std::f64::consts::TAU + EPS {
1423        return Err("makeArc: sweep exceeds full circle".into());
1424    }
1425    theta = theta.min(std::f64::consts::TAU);
1426    let segment_count = ((theta / std::f64::consts::FRAC_PI_2 - EPS).ceil() as usize).clamp(1, 4);
1427    let segment_angle = theta / segment_count as f64;
1428    let middle_weight = (segment_angle / 2.0).cos();
1429    let point_at = |angle: f64| {
1430        center
1431            .add(x_axis.scale(radius * angle.cos()))
1432            .add(y_axis.scale(radius * angle.sin()))
1433    };
1434    let tangent_at = |angle: f64| x_axis.scale(-angle.sin()).add(y_axis.scale(angle.cos()));
1435
1436    let mut points = Vec::with_capacity(2 * segment_count + 1);
1437    let mut angle = start_angle;
1438    let mut first_point = point_at(angle);
1439    let mut first_tangent = tangent_at(angle);
1440    points.push(Vec4::from_point(first_point, 1.0));
1441    for _ in 0..segment_count {
1442        angle += segment_angle;
1443        let end_point = point_at(angle);
1444        let end_tangent = tangent_at(angle);
1445        let cross = first_tangent.cross(end_tangent);
1446        let denominator = cross.length_squared();
1447        if denominator <= EPS {
1448            return Err("makeArc: arc tangents are parallel".into());
1449        }
1450        let distance = end_point.sub(first_point).cross(end_tangent).dot(cross) / denominator;
1451        let middle = first_point.add(first_tangent.scale(distance));
1452        points.push(Vec4::from_point(middle, middle_weight));
1453        points.push(Vec4::from_point(end_point, 1.0));
1454        first_point = end_point;
1455        first_tangent = end_tangent;
1456    }
1457    let mut knots = vec![0.0, 0.0, 0.0];
1458    for index in 1..segment_count {
1459        let knot = index as f64 / segment_count as f64;
1460        knots.extend([knot, knot]);
1461    }
1462    knots.extend([1.0, 1.0, 1.0]);
1463    NurbsCurve::new(2, knots, points)
1464}
1465
1466pub fn make_circle(center: Vec3, normal: Vec3, radius: f64) -> Result<NurbsCurve, String> {
1467    let normal = normal.normalized()?;
1468    let x_axis = normal.perpendicular()?;
1469    let y_axis = normal.cross(x_axis).normalized()?;
1470    make_arc(center, x_axis, y_axis, radius, 0.0, std::f64::consts::TAU)
1471}
1472
1473/// Build the exactly orthonormal local frame shared by the conic
1474/// constructors.  The conic algebra below (implicit equation, tangent
1475/// intersection, shoulder weight) is only exact in an orthonormal frame, so
1476/// the in-plane hint is Gram-Schmidt-projected against the primary direction
1477/// instead of trusted verbatim: callers only owe us non-parallel vectors.
1478fn conic_frame(fn_name: &str, primary: Vec3, hint: Vec3) -> Result<(Vec3, Vec3), String> {
1479    let x_axis = primary
1480        .normalized()
1481        .map_err(|_| format!("{fn_name}: primary axis must be non-zero"))?;
1482    if hint.length() <= EPS {
1483        return Err(format!("{fn_name}: in-plane direction must be non-zero"));
1484    }
1485    hint.sub(x_axis.scale(hint.dot(x_axis)))
1486        .normalized()
1487        .map(|y_axis| (x_axis, y_axis))
1488        .map_err(|_| format!("{fn_name}: frame directions must not be parallel"))
1489}
1490
1491/// Trim-range validation shared by the conic constructors.  The knot span IS
1492/// the conic parameter range, so it must clear the knot identity band or the
1493/// resulting curve would fail knot validation with an unhelpful message.
1494fn conic_range(fn_name: &str, t0: f64, t1: f64) -> Result<(), String> {
1495    if !t0.is_finite() || !t1.is_finite() {
1496        return Err(format!("{fn_name}: parameter range must be finite"));
1497    }
1498    if t1 - t0 <= KNOT_IDENTITY_TOL {
1499        return Err(format!("{fn_name}: t1 ({t1}) must exceed t0 ({t0})"));
1500    }
1501    Ok(())
1502}
1503
1504/// Extreme trim parameters overflow the conic point formulas (cosh exceeds
1505/// f64 near |t| ~ 710, focal·t² near |t| ~ 1e150); surface that as the
1506/// constructor's own honest error instead of the generic NurbsCurve
1507/// finiteness rejection.
1508fn conic_points_finite(fn_name: &str, points: &[Vec4]) -> Result<(), String> {
1509    if points.iter().any(|point| {
1510        ![point.x, point.y, point.z, point.w]
1511            .iter()
1512            .all(|value| value.is_finite())
1513    }) {
1514        return Err(format!(
1515            "{fn_name}: control points overflow f64 — parameter range too extreme"
1516        ));
1517    }
1518    Ok(())
1519}
1520
1521/// Exact parabola segment y² = 4·focal·x in the local frame (vertex at the
1522/// origin, `axis` = +x, `latus_direction` = +y), parametrized the standard
1523/// way P(t) = (focal·t², 2·focal·t) and trimmed to t ∈ [t0, t1].  A parabola
1524/// segment is a plain quadratic polynomial in t (all weights 1), so a single
1525/// degree-2 Bézier over the knot span [t0, t1] reproduces both the point set
1526/// AND the parametrization exactly — no fitting, and evaluate(t) == P(t) for
1527/// every t, not just at the ends.
1528pub fn make_parabola(
1529    vertex: Vec3,
1530    axis: Vec3,
1531    latus_direction: Vec3,
1532    focal: f64,
1533    t0: f64,
1534    t1: f64,
1535) -> Result<NurbsCurve, String> {
1536    if !focal.is_finite() || focal <= EPS {
1537        return Err("make_parabola: focal distance must be positive".into());
1538    }
1539    conic_range("make_parabola", t0, t1)?;
1540    let (x_axis, y_axis) = conic_frame("make_parabola", axis, latus_direction)?;
1541    let point_at = |t: f64| {
1542        vertex
1543            .add(x_axis.scale(focal * t * t))
1544            .add(y_axis.scale(2.0 * focal * t))
1545    };
1546    // Bernstein middle point of the quadratic polynomial,
1547    // P(t0) + (t1−t0)/2·P'(t0), collapses to local (focal·t0·t1,
1548    // focal·(t0+t1)) — which is also the intersection of the two end
1549    // tangents, as it must be for any parabola segment.
1550    let middle = vertex
1551        .add(x_axis.scale(focal * t0 * t1))
1552        .add(y_axis.scale(focal * (t0 + t1)));
1553    let control_points = vec![
1554        Vec4::from_point(point_at(t0), 1.0),
1555        Vec4::from_point(middle, 1.0),
1556        Vec4::from_point(point_at(t1), 1.0),
1557    ];
1558    conic_points_finite("make_parabola", &control_points)?;
1559    NurbsCurve::new(2, vec![t0, t0, t0, t1, t1, t1], control_points)
1560}
1561
1562/// Exact arc of the hyperbola branch x²/a² − y²/b² = 1, x > 0 in the local
1563/// frame (center at the origin, `major_axis` = +x, `minor_axis` = +y),
1564/// parametrized P(t) = (a·cosh t, b·sinh t) and trimmed to t ∈ [t0, t1].
1565/// A single rational quadratic Bézier is exact for any sweep on one branch:
1566/// endpoints on the curve, middle control point at the intersection of the
1567/// end tangents, and middle weight cosh((t1−t0)/2) chosen so the shoulder
1568/// point lands back on the branch.  Only the point set is hyperbola-exact
1569/// away from the ends; the NURBS parameter coincides with the hyperbolic
1570/// parameter t exactly at t0, (t0+t1)/2 and t1.
1571pub fn make_hyperbola(
1572    center: Vec3,
1573    major_axis: Vec3,
1574    minor_axis: Vec3,
1575    a: f64,
1576    b: f64,
1577    t0: f64,
1578    t1: f64,
1579) -> Result<NurbsCurve, String> {
1580    if !a.is_finite() || a <= EPS {
1581        return Err("make_hyperbola: semi-axis a must be positive".into());
1582    }
1583    if !b.is_finite() || b <= EPS {
1584        return Err("make_hyperbola: semi-axis b must be positive".into());
1585    }
1586    conic_range("make_hyperbola", t0, t1)?;
1587    let (x_axis, y_axis) = conic_frame("make_hyperbola", major_axis, minor_axis)?;
1588    let point_at = |t: f64| {
1589        center
1590            .add(x_axis.scale(a * t.cosh()))
1591            .add(y_axis.scale(b * t.sinh()))
1592    };
1593    let mid = 0.5 * (t0 + t1);
1594    let middle_weight = (0.5 * (t1 - t0)).cosh();
1595    // In the scaled frame (x/a, y/b) the branch is the unit hyperbola and the
1596    // tangent at t is the line X·cosh t − Y·sinh t = 1; Cramer's rule on the
1597    // two end-tangent lines collapses their intersection to
1598    // P(mid)/cosh(half-sweep), so no explicit line-line solve is needed.
1599    // With this middle point, weight cosh(half-sweep) puts the shoulder point
1600    // (P0 + 2w·P1 + P2)/(2 + 2w) back on the branch at P(mid).
1601    let apex = center
1602        .add(x_axis.scale(a * mid.cosh() / middle_weight))
1603        .add(y_axis.scale(b * mid.sinh() / middle_weight));
1604    let control_points = vec![
1605        Vec4::from_point(point_at(t0), 1.0),
1606        Vec4::from_point(apex, middle_weight),
1607        Vec4::from_point(point_at(t1), 1.0),
1608    ];
1609    conic_points_finite("make_hyperbola", &control_points)?;
1610    NurbsCurve::new(2, vec![t0, t0, t0, t1, t1, t1], control_points)
1611}
1612
1613pub fn uniform_clamped_knots(
1614    control_point_count: usize,
1615    degree: usize,
1616) -> Result<Vec<f64>, String> {
1617    if control_point_count == 0 || control_point_count - 1 < degree {
1618        return Err("uniformClampedKnots: need at least degree+1 control points".into());
1619    }
1620    let n = control_point_count - 1;
1621    let mut knots = vec![0.0; degree + 1];
1622    let interior = n - degree;
1623    for index in 1..=interior {
1624        knots.push(index as f64 / (interior + 1) as f64);
1625    }
1626    knots.extend(std::iter::repeat_n(1.0, degree + 1));
1627    Ok(knots)
1628}
1629
1630fn binomial(n: usize, k: usize) -> f64 {
1631    if k > n {
1632        return 0.0;
1633    }
1634    let k = k.min(n - k);
1635    (1..=k).fold(1.0, |value, index| {
1636        value * (n - k + index) as f64 / index as f64
1637    })
1638}
1639
1640
1641
1642
1643/// SMALL CURVE DERIVATIVES (lane O row 21, 2026-10-29; on by default since
1644/// the batch 5 promotion, `BREP_CURVE_SMALL_DERIVATIVES=0` reads the heap): `NurbsCurve::derivatives`
1645/// up to second order is read from the stack twin
1646/// [`NurbsCurve::derivatives_small`] (one allocation for the result instead of
1647/// two), and the hot callers — point-in-face's nearest-curve refinement, the
1648/// imprint's parameter tolerance and its pierce tangents — read the twin
1649/// directly. Same arithmetic, same bits.
1650pub fn small_curve_derivatives_enabled() -> bool {
1651    switch!("BREP_CURVE_SMALL_DERIVATIVES", true)
1652}
1653
1654
1655
1656/// Piegl–Tiller A5.6 with caller-selected homogeneous arithmetic.
1657pub fn bezier_decompose_raw<T: Copy>(knots: &[f64], points: &[T], degree: usize, zero: T, blend: impl Fn(T, T, f64) -> T) -> Option<Vec<Vec<T>>> {
1658    let p = degree;
1659    let n = points.len();
1660    if p == 0 || n < p + 1 || knots.len() != n + p + 1 || knots.iter().any(|k| !k.is_finite()) || knots.windows(2).any(|w| w[1] < w[0]) {
1661        return None;
1662    }
1663    let (a, b) = (knots[0], knots[knots.len() - 1]);
1664    if !(b > a) || knots[..=p].iter().any(|k| *k != a) || knots[knots.len() - p - 1..].iter().any(|k| *k != b) {
1665        return None;
1666    }
1667    let m = knots.len() - 1;
1668    let (mut a, mut b) = (p, p + 1);
1669    let mut spans = Vec::with_capacity(n);
1670    let mut span: Vec<T> = points[..=p].to_vec();
1671    let mut alphas = vec![0.; p];
1672    while b < m {
1673        let first = b;
1674        while b < m && knots[b + 1] == knots[b] {
1675            b += 1;
1676        }
1677        let mult = b - first + 1;
1678        if b < m && mult > p {
1679            return None;
1680        }
1681        let mut next = vec![zero; p + 1];
1682        if mult < p {
1683            let numer = knots[b] - knots[a];
1684            for j in (mult + 1..=p).rev() {
1685                alphas[j - mult - 1] = numer / (knots[a + j] - knots[a]);
1686            }
1687            let r = p - mult;
1688            for j in 1..=r {
1689                let s = mult + j;
1690                for k in (s..=p).rev() {
1691                    let alpha = alphas[k - s];
1692                    span[k] = blend(span[k], span[k - 1], alpha);
1693                }
1694                if b < m {
1695                    next[r - j] = span[p];
1696                }
1697            }
1698        }
1699        spans.push(span);
1700        if b >= m {
1701            break;
1702        }
1703        for i in p - mult..=p {
1704            next[i] = points[b - p + i];
1705        }
1706        span = next;
1707        a = b;
1708        b += 1;
1709    }
1710    Some(spans)
1711}
1712
1713/// One raw Boehm insertion. Span selection and the denominator policy belong
1714/// to the caller, as does the interpolation expression's operand order.
1715pub fn boehm_insert_raw<T: Copy>(
1716    points: &[T], knots: &[f64], degree: usize, parameter: f64, span: usize,
1717    blend: impl Fn(T, T, f64, f64) -> T,
1718) -> (Vec<T>, Vec<f64>) {
1719    let mut out = Vec::with_capacity(points.len() + 1);
1720    out.extend_from_slice(&points[..=span - degree]);
1721    for i in span - degree + 1..=span {
1722        out.push(blend(points[i - 1], points[i], parameter - knots[i], knots[i + degree] - knots[i]));
1723    }
1724    out.extend_from_slice(&points[span..]);
1725    let mut fresh_knots = knots.to_vec();
1726    fresh_knots.insert(span + 1, parameter);
1727    (out, fresh_knots)
1728}
1729
1730
1731/// Heap basis for raw/unclamped knots or degrees beyond the stack specialization.
1732pub fn basis_functions_raw(knots: &[f64], degree: usize, span: usize, parameter: f64, guard: f64) -> Vec<f64> {
1733    let mut basis = vec![0.0; degree + 1];
1734    let mut left = vec![0.0; degree + 1];
1735    let mut right = vec![0.0; degree + 1];
1736    basis_functions_raw_into(knots, degree, span, parameter, guard, &mut basis, &mut left, &mut right);
1737    basis
1738}
1739
1740#[inline(always)]
1741pub fn basis_functions_raw_into(knots: &[f64], degree: usize, span: usize, parameter: f64,
1742    guard: f64, basis: &mut [f64], left: &mut [f64], right: &mut [f64]) {
1743        let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::BASIS);
1744    basis[0] = 1.0;
1745    for j in 1..=degree {
1746        left[j] = parameter - knots[span + 1 - j];
1747        right[j] = knots[span + j] - parameter;
1748        let mut saved = 0.0;
1749        for r in 0..j {
1750            let denominator = right[r + 1] + left[j - r];
1751            let temporary = if denominator.abs() <= guard {
1752                0.0
1753            } else {
1754                basis[r] / denominator
1755            };
1756            basis[r] = saved + right[r + 1] * temporary;
1757            saved = left[j - r] * temporary;
1758        }
1759        basis[j] = saved;
1760    }
1761}