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        // The benchy's support carriers are low-degree sweeps: (2, 1) and
795        // (3, 1) rulings, (3, 2) and (3, 3) walls, (1, 1) planes, in either
796        // orientation. Fixed, their tensor loops unroll.
797        match (self.degree_u, self.degree_v) {
798            (1, 1) => self.derivatives_small_degrees::<1, 1, COUNT>(u, v, COUNT),
799            (2, 1) => self.derivatives_small_degrees::<2, 1, COUNT>(u, v, COUNT),
800            (1, 2) => self.derivatives_small_degrees::<1, 2, COUNT>(u, v, COUNT),
801            (3, 1) => self.derivatives_small_degrees::<3, 1, COUNT>(u, v, COUNT),
802            (1, 3) => self.derivatives_small_degrees::<1, 3, COUNT>(u, v, COUNT),
803            (2, 2) => self.derivatives_small_degrees::<2, 2, COUNT>(u, v, COUNT),
804            (3, 2) => self.derivatives_small_degrees::<3, 2, COUNT>(u, v, COUNT),
805            (2, 3) => self.derivatives_small_degrees::<2, 3, COUNT>(u, v, COUNT),
806            (3, 3) => self.derivatives_small_degrees::<3, 3, COUNT>(u, v, COUNT),
807            (3, 9) => self.derivatives_small_degrees::<3, 9, COUNT>(u, v, COUNT),
808            (5, 9) => self.derivatives_small_degrees::<5, 9, COUNT>(u, v, COUNT),
809            _ => self.derivatives_small_degrees::<{usize::MAX}, {usize::MAX}, COUNT>(u, v, COUNT),
810        }
811    }
812
813    // The same recurrence and control-point order, with partial count and common
814    // screw-wall degrees fixed so bounds and loop trips can fold. MAX retains
815    // the runtime argument for the generic path and its bitwise comparison.
816    fn derivatives_small_degrees<const U: usize, const V: usize, const COUNT: usize>(
817        &self, u: f64, v: f64, derivative_count: usize,
818    ) -> Result<[[Vec3; 3]; 3], String> {
819        let degree_u = if U == usize::MAX { self.degree_u } else { U };
820        let degree_v = if V == usize::MAX { self.degree_v } else { V };
821        let derivative_count = if COUNT == usize::MAX { derivative_count } else { COUNT };
822        // Row zero of the derivative basis has the value recurrence's exact
823        // arithmetic. Keep its row-major sum and reciprocal multiplication,
824        // but avoid the derivative scratch grids for a point-only request.
825        // The experimental analytic evaluator is a separate policy: retain
826        // the original derivative path whenever that policy is enabled.
827        if derivative_count == 0 && switch!("BREP_SURFACE_POINT_ONLY", false)
828            && u.is_finite() && v.is_finite()
829            && degree_u <= MAX_STACK_DEGREE && degree_v <= MAX_STACK_DEGREE
830            && !analytic_point_on() {
831            let point = self.evaluate_homogeneous(u, v)?;
832            if point.w.abs() <= EPS {
833                return Err("NurbsSurface: zero evaluated weight".into());
834            }
835            let mut result = [[Vec3::default(); 3]; 3];
836            result[0][0] = Vec3::new(point.x, point.y, point.z).scale(1.0 / point.w);
837            return Ok(result);
838        }
839        debug_assert!(derivative_count <= 2);
840        self.ensure_valid()?;
841        let du = derivative_count.min(degree_u);
842        let dv = derivative_count.min(degree_v);
843        let stride = derivative_count + 1;
844        let zero = Vec4 {
845            x: 0.0,
846            y: 0.0,
847            z: 0.0,
848            w: 0.0,
849        };
850        let mut homogeneous = [zero; 9];
851        if degree_u <= MAX_STACK_DEGREE && degree_v <= MAX_STACK_DEGREE {
852            let u = knot_clamp(&self.knots_u, degree_u, u);
853            let v = knot_clamp(&self.knots_v, degree_v, v);
854            let span_u = knot_find_span(&self.knots_u, degree_u, u);
855            let span_v = knot_find_span(&self.knots_v, degree_v, v);
856            // Rows `..=du` / `..=dv` (at most three) are the only ones written
857            // or read; the eight-row fill was a measurable share of a sign
858            // reading's surface station (2026-11-02).
859            let mut basis_u = [[0.0f64; MAX_STACK_ORDER]; 3];
860            let mut basis_v = [[0.0f64; MAX_STACK_ORDER]; 3];
861            basis_derivatives_into(
862                &self.knots_u,
863                degree_u,
864                span_u,
865                u,
866                du,
867                &mut basis_u[..=du],
868            );
869            basis_derivatives_into(
870                &self.knots_v,
871                degree_v,
872                span_v,
873                v,
874                dv,
875                &mut basis_v[..=dv],
876            );
877            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
878            for k in 0..=du {
879                for l in 0..=dv {
880                    if k + l > derivative_count {
881                        continue;
882                    }
883                    let mut point = zero;
884                    for i in 0..=degree_u {
885                        let row = &self.control_points[span_u - degree_u + i][span_v - degree_v..=span_v];
886                        for j in 0..=degree_v {
887                            point = point.add(
888                                row[j]
889                                    .scale(basis_u[k][i] * basis_v[l][j]),
890                            );
891                        }
892                    }
893                    homogeneous[k * stride + l] = point;
894                }
895            }
896        } else {
897            let (knot_u, knot_v) = self.knot_vectors()?;
898            let u = knot_u.clamp_param(u);
899            let v = knot_v.clamp_param(v);
900            let span_u = knot_u.find_span(u);
901            let span_v = knot_v.find_span(v);
902            let basis_u = knot_u.basis_derivatives(span_u, u, du);
903            let basis_v = knot_v.basis_derivatives(span_v, v, dv);
904            let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
905            for k in 0..=du {
906                for l in 0..=dv {
907                    if k + l > derivative_count {
908                        continue;
909                    }
910                    let mut point = zero;
911                    for i in 0..=degree_u {
912                        let row = &self.control_points[span_u - degree_u + i];
913                        for j in 0..=degree_v {
914                            point = point.add(
915                                row[span_v - degree_v + j]
916                                    .scale(basis_u[k][i] * basis_v[l][j]),
917                            );
918                        }
919                    }
920                    homogeneous[k * stride + l] = point;
921                }
922            }
923        }
924
925        let mut result = [[Vec3::default(); 3]; 3];
926        let weight = homogeneous[0].w;
927        if weight.abs() <= EPS {
928            return Err("NurbsSurface: zero evaluated weight".into());
929        }
930        for k in 0..=derivative_count {
931            for l in 0..=derivative_count - k {
932                if k > du || l > dv {
933                    continue;
934                }
935                let at = |row: usize, column: usize| homogeneous[row * stride + column];
936                let mut value = Vec3::new(at(k, l).x, at(k, l).y, at(k, l).z);
937                for j in 1..=l {
938                    value = value.sub(result[k][l - j].scale(binomial(l, j) * at(0, j).w));
939                }
940                for i in 1..=k {
941                    value = value.sub(result[k - i][l].scale(binomial(k, i) * at(i, 0).w));
942                    let mut mixed = Vec3::default();
943                    for j in 1..=l {
944                        mixed = mixed.add(result[k - i][l - j].scale(binomial(l, j) * at(i, j).w));
945                    }
946                    value = value.sub(mixed.scale(binomial(k, i)));
947                }
948                result[k][l] = value.scale(1.0 / weight);
949            }
950        }
951        Ok(result)
952    }
953
954    /// Whether [`Self::deriv1_tensor_each`] can drive this patch: the stack
955    /// basis tables only reach `MAX_STACK_DEGREE`, and a higher-degree patch
956    /// must be evaluated station by station through [`Self::deriv1`].
957    #[inline]
958    pub fn deriv1_tensor_supported(&self) -> bool {
959        self.degree_u <= MAX_STACK_DEGREE && self.degree_v <= MAX_STACK_DEGREE
960    }
961
962    /// `(S, S_u, S_v)` at every station of the TENSOR BLOCK `us x vs`, handed
963    /// to `f` as `(u index, v index, S, S_u, S_v)` with `us` outer and `vs`
964    /// inner.
965    ///
966    /// Bit-identical to calling [`Self::deriv1`] at each pair, and that is the
967    /// whole point of it: the block's `us.len() + vs.len()` spans and basis
968    /// rows are evaluated ONCE each instead of once per station, which is
969    /// where a fixed tensor-Gauss cell spends most of its time (the basis
970    /// recurrence carries a division per knot per derivative order, and an
971    /// 8x8 cell asks for the same 8 u rows and 8 v rows sixty-four times).
972    /// Nothing else changes: `knot_clamp` / `knot_find_span` /
973    /// `basis_derivatives_into` see the same arguments and so return the same
974    /// floats, the control-point sum runs in the same row-outer/column-inner
975    /// order from the same zero `Vec4`, and the rational de-homogenization is
976    /// [`Self::derivatives_small`]'s recurrence written out for
977    /// `derivative_count == 1`.
978    ///
979    /// Two steps of that recurrence are elided because they are exact no-ops
980    /// at this order: `binomial(1, 1)` is exactly `1.0`, and the mixed term it
981    /// scales is the zero vector, whose subtraction leaves every component
982    /// (including a negative zero) bit-unchanged.
983    pub fn deriv1_tensor_each<F>(
984        &self,
985        us: &[f64],
986        vs: &[f64],
987        mut f: F,
988    ) -> Result<(), String>
989    where
990        F: FnMut(usize, usize, Vec3, Vec3, Vec3) -> Result<(), String>,
991    {
992        self.ensure_valid()?;
993        // Width and rationale: `TENSOR_MAX_BLOCK` at the top of this module.
994        const MAX_BLOCK: usize = TENSOR_MAX_BLOCK;
995        if !self.deriv1_tensor_supported() || us.len() > MAX_BLOCK || vs.len() > MAX_BLOCK {
996            return Err("NurbsSurface: tensor block outside the stack evaluator".into());
997        }
998        let du = 1usize.min(self.degree_u);
999        let dv = 1usize.min(self.degree_v);
1000        let mut span_u = [0usize; MAX_BLOCK];
1001        let mut span_v = [0usize; MAX_BLOCK];
1002        let mut basis_u = [[[0.0f64; MAX_STACK_ORDER]; 2]; MAX_BLOCK];
1003        let mut basis_v = [[[0.0f64; MAX_STACK_ORDER]; 2]; MAX_BLOCK];
1004        for (index, &value) in us.iter().enumerate() {
1005            let value = knot_clamp(&self.knots_u, self.degree_u, value);
1006            span_u[index] = knot_find_span(&self.knots_u, self.degree_u, value);
1007            basis_derivatives_into(
1008                &self.knots_u,
1009                self.degree_u,
1010                span_u[index],
1011                value,
1012                du,
1013                &mut basis_u[index][..=du],
1014            );
1015        }
1016        for (index, &value) in vs.iter().enumerate() {
1017            let value = knot_clamp(&self.knots_v, self.degree_v, value);
1018            span_v[index] = knot_find_span(&self.knots_v, self.degree_v, value);
1019            basis_derivatives_into(
1020                &self.knots_v,
1021                self.degree_v,
1022                span_v[index],
1023                value,
1024                dv,
1025                &mut basis_v[index][..=dv],
1026            );
1027        }
1028        if tensor_fused_on() {
1029            let (count_u, count_v) = (us.len(), vs.len());
1030            let tables = (&span_u, &span_v, &basis_u, &basis_v);
1031            match (self.degree_u, self.degree_v) {
1032                (1, 1) => return self.deriv1_tensor_fused::<1, 1, F>(count_u, count_v, tables, &mut f),
1033                (1, 2) => return self.deriv1_tensor_fused::<1, 2, F>(count_u, count_v, tables, &mut f),
1034                (1, 3) => return self.deriv1_tensor_fused::<1, 3, F>(count_u, count_v, tables, &mut f),
1035                (2, 1) => return self.deriv1_tensor_fused::<2, 1, F>(count_u, count_v, tables, &mut f),
1036                (2, 2) => return self.deriv1_tensor_fused::<2, 2, F>(count_u, count_v, tables, &mut f),
1037                (2, 3) => return self.deriv1_tensor_fused::<2, 3, F>(count_u, count_v, tables, &mut f),
1038                (3, 1) => return self.deriv1_tensor_fused::<3, 1, F>(count_u, count_v, tables, &mut f),
1039                (3, 2) => return self.deriv1_tensor_fused::<3, 2, F>(count_u, count_v, tables, &mut f),
1040                (3, 3) => return self.deriv1_tensor_fused::<3, 3, F>(count_u, count_v, tables, &mut f),
1041                _ => {}
1042            }
1043        }
1044        let zero = Vec4 {
1045            x: 0.0,
1046            y: 0.0,
1047            z: 0.0,
1048            w: 0.0,
1049        };
1050        for i in 0..us.len() {
1051            let rows = &self.control_points[span_u[i] - self.degree_u..];
1052            for j in 0..vs.len() {
1053                let column = span_v[j] - self.degree_v;
1054                // The (k, l) homogeneous grid `derivatives_small` builds for
1055                // `derivative_count == 1`: (0,0) always, (0,1) when dv >= 1,
1056                // (1,0) when du >= 1.
1057                let sum = |k: usize, l: usize| {
1058                    let mut point = zero;
1059                    for row_index in 0..=self.degree_u {
1060                        let row = &rows[row_index];
1061                        for column_index in 0..=self.degree_v {
1062                            point = point.add(
1063                                row[column + column_index]
1064                                    .scale(basis_u[i][k][row_index] * basis_v[j][l][column_index]),
1065                            );
1066                        }
1067                    }
1068                    point
1069                };
1070                let h00 = sum(0, 0);
1071                let h01 = if dv >= 1 { sum(0, 1) } else { zero };
1072                let h10 = if du >= 1 { sum(1, 0) } else { zero };
1073                let weight = h00.w;
1074                if weight.abs() <= EPS {
1075                    return Err("NurbsSurface: zero evaluated weight".into());
1076                }
1077                let inverse = 1.0 / weight;
1078                let point = Vec3::new(h00.x, h00.y, h00.z).scale(inverse);
1079                let partial_v = if dv >= 1 {
1080                    Vec3::new(h01.x, h01.y, h01.z)
1081                        .sub(point.scale(h01.w))
1082                        .scale(inverse)
1083                } else {
1084                    Vec3::default()
1085                };
1086                let partial_u = if du >= 1 {
1087                    Vec3::new(h10.x, h10.y, h10.z)
1088                        .sub(point.scale(h10.w))
1089                        .scale(inverse)
1090                } else {
1091                    Vec3::default()
1092                };
1093                f(i, j, point, partial_u, partial_v)?;
1094            }
1095        }
1096        Ok(())
1097    }
1098
1099    /// [`Self::deriv1_tensor_each`]'s station loop for a patch of degrees
1100    /// `DEGREE_U × DEGREE_V`, both at least 1, from the block's span and basis
1101    /// tables. The same bits as the run-time-degree loop: each of the three
1102    /// homogeneous sums (`S`, `∂_v`, `∂_u`) gets the same products
1103    /// `basis_u · basis_v` of the same control points, scaled and then added in
1104    /// the same row-outer, column-inner order from the same zero `Vec4`, and
1105    /// the dehomogenization is that loop's line for line. What changes is only
1106    /// that the three sums share one walk over the control points, and the trip
1107    /// counts are constants the compiler unrolls. A mass integral's adaptive
1108    /// area reads spend most of their time here: on a fitted bicubic offset
1109    /// shell, about a billion stations for one solid.
1110    #[allow(clippy::type_complexity)]
1111    #[inline(always)]
1112    fn deriv1_tensor_fused<const DEGREE_U: usize, const DEGREE_V: usize, F>(
1113        &self,
1114        count_u: usize,
1115        count_v: usize,
1116        (span_u, span_v, basis_u, basis_v): (
1117            &[usize; TENSOR_MAX_BLOCK],
1118            &[usize; TENSOR_MAX_BLOCK],
1119            &[[[f64; MAX_STACK_ORDER]; 2]; TENSOR_MAX_BLOCK],
1120            &[[[f64; MAX_STACK_ORDER]; 2]; TENSOR_MAX_BLOCK],
1121        ),
1122        f: &mut F,
1123    ) -> Result<(), String>
1124    where
1125        F: FnMut(usize, usize, Vec3, Vec3, Vec3) -> Result<(), String>,
1126    {
1127        let zero = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
1128        for i in 0..count_u {
1129            let rows = &self.control_points[span_u[i] - DEGREE_U..=span_u[i]];
1130            let (value_u, slope_u) = (&basis_u[i][0], &basis_u[i][1]);
1131            for j in 0..count_v {
1132                let column = span_v[j] - DEGREE_V;
1133                let (value_v, slope_v) = (&basis_v[j][0], &basis_v[j][1]);
1134                let (mut h00, mut h01, mut h10) = (zero, zero, zero);
1135                for row_index in 0..=DEGREE_U {
1136                    let row = &rows[row_index][column..=column + DEGREE_V];
1137                    for column_index in 0..=DEGREE_V {
1138                        let control = row[column_index];
1139                        h00 = h00.add(control.scale(value_u[row_index] * value_v[column_index]));
1140                        h01 = h01.add(control.scale(value_u[row_index] * slope_v[column_index]));
1141                        h10 = h10.add(control.scale(slope_u[row_index] * value_v[column_index]));
1142                    }
1143                }
1144                let weight = h00.w;
1145                if weight.abs() <= EPS {
1146                    return Err("NurbsSurface: zero evaluated weight".into());
1147                }
1148                let inverse = 1.0 / weight;
1149                let point = Vec3::new(h00.x, h00.y, h00.z).scale(inverse);
1150                let partial_v = Vec3::new(h01.x, h01.y, h01.z).sub(point.scale(h01.w)).scale(inverse);
1151                let partial_u = Vec3::new(h10.x, h10.y, h10.z).sub(point.scale(h10.w)).scale(inverse);
1152                f(i, j, point, partial_u, partial_v)?;
1153            }
1154        }
1155        Ok(())
1156    }
1157
1158    /// Point and first partials `(S, S_u, S_v)` with zero heap allocation.
1159    /// Bit-identical to `derivatives(u, v, 1)` at `[0][0] / [1][0] / [0][1]`.
1160    #[inline]
1161    pub fn deriv1(&self, u: f64, v: f64) -> Result<(Vec3, Vec3, Vec3), String> {
1162        // Degrees 1 and 2 in both directions (every carrier the kernel builds
1163        // and the fitted patches it blends with) take the first-order twin
1164        // with both degrees fixed at compile time; its arithmetic is
1165        // `derivatives_small`'s to the bit (`deriv1_small_fixed`), and the
1166        // mass sign reading's chord stations were a third `derivatives_small`
1167        // self time after the basis recurrence (2026-11-02).
1168        match (self.degree_u, self.degree_v) {
1169            (1, 1) => self.deriv1_small_fixed::<1, 1>(u, v),
1170            (2, 1) => self.deriv1_small_fixed::<2, 1>(u, v),
1171            (1, 2) => self.deriv1_small_fixed::<1, 2>(u, v),
1172            (2, 2) => self.deriv1_small_fixed::<2, 2>(u, v),
1173            (3, 9) => self.deriv1_small_fixed::<3, 9>(u, v),
1174            (5, 9) => self.deriv1_small_fixed::<5, 9>(u, v),
1175            _ => {
1176                let g = self.derivatives_small(u, v, 1)?;
1177                Ok((g[0][0], g[1][0], g[0][1]))
1178            }
1179        }
1180    }
1181
1182    /// First-order rational recurrence with only its three live sums, for a
1183    /// patch whose degrees are the const parameters. The clamp, span, basis
1184    /// rows, control summation (row outer, column inner, scale then add from
1185    /// the zero `Vec4`) and dehomogenization are `derivatives_small`'s in the
1186    /// same order; the two recurrence steps written out here that
1187    /// `derivatives_small` runs generically are exact no-ops at this order
1188    /// (`binomial(1, 1)` is exactly `1.0`; the mixed term is the zero vector,
1189    /// whose subtraction changes no bit). So the three results are the same
1190    /// bits as `derivatives_small(u, v, 1)` at `[0][0]`, `[1][0]`, `[0][1]`
1191    /// for ANY surface of these degrees, analytic or not
1192    /// (`deriv1_degree_dispatch_tests`). Caller retains the existing
1193    /// wrapping, extension and refusal paths.
1194    fn deriv1_small_fixed<const DEGREE_U: usize, const DEGREE_V: usize>(&self, u: f64, v: f64) -> Result<(Vec3, Vec3, Vec3), String> {
1195        self.ensure_valid()?;
1196        let du = DEGREE_U.min(1);
1197        let dv = DEGREE_V.min(1);
1198        let u = knot_clamp(&self.knots_u, DEGREE_U, u);
1199        let v = knot_clamp(&self.knots_v, DEGREE_V, v);
1200        let span_u = knot_find_span(&self.knots_u, DEGREE_U, u);
1201        let span_v = knot_find_span(&self.knots_v, DEGREE_V, v);
1202        let mut basis_u = [[0.0; MAX_STACK_ORDER]; 2];
1203        let mut basis_v = [[0.0; MAX_STACK_ORDER]; 2];
1204        basis_derivatives_into(&self.knots_u, DEGREE_U, span_u, u, du, &mut basis_u[..=du]);
1205        basis_derivatives_into(&self.knots_v, DEGREE_V, span_v, v, dv, &mut basis_v[..=dv]);
1206        let zero = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
1207        let sum = |k: usize, l: usize| {
1208            let mut value = zero;
1209            for i in 0..=DEGREE_U {
1210                let row = &self.control_points[span_u - DEGREE_U + i][span_v - DEGREE_V..=span_v];
1211                for j in 0..=DEGREE_V {
1212                    value = value.add(row[j].scale(basis_u[k][i] * basis_v[l][j]));
1213                }
1214            }
1215            value
1216        };
1217        let h00 = sum(0, 0);
1218        let h01 = if dv == 1 { sum(0, 1) } else { zero };
1219        let h10 = if du == 1 { sum(1, 0) } else { zero };
1220        if h00.w.abs() <= EPS { return Err("NurbsSurface: zero evaluated weight".into()); }
1221        let inverse = 1.0 / h00.w;
1222        let point = Vec3::new(h00.x, h00.y, h00.z).scale(inverse);
1223        let partial_v = if dv == 1 {
1224            Vec3::new(h01.x, h01.y, h01.z).sub(point.scale(1.0 * h01.w)).scale(inverse)
1225        } else { Vec3::default() };
1226        let partial_u = if du == 1 {
1227            Vec3::new(h10.x, h10.y, h10.z).sub(point.scale(1.0 * h10.w))
1228                .sub(Vec3::default().scale(1.0)).scale(inverse)
1229        } else { Vec3::default() };
1230        Ok((point, partial_u, partial_v))
1231    }
1232
1233    /// The four anchor terms used by a first-order bilinear extension.
1234    /// Pure second partials do not feed these terms. Keep the control sums
1235    /// and rational recurrence in the generic evaluator's arithmetic order.
1236    fn extension_anchor_fixed<const U: usize, const V: usize>(&self, u: f64, v: f64) -> Result<(Vec3, Vec3, Vec3, Vec3), String> {
1237        self.ensure_valid()?;
1238        let u = knot_clamp(&self.knots_u, U, u);
1239        let v = knot_clamp(&self.knots_v, V, v);
1240        let span_u = knot_find_span(&self.knots_u, U, u);
1241        let span_v = knot_find_span(&self.knots_v, V, v);
1242        let mut basis_u = [[0.0; MAX_STACK_ORDER]; 2];
1243        let mut basis_v = [[0.0; MAX_STACK_ORDER]; 2];
1244        basis_derivatives_into(&self.knots_u, U, span_u, u, 1, &mut basis_u);
1245        basis_derivatives_into(&self.knots_v, V, span_v, v, 1, &mut basis_v);
1246        let zero = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
1247        let sum = |k: usize, l: usize| {
1248            let mut value = zero;
1249            for i in 0..=U {
1250                let row = &self.control_points[span_u - U + i];
1251                for j in 0..=V {
1252                    value = value.add(row[span_v - V + j].scale(basis_u[k][i] * basis_v[l][j]));
1253                }
1254            }
1255            value
1256        };
1257        let (h00,h01,h10,h11) = (sum(0,0),sum(0,1),sum(1,0),sum(1,1));
1258        if h00.w.abs() <= EPS { return Err("NurbsSurface: zero evaluated weight".into()); }
1259        let inverse = 1.0 / h00.w;
1260        let point = Vec3::new(h00.x,h00.y,h00.z).scale(inverse);
1261        let sv = Vec3::new(h01.x,h01.y,h01.z).sub(point.scale(1.0*h01.w)).scale(inverse);
1262        let su = Vec3::new(h10.x,h10.y,h10.z).sub(point.scale(1.0*h10.w))
1263            .sub(Vec3::default().scale(1.0)).scale(inverse);
1264        let mixed = Vec3::default().add(point.scale(1.0*h11.w));
1265        let suv = Vec3::new(h11.x,h11.y,h11.z).sub(su.scale(1.0*h01.w))
1266            .sub(sv.scale(1.0*h10.w)).sub(mixed.scale(1.0)).scale(inverse);
1267        Ok((point,su,sv,suv))
1268    }
1269
1270    fn extension_anchor(&self, u: f64, v: f64) -> Result<(Vec3, Vec3, Vec3, Vec3), String> {
1271        match (self.degree_u,self.degree_v) {
1272            (1,1) => self.extension_anchor_fixed::<1,1>(u,v),
1273            (1,2) => self.extension_anchor_fixed::<1,2>(u,v),
1274            (1,3) => self.extension_anchor_fixed::<1,3>(u,v),
1275            (2,1) => self.extension_anchor_fixed::<2,1>(u,v),
1276            (2,2) => self.extension_anchor_fixed::<2,2>(u,v),
1277            (2,3) => self.extension_anchor_fixed::<2,3>(u,v),
1278            (3,1) => self.extension_anchor_fixed::<3,1>(u,v),
1279            (3,2) => self.extension_anchor_fixed::<3,2>(u,v),
1280            (3,3) => self.extension_anchor_fixed::<3,3>(u,v),
1281            _ => { let g = self.derivatives_small(u,v,2)?; Ok((g[0][0],g[1][0],g[0][1],g[1][1])) }
1282        }
1283    }
1284
1285    /// First-order extension using only the anchor terms that it consumes.
1286    pub fn deriv1_extended_trim(&self, u: f64, v: f64) -> Result<(Vec3, Vec3, Vec3), String> {
1287        self.deriv1_extended_impl(u,v,true)
1288    }
1289
1290    /// Allocation-free `(S, S_u, S_v)` twin of `derivatives_extended(u, v, 1)`.
1291    ///
1292    /// Mirrors the exact C¹ ruled/bilinear extension arithmetic of
1293    /// [`Self::derivatives_extended`] (only the count == 1 partials), but drives
1294    /// it from [`Self::derivatives_small`] so the in-domain and boundary-anchor
1295    /// evaluations allocate nothing. Bit-identical to
1296    /// `derivatives_extended(u, v, 1)` at `[0][0] / [1][0] / [0][1]`.
1297    pub fn deriv1_extended(&self, u: f64, v: f64) -> Result<(Vec3, Vec3, Vec3), String> {
1298        self.deriv1_extended_impl(u,v,false)
1299    }
1300
1301    fn deriv1_extended_impl(&self, u: f64, v: f64, reduced_anchor: bool) -> Result<(Vec3, Vec3, Vec3), String> {
1302        let [u0, u1] = self.domain_u()?;
1303        let [v0, v1] = self.domain_v()?;
1304        let (closed_u, closed_v) = self.closed_directions()?;
1305        let mut uu = u;
1306        let mut vv = v;
1307        if closed_u && (u < u0 || u > u1) {
1308            uu = u0 + (u - u0).rem_euclid(u1 - u0);
1309        }
1310        if closed_v && (v < v0 || v > v1) {
1311            vv = v0 + (v - v0).rem_euclid(v1 - v0);
1312        }
1313        let du_out = if uu < u0 {
1314            uu - u0
1315        } else if uu > u1 {
1316            uu - u1
1317        } else {
1318            0.0
1319        };
1320        let dv_out = if vv < v0 {
1321            vv - v0
1322        } else if vv > v1 {
1323            vv - v1
1324        } else {
1325            0.0
1326        };
1327        if du_out == 0.0 && dv_out == 0.0 {
1328            if reduced_anchor {
1329                match (self.degree_u,self.degree_v) {
1330                    (3,1) => return self.deriv1_small_fixed::<3,1>(uu,vv),
1331                    (1,3) => return self.deriv1_small_fixed::<1,3>(uu,vv),
1332                    (3,2) => return self.deriv1_small_fixed::<3,2>(uu,vv),
1333                    (2,3) => return self.deriv1_small_fixed::<2,3>(uu,vv),
1334                    (3,3) => return self.deriv1_small_fixed::<3,3>(uu,vv),
1335                    _ => {}
1336                }
1337            }
1338            if analytic_deriv1_on() && matches!((self.degree_u, self.degree_v), (1, 1) | (2, 1) | (1, 2) | (2, 2))
1339                && matches!(self.analytic(), Some(crate::AnalyticSurface::Plane { .. }
1340                    | crate::AnalyticSurface::RuledRevolution { .. } | crate::AnalyticSurface::Sphere { .. }
1341                    | crate::AnalyticSurface::Torus { .. })) {
1342                return match (self.degree_u, self.degree_v) {
1343                    (1, 1) => self.deriv1_small_fixed::<1, 1>(uu, vv),
1344                    (2, 1) => self.deriv1_small_fixed::<2, 1>(uu, vv),
1345                    (1, 2) => self.deriv1_small_fixed::<1, 2>(uu, vv),
1346                    (2, 2) => self.deriv1_small_fixed::<2, 2>(uu, vv),
1347                    _ => unreachable!(),
1348                };
1349            }
1350            let g = self.derivatives_small(uu, vv, 1)?;
1351            return Ok((g[0][0], g[1][0], g[0][1]));
1352        }
1353        let anchor_u = uu - du_out;
1354        let anchor_v = vv - dv_out;
1355        let (a00,a10,a01,a11) = if reduced_anchor {
1356            self.extension_anchor(anchor_u,anchor_v)?
1357        } else {
1358            let base = self.derivatives_small(anchor_u,anchor_v,2)?;
1359            (base[0][0],base[1][0],base[0][1],base[1][1])
1360        };
1361        // Bilinear extension: S = A00 + du·A10 + dv·A01 + du·dv·A11.
1362        // The mixed anchor derivative has total order two, even when
1363        // the caller requests only the value or first partials.
1364        let s = a00.add(a10.scale(du_out)).add(a01.scale(dv_out)).add(a11.scale(du_out * dv_out));
1365        let su = a10.add(a11.scale(dv_out));
1366        let sv = a01.add(a11.scale(du_out));
1367        Ok((s, su, sv))
1368    }
1369
1370    /// One first partial at `(u, v)` (clamped into the domain), `S_u` when
1371    /// `along_u`, else `S_v`, evaluated from the DIFFERENCES of the control net
1372    /// rather than from the basis derivatives.
1373    ///
1374    /// [`Self::derivatives`] forms `S_u = (A_u − W_u·S) / W` from `A_u = Σ N′ᵢ·Hᵢ`,
1375    /// a sum of terms the size of the control points whose exact total may be
1376    /// zero. Its rounding is therefore ABSOLUTE, a few ulps of the point, and
1377    /// where the partial itself vanishes (an isoline on which the
1378    /// parameterization is stationary, as on an extrusion of a cubic with
1379    /// coincident end poles) the DIRECTION of what is left is that rounding:
1380    /// measured 2.7e-15 of `x` on a partial of 7.7e-5 along `y`, a normal tilted
1381    /// by 3.5e-11.
1382    ///
1383    /// The hodograph `A_u = Σ N_{i+1,p−1}·p·(H_{i+1} − H_i)/(ξ_{i+p+1} − ξ_{i+1})`
1384    /// (The NURBS Book eq. 3.4, per row) carries the same partial with rounding
1385    /// that scales with its own terms: coincident control points difference to
1386    /// an exact zero, and every other difference is weighted by a basis function
1387    /// that vanishes with the partial. The rational part subtracts
1388    /// `W_u·S` with `W_u` taken from the weight differences, which is an exact
1389    /// zero wherever neighbouring weights are equal.
1390    ///
1391    /// Not bit-identical to `derivatives`, so it is read only where the bare
1392    /// partial has lost its direction (`offset/point.rs`). Refuses above the
1393    /// stack basis tables' degree.
1394    pub fn partial_by_differences(
1395        &self,
1396        along_u: bool,
1397        u: f64,
1398        v: f64,
1399    ) -> Result<Vec3, String> {
1400        self.ensure_valid()?;
1401        if self.degree_u > crate::curve::MAX_STACK_DEGREE || self.degree_v > crate::curve::MAX_STACK_DEGREE {
1402            return Err("NurbsSurface: partial by differences exceeds the stack degree".into());
1403        }
1404        let (pu, pv) = (self.degree_u, self.degree_v);
1405        let u = knot_clamp(&self.knots_u, pu, u);
1406        let v = knot_clamp(&self.knots_v, pv, v);
1407        let span_u = knot_find_span(&self.knots_u, pu, u);
1408        let span_v = knot_find_span(&self.knots_v, pv, v);
1409        let mut full_u = [0.0f64; MAX_STACK_ORDER];
1410        let mut full_v = [0.0f64; MAX_STACK_ORDER];
1411        basis_functions_into(&self.knots_u, pu, span_u, u, &mut full_u);
1412        basis_functions_into(&self.knots_v, pv, span_v, v, &mut full_v);
1413        let zero = Vec4 {
1414            x: 0.0,
1415            y: 0.0,
1416            z: 0.0,
1417            w: 0.0,
1418        };
1419        let control = |i: usize, j: usize| self.control_points[span_u - pu + i][span_v - pv + j];
1420        let mut point = zero;
1421        for i in 0..=pu {
1422            for j in 0..=pv {
1423                point = point.add(control(i, j).scale(full_u[i] * full_v[j]));
1424            }
1425        }
1426        if point.w.abs() <= EPS {
1427            return Err("NurbsSurface: zero evaluated weight".into());
1428        }
1429        let source = Vec3::new(point.x, point.y, point.z).scale(1.0 / point.w);
1430        let (knots, degree, span, parameter) = if along_u {
1431            (&self.knots_u, pu, span_u, u)
1432        } else {
1433            (&self.knots_v, pv, span_v, v)
1434        };
1435        if degree == 0 {
1436            return Ok(Vec3::default());
1437        }
1438        let mut lowered = [0.0f64; MAX_STACK_ORDER];
1439        basis_functions_into(knots, degree - 1, span, parameter, &mut lowered);
1440        // The hodograph's homogeneous value, Σ over the (degree) differences of
1441        // the basis span times the other direction's full basis.
1442        let mut hodograph = zero;
1443        for r in 0..degree {
1444            // Difference r joins control indices (span − degree + r) and
1445            // (span − degree + r + 1); its lowered basis is N_{span−degree+r+1, degree−1}.
1446            let index = span - degree + r;
1447            let width = knots[index + degree + 1] - knots[index + 1];
1448            if width.abs() <= EPS {
1449                continue;
1450            }
1451            let factor = lowered[r] * degree as f64 / width;
1452            if along_u {
1453                for j in 0..=pv {
1454                    let difference = control(r + 1, j).add(control(r, j).scale(-1.0));
1455                    hodograph = hodograph.add(difference.scale(factor * full_v[j]));
1456                }
1457            } else {
1458                for i in 0..=pu {
1459                    let difference = control(i, r + 1).add(control(i, r).scale(-1.0));
1460                    hodograph = hodograph.add(difference.scale(factor * full_u[i]));
1461                }
1462            }
1463        }
1464        Ok(Vec3::new(hodograph.x, hodograph.y, hodograph.z)
1465            .sub(source.scale(hodograph.w))
1466            .scale(1.0 / point.w))
1467    }
1468
1469    pub fn normal(&self, u: f64, v: f64) -> Result<Vec3, String> {
1470        if small_derivatives_enabled() {
1471            let derivatives = self.derivatives_small(u, v, 1)?;
1472            return derivatives[1][0].cross(derivatives[0][1]).normalized();
1473        }
1474        let derivatives = self.derivatives(u, v, 1)?;
1475        derivatives[1][0].cross(derivatives[0][1]).normalized()
1476    }
1477
1478    /// Principal curvatures (κ_min, κ_max) at (u, v), signed with respect to
1479    /// the parametrization normal n = Su × Sv / |Su × Sv| via the shape
1480    /// operator I⁻¹·II.  Convention check: a cylinder of radius R whose normal
1481    /// points AWAY from the axis has κ = −1/R along the circular direction, so
1482    /// an offset's regularity factor 1 − d·κ vanishes exactly when an inward
1483    /// offset (d = −R) reaches the axis.
1484    pub fn principal_curvatures(&self, u: f64, v: f64) -> Result<(f64, f64), String> {
1485        self.principal_curvatures_and_tangents(u, v)
1486            .map(|(kappa_min, kappa_max, _, _)| (kappa_min, kappa_max))
1487    }
1488
1489    /// [`Self::principal_curvatures`] together with the first derivatives
1490    /// `Su` and `Sv` it was read from, so a caller can judge how well
1491    /// conditioned the reading is without evaluating the surface twice.
1492    pub fn principal_curvatures_and_tangents(&self, u: f64, v: f64) -> Result<(f64, f64, Vec3, Vec3), String> {
1493        let derivatives: [[Vec3; 3]; 3] = if small_derivatives_enabled() {
1494            self.derivatives_small(u, v, 2)?
1495        } else {
1496            let heap = self.derivatives(u, v, 2)?;
1497            [[heap[0][0], heap[0][1], heap[0][2]], [heap[1][0], heap[1][1], Vec3::default()], [heap[2][0], Vec3::default(), Vec3::default()]]
1498        };
1499        let su = derivatives[1][0];
1500        let sv = derivatives[0][1];
1501        let cross = su.cross(sv);
1502        let cross_length = cross.length();
1503        if cross_length <= 1e-12 {
1504            return Err(format!(
1505                "degenerate parametrization at (u={u:.4}, v={v:.4})"
1506            ));
1507        }
1508        let normal = cross.scale(1.0 / cross_length);
1509        let e1 = su.dot(su);
1510        let f1 = su.dot(sv);
1511        let g1 = sv.dot(sv);
1512        let l2 = derivatives[2][0].dot(normal);
1513        let m2 = derivatives[1][1].dot(normal);
1514        let n2 = derivatives[0][2].dot(normal);
1515        let denominator = e1 * g1 - f1 * f1;
1516        let mean_double = (l2 * g1 - 2.0 * m2 * f1 + n2 * e1) / denominator; // 2H
1517        let gauss = (l2 * n2 - m2 * m2) / denominator; // K
1518        let discriminant = (mean_double * mean_double * 0.25 - gauss).max(0.0).sqrt();
1519        Ok((
1520            mean_double * 0.5 - discriminant,
1521            mean_double * 0.5 + discriminant,
1522            su,
1523            sv,
1524        ))
1525    }
1526
1527    /// Whether this is a genuinely affine degree-1 by degree-1 patch.
1528    ///
1529    /// A tapered bilinear patch is planar but not affine, so degree alone is
1530    /// insufficient for exact inverse-parameter and integration shortcuts.
1531    pub fn is_affine(&self) -> Result<bool, String> {
1532        if self.degree_u != 1
1533            || self.degree_v != 1
1534            || self.control_points.len() != 2
1535            || self.control_points[0].len() != 2
1536            || self.control_points[1].len() != 2
1537        {
1538            return Ok(false);
1539        }
1540        let weight = self.control_points[0][0].w;
1541        if [
1542            self.control_points[0][1].w,
1543            self.control_points[1][0].w,
1544            self.control_points[1][1].w,
1545        ]
1546        .iter()
1547        .any(|other| (*other - weight).abs() > 1e-12 * other.abs().max(weight.abs()))
1548        {
1549            return Ok(false);
1550        }
1551        let p00 = self.control_points[0][0].point()?;
1552        let p01 = self.control_points[0][1].point()?;
1553        let p10 = self.control_points[1][0].point()?;
1554        let p11 = self.control_points[1][1].point()?;
1555        let gap = p11.sub(p10).sub(p01.sub(p00)).length();
1556        // The parallelogram defect measures the non-affine bilinear term.
1557        // Scale it by the patch extent, never its distance from the origin:
1558        // falsely accepting a translated warped patch also labels it a plane
1559        // and sends its pcurves and offsets through exact affine shortcuts.
1560        let extent = [
1561            p01.sub(p00),
1562            p10.sub(p00),
1563            p11.sub(p00),
1564            p10.sub(p01),
1565            p11.sub(p01),
1566            p11.sub(p10),
1567        ]
1568        .iter()
1569        .map(|delta| delta.length())
1570        .fold(0.0, f64::max);
1571        Ok(gap <= 1e-9 * (1.0 + extent))
1572    }
1573
1574    pub fn iso_curve_u(&self, u: f64) -> Result<NurbsCurve, String> {
1575        self.ensure_valid()?;
1576        let u = knot_clamp(&self.knots_u, self.degree_u, u);
1577        let span = knot_find_span(&self.knots_u, self.degree_u, u);
1578        let basis = if self.degree_u <= MAX_STACK_DEGREE {
1579            let mut stack = [0.0f64; MAX_STACK_ORDER];
1580            basis_functions_into(&self.knots_u, self.degree_u, span, u, &mut stack);
1581            stack[..=self.degree_u].to_vec()
1582        } else {
1583            KnotVector::new(self.knots_u.clone(), self.degree_u)?.basis_functions(span, u)
1584        };
1585        let mut points = Vec::with_capacity(self.control_points[0].len());
1586        for column in 0..self.control_points[0].len() {
1587            let mut point = Vec4 {
1588                x: 0.0,
1589                y: 0.0,
1590                z: 0.0,
1591                w: 0.0,
1592            };
1593            for (index, value) in basis.iter().enumerate() {
1594                point = point
1595                    .add(self.control_points[span - self.degree_u + index][column].scale(*value));
1596            }
1597            points.push(point);
1598        }
1599        NurbsCurve::new(self.degree_v, self.knots_v.clone(), points)
1600    }
1601
1602    pub fn iso_curve_v(&self, v: f64) -> Result<NurbsCurve, String> {
1603        self.ensure_valid()?;
1604        let v = knot_clamp(&self.knots_v, self.degree_v, v);
1605        let span = knot_find_span(&self.knots_v, self.degree_v, v);
1606        let basis = if self.degree_v <= MAX_STACK_DEGREE {
1607            let mut stack = [0.0f64; MAX_STACK_ORDER];
1608            basis_functions_into(&self.knots_v, self.degree_v, span, v, &mut stack);
1609            stack[..=self.degree_v].to_vec()
1610        } else {
1611            KnotVector::new(self.knots_v.clone(), self.degree_v)?.basis_functions(span, v)
1612        };
1613        let mut points = Vec::with_capacity(self.control_points.len());
1614        for row in &self.control_points {
1615            let mut point = Vec4 {
1616                x: 0.0,
1617                y: 0.0,
1618                z: 0.0,
1619                w: 0.0,
1620            };
1621            for (index, value) in basis.iter().enumerate() {
1622                point = point.add(row[span - self.degree_v + index].scale(*value));
1623            }
1624            points.push(point);
1625        }
1626        NurbsCurve::new(self.degree_u, self.knots_u.clone(), points)
1627    }
1628}
1629
1630pub fn make_plane(
1631    origin: Vec3,
1632    u_direction: Vec3,
1633    v_direction: Vec3,
1634    u_max: f64,
1635    v_max: f64,
1636) -> Result<NurbsSurface, String> {
1637    if u_max <= EPS || v_max <= EPS {
1638        return Err("makePlane: parameter extents must be positive".into());
1639    }
1640    let p10 = origin.add(u_direction.scale(u_max));
1641    let p01 = origin.add(v_direction.scale(v_max));
1642    let p11 = p10.add(v_direction.scale(v_max));
1643    NurbsSurface::new(
1644        1,
1645        1,
1646        vec![0.0, 0.0, u_max, u_max],
1647        vec![0.0, 0.0, v_max, v_max],
1648        vec![
1649            vec![Vec4::from_point(origin, 1.0), Vec4::from_point(p01, 1.0)],
1650            vec![Vec4::from_point(p10, 1.0), Vec4::from_point(p11, 1.0)],
1651        ],
1652    )
1653}
1654
1655pub fn make_extrusion(profile: &NurbsCurve, direction: Vec3) -> Result<NurbsSurface, String> {
1656    let rows = profile
1657        .control_points
1658        .iter()
1659        .map(|point| {
1660            vec![
1661                *point,
1662                Vec4 {
1663                    x: point.x + point.w * direction.x,
1664                    y: point.y + point.w * direction.y,
1665                    z: point.z + point.w * direction.z,
1666                    w: point.w,
1667                },
1668            ]
1669        })
1670        .collect();
1671    NurbsSurface::new(
1672        profile.degree,
1673        1,
1674        profile.knots.clone(),
1675        vec![0.0, 0.0, 1.0, 1.0],
1676        rows,
1677    )
1678}
1679
1680pub fn make_revolution(
1681    axis_point: Vec3,
1682    axis_direction: Vec3,
1683    generatrix: &NurbsCurve,
1684    theta: f64,
1685) -> Result<NurbsSurface, String> {
1686    revolution_in_spans(axis_point, axis_direction, generatrix, theta, None)
1687}
1688
1689/// [`make_revolution`] with the turn in ONE rational quadratic span (middle
1690/// weight cos(theta/2)) for `theta` under 180 degrees, where
1691/// `make_revolution` splits past 90. Its circles then run at the parameter of
1692/// a one-conic arc of the same turn, so an edge built that way lies on an
1693/// iso line of it. Up to 90 degrees the two are the same surface.
1694pub fn make_revolution_one_span(
1695    axis_point: Vec3,
1696    axis_direction: Vec3,
1697    generatrix: &NurbsCurve,
1698    theta: f64,
1699) -> Result<NurbsSurface, String> {
1700    if !(theta < std::f64::consts::PI - 1e-6) {
1701        return Err("makeRevolution: one span needs theta under PI".into());
1702    }
1703    revolution_in_spans(axis_point, axis_direction, generatrix, theta, Some(1))
1704}
1705
1706fn revolution_in_spans(
1707    axis_point: Vec3,
1708    axis_direction: Vec3,
1709    generatrix: &NurbsCurve,
1710    theta: f64,
1711    spans: Option<usize>,
1712) -> Result<NurbsSurface, String> {
1713    if theta <= EPS || theta > std::f64::consts::TAU + EPS {
1714        return Err("makeRevolution: theta must be in (0, 2*PI]".into());
1715    }
1716    let theta = theta.min(std::f64::consts::TAU);
1717    let axis = axis_direction.normalized()?;
1718    let arc_count = spans.unwrap_or_else(|| ((theta / std::f64::consts::FRAC_PI_2 - EPS).ceil() as usize).clamp(1, 4));
1719    let arc_angle = theta / arc_count as f64;
1720    let middle_weight = (arc_angle / 2.0).cos();
1721    let mut knots_u = vec![0.0, 0.0, 0.0];
1722    for index in 1..arc_count {
1723        let knot = index as f64 / arc_count as f64;
1724        knots_u.extend([knot, knot]);
1725    }
1726    knots_u.extend([1.0, 1.0, 1.0]);
1727    let mut rows = vec![
1728        vec![
1729            Vec4 {
1730                x: 0.0,
1731                y: 0.0,
1732                z: 0.0,
1733                w: 1.0,
1734            };
1735            generatrix.control_points.len()
1736        ];
1737        2 * arc_count + 1
1738    ];
1739
1740    // How far the generatrix reaches from the axis — the scale every "is this
1741    // control point on the axis?" question below is measured against.
1742    let mut radial_extent: f64 = 0.0;
1743    for control_point in &generatrix.control_points {
1744        let point = control_point.point()?;
1745        let offset = point.sub(axis_point);
1746        radial_extent = radial_extent.max(offset.sub(axis.scale(offset.dot(axis))).length());
1747    }
1748
1749    for (column, control_point) in generatrix.control_points.iter().enumerate() {
1750        let point = control_point.point()?;
1751        let weight = control_point.w;
1752        let axis_origin = axis_point.add(axis.scale(point.sub(axis_point).dot(axis)));
1753        let radial_vector = point.sub(axis_origin);
1754        // On-axis classification must be RELATIVE like the fuzzy band below:
1755        // the absolute EPS floor alone broke when the importer's mm conversion
1756        // scaled vendor pole noise (1.5e-13 m -> 1.5e-10 mm) past it, hard-
1757        // rejecting files whose poles are intended on-axis. 1e-8 of the radial
1758        // extent snaps that noise to an EXACT pole (radius 0, so every
1759        // downstream `radius <= EPS` branch takes the degenerate path):
1760        // corpus vendor noise measures up to ~2e-9 relative, and the
1761        // 1e-6-relative nudge the fuzzy-pole test rejects stays two decades
1762        // above the snap.
1763        let measured_radius = radial_vector.length();
1764        let pole_tolerance = EPS.max(1e-8 * radial_extent);
1765        let radius = if measured_radius <= pole_tolerance {
1766            0.0
1767        } else {
1768            measured_radius
1769        };
1770        let (x_axis, y_axis) = if radius <= EPS {
1771            (Vec3::default(), Vec3::default())
1772        } else {
1773            // A control point is either ON the axis — the degenerate pole row
1774            // above, whose rotation is a fixed point — or clearly off it. In
1775            // between the revolution carries a fuzzy PINCH where a pole was
1776            // meant to be, which downstream code (analytic recognition, pair
1777            // classification, the imprint) reads as an ordinary tiny circle:
1778            // refuse it here instead. This refusal used to fall out of the
1779            // parallel-tangent guard below, whose ABSOLUTE floor made it
1780            // "radius <= 1e-3" — which on a metre-unit STEP file rejected every
1781            // healthy 1.524e-4 cylinder in the part. Relative to the
1782            // generatrix's own radial extent it catches the fuzzy pole at any
1783            // model scale and lets real geometry through at any size.
1784            if radius <= NEAR_AXIS_RELATIVE_TOLERANCE * radial_extent {
1785                return Err(format!(
1786                    "makeRevolution: generatrix control point {column} sits {radius:e} from the \
1787                     axis, neither on it nor clear of it against the generatrix's {radial_extent:e} \
1788                     radial extent (a fuzzy pole)"
1789                ));
1790            }
1791            let x_axis = radial_vector.scale(1.0 / radius);
1792            (x_axis, axis.cross(x_axis))
1793        };
1794        rows[0][column] = Vec4::from_point(point, weight);
1795        let mut start_point = point;
1796        let mut start_tangent = y_axis.scale(radius);
1797        let mut angle = 0.0;
1798        for arc in 1..=arc_count {
1799            angle += arc_angle;
1800            let end_point = if radius <= EPS {
1801                point
1802            } else {
1803                axis_origin
1804                    .add(x_axis.scale(radius * angle.cos()))
1805                    .add(y_axis.scale(radius * angle.sin()))
1806            };
1807            let end_tangent = if radius <= EPS {
1808                Vec3::default()
1809            } else {
1810                x_axis
1811                    .scale(-radius * angle.sin())
1812                    .add(y_axis.scale(radius * angle.cos()))
1813            };
1814            let row = 2 * (arc - 1);
1815            if radius <= EPS {
1816                rows[row + 1][column] = Vec4::from_point(point, weight * middle_weight);
1817            } else {
1818                let cross = start_tangent.cross(end_tangent);
1819                let denominator = cross.length_squared();
1820                // Both tangents have length `radius`, so `denominator` is
1821                // radius^4 * sin^2(arc_angle) and an ABSOLUTE floor here reads
1822                // as "radius <= 1e-3", conflating a small part with a
1823                // degenerate sweep. Parallel tangents are purely an ANGULAR
1824                // condition, so scale the floor by the tangent lengths: the
1825                // test becomes sin^2(arc_angle) <= EPS, exactly what make_arc
1826                // applies to its already-unit tangents. Near-axis control
1827                // points are the near-axis check's business, above.
1828                let tangent_scale = start_tangent.length_squared() * end_tangent.length_squared();
1829                if denominator <= EPS * tangent_scale {
1830                    return Err("makeRevolution: arc tangents are parallel".into());
1831                }
1832                let distance =
1833                    end_point.sub(start_point).cross(end_tangent).dot(cross) / denominator;
1834                let middle = start_point.add(start_tangent.scale(distance));
1835                rows[row + 1][column] = Vec4::from_point(middle, weight * middle_weight);
1836            }
1837            rows[row + 2][column] = Vec4::from_point(end_point, weight);
1838            start_point = end_point;
1839            start_tangent = end_tangent;
1840        }
1841    }
1842    NurbsSurface::new(
1843        2,
1844        generatrix.degree,
1845        knots_u,
1846        generatrix.knots.clone(),
1847        rows,
1848    )
1849}
1850
1851pub fn make_cylinder_surface(
1852    base: Vec3,
1853    axis_direction: Vec3,
1854    radius: f64,
1855    height: f64,
1856) -> Result<NurbsSurface, String> {
1857    if radius <= EPS || height <= EPS {
1858        return Err("makeCylinder: radius and height must be positive".into());
1859    }
1860    let axis = axis_direction.normalized()?;
1861    let x_axis = axis.perpendicular()?;
1862    let start = base.add(x_axis.scale(radius));
1863    let end = start.add(axis.scale(height));
1864    let generatrix = crate::make_line(start, end)?;
1865    make_revolution(base, axis, &generatrix, std::f64::consts::TAU)
1866}
1867
1868pub fn make_cone_surface(
1869    base: Vec3,
1870    axis_direction: Vec3,
1871    radius_bottom: f64,
1872    radius_top: f64,
1873    height: f64,
1874) -> Result<NurbsSurface, String> {
1875    if radius_bottom <= EPS || radius_top < 0.0 || height <= EPS {
1876        return Err("makeCone: invalid radius or height".into());
1877    }
1878    let axis = axis_direction.normalized()?;
1879    let x_axis = axis.perpendicular()?;
1880    let start = base.add(x_axis.scale(radius_bottom));
1881    let end = base.add(axis.scale(height)).add(x_axis.scale(radius_top));
1882    let generatrix = crate::make_line(start, end)?;
1883    make_revolution(base, axis, &generatrix, std::f64::consts::TAU)
1884}
1885
1886pub fn make_sphere_surface(
1887    center: Vec3,
1888    radius: f64,
1889    polar_axis: Vec3,
1890) -> Result<NurbsSurface, String> {
1891    make_sphere_surface_framed(center, radius, polar_axis, None)
1892}
1893
1894/// A sphere with BOTH halves of its frame chosen: the polar axis (where the two
1895/// degenerate poles sit) and the SEAM direction (where the `u = 0` meridian
1896/// runs). `seam_direction` is Gram-Schmidt'd against the axis; `None` — and a
1897/// seam parallel to the axis, which names no meridian — falls back to
1898/// [`Vec3::perpendicular`], i.e. exactly what [`make_sphere_surface`] builds.
1899///
1900/// A caller that KNOWS where the sphere will be trimmed uses this to park the
1901/// poles and the seam inside the region the trim removes, so the surviving face
1902/// carries neither. `feature_pipeline::features::tube` does that for its joint
1903/// balls: a seam that survives into the result is an edge bordering ONE face,
1904/// which is a real edge in the topology and a visible line on the model.
1905pub fn make_sphere_surface_framed(
1906    center: Vec3,
1907    radius: f64,
1908    polar_axis: Vec3,
1909    seam_direction: Option<Vec3>,
1910) -> Result<NurbsSurface, String> {
1911    if radius <= EPS {
1912        return Err("makeSphere: radius must be positive".into());
1913    }
1914    let axis = polar_axis.normalized()?;
1915    let x_axis = match seam_direction {
1916        Some(seam) => {
1917            let planar = seam.sub(axis.scale(seam.dot(axis)));
1918            match planar.normalized() {
1919                Ok(unit) if planar.length() > EPS => unit,
1920                _ => axis.perpendicular()?,
1921            }
1922        }
1923        None => axis.perpendicular()?,
1924    };
1925    let meridian = crate::make_arc(
1926        center,
1927        x_axis,
1928        axis,
1929        radius,
1930        -std::f64::consts::FRAC_PI_2,
1931        std::f64::consts::FRAC_PI_2,
1932    )?;
1933    make_revolution(center, axis, &meridian, std::f64::consts::TAU)
1934}
1935
1936pub fn make_torus_surface(
1937    center: Vec3,
1938    axis_direction: Vec3,
1939    major_radius: f64,
1940    minor_radius: f64,
1941) -> Result<NurbsSurface, String> {
1942    if minor_radius <= EPS || major_radius <= minor_radius {
1943        return Err("makeTorus: requires positive minorRadius < majorRadius".into());
1944    }
1945    let axis = axis_direction.normalized()?;
1946    let x_axis = axis.perpendicular()?;
1947    let tube_center = center.add(x_axis.scale(major_radius));
1948    let tube = crate::make_arc(
1949        tube_center,
1950        x_axis,
1951        axis,
1952        minor_radius,
1953        0.0,
1954        std::f64::consts::TAU,
1955    )?;
1956    make_revolution(center, axis, &tube, std::f64::consts::TAU)
1957}
1958
1959fn binomial(n: usize, k: usize) -> f64 {
1960    if k > n {
1961        return 0.0;
1962    }
1963    let k = k.min(n - k);
1964    (1..=k).fold(1.0, |value, index| {
1965        value * (n - k + index) as f64 / index as f64
1966    })
1967}
1968
1969
1970
1971/// Diagnostic "carrier preview" patch (§3.15 applied to display): re-express
1972/// the surface over an INFLATED domain so an inspector can show where the
1973/// carrier continues beyond the face's trim. Open directions inflate about
1974/// the domain centre by `inflate` (a factor; 1 = unchanged), evaluated
1975/// through `evaluate_extended` — exact linear extension for affine carriers,
1976/// ruled/tangent extension generally. CLOSED (periodic) directions keep the
1977/// stored full period instead of inflating — wrapping further would overlap
1978/// the surface onto itself. A torus (closed both ways) returns unchanged.
1979///
1980/// Affine carriers rebuild EXACTLY from four extended corners; everything
1981/// else is a preview-quality degree-3 interpolation over a 33-sample grid.
1982pub fn carrier_preview_patch(surface: &NurbsSurface, inflate: f64) -> Result<NurbsSurface, String> {
1983    let inflate = if inflate.is_finite() {
1984        inflate.clamp(1.0, 16.0)
1985    } else {
1986        2.0
1987    };
1988    let (closed_u, closed_v) = surface.closed_directions()?;
1989    let [u0, u1] = surface.domain_u()?;
1990    let [v0, v1] = surface.domain_v()?;
1991    let stretch = |d0: f64, d1: f64, closed: bool| -> (f64, f64) {
1992        if closed || inflate <= 1.0 {
1993            (d0, d1)
1994        } else {
1995            let centre = 0.5 * (d0 + d1);
1996            let half = 0.5 * (d1 - d0) * inflate;
1997            (centre - half, centre + half)
1998        }
1999    };
2000    let (nu0, nu1) = stretch(u0, u1, closed_u);
2001    let (nv0, nv1) = stretch(v0, v1, closed_v);
2002    if (nu0, nu1) == (u0, u1) && (nv0, nv1) == (v0, v1) {
2003        return Ok(surface.clone());
2004    }
2005    if surface.is_affine()? {
2006        // Exact: the linear extension of an affine patch is the same affine
2007        // map over the larger rectangle.
2008        let corners = [
2009            surface.evaluate_extended(nu0, nv0)?,
2010            surface.evaluate_extended(nu1, nv0)?,
2011            surface.evaluate_extended(nu0, nv1)?,
2012            surface.evaluate_extended(nu1, nv1)?,
2013        ];
2014        return NurbsSurface::new(
2015            1,
2016            1,
2017            vec![nu0, nu0, nu1, nu1],
2018            vec![nv0, nv0, nv1, nv1],
2019            vec![
2020                vec![
2021                    Vec4::from_point(corners[0], 1.0),
2022                    Vec4::from_point(corners[2], 1.0),
2023                ],
2024                vec![
2025                    Vec4::from_point(corners[1], 1.0),
2026                    Vec4::from_point(corners[3], 1.0),
2027                ],
2028            ],
2029        );
2030    }
2031    const SAMPLES: usize = 32;
2032    let u_params: Vec<f64> = (0..=SAMPLES)
2033        .map(|index| nu0 + (nu1 - nu0) * index as f64 / SAMPLES as f64)
2034        .collect();
2035    let v_params: Vec<f64> = (0..=SAMPLES)
2036        .map(|index| nv0 + (nv1 - nv0) * index as f64 / SAMPLES as f64)
2037        .collect();
2038    // Two-pass grid interpolation: fit each v-column, then fit the resulting
2039    // control rows across u, sharing knots per pass (identical parameters).
2040    let mut column_curves = Vec::with_capacity(u_params.len());
2041    for &u in &u_params {
2042        let column: Vec<Vec3> = v_params
2043            .iter()
2044            .map(|&v| surface.evaluate_extended(u, v))
2045            .collect::<Result<_, _>>()?;
2046        column_curves.push(crate::interpolate_curve(
2047            &column,
2048            3,
2049            &normalized(&v_params),
2050        )?);
2051    }
2052    let v_knots = column_curves[0].knots.clone();
2053    let control_rows = column_curves[0].control_points.len();
2054    let mut grid: Vec<Vec<Vec4>> = Vec::with_capacity(u_params.len());
2055    let mut u_knots = Vec::new();
2056    for row_index in 0..control_rows {
2057        let row: Vec<Vec3> = column_curves
2058            .iter()
2059            .map(|curve| curve.control_points[row_index].point())
2060            .collect::<Result<_, _>>()?;
2061        let fitted = crate::interpolate_curve(&row, 3, &normalized(&u_params))?;
2062        u_knots = fitted.knots.clone();
2063        for (u_index, control) in fitted.control_points.iter().enumerate() {
2064            if grid.len() <= u_index {
2065                grid.push(Vec::new());
2066            }
2067            grid[u_index].push(*control);
2068        }
2069    }
2070    // Re-scale the normalized fit knots back onto the inflated domains so the
2071    // preview's parameter space lines up with the original surface's.
2072    let rescale = |knots: &[f64], d0: f64, d1: f64| -> Vec<f64> {
2073        knots.iter().map(|k| d0 + (d1 - d0) * k).collect()
2074    };
2075    NurbsSurface::new(
2076        3,
2077        3,
2078        rescale(&u_knots, nu0, nu1),
2079        rescale(&v_knots, nv0, nv1),
2080        grid,
2081    )
2082}
2083
2084fn normalized(parameters: &[f64]) -> Vec<f64> {
2085    let first = parameters[0];
2086    let last = parameters[parameters.len() - 1];
2087    parameters
2088        .iter()
2089        .map(|p| (p - first) / (last - first))
2090        .collect()
2091}
2092
2093
2094
2095
2096
2097fn analytic_deriv1_on() -> bool {
2098    switch!("BREP_ANALYTIC_DERIV1", true)
2099}
2100
2101
2102/// Default-off until the evaluator's bitwise and complete-body gates qualify it.
2103fn analytic_point_on() -> bool {
2104    switch!("BREP_ANALYTIC_POINT", false)
2105}
2106
2107/// SMALL DERIVATIVES (lane O row 20, 2026-10-29; on by default since the batch 5
2108/// promotion, `BREP_SURFACE_SMALL_DERIVATIVES=0` reads the heap grid): `evaluate_extended`, `derivatives_extended` up to second order,
2109/// `normal` and `principal_curvatures` read the stack twin
2110/// [`NurbsSurface::derivatives_small`] instead of the heap grid. A third of the
2111/// D2 outward shell's heap allocations were `NurbsSurface::derivatives` (a
2112/// sampled-backtrace allocation census); the values are the same bits.
2113pub fn small_derivatives_enabled() -> bool {
2114    switch!("BREP_SURFACE_SMALL_DERIVATIVES", true)
2115}
2116
2117
2118
2119
2120
2121