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