Skip to main content

brep_geometry/geometry/
surface.rs

1use crate::curve::{
2    basis_derivatives_wide as basis_derivatives_into, basis_functions_wide as basis_functions_into,
3    knot_clamp, knot_domain, knot_find_span,
4    validate_knots, EVALUATOR_STACK_DEGREE as MAX_STACK_DEGREE,
5    EVALUATOR_STACK_ORDER as MAX_STACK_ORDER,
6};
7pub use crate::{KnotVector, NurbsCurve, Vec3, Vec4};
8use serde::{Deserialize, Serialize};
9
10#[path = "surface/extension.rs"]
11mod extension;
12#[path = "surface/trim_partials.rs"]
13mod trim_partials;
14#[path = "surface/refine.rs"]
15mod refine;
16pub use refine::{KnotDirection, KnotRefinementRefusal};
17pub use trim_partials::PreparedTrimPartials;
18pub use extension::{
19    ExtendRefusal, SurfaceSide, WeightSite, MAXIMUM_FOLD_ANGLE, MAXIMUM_GROWTH_RATIO,
20};
21
22const EPS: f64 = crate::tolerance::FP_FLOOR;
23/// A generatrix control point that is neither ON the axis of revolution nor
24/// this fraction of the generatrix's own radial extent clear of it is a fuzzy
25/// pole, and `make_revolution` refuses it (see the comment at the check).
26const NEAR_AXIS_RELATIVE_TOLERANCE: f64 = 1e-4;
27
28/// The widest tensor block [`NurbsSurface::deriv1_tensor_each`] will evaluate,
29/// per direction. The mass integrator reads a RATIONAL patch's cell at up to
30/// this many stations; `props::mass_properties::rule::MAX_ORDER` is DEFINED as
31/// this constant rather than repeating its value, because the block's arrays
32/// here and the station arrays there must agree and a drift between them is a
33/// hard failure, not a slow path (the callers propagate the refusal below
34/// rather than falling back). 8 was the fixed rule's own width; the arrays are
35/// stack-resident either way.
36pub const TENSOR_MAX_BLOCK: usize = 24;
37
38/// `BREP_SURFACE_TENSOR_FUSED` (default on): [`NurbsSurface::deriv1_tensor_each`]
39/// runs a patch of degrees 1 to 3 in each direction through its
40/// constant-degree loop, the same bits; `=0` keeps the run-time-degree loop,
41/// for a same-binary A/B.
42fn tensor_fused_on() -> bool {
43    switch!("BREP_SURFACE_TENSOR_FUSED", true)
44}
45
46/// A rational B-spline surface.
47///
48/// **Invariant: do not mutate the public fields after the surface has been
49/// evaluated.** The surface memoizes derived data (its analytic carrier, seam
50/// closure, projection grids, validation) the first time it is asked, and
51/// `Clone` copies those caches. Editing `control_points`, `knots_*` or a degree
52/// in place afterwards leaves every later query answering for the OLD
53/// geometry. Build a new value with [`NurbsSurface::new`] instead (lane K2
54/// audit 2026-10-16: no production path does this today; a test fixture did).
55#[derive(Clone, Debug, Deserialize, Serialize)]
56pub struct NurbsSurface {
57    pub degree_u: usize,
58    pub degree_v: usize,
59    pub knots_u: Vec<f64>,
60    pub knots_v: Vec<f64>,
61    pub control_points: Vec<Vec<Vec4>>,
62    /// Lazily recognized analytic carrier (plane/cylinder/cone/sphere/torus).
63    /// Purely an acceleration cache: never serialized, cloned with the
64    /// surface, and recomputed on demand after deserialization.
65    #[serde(skip, default)]
66    pub analytic: std::cell::OnceCell<Option<crate::AnalyticSurface>>,
67    /// Translation structure, queried independently of the classic analytic
68    /// enum so adding this carrier does not break exhaustive API matches.
69    #[serde(skip, default)]
70    linear_extrusion: std::cell::OnceCell<Option<crate::analytic_surface::ExtrusionStructure>>,
71    /// The extrusion's profile reduced across its direction, with its seed samples
72    /// (`BREP_EXTRUSION_HELD_PROFILE`); built from `linear_extrusion` on first use.
73    #[serde(skip, default)]
74    extrusion_profile: std::cell::OnceCell<Option<crate::analytic_surface::ReducedProfile>>,
75    /// A general revolution's generatrix with its seed samples, when it lies on
76    /// a meridional half-plane (`BREP_REVOLUTION_HELD_GENERATRIX`); built from
77    /// `analytic` on first use.
78    #[serde(skip, default)]
79    revolution_generatrix: std::cell::OnceCell<Option<crate::projection::HeldCurve>>,
80    /// Lazily recognized affine sphere (`geometry/affine_sphere.rs`), read
81    /// only under `BREP_AFFINE_SPHERE` and only when no analytic carrier was
82    /// recognized; an acceleration cache like `analytic`.
83    #[serde(skip, default)]
84    affine_sphere: std::cell::OnceCell<Option<crate::affine_sphere::AffineSphere>>,
85    /// One-time validation cache (see `NurbsCurve::ensure_valid`).
86    #[serde(skip, default)]
87    validated: std::cell::Cell<bool>,
88    /// Cached (closed_u, closed_v) seam test — a pure function of the
89    /// immutable geometry, recomputed on demand after deserialization.
90    #[serde(skip, default)]
91    closed_directions: std::cell::OnceCell<(bool, bool)>,
92    /// Cached Newton seed grid for general point projection (see
93    /// `projection.rs`) — (u, v, point) samples over the knot spans.
94    #[serde(skip, default)]
95    pub projection_grid: std::cell::OnceCell<crate::projection::SampleGrid>,
96    /// Cached dense fallback grid for degenerate general projection
97    /// (`projection.rs`) — (u, v, point) samples at fixed per-surface
98    /// parameters, so the ~1.7M-call metre-mm fallback reuses the evals.
99    #[serde(skip, default)]
100    pub projection_dense_grid: std::cell::OnceCell<crate::projection::SampleGrid>,
101    /// Cached boundary-ring sample points for the degenerate projection
102    /// fallback (`projection.rs`), flattened as 4 sides × 22 exponents ×
103    /// 33 indices of evaluated surface points at fixed per-surface params.
104    #[serde(skip, default)]
105    pub projection_ring_grid: std::cell::OnceCell<Vec<Vec3>>,
106    /// Cached convex-hull enclosure of every projection lattice cell
107    /// (`projection.rs`'s global stage), built on the first query the local
108    /// answer does not already settle. `None` when the net cannot be refined.
109    #[serde(skip, default)]
110    pub projection_cells: std::cell::OnceCell<Option<crate::projection::ProjectionCells>>,
111    /// Cached Bézier patches and their hull boxes for the curve-clear proof
112    /// (`intersect/curve_clear.rs`), built on its first query of this surface.
113    #[serde(skip, default)]
114    pub(crate) bezier_patches: std::cell::OnceCell<Option<std::sync::Arc<crate::curve_clear::SurfacePatches>>>,
115    /// Cached content hash of the net (degrees, knots, weighted controls),
116    /// the surface's part of the projection memo's key
117    /// (`projection.rs`, `BREP_SURFACE_PROJECTION_MEMO`).
118    #[serde(skip, default)]
119    content_key: std::cell::OnceCell<[u64; 2]>,
120}
121
122impl NurbsSurface {
123    /// The net's content hash ([`crate::identity_hash::hash_surface`]),
124    /// computed once per value and carried by its clones.
125    pub fn content_key(&self) -> [u64; 2] {
126        *self.content_key.get_or_init(|| {
127            let mut lane = crate::identity_hash::TwoLane::new();
128            crate::identity_hash::hash_surface(&mut lane, self);
129            lane.finish()
130        })
131    }
132
133    pub fn new(
134        degree_u: usize,
135        degree_v: usize,
136        knots_u: Vec<f64>,
137        knots_v: Vec<f64>,
138        control_points: Vec<Vec<Vec4>>,
139    ) -> Result<Self, String> {
140        let surface = Self {
141            degree_u,
142            degree_v,
143            knots_u,
144            knots_v,
145            control_points,
146            analytic: std::cell::OnceCell::new(),
147            linear_extrusion: std::cell::OnceCell::new(),
148            extrusion_profile: std::cell::OnceCell::new(),
149            revolution_generatrix: std::cell::OnceCell::new(),
150            affine_sphere: std::cell::OnceCell::new(),
151            validated: std::cell::Cell::new(false),
152            closed_directions: std::cell::OnceCell::new(),
153            projection_grid: std::cell::OnceCell::new(),
154            projection_dense_grid: std::cell::OnceCell::new(),
155            projection_ring_grid: std::cell::OnceCell::new(),
156            projection_cells: std::cell::OnceCell::new(),
157            bezier_patches: std::cell::OnceCell::new(),
158            content_key: std::cell::OnceCell::new(),
159        };
160        surface.ensure_valid()?;
161        Ok(surface)
162    }
163
164    /// Whether the surface joins itself along u (first) and v (second):
165    /// opposite domain edges coincide at three sampled fractions. The 1e-6
166    /// threshold matches the historical `LINEAR_TOLERANCE * 10` used by the
167    /// projection and curve×surface intersection modules.
168    pub fn closed_directions(&self) -> Result<(bool, bool), String> {
169        if let Some(&cached) = self.closed_directions.get() {
170            return Ok(cached);
171        }
172        const CLOSED_SEAM_TOLERANCE: f64 = 1e-6;
173        let [u0, u1] = self.domain_u()?;
174        let [v0, v1] = self.domain_v()?;
175        let closed_along = |direction_u: bool| -> Result<bool, String> {
176            // A direction whose two boundary rows coincide is closed only if
177            // the surface TRAVELS between them: a sliver patch narrower than
178            // the seam tolerance (a 7.24e-7-wide plane our own STL→STEP writer
179            // emits for a degenerate facet, 2026-09-26) has coincident rows
180            // too, and reading it as periodic wraps its far edge onto its near
181            // one — `evaluate_extended` then images a trim on that edge a
182            // whole patch width away.
183            let mut travels = false;
184            for fraction in [0.17, 0.5, 0.83] {
185                let (a, b, middle) = if direction_u {
186                    let v = v0 + (v1 - v0) * fraction;
187                    (
188                        self.evaluate(u0, v)?,
189                        self.evaluate(u1, v)?,
190                        self.evaluate(0.5 * (u0 + u1), v)?,
191                    )
192                } else {
193                    let u = u0 + (u1 - u0) * fraction;
194                    (
195                        self.evaluate(u, v0)?,
196                        self.evaluate(u, v1)?,
197                        self.evaluate(u, 0.5 * (v0 + v1))?,
198                    )
199                };
200                if a.sub(b).length() > CLOSED_SEAM_TOLERANCE {
201                    return Ok(false);
202                }
203                if middle.sub(a).length() > CLOSED_SEAM_TOLERANCE {
204                    travels = true;
205                }
206            }
207            Ok(travels)
208        };
209        let value = (closed_along(true)?, closed_along(false)?);
210        Ok(*self.closed_directions.get_or_init(|| value))
211    }
212
213    /// The full construction-time checks, run at most once per instance.
214    fn ensure_valid(&self) -> Result<(), String> {
215        if self.validated.get() {
216            return Ok(());
217        }
218        validate_knots(&self.knots_u, self.degree_u)?;
219        validate_knots(&self.knots_v, self.degree_v)?;
220        let rows = self.knots_u.len() - self.degree_u - 1;
221        let columns = self.knots_v.len() - self.degree_v - 1;
222        if self.control_points.len() != rows {
223            return Err(format!(
224                "NurbsSurface: u knot vector implies {} rows, got {}",
225                rows,
226                self.control_points.len()
227            ));
228        }
229        for row in &self.control_points {
230            if row.len() != columns {
231                return Err(format!(
232                    "NurbsSurface: v knot vector implies {} columns, got {}",
233                    columns,
234                    row.len()
235                ));
236            }
237            if row.iter().any(|point| {
238                point.w <= EPS
239                    || ![point.x, point.y, point.z, point.w]
240                        .iter()
241                        .all(|value| value.is_finite())
242            }) {
243                return Err(
244                    "NurbsSurface: control points must be finite with positive weights".into(),
245                );
246            }
247        }
248        self.validated.set(true);
249        Ok(())
250    }
251
252    pub fn domain_u(&self) -> Result<[f64; 2], String> {
253        self.ensure_valid()?;
254        Ok(knot_domain(&self.knots_u, self.degree_u))
255    }
256
257    pub fn domain_v(&self) -> Result<[f64; 2], String> {
258        self.ensure_valid()?;
259        Ok(knot_domain(&self.knots_v, self.degree_v))
260    }
261
262    /// Exact affine translation structure in this surface's own chart.
263    pub fn linear_extrusion(&self) -> Option<&crate::analytic_surface::ExtrusionStructure> {
264        self.linear_extrusion.get_or_init(|| crate::analytic_surface::extrusion_structure(self)).as_ref()
265    }
266
267    /// The held reduced profile of `extrusion` when it is this surface's own recognized
268    /// structure (`Some(None)` when it cannot be reduced); `None` for any other structure.
269    pub(crate) fn held_extrusion_profile(&self, extrusion: &crate::analytic_surface::ExtrusionStructure) -> Option<Option<&crate::analytic_surface::ReducedProfile>> {
270        let own = self.linear_extrusion.get().and_then(Option::as_ref).is_some_and(|e| std::ptr::eq(e, extrusion));
271        own.then(|| self.extrusion_profile.get_or_init(|| extrusion.reduce(true)).as_ref())
272    }
273
274    /// The held generatrix of `analytic` when it is this surface's own recognized
275    /// general revolution: `Some(Some(_))` when the generatrix lies on a meridional
276    /// half-plane (the closed form applies), `Some(None)` when it does not; `None`
277    /// for any other carrier, which the caller reads afresh.
278    pub(crate) fn held_revolution_generatrix(&self, analytic: &crate::AnalyticSurface) -> Option<Option<&crate::projection::HeldCurve>> {
279        let own = self.analytic.get().and_then(Option::as_ref).is_some_and(|a| std::ptr::eq(a, analytic));
280        let crate::AnalyticSurface::Revolution { frame, generatrix, .. } = analytic else { return None };
281        own.then(|| {
282            self.revolution_generatrix
283                .get_or_init(|| {
284                    crate::analytic_surface::generatrix_is_meridional_half_ray(generatrix, frame)
285                        .then(|| crate::projection::HeldCurve::new(generatrix.clone()))
286                })
287                .as_ref()
288        })
289    }
290
291    /// The recognized analytic carrier, if this exact rational patch is a
292    /// plane or a full revolution quadric/torus. Computed once per instance.
293    pub fn analytic(&self) -> Option<&crate::AnalyticSurface> {
294        self.analytic
295            .get_or_init(|| crate::analytic_surface::recognize(self))
296            .as_ref()
297    }
298
299    /// The recognized affine sphere (an ellipsoid), under `BREP_AFFINE_SPHERE`
300    /// and only when this net is not an analytic carrier; `None` otherwise.
301    pub fn affine_sphere(&self) -> Option<&crate::affine_sphere::AffineSphere> {
302        self.affine_sphere
303            .get_or_init(|| {
304                if !crate::affine_sphere::affine_sphere_enabled() || self.analytic().is_some() {
305                    None
306                } else {
307                    crate::affine_sphere::recognize(self)
308                }
309            })
310            .as_ref()
311    }
312
313    /// The names of this surface's caches that hold a value, in declaration
314    /// order. For the boolean's operand-state instrument
315    /// (`BREP_DEBUG_OPERAND_STATE`), which reads which caches arrive warm.
316    pub fn warm_caches(&self) -> Vec<&'static str> {
317        let mut warm = Vec::new();
318        let cells = [
319            ("analytic", self.analytic.get().is_some()),
320            ("linear_extrusion", self.linear_extrusion.get().is_some()),
321            ("extrusion_profile", self.extrusion_profile.get().is_some()),
322            ("revolution_generatrix", self.revolution_generatrix.get().is_some()),
323            ("affine_sphere", self.affine_sphere.get().is_some()),
324            ("validated", self.validated.get()),
325            ("closed", self.closed_directions.get().is_some()),
326            ("grid", self.projection_grid.get().is_some()),
327            ("dense", self.projection_dense_grid.get().is_some()),
328            ("ring", self.projection_ring_grid.get().is_some()),
329            ("cells", self.projection_cells.get().is_some()),
330            ("bezier", self.bezier_patches.get().is_some()),
331        ];
332        for (name, held) in cells {
333            if held {
334                warm.push(name);
335            }
336        }
337        warm
338    }
339
340    /// Empties the named caches (`warm_caches`' names; `all` for every one),
341    /// or, with `from`, sets each to `from`'s value. For the operand-state
342    /// instrument only: a cache that decides an answer is a defect, and this
343    /// is how the bisect finds it.
344    pub fn exchange_caches(&mut self, names: &[&str], from: Option<&Self>) {
345        let wants = |name: &str| names.iter().any(|&n| n == name || n == "all");
346        // the held generatrix is built from the analytic carrier, so it goes wherever that goes
347        if wants("analytic") || wants("revolution_generatrix") {
348            self.analytic = from.map(|f| f.analytic.clone()).unwrap_or_default();
349            self.revolution_generatrix = from.map(|f| f.revolution_generatrix.clone()).unwrap_or_default();
350        }
351        // the held profile is built from the structure, so it goes wherever the structure goes
352        if wants("linear_extrusion") || wants("extrusion_profile") {
353            self.linear_extrusion = from.map(|f|f.linear_extrusion.clone()).unwrap_or_default();
354            self.extrusion_profile = from.map(|f| f.extrusion_profile.clone()).unwrap_or_default();
355        }
356        if wants("affine_sphere") {
357            self.affine_sphere = from.map(|f| f.affine_sphere.clone()).unwrap_or_default();
358        }
359        if wants("validated") {
360            self.validated = std::cell::Cell::new(from.is_some_and(|f| f.validated.get()));
361        }
362        if wants("closed") {
363            self.closed_directions = from.map(|f| f.closed_directions.clone()).unwrap_or_default();
364        }
365        if wants("grid") {
366            self.projection_grid = from.map(|f| f.projection_grid.clone()).unwrap_or_default();
367        }
368        if wants("dense") {
369            self.projection_dense_grid = from.map(|f| f.projection_dense_grid.clone()).unwrap_or_default();
370        }
371        if wants("ring") {
372            self.projection_ring_grid = from.map(|f| f.projection_ring_grid.clone()).unwrap_or_default();
373        }
374        if wants("cells") {
375            self.projection_cells = from.map(|f| f.projection_cells.clone()).unwrap_or_default();
376        }
377        if wants("bezier") {
378            self.bezier_patches = from.map(|f| f.bezier_patches.clone()).unwrap_or_default();
379        }
380    }
381
382    fn knot_vectors(&self) -> Result<(KnotVector, KnotVector), String> {
383        Ok((
384            KnotVector::new(self.knots_u.clone(), self.degree_u)?,
385            KnotVector::new(self.knots_v.clone(), self.degree_v)?,
386        ))
387    }
388
389    #[cfg_attr(feature = "profile-wall", track_caller)]
390    pub fn evaluate_homogeneous(&self, u: f64, v: f64) -> Result<Vec4, String> {
391        let _reader = crate::reader_profile::Point::open(crate::reader_profile::SURFACE, std::panic::Location::caller());
392    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::POINT);
393        crate::projection_profile::count(crate::projection_profile::LANE_EVALUATE, self);
394        self.ensure_valid()?;
395        if self.degree_u > MAX_STACK_DEGREE || self.degree_v > MAX_STACK_DEGREE {
396            return self.evaluate_homogeneous_heap(u, v);
397        }
398        let u = knot_clamp(&self.knots_u, self.degree_u, u);
399        let v = knot_clamp(&self.knots_v, self.degree_v, v);
400        let span_u = knot_find_span(&self.knots_u, self.degree_u, u);
401        let span_v = knot_find_span(&self.knots_v, self.degree_v, v);
402        // Recognition evaluates points itself. Inspect only an initialized cache:
403        // asking analytic() here would recursively initialize that same cache.
404        if analytic_point_on() && matches!((self.degree_u, self.degree_v), (1, 1) | (2, 1) | (1, 2) | (2, 2))
405            && matches!(self.analytic.get().and_then(|carrier| carrier.as_ref()),
406                Some(crate::AnalyticSurface::Plane { .. } | crate::AnalyticSurface::RuledRevolution { .. }
407                    | crate::AnalyticSurface::Sphere { .. } | crate::AnalyticSurface::Torus { .. })) {
408            return Ok(match (self.degree_u, self.degree_v) {
409                (1, 1) => self.analytic_point_small::<1, 1>(u, v, span_u, span_v),
410                (2, 1) => self.analytic_point_small::<2, 1>(u, v, span_u, span_v),
411                (1, 2) => self.analytic_point_small::<1, 2>(u, v, span_u, span_v),
412                (2, 2) => self.analytic_point_small::<2, 2>(u, v, span_u, span_v),
413                _ => unreachable!(),
414            });
415        }
416        let mut basis_u = [0.0f64; MAX_STACK_ORDER];
417        let mut basis_v = [0.0f64; MAX_STACK_ORDER];
418        basis_functions_into(&self.knots_u, self.degree_u, span_u, u, &mut basis_u);
419        basis_functions_into(&self.knots_v, self.degree_v, span_v, v, &mut basis_v);
420        let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
421        let mut point = Vec4 {
422            x: 0.0,
423            y: 0.0,
424            z: 0.0,
425            w: 0.0,
426        };
427        for (i, value_u) in basis_u[..=self.degree_u].iter().enumerate() {
428            let row = &self.control_points[span_u - self.degree_u + i];
429            for (j, value_v) in basis_v[..=self.degree_v].iter().enumerate() {
430                point = point.add(row[span_v - self.degree_v + j].scale(value_u * value_v));
431            }
432        }
433        Ok(point)
434    }
435
436    /// The stored rational net, with the general evaluator's arithmetic order.
437    /// Const degrees shrink the scratch arrays and specialize the short loops;
438    /// this is not a trigonometric replacement of the rational parameterization.
439    fn analytic_point_small<const DU: usize, const DV: usize>(&self, u: f64, v: f64, span_u: usize, span_v: usize) -> Vec4 {
440        fn basis<const D: usize>(knots: &[f64], span: usize, parameter: f64) -> [f64; 3] {
441        let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::BASIS);
442            let mut values = [0.0; 3];
443            let mut left = [0.0; 3];
444            let mut right = [0.0; 3];
445            values[0] = 1.0;
446            for j in 1..=D {
447                left[j] = parameter - knots[span + 1 - j];
448                right[j] = knots[span + j] - parameter;
449                let mut saved = 0.0;
450                for r in 0..j {
451                    let denominator = right[r + 1] + left[j - r];
452                    let temporary = if denominator.abs() <= EPS { 0.0 } else { values[r] / denominator };
453                    values[r] = saved + right[r + 1] * temporary;
454                    saved = left[j - r] * temporary;
455                }
456                values[j] = saved;
457            }
458            values
459        }
460        let basis_u = basis::<DU>(&self.knots_u, span_u, u);
461        let basis_v = basis::<DV>(&self.knots_v, span_v, v);
462        let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
463        let mut point = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
464        for (i, value_u) in basis_u[..=DU].iter().enumerate() {
465            let row = &self.control_points[span_u - DU + i];
466            for (j, value_v) in basis_v[..=DV].iter().enumerate() {
467                point = point.add(row[span_v - DV + j].scale(value_u * value_v));
468            }
469        }
470        point
471    }
472
473    fn evaluate_homogeneous_heap(&self, u: f64, v: f64) -> Result<Vec4, String> {
474        let (knot_u, knot_v) = self.knot_vectors()?;
475        let u = knot_u.clamp_param(u);
476        let v = knot_v.clamp_param(v);
477        let span_u = knot_u.find_span(u);
478        let span_v = knot_v.find_span(v);
479        let basis_u = knot_u.basis_functions(span_u, u);
480        let basis_v = knot_v.basis_functions(span_v, v);
481        let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
482        let mut point = Vec4 {
483            x: 0.0,
484            y: 0.0,
485            z: 0.0,
486            w: 0.0,
487        };
488        for (i, value_u) in basis_u.iter().enumerate() {
489            let row = &self.control_points[span_u - self.degree_u + i];
490            for (j, value_v) in basis_v.iter().enumerate() {
491                point = point.add(row[span_v - self.degree_v + j].scale(value_u * value_v));
492            }
493        }
494        Ok(point)
495    }
496
497    #[cfg_attr(feature = "profile-wall", track_caller)]
498    pub fn evaluate(&self, u: f64, v: f64) -> Result<Vec3, String> {
499        let _reader = crate::reader_profile::Point::open(crate::reader_profile::SURFACE, std::panic::Location::caller());
500    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::POINT);
501        self.evaluate_homogeneous(u, v)?.point()
502    }
503
504    /// Value beyond the domain (Golovanov §3.15): closed directions wrap
505    /// cyclically; open directions extend along the boundary tangent
506    /// plane, with the bilinear corner form when both parameters are
507    /// outside.  Intersection and projection algorithms probe outside the
508    /// domain, so this is a required capability of every surface.
509    #[cfg_attr(feature = "profile-wall", track_caller)]
510    pub fn evaluate_extended(&self, u: f64, v: f64) -> Result<Vec3, String> {
511        let _reader = crate::reader_profile::Point::open(crate::reader_profile::SURFACE, std::panic::Location::caller());
512    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::POINT);
513        if small_derivatives_enabled() {
514            return Ok(self.derivatives_extended_small(u, v, 0)?[0][0]);
515        }
516        Ok(self.derivatives_extended(u, v, 0)?[0][0])
517    }
518
519    /// Allocation-free twin of [`Self::derivatives_extended`] for
520    /// `derivative_count <= 2` (lane O row 20): the same wrap, anchor and
521    /// bilinear extension, over [`Self::derivatives_small`], which is the
522    /// byte-faithful stack copy of [`Self::derivatives`]. Entries outside
523    /// `k + l <= derivative_count` stay `Vec3::default()`, as the Vec form
524    /// leaves them.
525    pub fn derivatives_extended_small(
526        &self,
527        u: f64,
528        v: f64,
529        derivative_count: usize,
530    ) -> Result<[[Vec3; 3]; 3], String> {
531        debug_assert!(derivative_count <= 2);
532        let [u0, u1] = self.domain_u()?;
533        let [v0, v1] = self.domain_v()?;
534        let (closed_u, closed_v) = self.closed_directions()?;
535        let mut uu = u;
536        let mut vv = v;
537        if closed_u && (u < u0 || u > u1) {
538            uu = u0 + (u - u0).rem_euclid(u1 - u0);
539        }
540        if closed_v && (v < v0 || v > v1) {
541            vv = v0 + (v - v0).rem_euclid(v1 - v0);
542        }
543        let du_out = if uu < u0 { uu - u0 } else if uu > u1 { uu - u1 } else { 0.0 };
544        let dv_out = if vv < v0 { vv - v0 } else if vv > v1 { vv - v1 } else { 0.0 };
545        if du_out == 0.0 && dv_out == 0.0 {
546            return self.derivatives_small(uu, vv, derivative_count);
547        }
548        let anchor_u = uu - du_out;
549        let anchor_v = vv - dv_out;
550        let base = self.derivatives_small(anchor_u, anchor_v, 2)?;
551        let mut result = [[Vec3::default(); 3]; 3];
552        result[0][0] = base[0][0]
553            .add(base[1][0].scale(du_out))
554            .add(base[0][1].scale(dv_out))
555            .add(base[1][1].scale(du_out * dv_out));
556        if derivative_count >= 1 {
557            result[1][0] = base[1][0].add(base[1][1].scale(dv_out));
558            result[0][1] = base[0][1].add(base[1][1].scale(du_out));
559            result[1][1] = base[1][1];
560        }
561        if derivative_count >= 2 {
562            if du_out == 0.0 {
563                result[2][0] = base[2][0];
564            }
565            if dv_out == 0.0 {
566                result[0][2] = base[0][2];
567            }
568        }
569        Ok(result)
570    }
571
572    /// Derivatives beyond the domain (§3.15).  The extension is C¹: first
573    /// derivatives follow the ruled/bilinear extension, second derivatives
574    /// are taken at the boundary anchor (zero across an extended
575    /// direction).
576    pub fn derivatives_extended(
577        &self,
578        u: f64,
579        v: f64,
580        derivative_count: usize,
581    ) -> Result<Vec<Vec<Vec3>>, String> {
582        if derivative_count <= 2 && small_derivatives_enabled() {
583            let small = self.derivatives_extended_small(u, v, derivative_count)?;
584            let order = derivative_count + 1;
585            return Ok((0..order).map(|k| (0..order).map(|l| small[k][l]).collect()).collect());
586        }
587        let [u0, u1] = self.domain_u()?;
588        let [v0, v1] = self.domain_v()?;
589        let (closed_u, closed_v) = self.closed_directions()?;
590        let mut uu = u;
591        let mut vv = v;
592        if closed_u && (u < u0 || u > u1) {
593            uu = u0 + (u - u0).rem_euclid(u1 - u0);
594        }
595        if closed_v && (v < v0 || v > v1) {
596            vv = v0 + (v - v0).rem_euclid(v1 - v0);
597        }
598        let du_out = if uu < u0 {
599            uu - u0
600        } else if uu > u1 {
601            uu - u1
602        } else {
603            0.0
604        };
605        let dv_out = if vv < v0 {
606            vv - v0
607        } else if vv > v1 {
608            vv - v1
609        } else {
610            0.0
611        };
612        if du_out == 0.0 && dv_out == 0.0 {
613            return self.derivatives(uu, vv, derivative_count);
614        }
615        let anchor_u = uu - du_out;
616        let anchor_v = vv - dv_out;
617        let base = self.derivatives(anchor_u, anchor_v, derivative_count.max(2))?;
618        let order = derivative_count + 1;
619        let mut result = vec![vec![Vec3::default(); order]; order];
620        // Bilinear extension: S = A00 + du·A10 + dv·A01 + du·dv·A11
621        // (reduces to the ruled tangent-plane extension when only one
622        // parameter is outside).
623        result[0][0] = base[0][0]
624            .add(base[1][0].scale(du_out))
625            .add(base[0][1].scale(dv_out))
626            .add(base[1][1].scale(du_out * dv_out));
627        if derivative_count >= 1 {
628            result[1][0] = base[1][0].add(base[1][1].scale(dv_out));
629            result[0][1] = base[0][1].add(base[1][1].scale(du_out));
630            result[1][1] = base[1][1];
631        }
632        if derivative_count >= 2 {
633            let second = self.derivatives(anchor_u, anchor_v, 2)?;
634            if du_out == 0.0 {
635                result[2][0] = second[2][0];
636            }
637            if dv_out == 0.0 {
638                result[0][2] = second[0][2];
639            }
640        }
641        Ok(result)
642    }
643
644    pub fn derivatives(
645        &self,
646        u: f64,
647        v: f64,
648        derivative_count: usize,
649    ) -> Result<Vec<Vec<Vec3>>, String> {
650        crate::projection_profile::count(crate::projection_profile::LANE_DERIVATIVES, self);
651        self.ensure_valid()?;
652        let du = derivative_count.min(self.degree_u);
653        let dv = derivative_count.min(self.degree_v);
654        let stride = derivative_count + 1;
655        // Flat (k, l) grid: one allocation instead of nested per-row Vecs.
656        let zero = Vec4 {
657            x: 0.0,
658            y: 0.0,
659            z: 0.0,
660            w: 0.0,
661        };
662        let mut homogeneous = vec![zero; stride * stride];
663        if self.degree_u <= MAX_STACK_DEGREE && self.degree_v <= MAX_STACK_DEGREE {
664            let u = knot_clamp(&self.knots_u, self.degree_u, u);
665            let v = knot_clamp(&self.knots_v, self.degree_v, v);
666            let span_u = knot_find_span(&self.knots_u, self.degree_u, u);
667            let span_v = knot_find_span(&self.knots_v, self.degree_v, v);
668            // `derivative_count` reaches the degree here (blends ask for third
669            // partials), so the rows retain the full stack order.
670            let mut basis_u = [[0.0f64; MAX_STACK_ORDER]; MAX_STACK_ORDER];
671            let mut basis_v = [[0.0f64; MAX_STACK_ORDER]; MAX_STACK_ORDER];
672            basis_derivatives_into(
673                &self.knots_u,
674                self.degree_u,
675                span_u,
676                u,
677                du,
678                &mut basis_u[..=du],
679            );
680            basis_derivatives_into(
681                &self.knots_v,
682                self.degree_v,
683                span_v,
684                v,
685                dv,
686                &mut basis_v[..=dv],
687            );
688            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
689            for k in 0..=du {
690                for l in 0..=dv {
691                    if k + l > derivative_count {
692                        continue;
693                    }
694                    let mut point = zero;
695                    for i in 0..=self.degree_u {
696                        let row = &self.control_points[span_u - self.degree_u + i];
697                        for j in 0..=self.degree_v {
698                            point = point.add(
699                                row[span_v - self.degree_v + j]
700                                    .scale(basis_u[k][i] * basis_v[l][j]),
701                            );
702                        }
703                    }
704                    homogeneous[k * stride + l] = point;
705                }
706            }
707        } else {
708            let (knot_u, knot_v) = self.knot_vectors()?;
709            let u = knot_u.clamp_param(u);
710            let v = knot_v.clamp_param(v);
711            let span_u = knot_u.find_span(u);
712            let span_v = knot_v.find_span(v);
713            let basis_u = knot_u.basis_derivatives(span_u, u, du);
714            let basis_v = knot_v.basis_derivatives(span_v, v, dv);
715            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
716            for k in 0..=du {
717                for l in 0..=dv {
718                    if k + l > derivative_count {
719                        continue;
720                    }
721                    let mut point = zero;
722                    for i in 0..=self.degree_u {
723                        let row = &self.control_points[span_u - self.degree_u + i];
724                        for j in 0..=self.degree_v {
725                            point = point.add(
726                                row[span_v - self.degree_v + j]
727                                    .scale(basis_u[k][i] * basis_v[l][j]),
728                            );
729                        }
730                    }
731                    homogeneous[k * stride + l] = point;
732                }
733            }
734        }
735
736        let mut result = vec![vec![Vec3::default(); derivative_count + 1]; derivative_count + 1];
737        let weight = homogeneous[0].w;
738        if weight.abs() <= EPS {
739            return Err("NurbsSurface: zero evaluated weight".into());
740        }
741        for k in 0..=derivative_count {
742            for l in 0..=derivative_count - k {
743                if k > du || l > dv {
744                    continue;
745                }
746                let at = |row: usize, column: usize| homogeneous[row * stride + column];
747                let mut value = Vec3::new(at(k, l).x, at(k, l).y, at(k, l).z);
748                for j in 1..=l {
749                    value = value.sub(result[k][l - j].scale(binomial(l, j) * at(0, j).w));
750                }
751                for i in 1..=k {
752                    value = value.sub(result[k - i][l].scale(binomial(k, i) * at(i, 0).w));
753                    let mut mixed = Vec3::default();
754                    for j in 1..=l {
755                        mixed = mixed.add(result[k - i][l - j].scale(binomial(l, j) * at(i, j).w));
756                    }
757                    value = value.sub(mixed.scale(binomial(k, i)));
758                }
759                result[k][l] = value.scale(1.0 / weight);
760            }
761        }
762        Ok(result)
763    }
764
765    /// Allocation-free twin of [`Self::derivatives`] for the hot
766    /// `derivative_count <= 2` path (point, first, and second partials).
767    ///
768    /// This is a byte-for-byte faithful copy of the arithmetic in
769    /// [`Self::derivatives`]: identical basis evaluation, identical summation
770    /// order (control-point row `i` outer, column `j` inner, `scale`-then-`add`),
771    /// and the identical rational `A(u,v)/w(u,v)` de-homogenization recurrence.
772    /// Only the storage differs — fixed-size stack arrays (`[Vec4; 9]` for the
773    /// `(count+1)²` homogeneous grid, `[[Vec3; 3]; 3]` for the result) replace
774    /// the heap `Vec<Vec4>` / `Vec<Vec<Vec3>>`. Grid entries outside
775    /// `k + l <= derivative_count` (and outside `k <= du`, `l <= dv`) stay
776    /// `Vec3::default()`, exactly as the heap version leaves them, so callers may
777    /// index `[k][l]` for any `k + l <= 2` and read the same value the Vec API
778    /// would have produced.
779    pub fn derivatives_small(
780        &self,
781        u: f64,
782        v: f64,
783        derivative_count: usize,
784    ) -> Result<[[Vec3; 3]; 3], String> {
785        match derivative_count {
786            0 => self.derivatives_small_count::<0>(u, v),
787            1 => self.derivatives_small_count::<1>(u, v),
788            2 => self.derivatives_small_count::<2>(u, v),
789            _ => self.derivatives_small_degrees::<{usize::MAX}, {usize::MAX}, {usize::MAX}>(u, v, derivative_count),
790        }
791    }
792
793    fn derivatives_small_count<const COUNT: usize>(&self, u: f64, v: f64) -> Result<[[Vec3; 3]; 3], String> {
794        match (self.degree_u, self.degree_v) {
795            (3, 9) => self.derivatives_small_degrees::<3, 9, COUNT>(u, v, COUNT),
796            (5, 9) => self.derivatives_small_degrees::<5, 9, COUNT>(u, v, COUNT),
797            _ => self.derivatives_small_degrees::<{usize::MAX}, {usize::MAX}, COUNT>(u, v, COUNT),
798        }
799    }
800
801    // The same recurrence and control-point order, with partial count and common
802    // screw-wall degrees fixed so bounds and loop trips can fold. MAX retains
803    // the runtime argument for the generic path and its bitwise comparison.
804    fn derivatives_small_degrees<const U: usize, const V: usize, const COUNT: usize>(
805        &self, u: f64, v: f64, derivative_count: usize,
806    ) -> Result<[[Vec3; 3]; 3], String> {
807        let degree_u = if U == usize::MAX { self.degree_u } else { U };
808        let degree_v = if V == usize::MAX { self.degree_v } else { V };
809        let derivative_count = if COUNT == usize::MAX { derivative_count } else { COUNT };
810        // Row zero of the derivative basis has the value recurrence's exact
811        // arithmetic. Keep its row-major sum and reciprocal multiplication,
812        // but avoid the derivative scratch grids for a point-only request.
813        // The experimental analytic evaluator is a separate policy: retain
814        // the original derivative path whenever that policy is enabled.
815        if derivative_count == 0 && switch!("BREP_SURFACE_POINT_ONLY", false)
816            && u.is_finite() && v.is_finite()
817            && degree_u <= MAX_STACK_DEGREE && degree_v <= MAX_STACK_DEGREE
818            && !analytic_point_on() {
819            let point = self.evaluate_homogeneous(u, v)?;
820            if point.w.abs() <= EPS {
821                return Err("NurbsSurface: zero evaluated weight".into());
822            }
823            let mut result = [[Vec3::default(); 3]; 3];
824            result[0][0] = Vec3::new(point.x, point.y, point.z).scale(1.0 / point.w);
825            return Ok(result);
826        }
827        debug_assert!(derivative_count <= 2);
828        self.ensure_valid()?;
829        let du = derivative_count.min(degree_u);
830        let dv = derivative_count.min(degree_v);
831        let stride = derivative_count + 1;
832        let zero = Vec4 {
833            x: 0.0,
834            y: 0.0,
835            z: 0.0,
836            w: 0.0,
837        };
838        let mut homogeneous = [zero; 9];
839        if degree_u <= MAX_STACK_DEGREE && degree_v <= MAX_STACK_DEGREE {
840            let u = knot_clamp(&self.knots_u, degree_u, u);
841            let v = knot_clamp(&self.knots_v, degree_v, v);
842            let span_u = knot_find_span(&self.knots_u, degree_u, u);
843            let span_v = knot_find_span(&self.knots_v, degree_v, v);
844            // Rows `..=du` / `..=dv` (at most three) are the only ones written
845            // or read; the eight-row fill was a measurable share of a sign
846            // reading's surface station (2026-11-02).
847            let mut basis_u = [[0.0f64; MAX_STACK_ORDER]; 3];
848            let mut basis_v = [[0.0f64; MAX_STACK_ORDER]; 3];
849            basis_derivatives_into(
850                &self.knots_u,
851                degree_u,
852                span_u,
853                u,
854                du,
855                &mut basis_u[..=du],
856            );
857            basis_derivatives_into(
858                &self.knots_v,
859                degree_v,
860                span_v,
861                v,
862                dv,
863                &mut basis_v[..=dv],
864            );
865            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
866            for k in 0..=du {
867                for l in 0..=dv {
868                    if k + l > derivative_count {
869                        continue;
870                    }
871                    let mut point = zero;
872                    for i in 0..=degree_u {
873                        let row = &self.control_points[span_u - degree_u + i][span_v - degree_v..=span_v];
874                        for j in 0..=degree_v {
875                            point = point.add(
876                                row[j]
877                                    .scale(basis_u[k][i] * basis_v[l][j]),
878                            );
879                        }
880                    }
881                    homogeneous[k * stride + l] = point;
882                }
883            }
884        } else {
885            let (knot_u, knot_v) = self.knot_vectors()?;
886            let u = knot_u.clamp_param(u);
887            let v = knot_v.clamp_param(v);
888            let span_u = knot_u.find_span(u);
889            let span_v = knot_v.find_span(v);
890            let basis_u = knot_u.basis_derivatives(span_u, u, du);
891            let basis_v = knot_v.basis_derivatives(span_v, v, dv);
892            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
893            for k in 0..=du {
894                for l in 0..=dv {
895                    if k + l > derivative_count {
896                        continue;
897                    }
898                    let mut point = zero;
899                    for i in 0..=degree_u {
900                        let row = &self.control_points[span_u - degree_u + i];
901                        for j in 0..=degree_v {
902                            point = point.add(
903                                row[span_v - degree_v + j]
904                                    .scale(basis_u[k][i] * basis_v[l][j]),
905                            );
906                        }
907                    }
908                    homogeneous[k * stride + l] = point;
909                }
910            }
911        }
912
913        let mut result = [[Vec3::default(); 3]; 3];
914        let weight = homogeneous[0].w;
915        if weight.abs() <= EPS {
916            return Err("NurbsSurface: zero evaluated weight".into());
917        }
918        for k in 0..=derivative_count {
919            for l in 0..=derivative_count - k {
920                if k > du || l > dv {
921                    continue;
922                }
923                let at = |row: usize, column: usize| homogeneous[row * stride + column];
924                let mut value = Vec3::new(at(k, l).x, at(k, l).y, at(k, l).z);
925                for j in 1..=l {
926                    value = value.sub(result[k][l - j].scale(binomial(l, j) * at(0, j).w));
927                }
928                for i in 1..=k {
929                    value = value.sub(result[k - i][l].scale(binomial(k, i) * at(i, 0).w));
930                    let mut mixed = Vec3::default();
931                    for j in 1..=l {
932                        mixed = mixed.add(result[k - i][l - j].scale(binomial(l, j) * at(i, j).w));
933                    }
934                    value = value.sub(mixed.scale(binomial(k, i)));
935                }
936                result[k][l] = value.scale(1.0 / weight);
937            }
938        }
939        Ok(result)
940    }
941
942    /// Whether [`Self::deriv1_tensor_each`] can drive this patch: the stack
943    /// basis tables only reach `MAX_STACK_DEGREE`, and a higher-degree patch
944    /// must be evaluated station by station through [`Self::deriv1`].
945    #[inline]
946    pub fn deriv1_tensor_supported(&self) -> bool {
947        self.degree_u <= MAX_STACK_DEGREE && self.degree_v <= MAX_STACK_DEGREE
948    }
949
950    /// `(S, S_u, S_v)` at every station of the TENSOR BLOCK `us x vs`, handed
951    /// to `f` as `(u index, v index, S, S_u, S_v)` with `us` outer and `vs`
952    /// inner.
953    ///
954    /// Bit-identical to calling [`Self::deriv1`] at each pair, and that is the
955    /// whole point of it: the block's `us.len() + vs.len()` spans and basis
956    /// rows are evaluated ONCE each instead of once per station, which is
957    /// where a fixed tensor-Gauss cell spends most of its time (the basis
958    /// recurrence carries a division per knot per derivative order, and an
959    /// 8x8 cell asks for the same 8 u rows and 8 v rows sixty-four times).
960    /// Nothing else changes: `knot_clamp` / `knot_find_span` /
961    /// `basis_derivatives_into` see the same arguments and so return the same
962    /// floats, the control-point sum runs in the same row-outer/column-inner
963    /// order from the same zero `Vec4`, and the rational de-homogenization is
964    /// [`Self::derivatives_small`]'s recurrence written out for
965    /// `derivative_count == 1`.
966    ///
967    /// Two steps of that recurrence are elided because they are exact no-ops
968    /// at this order: `binomial(1, 1)` is exactly `1.0`, and the mixed term it
969    /// scales is the zero vector, whose subtraction leaves every component
970    /// (including a negative zero) bit-unchanged.
971    pub fn deriv1_tensor_each<F>(
972        &self,
973        us: &[f64],
974        vs: &[f64],
975        mut f: F,
976    ) -> Result<(), String>
977    where
978        F: FnMut(usize, usize, Vec3, Vec3, Vec3) -> Result<(), String>,
979    {
980        self.ensure_valid()?;
981        // Width and rationale: `TENSOR_MAX_BLOCK` at the top of this module.
982        const MAX_BLOCK: usize = TENSOR_MAX_BLOCK;
983        if !self.deriv1_tensor_supported() || us.len() > MAX_BLOCK || vs.len() > MAX_BLOCK {
984            return Err("NurbsSurface: tensor block outside the stack evaluator".into());
985        }
986        let du = 1usize.min(self.degree_u);
987        let dv = 1usize.min(self.degree_v);
988        let mut span_u = [0usize; MAX_BLOCK];
989        let mut span_v = [0usize; MAX_BLOCK];
990        let mut basis_u = [[[0.0f64; MAX_STACK_ORDER]; 2]; MAX_BLOCK];
991        let mut basis_v = [[[0.0f64; MAX_STACK_ORDER]; 2]; MAX_BLOCK];
992        for (index, &value) in us.iter().enumerate() {
993            let value = knot_clamp(&self.knots_u, self.degree_u, value);
994            span_u[index] = knot_find_span(&self.knots_u, self.degree_u, value);
995            basis_derivatives_into(
996                &self.knots_u,
997                self.degree_u,
998                span_u[index],
999                value,
1000                du,
1001                &mut basis_u[index][..=du],
1002            );
1003        }
1004        for (index, &value) in vs.iter().enumerate() {
1005            let value = knot_clamp(&self.knots_v, self.degree_v, value);
1006            span_v[index] = knot_find_span(&self.knots_v, self.degree_v, value);
1007            basis_derivatives_into(
1008                &self.knots_v,
1009                self.degree_v,
1010                span_v[index],
1011                value,
1012                dv,
1013                &mut basis_v[index][..=dv],
1014            );
1015        }
1016        if tensor_fused_on() {
1017            let (count_u, count_v) = (us.len(), vs.len());
1018            let tables = (&span_u, &span_v, &basis_u, &basis_v);
1019            match (self.degree_u, self.degree_v) {
1020                (1, 1) => return self.deriv1_tensor_fused::<1, 1, F>(count_u, count_v, tables, &mut f),
1021                (1, 2) => return self.deriv1_tensor_fused::<1, 2, F>(count_u, count_v, tables, &mut f),
1022                (1, 3) => return self.deriv1_tensor_fused::<1, 3, F>(count_u, count_v, tables, &mut f),
1023                (2, 1) => return self.deriv1_tensor_fused::<2, 1, F>(count_u, count_v, tables, &mut f),
1024                (2, 2) => return self.deriv1_tensor_fused::<2, 2, F>(count_u, count_v, tables, &mut f),
1025                (2, 3) => return self.deriv1_tensor_fused::<2, 3, F>(count_u, count_v, tables, &mut f),
1026                (3, 1) => return self.deriv1_tensor_fused::<3, 1, F>(count_u, count_v, tables, &mut f),
1027                (3, 2) => return self.deriv1_tensor_fused::<3, 2, F>(count_u, count_v, tables, &mut f),
1028                (3, 3) => return self.deriv1_tensor_fused::<3, 3, F>(count_u, count_v, tables, &mut f),
1029                _ => {}
1030            }
1031        }
1032        let zero = Vec4 {
1033            x: 0.0,
1034            y: 0.0,
1035            z: 0.0,
1036            w: 0.0,
1037        };
1038        for i in 0..us.len() {
1039            let rows = &self.control_points[span_u[i] - self.degree_u..];
1040            for j in 0..vs.len() {
1041                let column = span_v[j] - self.degree_v;
1042                // The (k, l) homogeneous grid `derivatives_small` builds for
1043                // `derivative_count == 1`: (0,0) always, (0,1) when dv >= 1,
1044                // (1,0) when du >= 1.
1045                let sum = |k: usize, l: usize| {
1046                    let mut point = zero;
1047                    for row_index in 0..=self.degree_u {
1048                        let row = &rows[row_index];
1049                        for column_index in 0..=self.degree_v {
1050                            point = point.add(
1051                                row[column + column_index]
1052                                    .scale(basis_u[i][k][row_index] * basis_v[j][l][column_index]),
1053                            );
1054                        }
1055                    }
1056                    point
1057                };
1058                let h00 = sum(0, 0);
1059                let h01 = if dv >= 1 { sum(0, 1) } else { zero };
1060                let h10 = if du >= 1 { sum(1, 0) } else { zero };
1061                let weight = h00.w;
1062                if weight.abs() <= EPS {
1063                    return Err("NurbsSurface: zero evaluated weight".into());
1064                }
1065                let inverse = 1.0 / weight;
1066                let point = Vec3::new(h00.x, h00.y, h00.z).scale(inverse);
1067                let partial_v = if dv >= 1 {
1068                    Vec3::new(h01.x, h01.y, h01.z)
1069                        .sub(point.scale(h01.w))
1070                        .scale(inverse)
1071                } else {
1072                    Vec3::default()
1073                };
1074                let partial_u = if du >= 1 {
1075                    Vec3::new(h10.x, h10.y, h10.z)
1076                        .sub(point.scale(h10.w))
1077                        .scale(inverse)
1078                } else {
1079                    Vec3::default()
1080                };
1081                f(i, j, point, partial_u, partial_v)?;
1082            }
1083        }
1084        Ok(())
1085    }
1086
1087    /// [`Self::deriv1_tensor_each`]'s station loop for a patch of degrees
1088    /// `DEGREE_U × DEGREE_V`, both at least 1, from the block's span and basis
1089    /// tables. The same bits as the run-time-degree loop: each of the three
1090    /// homogeneous sums (`S`, `∂_v`, `∂_u`) gets the same products
1091    /// `basis_u · basis_v` of the same control points, scaled and then added in
1092    /// the same row-outer, column-inner order from the same zero `Vec4`, and
1093    /// the dehomogenization is that loop's line for line. What changes is only
1094    /// that the three sums share one walk over the control points, and the trip
1095    /// counts are constants the compiler unrolls. A mass integral's adaptive
1096    /// area reads spend most of their time here: on a fitted bicubic offset
1097    /// shell, about a billion stations for one solid.
1098    #[allow(clippy::type_complexity)]
1099    #[inline(always)]
1100    fn deriv1_tensor_fused<const DEGREE_U: usize, const DEGREE_V: usize, F>(
1101        &self,
1102        count_u: usize,
1103        count_v: usize,
1104        (span_u, span_v, basis_u, basis_v): (
1105            &[usize; TENSOR_MAX_BLOCK],
1106            &[usize; TENSOR_MAX_BLOCK],
1107            &[[[f64; MAX_STACK_ORDER]; 2]; TENSOR_MAX_BLOCK],
1108            &[[[f64; MAX_STACK_ORDER]; 2]; TENSOR_MAX_BLOCK],
1109        ),
1110        f: &mut F,
1111    ) -> Result<(), String>
1112    where
1113        F: FnMut(usize, usize, Vec3, Vec3, Vec3) -> Result<(), String>,
1114    {
1115        let zero = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
1116        for i in 0..count_u {
1117            let rows = &self.control_points[span_u[i] - DEGREE_U..=span_u[i]];
1118            let (value_u, slope_u) = (&basis_u[i][0], &basis_u[i][1]);
1119            for j in 0..count_v {
1120                let column = span_v[j] - DEGREE_V;
1121                let (value_v, slope_v) = (&basis_v[j][0], &basis_v[j][1]);
1122                let (mut h00, mut h01, mut h10) = (zero, zero, zero);
1123                for row_index in 0..=DEGREE_U {
1124                    let row = &rows[row_index][column..=column + DEGREE_V];
1125                    for column_index in 0..=DEGREE_V {
1126                        let control = row[column_index];
1127                        h00 = h00.add(control.scale(value_u[row_index] * value_v[column_index]));
1128                        h01 = h01.add(control.scale(value_u[row_index] * slope_v[column_index]));
1129                        h10 = h10.add(control.scale(slope_u[row_index] * value_v[column_index]));
1130                    }
1131                }
1132                let weight = h00.w;
1133                if weight.abs() <= EPS {
1134                    return Err("NurbsSurface: zero evaluated weight".into());
1135                }
1136                let inverse = 1.0 / weight;
1137                let point = Vec3::new(h00.x, h00.y, h00.z).scale(inverse);
1138                let partial_v = Vec3::new(h01.x, h01.y, h01.z).sub(point.scale(h01.w)).scale(inverse);
1139                let partial_u = Vec3::new(h10.x, h10.y, h10.z).sub(point.scale(h10.w)).scale(inverse);
1140                f(i, j, point, partial_u, partial_v)?;
1141            }
1142        }
1143        Ok(())
1144    }
1145
1146    /// Point and first partials `(S, S_u, S_v)` with zero heap allocation.
1147    /// Bit-identical to `derivatives(u, v, 1)` at `[0][0] / [1][0] / [0][1]`.
1148    #[inline]
1149    pub fn deriv1(&self, u: f64, v: f64) -> Result<(Vec3, Vec3, Vec3), String> {
1150        // Degrees 1 and 2 in both directions (every carrier the kernel builds
1151        // and the fitted patches it blends with) take the first-order twin
1152        // with both degrees fixed at compile time; its arithmetic is
1153        // `derivatives_small`'s to the bit (`deriv1_small_fixed`), and the
1154        // mass sign reading's chord stations were a third `derivatives_small`
1155        // self time after the basis recurrence (2026-11-02).
1156        match (self.degree_u, self.degree_v) {
1157            (1, 1) => self.deriv1_small_fixed::<1, 1>(u, v),
1158            (2, 1) => self.deriv1_small_fixed::<2, 1>(u, v),
1159            (1, 2) => self.deriv1_small_fixed::<1, 2>(u, v),
1160            (2, 2) => self.deriv1_small_fixed::<2, 2>(u, v),
1161            (3, 9) => self.deriv1_small_fixed::<3, 9>(u, v),
1162            (5, 9) => self.deriv1_small_fixed::<5, 9>(u, v),
1163            _ => {
1164                let g = self.derivatives_small(u, v, 1)?;
1165                Ok((g[0][0], g[1][0], g[0][1]))
1166            }
1167        }
1168    }
1169
1170    /// First-order rational recurrence with only its three live sums, for a
1171    /// patch whose degrees are the const parameters. The clamp, span, basis
1172    /// rows, control summation (row outer, column inner, scale then add from
1173    /// the zero `Vec4`) and dehomogenization are `derivatives_small`'s in the
1174    /// same order; the two recurrence steps written out here that
1175    /// `derivatives_small` runs generically are exact no-ops at this order
1176    /// (`binomial(1, 1)` is exactly `1.0`; the mixed term is the zero vector,
1177    /// whose subtraction changes no bit). So the three results are the same
1178    /// bits as `derivatives_small(u, v, 1)` at `[0][0]`, `[1][0]`, `[0][1]`
1179    /// for ANY surface of these degrees, analytic or not
1180    /// (`deriv1_degree_dispatch_tests`). Caller retains the existing
1181    /// wrapping, extension and refusal paths.
1182    fn deriv1_small_fixed<const DEGREE_U: usize, const DEGREE_V: usize>(&self, u: f64, v: f64) -> Result<(Vec3, Vec3, Vec3), String> {
1183        self.ensure_valid()?;
1184        let du = DEGREE_U.min(1);
1185        let dv = DEGREE_V.min(1);
1186        let u = knot_clamp(&self.knots_u, DEGREE_U, u);
1187        let v = knot_clamp(&self.knots_v, DEGREE_V, v);
1188        let span_u = knot_find_span(&self.knots_u, DEGREE_U, u);
1189        let span_v = knot_find_span(&self.knots_v, DEGREE_V, v);
1190        let mut basis_u = [[0.0; MAX_STACK_ORDER]; 2];
1191        let mut basis_v = [[0.0; MAX_STACK_ORDER]; 2];
1192        basis_derivatives_into(&self.knots_u, DEGREE_U, span_u, u, du, &mut basis_u[..=du]);
1193        basis_derivatives_into(&self.knots_v, DEGREE_V, span_v, v, dv, &mut basis_v[..=dv]);
1194        let zero = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
1195        let sum = |k: usize, l: usize| {
1196            let mut value = zero;
1197            for i in 0..=DEGREE_U {
1198                let row = &self.control_points[span_u - DEGREE_U + i][span_v - DEGREE_V..=span_v];
1199                for j in 0..=DEGREE_V {
1200                    value = value.add(row[j].scale(basis_u[k][i] * basis_v[l][j]));
1201                }
1202            }
1203            value
1204        };
1205        let h00 = sum(0, 0);
1206        let h01 = if dv == 1 { sum(0, 1) } else { zero };
1207        let h10 = if du == 1 { sum(1, 0) } else { zero };
1208        if h00.w.abs() <= EPS { return Err("NurbsSurface: zero evaluated weight".into()); }
1209        let inverse = 1.0 / h00.w;
1210        let point = Vec3::new(h00.x, h00.y, h00.z).scale(inverse);
1211        let partial_v = if dv == 1 {
1212            Vec3::new(h01.x, h01.y, h01.z).sub(point.scale(1.0 * h01.w)).scale(inverse)
1213        } else { Vec3::default() };
1214        let partial_u = if du == 1 {
1215            Vec3::new(h10.x, h10.y, h10.z).sub(point.scale(1.0 * h10.w))
1216                .sub(Vec3::default().scale(1.0)).scale(inverse)
1217        } else { Vec3::default() };
1218        Ok((point, partial_u, partial_v))
1219    }
1220
1221    /// The four anchor terms used by a first-order bilinear extension.
1222    /// Pure second partials do not feed these terms. Keep the control sums
1223    /// and rational recurrence in the generic evaluator's arithmetic order.
1224    fn extension_anchor_fixed<const U: usize, const V: usize>(&self, u: f64, v: f64) -> Result<(Vec3, Vec3, Vec3, Vec3), String> {
1225        self.ensure_valid()?;
1226        let u = knot_clamp(&self.knots_u, U, u);
1227        let v = knot_clamp(&self.knots_v, V, v);
1228        let span_u = knot_find_span(&self.knots_u, U, u);
1229        let span_v = knot_find_span(&self.knots_v, V, v);
1230        let mut basis_u = [[0.0; MAX_STACK_ORDER]; 2];
1231        let mut basis_v = [[0.0; MAX_STACK_ORDER]; 2];
1232        basis_derivatives_into(&self.knots_u, U, span_u, u, 1, &mut basis_u);
1233        basis_derivatives_into(&self.knots_v, V, span_v, v, 1, &mut basis_v);
1234        let zero = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
1235        let sum = |k: usize, l: usize| {
1236            let mut value = zero;
1237            for i in 0..=U {
1238                let row = &self.control_points[span_u - U + i];
1239                for j in 0..=V {
1240                    value = value.add(row[span_v - V + j].scale(basis_u[k][i] * basis_v[l][j]));
1241                }
1242            }
1243            value
1244        };
1245        let (h00,h01,h10,h11) = (sum(0,0),sum(0,1),sum(1,0),sum(1,1));
1246        if h00.w.abs() <= EPS { return Err("NurbsSurface: zero evaluated weight".into()); }
1247        let inverse = 1.0 / h00.w;
1248        let point = Vec3::new(h00.x,h00.y,h00.z).scale(inverse);
1249        let sv = Vec3::new(h01.x,h01.y,h01.z).sub(point.scale(1.0*h01.w)).scale(inverse);
1250        let su = Vec3::new(h10.x,h10.y,h10.z).sub(point.scale(1.0*h10.w))
1251            .sub(Vec3::default().scale(1.0)).scale(inverse);
1252        let mixed = Vec3::default().add(point.scale(1.0*h11.w));
1253        let suv = Vec3::new(h11.x,h11.y,h11.z).sub(su.scale(1.0*h01.w))
1254            .sub(sv.scale(1.0*h10.w)).sub(mixed.scale(1.0)).scale(inverse);
1255        Ok((point,su,sv,suv))
1256    }
1257
1258    fn extension_anchor(&self, u: f64, v: f64) -> Result<(Vec3, Vec3, Vec3, Vec3), String> {
1259        match (self.degree_u,self.degree_v) {
1260            (1,1) => self.extension_anchor_fixed::<1,1>(u,v),
1261            (1,2) => self.extension_anchor_fixed::<1,2>(u,v),
1262            (1,3) => self.extension_anchor_fixed::<1,3>(u,v),
1263            (2,1) => self.extension_anchor_fixed::<2,1>(u,v),
1264            (2,2) => self.extension_anchor_fixed::<2,2>(u,v),
1265            (2,3) => self.extension_anchor_fixed::<2,3>(u,v),
1266            (3,1) => self.extension_anchor_fixed::<3,1>(u,v),
1267            (3,2) => self.extension_anchor_fixed::<3,2>(u,v),
1268            (3,3) => self.extension_anchor_fixed::<3,3>(u,v),
1269            _ => { let g = self.derivatives_small(u,v,2)?; Ok((g[0][0],g[1][0],g[0][1],g[1][1])) }
1270        }
1271    }
1272
1273    /// First-order extension using only the anchor terms that it consumes.
1274    pub fn deriv1_extended_trim(&self, u: f64, v: f64) -> Result<(Vec3, Vec3, Vec3), String> {
1275        self.deriv1_extended_impl(u,v,true)
1276    }
1277
1278    /// Allocation-free `(S, S_u, S_v)` twin of `derivatives_extended(u, v, 1)`.
1279    ///
1280    /// Mirrors the exact C¹ ruled/bilinear extension arithmetic of
1281    /// [`Self::derivatives_extended`] (only the count == 1 partials), but drives
1282    /// it from [`Self::derivatives_small`] so the in-domain and boundary-anchor
1283    /// evaluations allocate nothing. Bit-identical to
1284    /// `derivatives_extended(u, v, 1)` at `[0][0] / [1][0] / [0][1]`.
1285    pub fn deriv1_extended(&self, u: f64, v: f64) -> Result<(Vec3, Vec3, Vec3), String> {
1286        self.deriv1_extended_impl(u,v,false)
1287    }
1288
1289    fn deriv1_extended_impl(&self, u: f64, v: f64, reduced_anchor: bool) -> Result<(Vec3, Vec3, Vec3), String> {
1290        let [u0, u1] = self.domain_u()?;
1291        let [v0, v1] = self.domain_v()?;
1292        let (closed_u, closed_v) = self.closed_directions()?;
1293        let mut uu = u;
1294        let mut vv = v;
1295        if closed_u && (u < u0 || u > u1) {
1296            uu = u0 + (u - u0).rem_euclid(u1 - u0);
1297        }
1298        if closed_v && (v < v0 || v > v1) {
1299            vv = v0 + (v - v0).rem_euclid(v1 - v0);
1300        }
1301        let du_out = if uu < u0 {
1302            uu - u0
1303        } else if uu > u1 {
1304            uu - u1
1305        } else {
1306            0.0
1307        };
1308        let dv_out = if vv < v0 {
1309            vv - v0
1310        } else if vv > v1 {
1311            vv - v1
1312        } else {
1313            0.0
1314        };
1315        if du_out == 0.0 && dv_out == 0.0 {
1316            if reduced_anchor {
1317                match (self.degree_u,self.degree_v) {
1318                    (3,1) => return self.deriv1_small_fixed::<3,1>(uu,vv),
1319                    (1,3) => return self.deriv1_small_fixed::<1,3>(uu,vv),
1320                    (3,2) => return self.deriv1_small_fixed::<3,2>(uu,vv),
1321                    (2,3) => return self.deriv1_small_fixed::<2,3>(uu,vv),
1322                    (3,3) => return self.deriv1_small_fixed::<3,3>(uu,vv),
1323                    _ => {}
1324                }
1325            }
1326            if analytic_deriv1_on() && matches!((self.degree_u, self.degree_v), (1, 1) | (2, 1) | (1, 2) | (2, 2))
1327                && matches!(self.analytic(), Some(crate::AnalyticSurface::Plane { .. }
1328                    | crate::AnalyticSurface::RuledRevolution { .. } | crate::AnalyticSurface::Sphere { .. }
1329                    | crate::AnalyticSurface::Torus { .. })) {
1330                return match (self.degree_u, self.degree_v) {
1331                    (1, 1) => self.deriv1_small_fixed::<1, 1>(uu, vv),
1332                    (2, 1) => self.deriv1_small_fixed::<2, 1>(uu, vv),
1333                    (1, 2) => self.deriv1_small_fixed::<1, 2>(uu, vv),
1334                    (2, 2) => self.deriv1_small_fixed::<2, 2>(uu, vv),
1335                    _ => unreachable!(),
1336                };
1337            }
1338            let g = self.derivatives_small(uu, vv, 1)?;
1339            return Ok((g[0][0], g[1][0], g[0][1]));
1340        }
1341        let anchor_u = uu - du_out;
1342        let anchor_v = vv - dv_out;
1343        let (a00,a10,a01,a11) = if reduced_anchor {
1344            self.extension_anchor(anchor_u,anchor_v)?
1345        } else {
1346            let base = self.derivatives_small(anchor_u,anchor_v,2)?;
1347            (base[0][0],base[1][0],base[0][1],base[1][1])
1348        };
1349        // Bilinear extension: S = A00 + du·A10 + dv·A01 + du·dv·A11.
1350        // The mixed anchor derivative has total order two, even when
1351        // the caller requests only the value or first partials.
1352        let s = a00.add(a10.scale(du_out)).add(a01.scale(dv_out)).add(a11.scale(du_out * dv_out));
1353        let su = a10.add(a11.scale(dv_out));
1354        let sv = a01.add(a11.scale(du_out));
1355        Ok((s, su, sv))
1356    }
1357
1358    /// One first partial at `(u, v)` (clamped into the domain), `S_u` when
1359    /// `along_u`, else `S_v`, evaluated from the DIFFERENCES of the control net
1360    /// rather than from the basis derivatives.
1361    ///
1362    /// [`Self::derivatives`] forms `S_u = (A_u − W_u·S) / W` from `A_u = Σ N′ᵢ·Hᵢ`,
1363    /// a sum of terms the size of the control points whose exact total may be
1364    /// zero. Its rounding is therefore ABSOLUTE, a few ulps of the point, and
1365    /// where the partial itself vanishes (an isoline on which the
1366    /// parameterization is stationary, as on an extrusion of a cubic with
1367    /// coincident end poles) the DIRECTION of what is left is that rounding:
1368    /// measured 2.7e-15 of `x` on a partial of 7.7e-5 along `y`, a normal tilted
1369    /// by 3.5e-11.
1370    ///
1371    /// The hodograph `A_u = Σ N_{i+1,p−1}·p·(H_{i+1} − H_i)/(ξ_{i+p+1} − ξ_{i+1})`
1372    /// (The NURBS Book eq. 3.4, per row) carries the same partial with rounding
1373    /// that scales with its own terms: coincident control points difference to
1374    /// an exact zero, and every other difference is weighted by a basis function
1375    /// that vanishes with the partial. The rational part subtracts
1376    /// `W_u·S` with `W_u` taken from the weight differences, which is an exact
1377    /// zero wherever neighbouring weights are equal.
1378    ///
1379    /// Not bit-identical to `derivatives`, so it is read only where the bare
1380    /// partial has lost its direction (`offset/point.rs`). Refuses above the
1381    /// stack basis tables' degree.
1382    pub fn partial_by_differences(
1383        &self,
1384        along_u: bool,
1385        u: f64,
1386        v: f64,
1387    ) -> Result<Vec3, String> {
1388        self.ensure_valid()?;
1389        if self.degree_u > crate::curve::MAX_STACK_DEGREE || self.degree_v > crate::curve::MAX_STACK_DEGREE {
1390            return Err("NurbsSurface: partial by differences exceeds the stack degree".into());
1391        }
1392        let (pu, pv) = (self.degree_u, self.degree_v);
1393        let u = knot_clamp(&self.knots_u, pu, u);
1394        let v = knot_clamp(&self.knots_v, pv, v);
1395        let span_u = knot_find_span(&self.knots_u, pu, u);
1396        let span_v = knot_find_span(&self.knots_v, pv, v);
1397        let mut full_u = [0.0f64; MAX_STACK_ORDER];
1398        let mut full_v = [0.0f64; MAX_STACK_ORDER];
1399        basis_functions_into(&self.knots_u, pu, span_u, u, &mut full_u);
1400        basis_functions_into(&self.knots_v, pv, span_v, v, &mut full_v);
1401        let zero = Vec4 {
1402            x: 0.0,
1403            y: 0.0,
1404            z: 0.0,
1405            w: 0.0,
1406        };
1407        let control = |i: usize, j: usize| self.control_points[span_u - pu + i][span_v - pv + j];
1408        let mut point = zero;
1409        for i in 0..=pu {
1410            for j in 0..=pv {
1411                point = point.add(control(i, j).scale(full_u[i] * full_v[j]));
1412            }
1413        }
1414        if point.w.abs() <= EPS {
1415            return Err("NurbsSurface: zero evaluated weight".into());
1416        }
1417        let source = Vec3::new(point.x, point.y, point.z).scale(1.0 / point.w);
1418        let (knots, degree, span, parameter) = if along_u {
1419            (&self.knots_u, pu, span_u, u)
1420        } else {
1421            (&self.knots_v, pv, span_v, v)
1422        };
1423        if degree == 0 {
1424            return Ok(Vec3::default());
1425        }
1426        let mut lowered = [0.0f64; MAX_STACK_ORDER];
1427        basis_functions_into(knots, degree - 1, span, parameter, &mut lowered);
1428        // The hodograph's homogeneous value, Σ over the (degree) differences of
1429        // the basis span times the other direction's full basis.
1430        let mut hodograph = zero;
1431        for r in 0..degree {
1432            // Difference r joins control indices (span − degree + r) and
1433            // (span − degree + r + 1); its lowered basis is N_{span−degree+r+1, degree−1}.
1434            let index = span - degree + r;
1435            let width = knots[index + degree + 1] - knots[index + 1];
1436            if width.abs() <= EPS {
1437                continue;
1438            }
1439            let factor = lowered[r] * degree as f64 / width;
1440            if along_u {
1441                for j in 0..=pv {
1442                    let difference = control(r + 1, j).add(control(r, j).scale(-1.0));
1443                    hodograph = hodograph.add(difference.scale(factor * full_v[j]));
1444                }
1445            } else {
1446                for i in 0..=pu {
1447                    let difference = control(i, r + 1).add(control(i, r).scale(-1.0));
1448                    hodograph = hodograph.add(difference.scale(factor * full_u[i]));
1449                }
1450            }
1451        }
1452        Ok(Vec3::new(hodograph.x, hodograph.y, hodograph.z)
1453            .sub(source.scale(hodograph.w))
1454            .scale(1.0 / point.w))
1455    }
1456
1457    pub fn normal(&self, u: f64, v: f64) -> Result<Vec3, String> {
1458        if small_derivatives_enabled() {
1459            let derivatives = self.derivatives_small(u, v, 1)?;
1460            return derivatives[1][0].cross(derivatives[0][1]).normalized();
1461        }
1462        let derivatives = self.derivatives(u, v, 1)?;
1463        derivatives[1][0].cross(derivatives[0][1]).normalized()
1464    }
1465
1466    /// Principal curvatures (κ_min, κ_max) at (u, v), signed with respect to
1467    /// the parametrization normal n = Su × Sv / |Su × Sv| via the shape
1468    /// operator I⁻¹·II.  Convention check: a cylinder of radius R whose normal
1469    /// points AWAY from the axis has κ = −1/R along the circular direction, so
1470    /// an offset's regularity factor 1 − d·κ vanishes exactly when an inward
1471    /// offset (d = −R) reaches the axis.
1472    pub fn principal_curvatures(&self, u: f64, v: f64) -> Result<(f64, f64), String> {
1473        self.principal_curvatures_and_tangents(u, v)
1474            .map(|(kappa_min, kappa_max, _, _)| (kappa_min, kappa_max))
1475    }
1476
1477    /// [`Self::principal_curvatures`] together with the first derivatives
1478    /// `Su` and `Sv` it was read from, so a caller can judge how well
1479    /// conditioned the reading is without evaluating the surface twice.
1480    pub fn principal_curvatures_and_tangents(&self, u: f64, v: f64) -> Result<(f64, f64, Vec3, Vec3), String> {
1481        let derivatives: [[Vec3; 3]; 3] = if small_derivatives_enabled() {
1482            self.derivatives_small(u, v, 2)?
1483        } else {
1484            let heap = self.derivatives(u, v, 2)?;
1485            [[heap[0][0], heap[0][1], heap[0][2]], [heap[1][0], heap[1][1], Vec3::default()], [heap[2][0], Vec3::default(), Vec3::default()]]
1486        };
1487        let su = derivatives[1][0];
1488        let sv = derivatives[0][1];
1489        let cross = su.cross(sv);
1490        let cross_length = cross.length();
1491        if cross_length <= 1e-12 {
1492            return Err(format!(
1493                "degenerate parametrization at (u={u:.4}, v={v:.4})"
1494            ));
1495        }
1496        let normal = cross.scale(1.0 / cross_length);
1497        let e1 = su.dot(su);
1498        let f1 = su.dot(sv);
1499        let g1 = sv.dot(sv);
1500        let l2 = derivatives[2][0].dot(normal);
1501        let m2 = derivatives[1][1].dot(normal);
1502        let n2 = derivatives[0][2].dot(normal);
1503        let denominator = e1 * g1 - f1 * f1;
1504        let mean_double = (l2 * g1 - 2.0 * m2 * f1 + n2 * e1) / denominator; // 2H
1505        let gauss = (l2 * n2 - m2 * m2) / denominator; // K
1506        let discriminant = (mean_double * mean_double * 0.25 - gauss).max(0.0).sqrt();
1507        Ok((
1508            mean_double * 0.5 - discriminant,
1509            mean_double * 0.5 + discriminant,
1510            su,
1511            sv,
1512        ))
1513    }
1514
1515    /// Whether this is a genuinely affine degree-1 by degree-1 patch.
1516    ///
1517    /// A tapered bilinear patch is planar but not affine, so degree alone is
1518    /// insufficient for exact inverse-parameter and integration shortcuts.
1519    pub fn is_affine(&self) -> Result<bool, String> {
1520        if self.degree_u != 1
1521            || self.degree_v != 1
1522            || self.control_points.len() != 2
1523            || self.control_points[0].len() != 2
1524            || self.control_points[1].len() != 2
1525        {
1526            return Ok(false);
1527        }
1528        let weight = self.control_points[0][0].w;
1529        if [
1530            self.control_points[0][1].w,
1531            self.control_points[1][0].w,
1532            self.control_points[1][1].w,
1533        ]
1534        .iter()
1535        .any(|other| (*other - weight).abs() > 1e-12 * other.abs().max(weight.abs()))
1536        {
1537            return Ok(false);
1538        }
1539        let p00 = self.control_points[0][0].point()?;
1540        let p01 = self.control_points[0][1].point()?;
1541        let p10 = self.control_points[1][0].point()?;
1542        let p11 = self.control_points[1][1].point()?;
1543        let gap = p11.sub(p10).sub(p01.sub(p00)).length();
1544        // The parallelogram defect measures the non-affine bilinear term.
1545        // Scale it by the patch extent, never its distance from the origin:
1546        // falsely accepting a translated warped patch also labels it a plane
1547        // and sends its pcurves and offsets through exact affine shortcuts.
1548        let extent = [
1549            p01.sub(p00),
1550            p10.sub(p00),
1551            p11.sub(p00),
1552            p10.sub(p01),
1553            p11.sub(p01),
1554            p11.sub(p10),
1555        ]
1556        .iter()
1557        .map(|delta| delta.length())
1558        .fold(0.0, f64::max);
1559        Ok(gap <= 1e-9 * (1.0 + extent))
1560    }
1561
1562    pub fn iso_curve_u(&self, u: f64) -> Result<NurbsCurve, String> {
1563        self.ensure_valid()?;
1564        let u = knot_clamp(&self.knots_u, self.degree_u, u);
1565        let span = knot_find_span(&self.knots_u, self.degree_u, u);
1566        let basis = if self.degree_u <= MAX_STACK_DEGREE {
1567            let mut stack = [0.0f64; MAX_STACK_ORDER];
1568            basis_functions_into(&self.knots_u, self.degree_u, span, u, &mut stack);
1569            stack[..=self.degree_u].to_vec()
1570        } else {
1571            KnotVector::new(self.knots_u.clone(), self.degree_u)?.basis_functions(span, u)
1572        };
1573        let mut points = Vec::with_capacity(self.control_points[0].len());
1574        for column in 0..self.control_points[0].len() {
1575            let mut point = Vec4 {
1576                x: 0.0,
1577                y: 0.0,
1578                z: 0.0,
1579                w: 0.0,
1580            };
1581            for (index, value) in basis.iter().enumerate() {
1582                point = point
1583                    .add(self.control_points[span - self.degree_u + index][column].scale(*value));
1584            }
1585            points.push(point);
1586        }
1587        NurbsCurve::new(self.degree_v, self.knots_v.clone(), points)
1588    }
1589
1590    pub fn iso_curve_v(&self, v: f64) -> Result<NurbsCurve, String> {
1591        self.ensure_valid()?;
1592        let v = knot_clamp(&self.knots_v, self.degree_v, v);
1593        let span = knot_find_span(&self.knots_v, self.degree_v, v);
1594        let basis = if self.degree_v <= MAX_STACK_DEGREE {
1595            let mut stack = [0.0f64; MAX_STACK_ORDER];
1596            basis_functions_into(&self.knots_v, self.degree_v, span, v, &mut stack);
1597            stack[..=self.degree_v].to_vec()
1598        } else {
1599            KnotVector::new(self.knots_v.clone(), self.degree_v)?.basis_functions(span, v)
1600        };
1601        let mut points = Vec::with_capacity(self.control_points.len());
1602        for row in &self.control_points {
1603            let mut point = Vec4 {
1604                x: 0.0,
1605                y: 0.0,
1606                z: 0.0,
1607                w: 0.0,
1608            };
1609            for (index, value) in basis.iter().enumerate() {
1610                point = point.add(row[span - self.degree_v + index].scale(*value));
1611            }
1612            points.push(point);
1613        }
1614        NurbsCurve::new(self.degree_u, self.knots_u.clone(), points)
1615    }
1616}
1617
1618pub fn make_plane(
1619    origin: Vec3,
1620    u_direction: Vec3,
1621    v_direction: Vec3,
1622    u_max: f64,
1623    v_max: f64,
1624) -> Result<NurbsSurface, String> {
1625    if u_max <= EPS || v_max <= EPS {
1626        return Err("makePlane: parameter extents must be positive".into());
1627    }
1628    let p10 = origin.add(u_direction.scale(u_max));
1629    let p01 = origin.add(v_direction.scale(v_max));
1630    let p11 = p10.add(v_direction.scale(v_max));
1631    NurbsSurface::new(
1632        1,
1633        1,
1634        vec![0.0, 0.0, u_max, u_max],
1635        vec![0.0, 0.0, v_max, v_max],
1636        vec![
1637            vec![Vec4::from_point(origin, 1.0), Vec4::from_point(p01, 1.0)],
1638            vec![Vec4::from_point(p10, 1.0), Vec4::from_point(p11, 1.0)],
1639        ],
1640    )
1641}
1642
1643pub fn make_extrusion(profile: &NurbsCurve, direction: Vec3) -> Result<NurbsSurface, String> {
1644    let rows = profile
1645        .control_points
1646        .iter()
1647        .map(|point| {
1648            vec![
1649                *point,
1650                Vec4 {
1651                    x: point.x + point.w * direction.x,
1652                    y: point.y + point.w * direction.y,
1653                    z: point.z + point.w * direction.z,
1654                    w: point.w,
1655                },
1656            ]
1657        })
1658        .collect();
1659    NurbsSurface::new(
1660        profile.degree,
1661        1,
1662        profile.knots.clone(),
1663        vec![0.0, 0.0, 1.0, 1.0],
1664        rows,
1665    )
1666}
1667
1668pub fn make_revolution(
1669    axis_point: Vec3,
1670    axis_direction: Vec3,
1671    generatrix: &NurbsCurve,
1672    theta: f64,
1673) -> Result<NurbsSurface, String> {
1674    revolution_in_spans(axis_point, axis_direction, generatrix, theta, None)
1675}
1676
1677/// [`make_revolution`] with the turn in ONE rational quadratic span (middle
1678/// weight cos(theta/2)) for `theta` under 180 degrees, where
1679/// `make_revolution` splits past 90. Its circles then run at the parameter of
1680/// a one-conic arc of the same turn, so an edge built that way lies on an
1681/// iso line of it. Up to 90 degrees the two are the same surface.
1682pub fn make_revolution_one_span(
1683    axis_point: Vec3,
1684    axis_direction: Vec3,
1685    generatrix: &NurbsCurve,
1686    theta: f64,
1687) -> Result<NurbsSurface, String> {
1688    if !(theta < std::f64::consts::PI - 1e-6) {
1689        return Err("makeRevolution: one span needs theta under PI".into());
1690    }
1691    revolution_in_spans(axis_point, axis_direction, generatrix, theta, Some(1))
1692}
1693
1694fn revolution_in_spans(
1695    axis_point: Vec3,
1696    axis_direction: Vec3,
1697    generatrix: &NurbsCurve,
1698    theta: f64,
1699    spans: Option<usize>,
1700) -> Result<NurbsSurface, String> {
1701    if theta <= EPS || theta > std::f64::consts::TAU + EPS {
1702        return Err("makeRevolution: theta must be in (0, 2*PI]".into());
1703    }
1704    let theta = theta.min(std::f64::consts::TAU);
1705    let axis = axis_direction.normalized()?;
1706    let arc_count = spans.unwrap_or_else(|| ((theta / std::f64::consts::FRAC_PI_2 - EPS).ceil() as usize).clamp(1, 4));
1707    let arc_angle = theta / arc_count as f64;
1708    let middle_weight = (arc_angle / 2.0).cos();
1709    let mut knots_u = vec![0.0, 0.0, 0.0];
1710    for index in 1..arc_count {
1711        let knot = index as f64 / arc_count as f64;
1712        knots_u.extend([knot, knot]);
1713    }
1714    knots_u.extend([1.0, 1.0, 1.0]);
1715    let mut rows = vec![
1716        vec![
1717            Vec4 {
1718                x: 0.0,
1719                y: 0.0,
1720                z: 0.0,
1721                w: 1.0,
1722            };
1723            generatrix.control_points.len()
1724        ];
1725        2 * arc_count + 1
1726    ];
1727
1728    // How far the generatrix reaches from the axis — the scale every "is this
1729    // control point on the axis?" question below is measured against.
1730    let mut radial_extent: f64 = 0.0;
1731    for control_point in &generatrix.control_points {
1732        let point = control_point.point()?;
1733        let offset = point.sub(axis_point);
1734        radial_extent = radial_extent.max(offset.sub(axis.scale(offset.dot(axis))).length());
1735    }
1736
1737    for (column, control_point) in generatrix.control_points.iter().enumerate() {
1738        let point = control_point.point()?;
1739        let weight = control_point.w;
1740        let axis_origin = axis_point.add(axis.scale(point.sub(axis_point).dot(axis)));
1741        let radial_vector = point.sub(axis_origin);
1742        // On-axis classification must be RELATIVE like the fuzzy band below:
1743        // the absolute EPS floor alone broke when the importer's mm conversion
1744        // scaled vendor pole noise (1.5e-13 m -> 1.5e-10 mm) past it, hard-
1745        // rejecting files whose poles are intended on-axis. 1e-8 of the radial
1746        // extent snaps that noise to an EXACT pole (radius 0, so every
1747        // downstream `radius <= EPS` branch takes the degenerate path):
1748        // corpus vendor noise measures up to ~2e-9 relative, and the
1749        // 1e-6-relative nudge the fuzzy-pole test rejects stays two decades
1750        // above the snap.
1751        let measured_radius = radial_vector.length();
1752        let pole_tolerance = EPS.max(1e-8 * radial_extent);
1753        let radius = if measured_radius <= pole_tolerance {
1754            0.0
1755        } else {
1756            measured_radius
1757        };
1758        let (x_axis, y_axis) = if radius <= EPS {
1759            (Vec3::default(), Vec3::default())
1760        } else {
1761            // A control point is either ON the axis — the degenerate pole row
1762            // above, whose rotation is a fixed point — or clearly off it. In
1763            // between the revolution carries a fuzzy PINCH where a pole was
1764            // meant to be, which downstream code (analytic recognition, pair
1765            // classification, the imprint) reads as an ordinary tiny circle:
1766            // refuse it here instead. This refusal used to fall out of the
1767            // parallel-tangent guard below, whose ABSOLUTE floor made it
1768            // "radius <= 1e-3" — which on a metre-unit STEP file rejected every
1769            // healthy 1.524e-4 cylinder in the part. Relative to the
1770            // generatrix's own radial extent it catches the fuzzy pole at any
1771            // model scale and lets real geometry through at any size.
1772            if radius <= NEAR_AXIS_RELATIVE_TOLERANCE * radial_extent {
1773                return Err(format!(
1774                    "makeRevolution: generatrix control point {column} sits {radius:e} from the \
1775                     axis, neither on it nor clear of it against the generatrix's {radial_extent:e} \
1776                     radial extent (a fuzzy pole)"
1777                ));
1778            }
1779            let x_axis = radial_vector.scale(1.0 / radius);
1780            (x_axis, axis.cross(x_axis))
1781        };
1782        rows[0][column] = Vec4::from_point(point, weight);
1783        let mut start_point = point;
1784        let mut start_tangent = y_axis.scale(radius);
1785        let mut angle = 0.0;
1786        for arc in 1..=arc_count {
1787            angle += arc_angle;
1788            let end_point = if radius <= EPS {
1789                point
1790            } else {
1791                axis_origin
1792                    .add(x_axis.scale(radius * angle.cos()))
1793                    .add(y_axis.scale(radius * angle.sin()))
1794            };
1795            let end_tangent = if radius <= EPS {
1796                Vec3::default()
1797            } else {
1798                x_axis
1799                    .scale(-radius * angle.sin())
1800                    .add(y_axis.scale(radius * angle.cos()))
1801            };
1802            let row = 2 * (arc - 1);
1803            if radius <= EPS {
1804                rows[row + 1][column] = Vec4::from_point(point, weight * middle_weight);
1805            } else {
1806                let cross = start_tangent.cross(end_tangent);
1807                let denominator = cross.length_squared();
1808                // Both tangents have length `radius`, so `denominator` is
1809                // radius^4 * sin^2(arc_angle) and an ABSOLUTE floor here reads
1810                // as "radius <= 1e-3", conflating a small part with a
1811                // degenerate sweep. Parallel tangents are purely an ANGULAR
1812                // condition, so scale the floor by the tangent lengths: the
1813                // test becomes sin^2(arc_angle) <= EPS, exactly what make_arc
1814                // applies to its already-unit tangents. Near-axis control
1815                // points are the near-axis check's business, above.
1816                let tangent_scale = start_tangent.length_squared() * end_tangent.length_squared();
1817                if denominator <= EPS * tangent_scale {
1818                    return Err("makeRevolution: arc tangents are parallel".into());
1819                }
1820                let distance =
1821                    end_point.sub(start_point).cross(end_tangent).dot(cross) / denominator;
1822                let middle = start_point.add(start_tangent.scale(distance));
1823                rows[row + 1][column] = Vec4::from_point(middle, weight * middle_weight);
1824            }
1825            rows[row + 2][column] = Vec4::from_point(end_point, weight);
1826            start_point = end_point;
1827            start_tangent = end_tangent;
1828        }
1829    }
1830    NurbsSurface::new(
1831        2,
1832        generatrix.degree,
1833        knots_u,
1834        generatrix.knots.clone(),
1835        rows,
1836    )
1837}
1838
1839pub fn make_cylinder_surface(
1840    base: Vec3,
1841    axis_direction: Vec3,
1842    radius: f64,
1843    height: f64,
1844) -> Result<NurbsSurface, String> {
1845    if radius <= EPS || height <= EPS {
1846        return Err("makeCylinder: radius and height must be positive".into());
1847    }
1848    let axis = axis_direction.normalized()?;
1849    let x_axis = axis.perpendicular()?;
1850    let start = base.add(x_axis.scale(radius));
1851    let end = start.add(axis.scale(height));
1852    let generatrix = crate::make_line(start, end)?;
1853    make_revolution(base, axis, &generatrix, std::f64::consts::TAU)
1854}
1855
1856pub fn make_cone_surface(
1857    base: Vec3,
1858    axis_direction: Vec3,
1859    radius_bottom: f64,
1860    radius_top: f64,
1861    height: f64,
1862) -> Result<NurbsSurface, String> {
1863    if radius_bottom <= EPS || radius_top < 0.0 || height <= EPS {
1864        return Err("makeCone: invalid radius or height".into());
1865    }
1866    let axis = axis_direction.normalized()?;
1867    let x_axis = axis.perpendicular()?;
1868    let start = base.add(x_axis.scale(radius_bottom));
1869    let end = base.add(axis.scale(height)).add(x_axis.scale(radius_top));
1870    let generatrix = crate::make_line(start, end)?;
1871    make_revolution(base, axis, &generatrix, std::f64::consts::TAU)
1872}
1873
1874pub fn make_sphere_surface(
1875    center: Vec3,
1876    radius: f64,
1877    polar_axis: Vec3,
1878) -> Result<NurbsSurface, String> {
1879    make_sphere_surface_framed(center, radius, polar_axis, None)
1880}
1881
1882/// A sphere with BOTH halves of its frame chosen: the polar axis (where the two
1883/// degenerate poles sit) and the SEAM direction (where the `u = 0` meridian
1884/// runs). `seam_direction` is Gram-Schmidt'd against the axis; `None` — and a
1885/// seam parallel to the axis, which names no meridian — falls back to
1886/// [`Vec3::perpendicular`], i.e. exactly what [`make_sphere_surface`] builds.
1887///
1888/// A caller that KNOWS where the sphere will be trimmed uses this to park the
1889/// poles and the seam inside the region the trim removes, so the surviving face
1890/// carries neither. `feature_pipeline::features::tube` does that for its joint
1891/// balls: a seam that survives into the result is an edge bordering ONE face,
1892/// which is a real edge in the topology and a visible line on the model.
1893pub fn make_sphere_surface_framed(
1894    center: Vec3,
1895    radius: f64,
1896    polar_axis: Vec3,
1897    seam_direction: Option<Vec3>,
1898) -> Result<NurbsSurface, String> {
1899    if radius <= EPS {
1900        return Err("makeSphere: radius must be positive".into());
1901    }
1902    let axis = polar_axis.normalized()?;
1903    let x_axis = match seam_direction {
1904        Some(seam) => {
1905            let planar = seam.sub(axis.scale(seam.dot(axis)));
1906            match planar.normalized() {
1907                Ok(unit) if planar.length() > EPS => unit,
1908                _ => axis.perpendicular()?,
1909            }
1910        }
1911        None => axis.perpendicular()?,
1912    };
1913    let meridian = crate::make_arc(
1914        center,
1915        x_axis,
1916        axis,
1917        radius,
1918        -std::f64::consts::FRAC_PI_2,
1919        std::f64::consts::FRAC_PI_2,
1920    )?;
1921    make_revolution(center, axis, &meridian, std::f64::consts::TAU)
1922}
1923
1924pub fn make_torus_surface(
1925    center: Vec3,
1926    axis_direction: Vec3,
1927    major_radius: f64,
1928    minor_radius: f64,
1929) -> Result<NurbsSurface, String> {
1930    if minor_radius <= EPS || major_radius <= minor_radius {
1931        return Err("makeTorus: requires positive minorRadius < majorRadius".into());
1932    }
1933    let axis = axis_direction.normalized()?;
1934    let x_axis = axis.perpendicular()?;
1935    let tube_center = center.add(x_axis.scale(major_radius));
1936    let tube = crate::make_arc(
1937        tube_center,
1938        x_axis,
1939        axis,
1940        minor_radius,
1941        0.0,
1942        std::f64::consts::TAU,
1943    )?;
1944    make_revolution(center, axis, &tube, std::f64::consts::TAU)
1945}
1946
1947fn binomial(n: usize, k: usize) -> f64 {
1948    if k > n {
1949        return 0.0;
1950    }
1951    let k = k.min(n - k);
1952    (1..=k).fold(1.0, |value, index| {
1953        value * (n - k + index) as f64 / index as f64
1954    })
1955}
1956
1957
1958
1959/// Diagnostic "carrier preview" patch (§3.15 applied to display): re-express
1960/// the surface over an INFLATED domain so an inspector can show where the
1961/// carrier continues beyond the face's trim. Open directions inflate about
1962/// the domain centre by `inflate` (a factor; 1 = unchanged), evaluated
1963/// through `evaluate_extended` — exact linear extension for affine carriers,
1964/// ruled/tangent extension generally. CLOSED (periodic) directions keep the
1965/// stored full period instead of inflating — wrapping further would overlap
1966/// the surface onto itself. A torus (closed both ways) returns unchanged.
1967///
1968/// Affine carriers rebuild EXACTLY from four extended corners; everything
1969/// else is a preview-quality degree-3 interpolation over a 33-sample grid.
1970pub fn carrier_preview_patch(surface: &NurbsSurface, inflate: f64) -> Result<NurbsSurface, String> {
1971    let inflate = if inflate.is_finite() {
1972        inflate.clamp(1.0, 16.0)
1973    } else {
1974        2.0
1975    };
1976    let (closed_u, closed_v) = surface.closed_directions()?;
1977    let [u0, u1] = surface.domain_u()?;
1978    let [v0, v1] = surface.domain_v()?;
1979    let stretch = |d0: f64, d1: f64, closed: bool| -> (f64, f64) {
1980        if closed || inflate <= 1.0 {
1981            (d0, d1)
1982        } else {
1983            let centre = 0.5 * (d0 + d1);
1984            let half = 0.5 * (d1 - d0) * inflate;
1985            (centre - half, centre + half)
1986        }
1987    };
1988    let (nu0, nu1) = stretch(u0, u1, closed_u);
1989    let (nv0, nv1) = stretch(v0, v1, closed_v);
1990    if (nu0, nu1) == (u0, u1) && (nv0, nv1) == (v0, v1) {
1991        return Ok(surface.clone());
1992    }
1993    if surface.is_affine()? {
1994        // Exact: the linear extension of an affine patch is the same affine
1995        // map over the larger rectangle.
1996        let corners = [
1997            surface.evaluate_extended(nu0, nv0)?,
1998            surface.evaluate_extended(nu1, nv0)?,
1999            surface.evaluate_extended(nu0, nv1)?,
2000            surface.evaluate_extended(nu1, nv1)?,
2001        ];
2002        return NurbsSurface::new(
2003            1,
2004            1,
2005            vec![nu0, nu0, nu1, nu1],
2006            vec![nv0, nv0, nv1, nv1],
2007            vec![
2008                vec![
2009                    Vec4::from_point(corners[0], 1.0),
2010                    Vec4::from_point(corners[2], 1.0),
2011                ],
2012                vec![
2013                    Vec4::from_point(corners[1], 1.0),
2014                    Vec4::from_point(corners[3], 1.0),
2015                ],
2016            ],
2017        );
2018    }
2019    const SAMPLES: usize = 32;
2020    let u_params: Vec<f64> = (0..=SAMPLES)
2021        .map(|index| nu0 + (nu1 - nu0) * index as f64 / SAMPLES as f64)
2022        .collect();
2023    let v_params: Vec<f64> = (0..=SAMPLES)
2024        .map(|index| nv0 + (nv1 - nv0) * index as f64 / SAMPLES as f64)
2025        .collect();
2026    // Two-pass grid interpolation: fit each v-column, then fit the resulting
2027    // control rows across u, sharing knots per pass (identical parameters).
2028    let mut column_curves = Vec::with_capacity(u_params.len());
2029    for &u in &u_params {
2030        let column: Vec<Vec3> = v_params
2031            .iter()
2032            .map(|&v| surface.evaluate_extended(u, v))
2033            .collect::<Result<_, _>>()?;
2034        column_curves.push(crate::interpolate_curve(
2035            &column,
2036            3,
2037            &normalized(&v_params),
2038        )?);
2039    }
2040    let v_knots = column_curves[0].knots.clone();
2041    let control_rows = column_curves[0].control_points.len();
2042    let mut grid: Vec<Vec<Vec4>> = Vec::with_capacity(u_params.len());
2043    let mut u_knots = Vec::new();
2044    for row_index in 0..control_rows {
2045        let row: Vec<Vec3> = column_curves
2046            .iter()
2047            .map(|curve| curve.control_points[row_index].point())
2048            .collect::<Result<_, _>>()?;
2049        let fitted = crate::interpolate_curve(&row, 3, &normalized(&u_params))?;
2050        u_knots = fitted.knots.clone();
2051        for (u_index, control) in fitted.control_points.iter().enumerate() {
2052            if grid.len() <= u_index {
2053                grid.push(Vec::new());
2054            }
2055            grid[u_index].push(*control);
2056        }
2057    }
2058    // Re-scale the normalized fit knots back onto the inflated domains so the
2059    // preview's parameter space lines up with the original surface's.
2060    let rescale = |knots: &[f64], d0: f64, d1: f64| -> Vec<f64> {
2061        knots.iter().map(|k| d0 + (d1 - d0) * k).collect()
2062    };
2063    NurbsSurface::new(
2064        3,
2065        3,
2066        rescale(&u_knots, nu0, nu1),
2067        rescale(&v_knots, nv0, nv1),
2068        grid,
2069    )
2070}
2071
2072fn normalized(parameters: &[f64]) -> Vec<f64> {
2073    let first = parameters[0];
2074    let last = parameters[parameters.len() - 1];
2075    parameters
2076        .iter()
2077        .map(|p| (p - first) / (last - first))
2078        .collect()
2079}
2080
2081
2082
2083
2084
2085fn analytic_deriv1_on() -> bool {
2086    switch!("BREP_ANALYTIC_DERIV1", true)
2087}
2088
2089
2090/// Default-off until the evaluator's bitwise and complete-body gates qualify it.
2091fn analytic_point_on() -> bool {
2092    switch!("BREP_ANALYTIC_POINT", false)
2093}
2094
2095/// SMALL DERIVATIVES (lane O row 20, 2026-10-29; on by default since the batch 5
2096/// promotion, `BREP_SURFACE_SMALL_DERIVATIVES=0` reads the heap grid): `evaluate_extended`, `derivatives_extended` up to second order,
2097/// `normal` and `principal_curvatures` read the stack twin
2098/// [`NurbsSurface::derivatives_small`] instead of the heap grid. A third of the
2099/// D2 outward shell's heap allocations were `NurbsSurface::derivatives` (a
2100/// sampled-backtrace allocation census); the values are the same bits.
2101pub fn small_derivatives_enabled() -> bool {
2102    switch!("BREP_SURFACE_SMALL_DERIVATIVES", true)
2103}
2104
2105
2106
2107
2108
2109