Skip to main content

brep_kernel/geometry/
curve.rs

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