Skip to main content

brep_geometry/geometry/
pcurve.rs

1pub use crate::{
2    interpolate_curve, project_point_to_surface, project_point_to_surface_seeded, AnalyticSurface,
3    DiagnosticSeverity, KernelDiagnostics, KernelStage, KnotVector, NurbsCurve, NurbsSurface, Vec3,
4    Vec4, KNOT_IDENTITY_TOL,
5};
6
7const EPSILON: f64 = crate::tolerance::FP_FLOOR;
8const LINEAR_TOLERANCE: f64 = crate::tolerance::DEFAULT_MODEL;
9
10/// Coarse clocks only: no per-station timing overhead in a measured fit.
11struct PcurvePhaseClock {
12    started: Option<web_time::Instant>,
13    phase: &'static str,
14    samples: usize,
15    tracking: bool,
16}
17impl PcurvePhaseClock {
18    fn new(phase: &'static str, samples: usize, tracking: bool) -> Self {
19        Self { started: crate::profile::profile_enabled().then(web_time::Instant::now), phase, samples, tracking }
20    }
21}
22impl Drop for PcurvePhaseClock {
23    fn drop(&mut self) {
24        if let Some(started) = self.started {
25            crate::profile::profile_emit(format_args!("pcurve.phase_time phase={} initial_samples={} tracking={} ms={:.3}", self.phase, self.samples, self.tracking, started.elapsed().as_secs_f64()*1000.0));
26        }
27    }
28}
29
30pub fn surface_domains(surface: &NurbsSurface) -> Result<([f64; 2], [f64; 2]), String> {
31    Ok((
32        KnotVector::new(surface.knots_u.clone(), surface.degree_u)?.domain(),
33        KnotVector::new(surface.knots_v.clone(), surface.degree_v)?.domain(),
34    ))
35}
36
37/// The carrier's closed directions, as [`NurbsSurface::closed_directions`]
38/// reads them (cached on the surface, seam tolerance 1e-6, and a sliver patch
39/// whose rows coincide without the surface travelling between them is OPEN).
40/// Until 2026-09-26 this was a second reading with its own tolerance; the
41/// unwrap in [`build_interpolant`] and the wrap in `evaluate_extended` must
42/// agree on what a seam is, or a trim across a sliver reads a period wide.
43fn surface_closedness(surface: &NurbsSurface) -> Result<(bool, bool), String> {
44    surface.closed_directions()
45}
46
47thread_local! {
48    static PCURVE_REJECT_BOUNDS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
49}
50struct PcurveRejectScope(bool);
51impl PcurveRejectScope {
52    fn open(enabled: bool) -> Self {
53        Self(PCURVE_REJECT_BOUNDS.with(|state| state.replace(enabled)))
54    }
55}
56impl Drop for PcurveRejectScope {
57    fn drop(&mut self) { PCURVE_REJECT_BOUNDS.with(|state| state.set(self.0)); }
58}
59
60thread_local! {
61    static PCURVE_STACK_POINT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
62}
63pub struct PcurveStackPointScope(bool);
64impl PcurveStackPointScope {
65    pub fn open(enabled: bool) -> Self { Self(PCURVE_STACK_POINT.with(|state| state.replace(enabled))) }
66}
67impl Drop for PcurveStackPointScope {
68    fn drop(&mut self) { PCURVE_STACK_POINT.with(|state| state.set(self.0)); }
69}
70
71/// The count-zero basis recurrence has the same operations as the value
72/// basis recurrence. Its homogeneous sum uses the same row/column order.
73/// Preserve derivative dehomogenization (multiply by reciprocal, not divide)
74/// while avoiding both the derivative grids and their allocation. Other
75/// degrees and open-direction extension keep the original API. Periodic
76/// wrap retains the original parameter arithmetic before value evaluation.
77#[cfg_attr(feature = "profile-wall", track_caller)]
78pub fn section_extended_point(surface: &NurbsSurface, u: f64, v: f64, enabled: bool) -> Result<Vec3, String> {
79        let _reader = crate::reader_profile::Point::open(crate::reader_profile::SURFACE, std::panic::Location::caller());
80    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::POINT);
81    if enabled && u.is_finite() && v.is_finite()
82        && surface.degree_u <= crate::curve::MAX_STACK_DEGREE
83        && surface.degree_v <= crate::curve::MAX_STACK_DEGREE {
84        let [u0,u1] = surface.domain_u()?;
85        let [v0,v1] = surface.domain_v()?;
86        let mut uu = u;
87        let mut vv = v;
88        if u < u0 || u > u1 || v < v0 || v > v1 {
89            let (closed_u, closed_v) = surface_closedness(surface)?;
90            // Identical to derivatives_extended: keep the original add,
91            // subtract and remainder order before taking the count-zero path.
92            if closed_u && (u < u0 || u > u1) { uu = u0 + (u - u0).rem_euclid(u1 - u0); }
93            if closed_v && (v < v0 || v > v1) { vv = v0 + (v - v0).rem_euclid(v1 - v0); }
94        }
95        if uu >= u0 && uu <= u1 && vv >= v0 && vv <= v1 {
96            let point = surface.evaluate_homogeneous(uu, vv)?;
97            if point.w.abs() <= EPSILON {
98                return Err("NurbsSurface: zero evaluated weight".into());
99            }
100            return Ok(Vec3::new(point.x, point.y, point.z).scale(1.0 / point.w));
101        }
102    }
103    surface.evaluate_extended(u,v)
104}
105
106/// One immutable carrier/section pair; nested fits own separate maps. Keys
107/// preserve all parameter bits, and failed evaluations are never retained.
108pub struct PcurveSampleCache {
109    curve_trace: Option<crate::reuse_profile::Trace<u64>>,
110    surface_trace: Option<crate::reuse_profile::Trace<(u64, u64, bool, bool)>>,
111    rollover: bool,
112    point_limit: usize,
113    surface: usize,
114    curve: usize,
115    pub curves: rustc_hash::FxHashMap<u64, Vec3>,
116    pub surfaces: rustc_hash::FxHashMap<(u64, u64, bool, bool), Vec3>,
117    pub inversions: rustc_hash::FxHashMap<[u64; 3], ([f64; 2], f64)>,
118    pub requests: [usize; 4],
119    pub hits: [usize; 4],
120    pub speeds: rustc_hash::FxHashMap<(u64, u64), f64>,
121}
122thread_local! {
123    pub static PCURVE_SAMPLES: std::cell::RefCell<Vec<Option<PcurveSampleCache>>> = const { std::cell::RefCell::new(Vec::new()) };
124}
125pub struct PcurveSampleScope<'a>(std::marker::PhantomData<(&'a NurbsSurface, &'a NurbsCurve)>);
126impl<'a> PcurveSampleScope<'a> {
127    pub fn open(surface: &'a NurbsSurface, curve: &'a NurbsCurve, enabled: bool) -> Self {
128        Self::open_limit(surface, curve, enabled, switch!("BREP_PCURVE_SAMPLE_ROLLOVER", false),
129            if larger_working_set() { 65536 } else { PCURVE_SAMPLE_CACHE_LIMIT })
130    }
131
132    pub fn open_limit(surface: &'a NurbsSurface, curve: &'a NurbsCurve, enabled: bool, rollover: bool, point_limit: usize) -> Self {
133        let cache = enabled
134            .then(|| PcurveSampleCache {
135                curve_trace: crate::reuse_profile::Trace::open("curve", || serde_json::json!({"curve":curve,"identity":curve as *const _ as usize,"limit":point_limit})),
136                surface_trace: crate::reuse_profile::Trace::open("surface", || serde_json::json!({"surface":surface,"identity":surface as *const _ as usize,"curve":curve,"limit":point_limit})),
137                rollover, point_limit, surface: surface as *const _ as usize,
138                curve: curve as *const _ as usize, curves: Default::default(),
139                surfaces: Default::default(), inversions: Default::default(), requests: [0; 4], hits: [0; 4], speeds: Default::default() });
140        PCURVE_SAMPLES.with(|stack| stack.borrow_mut().push(cache));
141        Self(std::marker::PhantomData)
142    }
143}
144impl Drop for PcurveSampleScope<'_> {
145    fn drop(&mut self) {
146        PCURVE_SAMPLES.with(|stack| {
147        let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
148            if let Some(Some(cache)) = stack.borrow_mut().pop() {
149                if crate::profile::profile_enabled() {
150                    profile_line!("pcurve.samples requests={:?} hits={:?} retained={:?}", cache.requests,
151                        cache.hits, [cache.curves.len(), cache.surfaces.len(), cache.inversions.len(), cache.speeds.len()]);
152                }
153            }
154        });
155    }
156}
157pub const PCURVE_SAMPLE_CACHE_LIMIT: usize = 16384;
158
159/// Exact reuse distances put the measured fit/point working sets above the
160/// old ceilings. This experiment retains the first entries under larger,
161/// fixed limits; it never evicts useful early stations or changes a reader.
162pub fn larger_working_set() -> bool {
163    switch!("BREP_PCURVE_WORKING_SET", false)
164}
165
166/// The old policy retains only the first stations of a fit, even when later
167/// verification passes repeatedly visit a different working set. Rollover
168/// preserves the bound and every exact-bit key; evicted values are evaluated
169/// by the original reader. Apply only to the two maps observed to saturate.
170fn retain_sample<K: std::hash::Hash + Eq, V>(
171    map: &mut rustc_hash::FxHashMap<K, V>, key: K, value: V, rollover: bool, limit: usize,
172) {
173    if rollover && map.len() >= limit { map.clear(); }
174    if map.len() < limit { map.insert(key, value); }
175}
176pub fn section_u_speed(surface: &NurbsSurface, u: f64, v: f64) -> Result<f64, String> {
177    let key = (u.to_bits(), v.to_bits());
178    let (active, hit) = PCURVE_SAMPLES.with(|stack| {
179        let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
180        let mut stack = stack.borrow_mut();
181        let Some(Some(cache)) = stack.last_mut() else { return (false, None) };
182        if cache.surface != surface as *const _ as usize { return (false, None) }
183        cache.requests[3] += 1;
184        let hit = cache.speeds.get(&key).copied();
185        cache.hits[3] += usize::from(hit.is_some());
186        (true, hit)
187    });
188    if let Some(hit) = hit { return Ok(hit) }
189    let speed = surface.deriv1(u, v)?.1.length();
190    if active { PCURVE_SAMPLES.with(|stack| {
191        let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
192        let mut stack = stack.borrow_mut();
193        let cache = stack.last_mut().unwrap().as_mut().unwrap();
194        if cache.speeds.len() < PCURVE_SAMPLE_CACHE_LIMIT { cache.speeds.insert(key, speed); }
195    }); }
196    Ok(speed)
197}
198
199#[track_caller]
200pub fn section_curve_point(curve: &NurbsCurve, parameter: f64) -> Result<Vec3, String> {
201    let caller = std::panic::Location::caller();
202    let key = parameter.to_bits();
203    let (active, hit) = PCURVE_SAMPLES.with(|stack| {
204        let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
205        let mut stack = stack.borrow_mut();
206        let Some(Some(cache)) = stack.last_mut() else { return (false, None) };
207        if cache.curve != curve as *const _ as usize { return (false, None) }
208        cache.requests[0] += 1;
209        let hit = cache.curves.get(&key).copied();
210        cache.hits[0] += usize::from(hit.is_some());
211        if hit.is_some() { if let Some(trace) = &mut cache.curve_trace { trace.access(&key, caller, true, true); } }
212        (true, hit)
213    });
214    if let Some(hit) = hit { return Ok(hit) }
215    let result = curve.evaluate(parameter);
216    let point = match result {
217        Ok(point) => point,
218        Err(error) => {
219            if active { PCURVE_SAMPLES.with(|stack| {
220        let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP); if let Some(trace) = &mut stack.borrow_mut().last_mut().unwrap().as_mut().unwrap().curve_trace {
221                trace.access(&key, caller, false, false);
222            } }); }
223            return Err(error);
224        }
225    };
226    if active { PCURVE_SAMPLES.with(|stack| {
227        let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
228        let mut stack = stack.borrow_mut();
229        let cache = stack.last_mut().unwrap().as_mut().unwrap();
230        if let Some(trace) = &mut cache.curve_trace { trace.access(&key, caller, false, true); }
231        retain_sample(&mut cache.curves, key, point, cache.rollover, cache.point_limit);
232    }); }
233    Ok(point)
234}
235#[track_caller]
236pub fn section_surface_point(surface: &NurbsSurface, u: f64, v: f64, extended: bool) -> Result<Vec3, String> {
237    let caller = std::panic::Location::caller();
238    // Extended evaluation has two arithmetic paths. Keep them separate even
239    // if a nested caller changes the stack-point policy within this scope.
240    let stack_point = PCURVE_STACK_POINT.with(|state| state.get());
241    let key = (u.to_bits(), v.to_bits(), extended, stack_point);
242    let (active, hit) = PCURVE_SAMPLES.with(|stack| {
243        let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
244        let mut stack = stack.borrow_mut();
245        let Some(Some(cache)) = stack.last_mut() else { return (false, None) };
246        if cache.surface != surface as *const _ as usize { return (false, None) }
247        cache.requests[1] += 1;
248        let hit = cache.surfaces.get(&key).copied();
249        cache.hits[1] += usize::from(hit.is_some());
250        if hit.is_some() { if let Some(trace) = &mut cache.surface_trace { trace.access(&key, caller, true, true); } }
251        (true, hit)
252    });
253    if let Some(hit) = hit { return Ok(hit) }
254    let result = if extended { section_extended_point(surface, u, v, stack_point) } else { surface.evaluate(u, v) };
255    let point = match result {
256        Ok(point) => point,
257        Err(error) => {
258            if active { PCURVE_SAMPLES.with(|stack| {
259        let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP); if let Some(trace) = &mut stack.borrow_mut().last_mut().unwrap().as_mut().unwrap().surface_trace {
260                trace.access(&key, caller, false, false);
261            } }); }
262            return Err(error);
263        }
264    };
265    if active { PCURVE_SAMPLES.with(|stack| {
266        let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
267        let mut stack = stack.borrow_mut();
268        let cache = stack.last_mut().unwrap().as_mut().unwrap();
269        if let Some(trace) = &mut cache.surface_trace { trace.access(&key, caller, false, true); }
270        retain_sample(&mut cache.surfaces, key, point, cache.rollover, cache.point_limit);
271    }); }
272    Ok(point)
273}
274pub fn invert_checked(surface: &NurbsSurface, point: Vec3) -> Result<([f64; 2], f64), String> {
275    let key = [point.x.to_bits(), point.y.to_bits(), point.z.to_bits()];
276    let (active, hit) = PCURVE_SAMPLES.with(|stack| {
277        let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
278        let mut stack = stack.borrow_mut();
279        let Some(Some(cache)) = stack.last_mut() else { return (false, None) };
280        if cache.surface != surface as *const _ as usize { return (false, None) }
281        cache.requests[2] += 1;
282        let hit = cache.inversions.get(&key).copied();
283        cache.hits[2] += usize::from(hit.is_some());
284        (true, hit)
285    });
286    if let Some(hit) = hit { return Ok(hit) }
287    let projection = invert_checked_uncached(surface, point)?;
288    if active { PCURVE_SAMPLES.with(|stack| {
289        let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
290        let mut stack = stack.borrow_mut();
291        let cache = stack.last_mut().unwrap().as_mut().unwrap();
292        if cache.inversions.len() < PCURVE_SAMPLE_CACHE_LIMIT { cache.inversions.insert(key, projection); }
293    }); }
294    Ok(projection)
295}
296
297pub fn invert_checked_uncached(surface: &NurbsSurface, point: Vec3) -> Result<([f64; 2], f64), String> {
298    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_INVERT_CHECKED, surface);
299    if surface.is_affine()? {
300        let ([u0, _], [v0, _]) = surface_domains(surface)?;
301        let (origin, du, dv) = surface.deriv1(u0, v0)?;
302        let delta = point.sub(origin);
303        let uu = du.dot(du);
304        let uv = du.dot(dv);
305        let vv = dv.dot(dv);
306        let along_u = delta.dot(du);
307        let along_v = delta.dot(dv);
308        let determinant = uu * vv - uv * uv;
309        if determinant.abs() > EPSILON {
310            let parameter = [
311                u0 + (along_u * vv - along_v * uv) / determinant,
312                v0 + (along_v * uu - along_u * uv) / determinant,
313            ];
314            // The standoff is a MEASUREMENT here as on every other carrier:
315            // until 2026-09-26 this returned 0.0 for "affine, not measured",
316            // and a curve 1e-2 off its plane read as lying on it.
317            let foot = origin.add(du.scale(parameter[0] - u0)).add(dv.scale(parameter[1] - v0));
318            return Ok((parameter, point.sub(foot).length()));
319        }
320    }
321    let projection = project_point_to_surface(surface, point)?;
322    // Retain the projector's actual result, before the ordinary inverter
323    // reduces it to parameters and distance. A later precision scope still
324    // refines this input; it does not reconstruct a foot from rounded data.
325    if crate::switch!("BREP_STEP_PRECISION_FOOT_REUSE", true) && !crate::projection::global_site_filter_active() {
326        FOOT_MEMO.with(|memo| {
327            if let Some(open) = memo.borrow_mut().as_mut().filter(|m| !m.precision && std::ptr::eq(m.surface,surface)) {
328                let key = point_bits(point);
329                if DEFER_FOOT_INSERTS.with(|cell|cell.get()) {
330                    open.pending_global.push((key,Some(projection)));
331                } else {
332                    open.global.insert(key,Some(projection));
333                }
334            }
335        });
336    }
337    Ok(([projection.u, projection.v], projection.distance))
338}
339
340/// Whether an end station at a cone's apex takes its nearest regular
341/// station's u (`true`), as in `build_interpolant`, or the projector's
342/// arbitrary u there as before 2026-09-27. `BREP_PCURVE_CONE_APEX_U=0`
343/// restores the projector's u, for a same-binary A/B.
344fn cone_apex_u() -> bool {
345    switch!("BREP_PCURVE_CONE_APEX_U", true)
346}
347
348/// Whether a round with more candidates than the cap has room for keeps its
349/// WORST probes (`true`), or the first in span order as before 2026-09-27.
350/// `BREP_PCURVE_WORST_FIRST=0` restores span order, for a same-binary A/B.
351fn worst_first() -> bool {
352    switch!("BREP_PCURVE_WORST_FIRST", true)
353}
354
355/// `BREP_PCURVE_C0_JOIN=0` builds one C2 interpolant through the stations as
356/// before 2026-10-03 (the C0 joins at the curve's corners off), for a
357/// same-binary A/B. Read once per process.
358/// `BREP_PCURVE_POLE_ROW_CROSSING` (default on, `0` off): on a closed-u
359/// carrier other than the analytic sphere (which has its own pole rules), a C0
360/// join of a trim on the carrier's collapsed row (a pole) where the trim comes in
361/// along one longitude and leaves along another is built as the incoming piece
362/// held at its longitude, a link along the row, and the outgoing piece held at
363/// its own. Off, both pieces share the pole station's single (arbitrary)
364/// longitude, and the piece whose meridian it is not swings sideways in its
365/// last span: a trim through a spherical cap's pole read 1.0e-3 off its edge
366/// at v = 0.9995 while every station read 1e-8 (1.2e-5 of a union's volume).
367fn pole_row_crossing() -> bool {
368    switch!(live "BREP_PCURVE_POLE_ROW_CROSSING", true)
369}
370
371/// Whether `v`'s row of `surface` is collapsed. The row is the curve whose
372/// control points are the columns' points at `v` (each column of the net read
373/// as a curve in v); with positive weights the row lies in their hull, so the
374/// row is one point exactly when they are (within 1e-12 of the net's extent).
375fn row_collapsed(surface: &NurbsSurface, v: f64) -> Result<bool, String> {
376    if surface.control_points.iter().flatten().any(|control| !(control.w > 0.0)) {
377        return Ok(false);
378    }
379    let mut row = Vec::with_capacity(surface.control_points.len());
380    for column in &surface.control_points {
381        let curve = NurbsCurve::new(surface.degree_v, surface.knots_v.clone(), column.clone())?;
382        row.push(curve.evaluate(v)?);
383    }
384    let Some(&first) = row.first() else { return Ok(false) };
385    let extent = surface
386        .control_points
387        .iter()
388        .flatten()
389        .filter_map(|control| control.point().ok())
390        .map(|point| point.sub(first).length())
391        .fold(0.0_f64, f64::max);
392    Ok(row.iter().all(|point| point.sub(first).length() <= 1e-12 * (1.0 + extent)))
393}
394
395/// The longitude a trim reaches a pole at, from the two stations nearest it
396/// on one side (`near`, then `far`): linear in the curve parameter, so a trim
397/// whose longitude varies toward the pole keeps its locus, and a meridian its
398/// constant longitude.
399fn pole_longitude(points: &[Vec3], parameters: &[f64], pole: usize, near: usize, far: usize) -> f64 {
400    let (t_pole, t_near, t_far) = (parameters[pole], parameters[near], parameters[far]);
401    if (t_near - t_far).abs() <= f64::EPSILON * t_near.abs().max(1.0) {
402        return points[near].x;
403    }
404    points[near].x + (points[near].x - points[far].x) * (t_pole - t_near) / (t_near - t_far)
405}
406
407/// The pole-row crossings among `pieces`' joins: `(join index, the incoming
408/// side's end point, the outgoing side's start point)` in (u, v). A join is a
409/// crossing when its station lies on a collapsed row ([`row_collapsed`]),
410/// where its longitude is arbitrary, and the two sides reach it at different
411/// longitudes ([`pole_longitude`]). No station other than the pole's moves.
412fn pole_row_crossings(surface: &NurbsSurface, points: &mut [Vec3], parameters: &[f64], pieces: &[usize]) -> Result<Vec<(usize, Vec3, Vec3)>, String> {
413    let ([u0, u1], _) = surface_domains(surface)?;
414    let period = (u1 - u0).abs();
415    let mut crossings = Vec::new();
416    for &join in &pieces[1..pieces.len() - 1] {
417        if join < 2 || join + 2 >= points.len() || !row_collapsed(surface, points[join].y)? {
418            continue;
419        }
420        let incoming = pole_longitude(points, parameters, join, join - 1, join - 2);
421        let outgoing = pole_longitude(points, parameters, join, join + 1, join + 2);
422        if (incoming - outgoing).abs() <= 1e-12 * period.max(1.0) {
423            continue;
424        }
425        let pole_v = points[join].y;
426        crossings.push((join, Vec3::new(incoming, pole_v, 0.0), Vec3::new(outgoing, pole_v, 0.0)));
427    }
428    Ok(crossings)
429}
430
431/// A trim station at either END on a collapsed row ([`row_collapsed`]) takes
432/// the longitude the trim reaches it at ([`pole_longitude`]); no other
433/// station moves.
434fn hold_pole_row_ends(surface: &NurbsSurface, points: &mut [Vec3], parameters: &[f64]) -> Result<(), String> {
435    if points.len() < 3 {
436        return Ok(());
437    }
438    let last = points.len() - 1;
439    if row_collapsed(surface, points[0].y)? && !row_collapsed(surface, points[1].y)? {
440        points[0].x = pole_longitude(points, parameters, 0, 1, 2);
441    }
442    if row_collapsed(surface, points[last].y)? && !row_collapsed(surface, points[last - 1].y)? {
443        points[last].x = pole_longitude(points, parameters, last, last - 1, last - 2);
444    }
445    Ok(())
446}
447
448fn c0_joins() -> bool {
449    switch!("BREP_PCURVE_C0_JOIN", true)
450}
451
452fn seeded_inserts() -> bool {
453    switch!("BREP_PCURVE_SEEDED_INSERTS", true)
454}
455
456/// [`invert_checked`] for a station inserted between two whose feet are known:
457/// Newton from the pcurve's own `(u, v)` at that fraction, which already lies
458/// between the neighbours' feet on their branch, and the global search only
459/// when that local foot stands off further than the neighbours do (plus the
460/// refinement floor) — a local minimum the curve does not sit at. The global
461/// search was 30 s of a 54 s `abc_00000011` import (732k calls, 41 µs each,
462/// measured 2026-09-26). Planes and analytic carriers keep their closed forms.
463/// `BREP_PCURVE_SEEDED_INSERTS=0` restores the global search at every insert,
464/// for a same-binary A/B.
465fn invert_near(
466    surface: &NurbsSurface,
467    point: Vec3,
468    seed: [f64; 2],
469    neighbour_gap: f64,
470) -> Result<([f64; 2], f64), String> {
471    if !seeded_inserts() || surface.is_affine()? || surface.analytic().is_some() || surface.affine_sphere().is_some() {
472        return invert_checked(surface, point);
473    }
474    let seeded = project_point_to_surface_seeded(surface, point, seed[0], seed[1])?;
475    if seeded.distance <= neighbour_gap + PCURVE_REFINEMENT_TOLERANCE {
476        return Ok(([seeded.u, seeded.v], seeded.distance));
477    }
478    invert_checked(surface, point)
479}
480
481fn unwrap_periodic(values: &mut [f64], minimum: f64, maximum: f64) {
482    let period = maximum - minimum;
483    for index in 1..values.len() {
484        while values[index] - values[index - 1] > period / 2.0 {
485            values[index] -= period;
486        }
487        while values[index] - values[index - 1] < -period / 2.0 {
488            values[index] += period;
489        }
490    }
491    if values.len() > 1 {
492        while values[0] - values[1] > period / 2.0 {
493            values[0] -= period;
494        }
495        while values[0] - values[1] < -period / 2.0 {
496            values[0] += period;
497        }
498    }
499    // Recenter the whole (now continuous) sequence into the domain by the
500    // whole-period shift that leaves the LEAST parameter outside [minimum,
501    // maximum]. A single middle/mean sample is NOT representative of a curve
502    // that bulges out to touch — or straddle — the periodic seam: when that
503    // sample is a boundary-kissing point (the at-seam projection unwraps a hair
504    // past the boundary), a single-sample test misfires and shoves the entire
505    // curve a full period out of range (ABC helmet 00000011/12 side channels:
506    // a touching edge's parameter run snapped a whole period off its true
507    // interior, tearing the loop open in parameter space).
508    if values.len() > 1 {
509        let excursion = |shift: f64| -> f64 {
510            values
511                .iter()
512                .map(|value| {
513                    let v = value + shift;
514                    (minimum - v).max(0.0) + (v - maximum).max(0.0)
515                })
516                .sum::<f64>()
517        };
518        let mean = values.iter().copied().sum::<f64>() / values.len() as f64;
519        let center = 0.5 * (minimum + maximum);
520        let base_k = ((center - mean) / period).round() as i64;
521        let mut best_shift = 0.0;
522        let mut best_excursion = f64::INFINITY;
523        for k in (base_k - 1)..=(base_k + 1) {
524            let shift = k as f64 * period;
525            let value = excursion(shift);
526            if value < best_excursion {
527                best_excursion = value;
528                best_shift = shift;
529            }
530        }
531        if best_shift != 0.0 {
532            for value in values.iter_mut() {
533                *value += best_shift;
534            }
535        }
536    }
537}
538
539/// The interpolant through `raw_parameters`, and what building it CLAMPED:
540/// the largest parameter distance a sample was pulled back into an open
541/// direction's domain, and the 3D distance between the extended surface at
542/// the raw parameter and the clamped foot. Both zero when nothing was pulled.
543/// A closed direction wraps and is never clamped.
544pub fn build_interpolant(
545    surface: &NurbsSurface,
546    raw_parameters: &[[f64; 2]],
547    curve_parameters: &[f64],
548) -> Result<(NurbsCurve, f64, f64), String> {
549    build_interpolant_joined(surface, raw_parameters, curve_parameters, &[])
550}
551
552/// [`build_interpolant`] with C0 JOINS: `joins` are values of
553/// `curve_parameters` at which the edge curve itself has a corner (a knot of
554/// multiplicity ≥ its degree, `range_breaks`). One cubic through all the
555/// stations is C2 everywhere, so across a corner it overshoots on both sides
556/// by a first-order amount however many stations are inserted: `abc_00000011`
557/// face #585 edge 179 (79 such knots on a 241-point curve) read 2.055e-4 off
558/// at 153 stations with the file's curve 2.1e-7 off the carrier (measured
559/// 2026-10-03). The stations have been planted at those knots since
560/// 2026-09-26; what was missing was the interpolant honouring them. Each
561/// piece between joins is interpolated on its own and the pieces are
562/// concatenated at knots of multiplicity 3 — the join `blend/track_fit.rs`
563/// makes for a blend track. A piece shorter than four stations cannot carry
564/// a cubic, so its join is dropped and it merges with its neighbour.
565pub fn build_interpolant_joined(
566    surface: &NurbsSurface,
567    raw_parameters: &[[f64; 2]],
568    curve_parameters: &[f64],
569    joins: &[f64],
570) -> Result<(NurbsCurve, f64, f64), String> {
571    let _clock = PcurvePhaseClock::new("interpolant", raw_parameters.len(), false);
572    let ([u0, u1], [v0, v1]) = surface_domains(surface)?;
573    let (closed_u, closed_v) = surface_closedness(surface)?;
574    let mut parameters = raw_parameters.to_vec();
575    // A cone's apex has no longitude either: every u there is the same point,
576    // and the projector answers one arbitrarily (0, which unwraps to 1). A trim
577    // that ENDS at the apex then turns sideways in its last span —
578    // `abc 00008080` face #163 edge 476, a generatrix at u = 0.80255 whose
579    // apex station read u = 1.0 (2026-09-27). An apex station at either end of
580    // the run takes the u of its nearest regular station, so a generatrix's
581    // pcurve is the straight u = const it is. Interior apex crossings are left
582    // to the branch logic below. `BREP_PCURVE_CONE_APEX_U=0` switches this off,
583    // for a same-binary A/B.
584    if cone_apex_u() && matches!(surface.analytic(), Some(AnalyticSurface::RuledRevolution { .. })) && parameters.len() >= 2 {
585        let speeds = parameters
586            .iter()
587            .map(|parameter| section_u_speed(surface, parameter[0], parameter[1]))
588            .collect::<Result<Vec<_>, _>>()?;
589        let reference = speeds.iter().copied().fold(0.0_f64, f64::max);
590        let singular = |index: usize| speeds[index] <= reference * 1e-2;
591        if let (Some(first), Some(last)) = (
592            (0..parameters.len()).find(|&index| !singular(index)),
593            (0..parameters.len()).rfind(|&index| !singular(index)),
594        ) {
595            for index in 0..first {
596                parameters[index][0] = parameters[first][0];
597            }
598            for index in last + 1..parameters.len() {
599                parameters[index][0] = parameters[last][0];
600            }
601        }
602    }
603    // Longitude is undefined at a sphere pole: the surface's u tangent
604    // vanishes there, and closest-point inversion is free to return any u.
605    // Letting that arbitrary value participate in periodic unwrapping can move
606    // the first real meridian by a whole period (e.g. 0.75 -> -0.25). Analytic
607    // carriers are subsequently clamped, collapsing that meridian onto u=0.
608    //
609    // Keep this deliberately sphere- and singularity-gated. Split the u values
610    // into maximal non-pole runs, unwrap each run independently, and leave the
611    // pole samples untouched. The existing interpolant degree stays unchanged;
612    // lowering it here would also change endpoint-tangent decisions made later
613    // while stitching the face loop.
614    let sphere_u_singular = if matches!(surface.analytic(), Some(AnalyticSurface::Sphere { .. })) {
615        let speeds = parameters
616            .iter()
617            .map(|parameter| {
618                section_u_speed(surface, parameter[0], parameter[1])
619            })
620            .collect::<Result<Vec<_>, _>>()?;
621        let reference = speeds.iter().copied().fold(0.0_f64, f64::max);
622        speeds
623            .into_iter()
624            // Uniform edge stations need not hit the pole exactly (ABC 5360
625            // bottoms out at v=5.5e-4). In this small conditioning band,
626            // longitude is already numerically arbitrary and must not connect
627            // the two meridian runs across the pole.
628            .map(|speed| speed <= reference * 1e-2)
629            .collect::<Vec<_>>()
630    } else {
631        vec![false; parameters.len()]
632    };
633    // Do not perturb ordinary pole-touching trims. The special path is needed
634    // only when a pole band is bracketed by nonsingular samples and its raw
635    // longitude changes by at least half a period: a true through-pole branch
636    // reset whose two meridian runs must be unwrapped independently.
637    // Prefix/suffix pole samples on normal sphere caps retain the legacy
638    // interpolation byte-for-byte. Include the exactly-half-period case so
639    // floating-point noise cannot decide which entire run is lifted (ABC 5603).
640    let has_interior_pole_crossing = sphere_u_singular
641        .iter()
642        .position(|singular| !singular)
643        .zip(sphere_u_singular.iter().rposition(|singular| !singular))
644        .is_some_and(|(first, last)| sphere_u_singular[first..=last].iter().any(|value| *value));
645    let period = (u1 - u0).abs();
646    let interior_pole_branch_reset = closed_u
647        && has_interior_pole_crossing
648        && parameters.windows(2).zip(sphere_u_singular.windows(2)).any(
649            |(parameter_pair, singular_pair)| {
650                (singular_pair[0] || singular_pair[1])
651                    && (parameter_pair[1][0] - parameter_pair[0][0]).abs()
652                        >= 0.5 * period - 1e-12 * period.max(1.0)
653            },
654        );
655    if closed_u {
656        let mut values = parameters.iter().map(|value| value[0]).collect::<Vec<_>>();
657        if interior_pole_branch_reset {
658            let mut start = 0;
659            while start < values.len() {
660                while start < values.len() && sphere_u_singular[start] {
661                    start += 1;
662                }
663                let mut end = start;
664                while end < values.len() && !sphere_u_singular[end] {
665                    end += 1;
666                }
667                unwrap_periodic(&mut values[start..end], u0, u1);
668                start = end;
669            }
670        } else {
671            unwrap_periodic(&mut values, u0, u1);
672        }
673        for (parameter, value) in parameters.iter_mut().zip(values) {
674            parameter[0] = value;
675        }
676    }
677    if closed_v {
678        let mut values = parameters.iter().map(|value| value[1]).collect::<Vec<_>>();
679        unwrap_periodic(&mut values, v0, v1);
680        for (parameter, value) in parameters.iter_mut().zip(values) {
681            parameter[1] = value;
682        }
683    }
684    // A closed direction WRAPS: an edge that straddles the seam has no single
685    // in-domain parameter run, so keep the unwrapped (possibly slightly
686    // out-of-domain) values and let the periodic evaluator wrap them — clamping
687    // them onto the seam boundary would collapse the straddling geometry (and,
688    // via the interpolant, spike neighbouring stations). This applies to
689    // analytic carriers too: a refitted cylinder can have stepped rims that
690    // cross its seam. evaluate_extended wraps every closed direction.
691    // Open directions must stay in-domain; their extension is a ruling.
692    //
693    // The clamp is MEASURED, not silent: a sample pulled back into the domain
694    // is reported as the parameter distance it moved and the 3D distance
695    // between the extended surface at its raw parameter and the clamped foot
696    // ([`PcurveFitReport::clamped_excursion`]). Until 2026-09-30 a trim that
697    // ran past its chart came back folded onto the chart's boundary with
698    // nothing in the report to say so; on the rib-base document that was
699    // 3.03e-2 of volume on a body `validate()` passes.
700    let mut excursion = 0.0_f64;
701    let mut distance = 0.0_f64;
702    let mut points = Vec::with_capacity(parameters.len());
703    for parameter in parameters {
704        let u = if closed_u {
705            parameter[0]
706        } else {
707            parameter[0].clamp(u0, u1)
708        };
709        let v = if closed_v {
710            parameter[1]
711        } else {
712            parameter[1].clamp(v0, v1)
713        };
714        let pulled = ((parameter[0] - u).powi(2) + (parameter[1] - v).powi(2)).sqrt();
715        if pulled > 0.0 {
716            excursion = excursion.max(pulled);
717            let extended = surface.evaluate_extended(parameter[0], parameter[1])?;
718            distance = distance.max(extended.sub(surface.evaluate(u, v)?).length());
719        }
720        points.push(Vec3::new(u, v, 0.0));
721    }
722    let degree = 3usize.min(points.len() - 1);
723    let mut bounds: Vec<usize> = joins
724        .iter()
725        .filter_map(|join| curve_parameters.iter().position(|parameter| parameter == join))
726        .filter(|&index| index > 0 && index + 1 < curve_parameters.len())
727        .collect();
728    bounds.sort_unstable();
729    bounds.dedup();
730    // A trim that ENDS on a collapsed row (a pole of a closed-u carrier)
731    // holds the longitude of its nearest regular station through the pole
732    // band, as the cone apex does (`BREP_PCURVE_POLE_ROW_CROSSING`).
733    // The analytic sphere has its own pole rules above; this reads every
734    // other closed-u carrier (a surface of revolution's pole, e.g. a cap of a
735    // cone filled out to its sphere).
736    let pole_rows = pole_row_crossing() && closed_u && !matches!(surface.analytic(), Some(AnalyticSurface::Sphere { .. }));
737    if pole_rows {
738        hold_pole_row_ends(surface, &mut points, curve_parameters)?;
739    }
740    if degree < 3 || bounds.is_empty() || !c0_joins() {
741        let curve = interpolate_curve(&points, degree, curve_parameters)?;
742        return Ok((curve, excursion, distance));
743    }
744    // Every piece needs four stations for a cubic: drop the join that
745    // closes a shorter piece, from the left, until all pieces carry one.
746    let mut pieces = vec![0usize];
747    for bound in bounds {
748        if bound + 1 - pieces[pieces.len() - 1] >= 4 {
749            pieces.push(bound);
750        }
751    }
752    if curve_parameters.len() - pieces[pieces.len() - 1] < 4 {
753        pieces.pop();
754    }
755    pieces.push(curve_parameters.len() - 1);
756    if pieces.len() < 3 {
757        let curve = interpolate_curve(&points, degree, curve_parameters)?;
758        return Ok((curve, excursion, distance));
759    }
760    // A join on a collapsed row (a pole of a closed-u carrier) where the
761    // trim leaves along another longitude than it came in on: each side holds
762    // its own longitude up to the pole and a link runs along the row
763    // (`BREP_PCURVE_POLE_ROW_CROSSING`).
764    let mut points = points;
765    let crossings = if pole_rows { pole_row_crossings(surface, &mut points, curve_parameters, &pieces)? } else { Vec::new() };
766    let mut knots: Vec<f64> = Vec::with_capacity(curve_parameters.len() + 8);
767    let mut control: Vec<Vec4> = Vec::with_capacity(curve_parameters.len() + 4);
768    let last_piece = pieces.len() - 2;
769    // The longitude the next piece starts at, when a link precedes it.
770    let mut start_override: Option<Vec3> = None;
771    for piece in 0..=last_piece {
772        let (from, to) = (pieces[piece], pieces[piece + 1]);
773        let mut piece_points = points[from..=to].to_vec();
774        let mut piece_parameters = curve_parameters[from..=to].to_vec();
775        if let Some(start) = start_override.take() {
776            piece_points[0] = start;
777        }
778        let crossing = crossings.iter().find(|crossing| crossing.0 == to).copied();
779        if let Some((_, before, _)) = crossing {
780            // The link takes a sliver of the parameter just short of the
781            // pole: the piece ends there at its own longitude.
782            let span = piece_parameters[piece_parameters.len() - 1] - piece_parameters[piece_parameters.len() - 2];
783            let sliver = (1e-9 * (curve_parameters[curve_parameters.len() - 1] - curve_parameters[0]).abs()).min(0.1 * span);
784            let last = piece_parameters.len() - 1;
785            piece_parameters[last] -= sliver;
786            piece_points[last] = before;
787        }
788        let fitted = interpolate_curve(&piece_points, 3, &piece_parameters)?;
789        if piece == 0 {
790            knots.extend(fitted.knots[..4].iter().copied());
791        }
792        knots.extend(fitted.knots[4..fitted.knots.len() - 4].iter().copied());
793        control.extend(fitted.control_points.iter().skip(usize::from(piece > 0)).copied());
794        if let Some((_, before, after)) = crossing {
795            let link_start = piece_parameters[piece_parameters.len() - 1];
796            knots.extend(std::iter::repeat(link_start).take(3));
797            for k in 1..=3 {
798                let along = k as f64 / 3.0;
799                let point = Vec3::new(before.x + (after.x - before.x) * along, before.y + (after.y - before.y) * along, 0.0);
800                control.push(Vec4::from_point(point, 1.0));
801            }
802            start_override = Some(after);
803        }
804        let multiplicity = if piece == last_piece { 4 } else { 3 };
805        knots.extend(std::iter::repeat(curve_parameters[to]).take(multiplicity));
806    }
807    let curve = NurbsCurve::new(3, knots, control)?;
808    Ok((curve, excursion, distance))
809}
810
811/// The 3D residual a pcurve's image must reach before `build_pcurve_on_surface`
812/// accepts it, and the sample ceiling it refines up to.
813///
814/// A trimmed face's boundary is only ever as accurate as these two numbers, and
815/// every mass property is an integral over that boundary — so this is the floor
816/// under area, volume and centroid for every curved trim in the kernel.
817///
818/// These were `min(1e-3, 1e-4 * scale)` and 160, where `scale` is
819/// `1 + ||curve midpoint||` — the DISTANCE FROM THE WORLD ORIGIN of the curve's
820/// midpoint, not the part's size. That expression pinned to an absolute 1e-3
821/// once the midpoint sat more than about nine units from the origin, so on an
822/// ordinary part the bar was 1e-3 and tracked nothing.
823///
824/// Measured on `offset-shell-box-bore-dished-face`, whose dished wall is a
825/// closed-form identity at 2468.431782123 (three independent routes agree). The
826/// floor is one of TWO errors there; the other is the refitted sphere carrier
827/// that `sphere_offset_surface` now builds in closed form, and before both moved
828/// they partly CANCELLED — which is why either alone reads as a regression:
829///
830/// ```text
831/// floor     Box_O.S2            abs err     relative   gate total  worst case
832/// 1e-3   2468.442270355      +1.049e-02     4.25e-06        (old)
833/// 1e-6   2468.431785429      +3.306e-06     1.34e-09       181.4 s     31.2 s
834/// 1e-7   2468.431782170      +4.746e-08     1.92e-11       218.5 s     32.1 s
835/// 1e-9   2468.431782103      -2.037e-08    -8.25e-12       305.5 s     46.8 s
836/// ```
837///
838/// 1e-7 is chosen: 70x the accuracy of 1e-6 for +20% gate time, where 1e-9 costs
839/// a further +40% for a 2.3x residual no oracle in this corpus could resolve.
840/// All four cells are one session on one binary, so the times are comparable to
841/// each other. Every case carrying a closed-form oracle moves TOWARD it and none
842/// away (`PushFaceTest` 339x, `PushFaceTest2` 275x); no case changes class at
843/// any floor.
844///
845/// A flat ABSOLUTE is what was measured, not what was designed. This codebase
846/// otherwise keys identity bands to part size (`KernelTolerances::heal_band`,
847/// the `1e-11*(1+scale)` blend family), and on a 3000 mm part 1e-7 is 3e-11
848/// relative — refinement will exhaust `MAX_PCURVE_SAMPLES` and return whatever
849/// it reached. Until 2026-09-12 it did so SILENTLY; now the fit's
850/// [`PcurveFitReport`] carries the residual actually achieved and a
851/// [`PcurveFitExit::SampleCeiling`] exit, and the owning operation's
852/// diagnostics count it (`pcurve.unmet_floor`). That is far better than the
853/// 1e-3 it replaces but it is not a size-aware bar; deriving one from the
854/// surface's own extent is separate, unmeasured work. Being absolute does remove this gate's dependence on
855/// distance from the origin as a side effect — a real translation-VARIANCE
856/// defect, the same anti-pattern `tolerance::merge_scale` records being removed
857/// elsewhere. `drop_tolerance` and `endpoint_tolerance` below still carry it.
858pub const PCURVE_REFINEMENT_TOLERANCE: f64 = 1e-7;
859
860/// Sample ceiling for a fit's FIRST refinement pass. 160 could not reach
861/// [`PCURVE_REFINEMENT_TOLERANCE`] on a curved trim of any length; 600 is the
862/// value every cell of the table above was measured at.
863///
864/// It BINDS. On `boolean_fuzz_corpus/25_cube_pierce_solid` the fitter stopped
865/// here 1.65e-3 of volume short of the converged answer (2000 and 4000 samples
866/// agree exactly). Raising it globally to 2000 was costed and rejected: +23%
867/// case-gate time, concentrated in three offset/fillet cases, and one case
868/// (`inbox-20260910-offset-shell-collapsed-fillet`) driven 26x outside its
869/// volume band. So it is not raised here: a fit that stops at this ceiling
870/// with a residual still worse than its edge curve's own distance from the
871/// surface re-enters refinement with [`PCURVE_RAISED_SAMPLES`]
872/// ([`refine_pcurve`]); one whose residual is already that gap stops here and
873/// says so ([`PcurveFitReport::off_surface`]), because no sample count can
874/// close it.
875pub const MAX_PCURVE_SAMPLES: usize = 600;
876
877/// Sample ceiling for the ONE raised pass a fit may take past
878/// [`MAX_PCURVE_SAMPLES`]. 2000 is the ceiling the convergence sweep measured
879/// on `25_cube_pierce_solid`: its 2000 and 4000 cells agree to every printed
880/// digit because refinement there stops itself near 1540 samples, so the cap
881/// is not what binds.
882const PCURVE_RAISED_SAMPLES: usize = 2000;
883
884/// What a pcurve fit ACHIEVED, returned beside the curve so a ceiling exit can
885/// never be mistaken for a met floor.
886///
887/// [`fit_pcurve_on_surface`] asks for [`PCURVE_REFINEMENT_TOLERANCE`] and stops
888/// at `MAX_PCURVE_SAMPLES` — or, where that ceiling bound and the floor is
889/// reachable, at `PCURVE_RAISED_SAMPLES`. Until 2026-09-12 a trim that ran out
890/// of samples came back exactly like one that met the floor; on
891/// `boolean_fuzz_corpus/25_cube_pierce_solid` that silence hid a 1.65e-3 volume
892/// error. Now every fit says which it was: `residual` is measured on the curve
893/// that is actually returned and `exit` names why refinement stopped.
894///
895/// This is a MEASUREMENT taken at a construction, not a band.
896#[derive(Clone, Copy, Debug, PartialEq)]
897pub struct PcurveFitReport {
898    /// Largest 3D distance between the returned pcurve's image on the surface
899    /// and the edge curve. On a [`PcurveFitExit::Converged`] exit whose final
900    /// round probed every span this is that round's maximum — the refinement's
901    /// own acceptance test. On every other exit, including a converged round
902    /// that skipped spans narrower than 1e-3 of the parameter range, it is a
903    /// sweep over EVERY span of the returned curve.
904    pub residual: f64,
905    /// The residual the refinement was asked to reach.
906    pub floor: f64,
907    /// Interpolation samples in the returned curve.
908    pub samples: usize,
909    /// Why refinement stopped.
910    pub exit: PcurveFitExit,
911    /// Largest distance from the edge curve to the surface at every station
912    /// the fit inverted — the part of `residual` no pcurve can remove, since a
913    /// pcurve's image lies ON the surface. Zero for an affine carrier. A value
914    /// above `floor` says the floor is unreachable for this input; a ceiling
915    /// exit is retried only while `residual` exceeds it by more than the floor,
916    /// i.e. while the returned curve is worse than its input.
917    pub off_surface: f64,
918    /// Whether the fit re-entered refinement with `PCURVE_RAISED_SAMPLES`
919    /// after `MAX_PCURVE_SAMPLES` bound with the floor unmet.
920    pub raised: bool,
921    /// Largest parameter distance a station's inversion was pulled back into
922    /// an OPEN direction's domain when the returned curve was interpolated: a
923    /// trim asked for outside its chart is folded onto the chart's boundary,
924    /// the edge stays right and the face becomes the wrong region on a body
925    /// `validate()` passes (3.03e-2 of volume on the rib-base document). Zero
926    /// when nothing was pulled. A REPORT, not a bar: nothing here refuses on
927    /// it. Its coverage is the clamp in `build_interpolant`, which is the only
928    /// place a raw out-of-domain parameter reaches today — an affine carrier's
929    /// inversion is unclamped, so an affine plane fitted through the station
930    /// lane reads here. It does NOT see a clamp the projector applied before
931    /// the fit: the analytic `Plane` closed form (a non-affine net) clamps to
932    /// its domain, `RuledRevolution` clamps its axial parameter to `[0, 1]`
933    /// and the general Newton clamps through `fit_parameter`; those stations
934    /// arrive in-domain and read as `off_surface` instead. The exact affine
935    /// lanes (`fit_pcurve_on_surface` on an affine carrier,
936    /// `affine_pcurve_on_range`) never clamp and read zero by construction.
937    pub clamped_excursion: f64,
938    /// The 3D distance the clamp corresponds to: between the extended surface
939    /// at the raw parameter and the clamped foot, at the station of the
940    /// largest such distance. Zero when nothing was pulled.
941    pub clamped_distance: f64,
942}
943
944impl PcurveFitReport {
945    /// Whether the returned curve reaches the floor it was asked for.
946    pub fn met_floor(&self) -> bool {
947        self.residual <= self.floor
948    }
949
950    /// Whether the returned curve is on the ACCEPTANCE BAR: the floor it was
951    /// asked for, plus the stations' own standoff from the carrier.
952    ///
953    /// A pcurve's image lies on the carrier, so at a station standing `g` off
954    /// it no image can come closer than `g`; a fit whose residual is within
955    /// the floor of `off_surface` is as good as the input allows, and one over
956    /// it is worse than its input — the same condition `refine_pcurve` uses
957    /// to decide that a raise can still buy accuracy. This is the bar every
958    /// station builder refuses over ([`build_pcurve_on_surface_stations`]).
959    /// It is blind to sideways error quadratically (a station tracked `d`
960    /// aside of the projection of a point `g` off the surface reads only
961    /// `d²/(2g)` further away), which is stated rather than hidden: on the
962    /// import corpus the stations that stand off their carriers are the
963    /// FILE's curves, and the bar there is the file's own number.
964    pub fn on_bar(&self) -> bool {
965        self.residual <= self.floor + self.off_surface
966    }
967}
968
969/// Why a pcurve refinement stopped. Only [`PcurveFitExit::Converged`] means the
970/// floor was met; every other variant is a BUDGET exit, and the report's
971/// residual was measured on the returned curve rather than assumed.
972#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
973pub enum PcurveFitExit {
974    /// A probe round found every station within the floor. An affine carrier
975    /// maps exactly and reports this with a zero residual.
976    Converged,
977    /// The sample ceiling bound before the floor was met: `MAX_PCURVE_SAMPLES`
978    /// when the raise was declined (the residual is already explained by
979    /// [`PcurveFitReport::off_surface`]), `PCURVE_RAISED_SAMPLES` when it was
980    /// taken and bound too.
981    SampleCeiling,
982    /// Every refinement round was spent and the last one still inserted
983    /// samples, so the curve it built was never re-checked by the loop.
984    RoundBudget,
985    /// A round found stations over the floor but could improve none of them:
986    /// the edge point could not be inverted inside the drop band, or (in the
987    /// raised pass) the pcurve already tracks the surface's nearest point to
988    /// within the floor. Either way the edge curve itself sits off the surface
989    /// there and no pcurve can close that gap; the residual reports how far.
990    /// The range lane's end-span challenger (its station fitter's TRACKING
991    /// mode) also exits here when a round's probes all track their feet
992    /// within the floor while the deviation residual, which includes the
993    /// edge's standoff, stays over it.
994    Stalled,
995    /// The last probe round found every span it PROBED within the floor, but
996    /// skipped spans narrower than the loop's own resolution floor — 1e-3 of
997    /// the parameter range in `refine_pcurve`, `SPAN_FLOOR` (1e-6) in
998    /// [`fit_pcurve_on_surface_stations`] — and a sweep over those found the
999    /// floor unmet.
1000    /// Until 2026-09-12 this exit was reported as `Converged` with the probed
1001    /// spans' maximum: on `25_cube_pierce_solid` a 1539-sample fit with 1537
1002    /// narrow spans read 7e-8 that way while every span read 1.9e-4.
1003    SpanFloor,
1004}
1005
1006/// A fitted pcurve with what the fit achieved.
1007#[derive(Clone, Debug)]
1008pub struct PcurveFit {
1009    pub curve: NurbsCurve,
1010    pub report: PcurveFitReport,
1011}
1012
1013/// Per-operation tally of pcurve fits and how many missed their floor.
1014///
1015/// [`build_pcurve_on_surface`] and its marched twin are called from some forty
1016/// sites, most of which have no diagnostics record to write into. Rather than
1017/// thread one through every layer, an operation that returns
1018/// [`KernelDiagnostics`] opens a [`PcurveFitScope`]; every fit made on that
1019/// thread while the scope is open is tallied here, and closing the scope hands
1020/// the tally back for [`PcurveFitLedger::report_into`]. This is the shape the
1021/// boolean's `CONFORMANCE_REPAIRS` counter already uses. With no scope open,
1022/// recording is a no-op.
1023///
1024/// Scopes nest: CLOSING a child folds it into its parent, so an offset shell
1025/// sees the fits of the booleans it ran. A scope that is DROPPED without being
1026/// closed is discarded, not folded — a boolean attempt that refused (and may be
1027/// retried under perturbation) must not leave its fits on the caller's tally.
1028///
1029/// Thread-local by construction: a fit made on a rayon worker (the `parallel`
1030/// feature's STEP body import) is not seen by a scope on the calling thread. No
1031/// diagnostics-returning operation builds pcurves off-thread today.
1032#[derive(Clone, Copy, Debug, Default, PartialEq)]
1033pub struct PcurveFitLedger {
1034    /// Fits recorded, exact affine ones included.
1035    pub fits: u64,
1036    /// Fits whose returned curve did not reach its floor.
1037    pub unmet: u64,
1038    /// Unmet fits that stopped at a sample ceiling.
1039    pub sample_ceiling: u64,
1040    /// Unmet fits that spent every refinement round.
1041    pub round_budget: u64,
1042    /// Unmet fits that could insert nothing.
1043    pub stalled: u64,
1044    /// Unmet fits whose remaining over-floor spans were all below the loop's
1045    /// 1e-3 span floor.
1046    pub span_floor: u64,
1047    /// Largest residual among the unmet fits; zero when there are none.
1048    pub worst_unmet_residual: f64,
1049    /// Fits that re-entered refinement with `PCURVE_RAISED_SAMPLES`, met or
1050    /// not.
1051    pub raised: u64,
1052    /// Unmet ceiling exits that were NOT raised because the residual is
1053    /// already within the floor of the edge curve's own gap from the surface.
1054    pub raise_declined: u64,
1055    /// Largest [`PcurveFitReport::off_surface`] over every fit.
1056    pub worst_off_surface: f64,
1057    /// Fits whose interpolant was clamped into an open direction's domain
1058    /// ([`PcurveFitReport::clamped_excursion`] above zero), met or not.
1059    pub clamped: u64,
1060    /// Largest [`PcurveFitReport::clamped_excursion`] over every fit.
1061    pub worst_clamped_excursion: f64,
1062    /// Largest [`PcurveFitReport::clamped_distance`] over every fit.
1063    pub worst_clamped_distance: f64,
1064}
1065
1066impl PcurveFitLedger {
1067    fn record(&mut self, report: &PcurveFitReport) {
1068        self.fits += 1;
1069        if report.raised {
1070            self.raised += 1;
1071        }
1072        self.worst_off_surface = self.worst_off_surface.max(report.off_surface);
1073        if report.clamped_excursion > 0.0 {
1074            self.clamped += 1;
1075            self.worst_clamped_excursion = self.worst_clamped_excursion.max(report.clamped_excursion);
1076            self.worst_clamped_distance = self.worst_clamped_distance.max(report.clamped_distance);
1077        }
1078        if report.met_floor() {
1079            return;
1080        }
1081        self.unmet += 1;
1082        match report.exit {
1083            PcurveFitExit::Converged => {}
1084            PcurveFitExit::SampleCeiling => {
1085                self.sample_ceiling += 1;
1086                if !report.raised {
1087                    self.raise_declined += 1;
1088                }
1089            }
1090            PcurveFitExit::RoundBudget => self.round_budget += 1,
1091            PcurveFitExit::Stalled => self.stalled += 1,
1092            PcurveFitExit::SpanFloor => self.span_floor += 1,
1093        }
1094        self.worst_unmet_residual = self.worst_unmet_residual.max(report.residual);
1095    }
1096
1097    fn fold(&mut self, child: &PcurveFitLedger) {
1098        self.fits += child.fits;
1099        self.unmet += child.unmet;
1100        self.sample_ceiling += child.sample_ceiling;
1101        self.round_budget += child.round_budget;
1102        self.stalled += child.stalled;
1103        self.span_floor += child.span_floor;
1104        self.worst_unmet_residual = self.worst_unmet_residual.max(child.worst_unmet_residual);
1105        self.raised += child.raised;
1106        self.raise_declined += child.raise_declined;
1107        self.worst_off_surface = self.worst_off_surface.max(child.worst_off_surface);
1108        self.clamped += child.clamped;
1109        self.worst_clamped_excursion = self.worst_clamped_excursion.max(child.worst_clamped_excursion);
1110        self.worst_clamped_distance = self.worst_clamped_distance.max(child.worst_clamped_distance);
1111    }
1112
1113    /// Write the tally into an operation's diagnostics: the `pcurve.*`
1114    /// counters and measurements always, plus one `pcurve.unmet_floor` event at
1115    /// [`DiagnosticSeverity::Degraded`] when any fit missed its floor. Degraded,
1116    /// not Error: the result is still the kernel's best construction and stays
1117    /// shippable, but it no longer claims the accuracy its floor states.
1118    pub fn report_into(&self, diagnostics: &mut KernelDiagnostics) {
1119        diagnostics.count_n("pcurve.fits", self.fits);
1120        diagnostics.count_n("pcurve.unmet_floor", self.unmet);
1121        diagnostics.count_n("pcurve.exit.sample_ceiling", self.sample_ceiling);
1122        diagnostics.count_n("pcurve.exit.round_budget", self.round_budget);
1123        diagnostics.count_n("pcurve.exit.stalled", self.stalled);
1124        diagnostics.count_n("pcurve.exit.span_floor", self.span_floor);
1125        diagnostics.count_n("pcurve.budget_raised", self.raised);
1126        diagnostics.count_n("pcurve.budget_raise_declined", self.raise_declined);
1127        diagnostics.measure_max("pcurve.worst_unmet_residual", self.worst_unmet_residual);
1128        diagnostics.measure_max("pcurve.worst_off_surface", self.worst_off_surface);
1129        diagnostics.count_n("pcurve.clamped", self.clamped);
1130        diagnostics.measure_max("pcurve.worst_clamped_excursion", self.worst_clamped_excursion);
1131        diagnostics.measure_max("pcurve.worst_clamped_distance", self.worst_clamped_distance);
1132        if self.unmet > 0 {
1133            diagnostics.event(
1134                DiagnosticSeverity::Degraded,
1135                KernelStage::Refine,
1136                "pcurve.unmet_floor",
1137                format!(
1138                    "{} of {} pcurve fits did not reach the {:.0e} floor \
1139                     (sample ceiling {}, round budget {}, stalled {}, span floor {}); \
1140                     worst residual {:.3e}; budget raised on {}, declined on {}; \
1141                     edge curves sit off their surfaces by up to {:.3e}{}",
1142                    self.unmet,
1143                    self.fits,
1144                    PCURVE_REFINEMENT_TOLERANCE,
1145                    self.sample_ceiling,
1146                    self.round_budget,
1147                    self.stalled,
1148                    self.span_floor,
1149                    self.worst_unmet_residual,
1150                    self.raised,
1151                    self.raise_declined,
1152                    self.worst_off_surface,
1153                    if self.clamped > 0 {
1154                        format!(
1155                            "; {} fit(s) clamped into their chart by up to {:.3e} in parameter, {:.3e} in 3D",
1156                            self.clamped, self.worst_clamped_excursion, self.worst_clamped_distance
1157                        )
1158                    } else {
1159                        String::new()
1160                    },
1161                ),
1162            );
1163        }
1164    }
1165}
1166
1167thread_local! {
1168    /// The open [`FootMemo`] on this thread, if any ([`FootMemoScope`]).
1169    static FOOT_MEMO: std::cell::RefCell<Option<FootMemo>> = const { std::cell::RefCell::new(None) };
1170}
1171
1172/// Exact-input memo of the common reader's projections on ONE surface: the
1173/// global foot of an edge point and the foot seeded at a (u, v), keyed by the
1174/// bit patterns of their inputs. Both projectors are pure functions of
1175/// (surface, point[, seed]), so a hit returns the value a fresh call would:
1176/// the readings, decisions and fits are bit-identical with or without it.
1177/// It exists for cost: within one coedge the same edge points are read by
1178/// the trigger read, every tracking-mode verification round, the
1179/// challenger's final read and the importer's keep read, each of which
1180/// projected them again (`importTestWorking`, 2026-10-05: about 10k probes
1181/// read 3-5 times on each of nine off-carrier refits, 3-5 s apiece).
1182///
1183/// Feet computed while [`defer_foot_inserts`] is on are appended to the
1184/// `pending_*` lists instead of hashed, and folded into the maps at the first
1185/// lookup that misses while it is off. A tracking pair that reads clean is
1186/// never read again, so its 20-30k feet per read are never hashed (16% of
1187/// the reader on the elephant, 2026-11-03); a candidate read or
1188/// fit that follows sees every one of them. Deferral changes no answer: a
1189/// lookup that misses recomputes the same pure function.
1190pub struct FootMemo {
1191    precision: bool,
1192    surface: *const NurbsSurface,
1193    /// Ordinary global feet are only starting points for precision Newton;
1194    /// they never enter the precision answer map without refinement.
1195    coarse_global: Option<rustc_hash::FxHashMap<[u64; 3], Option<crate::SurfaceProjection>>>,
1196    global: rustc_hash::FxHashMap<[u64; 3], Option<crate::SurfaceProjection>>,
1197    seeded: rustc_hash::FxHashMap<[u64; 5], Option<crate::SurfaceProjection>>,
1198    pending_global: Vec<([u64; 3], Option<crate::SurfaceProjection>)>,
1199    pending_seeded: Vec<([u64; 5], Option<crate::SurfaceProjection>)>,
1200}
1201
1202impl FootMemo {
1203    fn new(surface: *const NurbsSurface) -> Self {
1204        Self { precision: false, surface, coarse_global: None, global: Default::default(), seeded: Default::default(), pending_global: Vec::new(), pending_seeded: Vec::new() }
1205    }
1206
1207    /// Fold the deferred feet into the maps (a later insert of the same key
1208    /// would carry the same value, so the order of folding is immaterial).
1209    fn fold_pending(&mut self) {
1210        if !self.pending_global.is_empty() {
1211            self.global.reserve(self.pending_global.len());
1212            self.global.extend(self.pending_global.drain(..));
1213        }
1214        if !self.pending_seeded.is_empty() {
1215            self.seeded.reserve(self.pending_seeded.len());
1216            self.seeded.extend(self.pending_seeded.drain(..));
1217        }
1218    }
1219}
1220
1221thread_local! {
1222    static DEFER_FOOT_INSERTS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1223}
1224
1225/// Run `read` with new feet appended to the open memo's pending lists rather
1226/// than hashed ([`FootMemo`]); restores the previous setting.
1227pub fn defer_foot_inserts<T>(read: impl FnOnce() -> T) -> T {
1228    let previous = DEFER_FOOT_INSERTS.with(|cell| cell.replace(true));
1229    let result = read();
1230    DEFER_FOOT_INSERTS.with(|cell| cell.set(previous));
1231    result
1232}
1233
1234/// Opens a [`FootMemo`] for `surface` on this thread until dropped. Opening
1235/// one where a memo for the SAME surface is already open reuses it (an inner
1236/// scope, e.g. the range challenger inside an importer coedge); a memo for
1237/// another surface is set aside and restored on drop. The borrow of `surface`
1238/// keeps it alive and unmodified for the scope, so the pointer key cannot be
1239/// reused by another surface while the memo answers for it.
1240pub struct FootMemoScope<'a> {
1241    previous: Option<Option<FootMemo>>,
1242    _surface: std::marker::PhantomData<&'a NurbsSurface>,
1243    /// Not `Send`: the scope must close on the thread that opened it.
1244    _thread_bound: std::marker::PhantomData<*const ()>,
1245}
1246
1247impl<'a> FootMemoScope<'a> {
1248    /// A fresh memo isolates precision construction feet from ordinary reads,
1249    /// including an enclosing importer scope on the same surface.
1250    fn precision(surface: &'a NurbsSurface) -> Self {
1251        let mut next = FootMemo::new(surface);
1252        next.precision = true;
1253        if crate::switch!("BREP_STEP_PRECISION_FOOT_REUSE", true) && !crate::projection::global_site_filter_active() {
1254            FOOT_MEMO.with(|memo| {
1255                if let Some(parent) = memo.borrow().as_ref().filter(|m| !m.precision && std::ptr::eq(m.surface,surface)) {
1256                    let mut coarse = parent.global.clone();
1257                    coarse.extend(parent.pending_global.iter().copied());
1258                    next.coarse_global = Some(coarse);
1259                }
1260            });
1261        }
1262        let previous = FOOT_MEMO.with(|memo| memo.replace(Some(next)));
1263        Self { previous: Some(previous), _surface: std::marker::PhantomData, _thread_bound: std::marker::PhantomData }
1264    }
1265
1266    pub fn open(surface: &'a NurbsSurface) -> Self {
1267        let key = surface as *const NurbsSurface;
1268        let previous = FOOT_MEMO.with(|memo| {
1269        let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
1270            let mut memo = memo.borrow_mut();
1271            if memo.as_ref().is_some_and(|open| std::ptr::eq(open.surface, key)) {
1272                None
1273            } else {
1274                Some(memo.replace(FootMemo::new(key)))
1275            }
1276        });
1277        Self { previous, _surface: std::marker::PhantomData, _thread_bound: std::marker::PhantomData }
1278    }
1279}
1280
1281impl Drop for FootMemoScope<'_> {
1282    fn drop(&mut self) {
1283        if let Some(previous) = self.previous.take() {
1284            if crate::profile::profile_enabled() {
1285                FOOT_MEMO.with(|memo| {
1286                    let memo = memo.borrow();
1287                    if let Some(open) = memo.as_ref().filter(|m| m.precision) {
1288                        if let Some(coarse) = &open.coarse_global {
1289                            let reused = open.global.keys().filter(|key|coarse.contains_key(*key)).count();
1290                            eprintln!("pcurve.precision_memo coarse={} reused_global={reused}",coarse.len());
1291                        }
1292                    }
1293                });
1294            }
1295            FOOT_MEMO.with(|memo| *memo.borrow_mut() = previous);
1296        }
1297    }
1298}
1299
1300/// Whether a [`FootMemo`] is open on this thread (for any surface).
1301pub fn foot_memo_open() -> bool {
1302    FOOT_MEMO.with(|memo| memo.borrow().is_some())
1303}
1304
1305fn precision_trim_feet(surface: &NurbsSurface) -> bool {
1306    FOOT_MEMO.with(|memo| memo.borrow().as_ref().is_some_and(|m| m.precision && std::ptr::eq(m.surface, surface)))
1307}
1308
1309fn refine_memo_foot(surface: &NurbsSurface, point: Vec3, foot: Option<crate::SurfaceProjection>) -> Option<crate::SurfaceProjection> {
1310    if precision_trim_feet(surface) {
1311        foot.and_then(|foot| crate::projection::refine_trim_foot(surface, point, foot).ok())
1312    } else { foot }
1313}
1314
1315fn point_bits(point: Vec3) -> [u64; 3] {
1316    [point.x.to_bits(), point.y.to_bits(), point.z.to_bits()]
1317}
1318
1319/// [`project_point_to_surface`] as `.ok()`, through the open memo for this
1320/// surface when there is one. `#[track_caller]`: the projector still sees the
1321/// reader's own call site. Under a `BREP_PROJECTION_GLOBAL_SITES`/`_EXCEPT`
1322/// filter the projector's answer depends on that site, so the memo is not
1323/// consulted then.
1324#[track_caller]
1325fn memo_global_foot(surface: &NurbsSurface, point: Vec3) -> Option<crate::SurfaceProjection> {
1326    if crate::projection::global_site_filter_active() {
1327        return refine_memo_foot(surface, point, project_point_to_surface(surface, point).ok());
1328    }
1329    let key = point_bits(point);
1330    let deferring = DEFER_FOOT_INSERTS.with(|cell| cell.get());
1331    let mut coarse = None;
1332    let hit = FOOT_MEMO.with(|memo| {
1333        let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
1334        memo.borrow_mut().as_mut().filter(|open| std::ptr::eq(open.surface, surface)).map(|open| {
1335            let hit = match open.global.get(&key).copied() {
1336                Some(foot) => Some(foot),
1337                None if !deferring && !open.pending_global.is_empty() => {
1338                    open.fold_pending();
1339                    open.global.get(&key).copied()
1340                }
1341                None => None,
1342            };
1343            if hit.is_none() {
1344                coarse = open.coarse_global.as_ref().and_then(|memo|memo.get(&key).copied());
1345            }
1346            hit
1347        })
1348    });
1349    match hit {
1350        Some(Some(foot)) => foot,
1351        Some(None) => {
1352            let raw = coarse.unwrap_or_else(||project_point_to_surface(surface,point).ok());
1353            let foot = refine_memo_foot(surface, point, raw);
1354            FOOT_MEMO.with(|memo| {
1355        let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
1356                if let Some(open) = memo.borrow_mut().as_mut().filter(|open| std::ptr::eq(open.surface, surface)) {
1357                    if deferring {
1358                        open.pending_global.push((key, foot));
1359                    } else {
1360                        open.global.insert(key, foot);
1361                    }
1362                }
1363            });
1364            foot
1365        }
1366        None => refine_memo_foot(surface, point, project_point_to_surface(surface, point).ok()),
1367    }
1368}
1369
1370/// [`project_point_to_surface_seeded`] as `.ok()`, through the open memo for
1371/// this surface when there is one.
1372fn memo_seeded_foot(surface: &NurbsSurface, point: Vec3, seed_u: f64, seed_v: f64) -> Option<crate::SurfaceProjection> {
1373    let [x, y, z] = point_bits(point);
1374    let key = [x, y, z, seed_u.to_bits(), seed_v.to_bits()];
1375    let deferring = DEFER_FOOT_INSERTS.with(|cell| cell.get());
1376    let hit = FOOT_MEMO.with(|memo| {
1377        let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
1378        memo.borrow_mut().as_mut().filter(|open| std::ptr::eq(open.surface, surface)).map(|open| {
1379            match open.seeded.get(&key).copied() {
1380                Some(foot) => Some(foot),
1381                None if !deferring && !open.pending_seeded.is_empty() => {
1382                    open.fold_pending();
1383                    open.seeded.get(&key).copied()
1384                }
1385                None => None,
1386            }
1387        })
1388    });
1389    match hit {
1390        Some(Some(foot)) => foot,
1391        Some(None) => {
1392            let foot = refine_memo_foot(surface, point, project_point_to_surface_seeded(surface, point, seed_u, seed_v).ok());
1393            FOOT_MEMO.with(|memo| {
1394        let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::LOOKUP);
1395                if let Some(open) = memo.borrow_mut().as_mut().filter(|open| std::ptr::eq(open.surface, surface)) {
1396                    if deferring {
1397                        open.pending_seeded.push((key, foot));
1398                    } else {
1399                        open.seeded.insert(key, foot);
1400                    }
1401                }
1402            });
1403            foot
1404        }
1405        None => refine_memo_foot(surface, point, project_point_to_surface_seeded(surface, point, seed_u, seed_v).ok()),
1406    }
1407}
1408
1409thread_local! {
1410    /// The open [`PcurveFitScope`]s on this thread, innermost last.
1411    static PCURVE_FIT_SCOPES: std::cell::RefCell<Vec<PcurveFitLedger>> =
1412        const { std::cell::RefCell::new(Vec::new()) };
1413}
1414
1415/// `BREP_DEBUG_PCURVE_FIT` only: a process-wide id per [`refine_pcurve`]
1416/// call, so its first-pass and candidate `PCURVE-TRACK` lines pair up even
1417/// when fits run on several threads.
1418static PCURVE_TRACK_CALL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1419
1420/// An open tally of the pcurve fits made on this thread — see
1421/// [`PcurveFitLedger`]. Open it where an operation starts, [`close`] it where
1422/// the operation returns its diagnostics; a `?` that unwinds past it drops the
1423/// tally.
1424///
1425/// [`close`]: PcurveFitScope::close
1426pub struct PcurveFitScope {
1427    /// Not `Send`: the scope must close on the thread that opened it.
1428    _thread_bound: std::marker::PhantomData<*const ()>,
1429}
1430
1431impl PcurveFitScope {
1432    pub fn open() -> Self {
1433        PCURVE_FIT_SCOPES.with(|scopes| scopes.borrow_mut().push(PcurveFitLedger::default()));
1434        Self {
1435            _thread_bound: std::marker::PhantomData,
1436        }
1437    }
1438
1439    /// Take the tally, folding it into the enclosing scope if there is one.
1440    pub fn close(self) -> PcurveFitLedger {
1441        let ledger = PCURVE_FIT_SCOPES.with(|scopes| {
1442            let mut scopes = scopes.borrow_mut();
1443            let ledger = scopes.pop().unwrap_or_default();
1444            if let Some(parent) = scopes.last_mut() {
1445                parent.fold(&ledger);
1446            }
1447            ledger
1448        });
1449        std::mem::forget(self);
1450        ledger
1451    }
1452}
1453
1454impl Drop for PcurveFitScope {
1455    fn drop(&mut self) {
1456        PCURVE_FIT_SCOPES.with(|scopes| {
1457            scopes.borrow_mut().pop();
1458        });
1459    }
1460}
1461
1462pub fn record_fit(report: &PcurveFitReport) {
1463    crate::work_counts::add(|c| { c.fit_reports += 1; c.fit_samples += report.samples as u64; c.fit_raised += u64::from(report.raised); });
1464    // Per-fit trace for the convergence probes (`trim_floor_sweep_probe` and
1465    // its offset-shell sibling): one line per fit with the whole report, the
1466    // way `BREP_DEBUG_PCURVE` traces an endpoint failure.
1467    if env_read!("BREP_DEBUG_PCURVE_FIT").is_some() {
1468        eprintln!("PCURVE-FIT {report:?}");
1469    }
1470    PCURVE_FIT_SCOPES.with(|scopes| {
1471        if let Some(open) = scopes.borrow_mut().last_mut() {
1472            open.record(report);
1473        }
1474    });
1475}
1476
1477/// Largest 3D distance between `pcurve`'s image and `curve` at the
1478/// quarter-points of every span of `parameters` — the stations refinement
1479/// probes, over EVERY span. Evaluations only; nothing is inverted. The sweep
1480/// measures, it does not decide.
1481pub fn probe_residual(
1482    surface: &NurbsSurface,
1483    curve: &NurbsCurve,
1484    pcurve: &NurbsCurve,
1485    parameters: &[f64],
1486    domain: [f64; 2],
1487    _u_domain: [f64; 2],
1488    _v_domain: [f64; 2],
1489) -> Result<f64, String> {
1490    probe_residual_at(surface, curve, pcurve, parameters, domain, &[0.25, 0.5, 0.75])
1491}
1492
1493/// Extra interior points per sample span, at `j/17` for `j = 1..=16`, that
1494/// [`tracking_acceptance_residual`] reads IN ADDITION to [`probe_residual`]'s
1495/// quarter, mid and three-quarter points (nineteen fractions per span in
1496/// all), so it can never read below the three-point maximum on the same
1497/// curve. The three quarter-points under-read the sixteen-point maximum by
1498/// 3.3–6.5 % on the constructed-cylinder union's imprint pcurves, and sixteen
1499/// sit within 0.4 % of sixty-four there (2026-10-04); the Converged path keeps
1500/// its own read.
1501pub const TRACKING_ACCEPTANCE_POINTS: usize = 16;
1502
1503/// Streaming batch over one immutable curve. Initialization is lazy so an empty
1504/// probe grid does not validate a curve that the scalar path never reads.
1505/// Span and basis scratch survive successive reads; equal clamped parameters
1506/// reuse their basis. No grid is reordered and no point is read ahead.
1507pub struct ProbeCurveReader<'a> {
1508    curve: &'a NurbsCurve,
1509    pub enabled: bool,
1510    pub domain: Option<[f64; 2]>,
1511    span: Option<usize>,
1512    pub previous: Option<u64>,
1513    pub basis: [f64; crate::curve::MAX_STACK_ORDER],
1514    left: [f64; crate::curve::MAX_STACK_ORDER],
1515    right: [f64; crate::curve::MAX_STACK_ORDER],
1516}
1517impl<'a> ProbeCurveReader<'a> {
1518    pub fn new(curve: &'a NurbsCurve, enabled: bool) -> Self {
1519        Self { curve, enabled, domain: None, span: None, previous: None,
1520            basis: [0.0; crate::curve::MAX_STACK_ORDER],
1521            left: [0.0; crate::curve::MAX_STACK_ORDER], right: [0.0; crate::curve::MAX_STACK_ORDER] }
1522    }
1523    #[cfg_attr(feature = "profile-wall", track_caller)]
1524    pub fn evaluate(&mut self, parameter: f64) -> Result<Vec3, String> {
1525        let _reader = crate::reader_profile::Point::open(crate::reader_profile::PCURVE, std::panic::Location::caller());
1526        if !self.enabled || self.curve.degree > crate::curve::MAX_STACK_DEGREE || !parameter.is_finite() {
1527            return self.curve.evaluate(parameter);
1528        }
1529        let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::POINT);
1530        let [start, end] = match self.domain {
1531            Some(domain) => domain,
1532            None => {
1533                let domain = self.curve.domain()?;
1534                // Import validation tolerates tiny descending knot differences;
1535                // only genuinely ordered vectors may use a forward span walk.
1536                if self.curve.knots.windows(2).any(|w| w[1] < w[0]) {
1537                    self.enabled = false;
1538                    return self.curve.evaluate(parameter);
1539                }
1540                self.domain = Some(domain); domain
1541            }
1542        };
1543        let parameter = parameter.clamp(start, end);
1544        if self.previous != Some(parameter.to_bits()) {
1545            let knots = &self.curve.knots;
1546            let degree = self.curve.degree;
1547            let span = match self.span {
1548                Some(mut span) if parameter > start && parameter < end && parameter >= knots[span] => {
1549                    while parameter >= knots[span + 1] { span += 1; }
1550                    span
1551                }
1552                _ => crate::curve::knot_find_span(knots, degree, parameter),
1553            };
1554            // Use the scalar recurrence verbatim, including its parameter-
1555            // dependent subtraction/addition order in the denominator. A
1556            // precomputed knot difference would change rounding.
1557            match degree {
1558                1 => self.fill_basis::<1>(span, parameter),
1559                2 => self.fill_basis::<2>(span, parameter),
1560                3 => self.fill_basis::<3>(span, parameter),
1561                4 => self.fill_basis::<4>(span, parameter),
1562                5 => self.fill_basis::<5>(span, parameter),
1563                6 => self.fill_basis::<6>(span, parameter),
1564                7 => self.fill_basis::<7>(span, parameter),
1565                _ => self.fill_basis::<0>(span, parameter),
1566            }
1567            self.span = Some(span);
1568            self.previous = Some(parameter.to_bits());
1569        }
1570        let span = self.span.unwrap();
1571        let _reader_part = crate::reader_profile::Part::open(crate::reader_profile::ACCUMULATE);
1572        let mut point = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
1573        for (index, value) in self.basis[..=self.curve.degree].iter().enumerate() {
1574            point = point.add(self.curve.control_points[span - self.curve.degree + index].scale(*value));
1575        }
1576        point.point()
1577    }
1578    #[inline(always)]
1579    fn fill_basis<const DEGREE: usize>(&mut self, span: usize, parameter: f64) {
1580        crate::curve::basis_functions_raw_into(&self.curve.knots, DEGREE, span, parameter,
1581            EPSILON, &mut self.basis, &mut self.left, &mut self.right);
1582    }
1583}
1584
1585fn probe_batch_enabled() -> bool { switch!("BREP_PCURVE_PROBE_BATCH", false) }
1586
1587/// The same-parameter image-vs-edge distance of `pcurve` at `locals` (span
1588/// fractions) inside every span of `parameters`: the largest, or an error if
1589/// any is not finite.
1590pub fn probe_residual_at(
1591    surface: &NurbsSurface,
1592    curve: &NurbsCurve,
1593    pcurve: &NurbsCurve,
1594    parameters: &[f64],
1595    [t0, t1]: [f64; 2],
1596    locals: &[f64],
1597) -> Result<f64, String> {
1598    crate::work_counts::add(|c| { c.pcurve_probe_passes += 1; c.pcurve_probe_samples += (parameters.len().saturating_sub(1) * locals.len()) as u64; });
1599    let mut worst = 0.0_f64;
1600    let mut reader = ProbeCurveReader::new(pcurve, probe_batch_enabled());
1601    for span in parameters.windows(2) {
1602        for &local in locals {
1603            let fraction = span[0] + (span[1] - span[0]) * local;
1604            let parameter = reader.evaluate(fraction)?;
1605            let on_surface =
1606                section_surface_point(surface, parameter.x, parameter.y, true)?;
1607            let on_curve = section_curve_point(curve, t0 + (t1 - t0) * fraction)?;
1608            // `f64::max` drops a NaN operand, so a non-finite distance would
1609            // leave `worst` reading the finite stations only. A residual that
1610            // can accept a curve must have measured every station: fail
1611            // closed instead.
1612            let distance = on_surface.sub(on_curve).length();
1613            if !distance.is_finite() {
1614                return Err(format!(
1615                    "probe_residual: non-finite image distance {distance} at fraction {fraction}"
1616                ));
1617            }
1618            worst = worst.max(distance);
1619        }
1620    }
1621    Ok(worst)
1622}
1623
1624/// The probe fractions a native read takes for the given pcurves: both
1625/// domain ENDPOINTS, and the quarter points plus 16 interior points of every
1626/// span between each curve's OWN distinct knots (the installed interpolant's
1627/// spans, not the construction stations). Merged over all the curves, sorted
1628/// and deduplicated, so a standing fit and a candidate are read at the SAME
1629/// fractions.
1630pub fn native_probe_fractions(curves: &[&NurbsCurve]) -> Result<Vec<f64>, String> {
1631    let locals: Vec<f64> = [0.25, 0.5, 0.75]
1632        .into_iter()
1633        .chain((1..=TRACKING_ACCEPTANCE_POINTS).map(|index| index as f64 / (TRACKING_ACCEPTANCE_POINTS + 1) as f64))
1634        .collect();
1635    let mut fractions = Vec::new();
1636    for curve in curves {
1637        let [q0, q1] = curve.domain()?;
1638        fractions.push(q0);
1639        fractions.push(q1);
1640        let mut knots: Vec<f64> = curve.knots.iter().copied().filter(|k| *k >= q0 && *k <= q1).collect();
1641        knots.dedup();
1642        for span in knots.windows(2).filter(|w| w[1] > w[0]) {
1643            for &local in &locals {
1644                fractions.push(span[0] + (span[1] - span[0]) * local);
1645            }
1646        }
1647    }
1648    fractions.sort_by(f64::total_cmp);
1649    fractions.dedup();
1650    Ok(fractions)
1651}
1652
1653/// One pcurve read at given probe fractions against the edge curve (whose
1654/// parameter is t0 + (t1 - t0) x fraction): the image's distance from the
1655/// edge point's FOOT on the carrier (its TRACKING, the part a pcurve can
1656/// improve; the foot is seeded at the pcurve's own uv, closed form on an
1657/// analytic carrier), the image's distance from the edge point itself (the
1658/// same-parameter DEVIATION), and the edge point's distance from the carrier
1659/// (its INHERITED STANDOFF). Maxima over the probes; fails closed on any
1660/// non-finite point or distance.
1661#[derive(Clone, Copy, Debug, PartialEq)]
1662pub struct NativeRead {
1663    pub tracking: f64,
1664    pub deviation: f64,
1665    pub standoff: f64,
1666}
1667
1668fn native_read(surface: &NurbsSurface, curve: &NurbsCurve, pcurve: &NurbsCurve, domain: [f64; 2], fractions: &[f64]) -> Result<NativeRead, String> {
1669    native_read_memo(surface, curve, pcurve, domain, fractions, None)
1670}
1671
1672/// One curve's [`native_read`] values per probe fraction (by its bits), for
1673/// one standing or candidate pcurve inside [`standoff_tracking_rungs`].
1674pub type NativeReadMemo = rustc_hash::FxHashMap<u64, NativeRead>;
1675
1676/// [`native_read`], with each probe's reading taken from `memo` when that
1677/// fraction was read before for the SAME pcurve, and stored there after.
1678///
1679/// A probe's reading depends only on the surface, the edge curve, this
1680/// pcurve and the fraction. The reader caches nothing but its span walk, the
1681/// sample caches return the values they would compute, and the seed is the
1682/// pcurve's own uv. The maximum over a set of finite values does not depend
1683/// on their order. So the result is the uncached one, bit for bit, while
1684/// `BREP_PCURVE_READ_MEMO` is on (default). A fraction whose reading is not
1685/// finite fails as before, and failures are not stored.
1686fn native_read_memo(
1687    surface: &NurbsSurface,
1688    curve: &NurbsCurve,
1689    pcurve: &NurbsCurve,
1690    [t0, t1]: [f64; 2],
1691    fractions: &[f64],
1692    mut memo: Option<&mut NativeReadMemo>,
1693) -> Result<NativeRead, String> {
1694    let mut read = NativeRead { tracking: 0.0, deviation: 0.0, standoff: 0.0 };
1695    let mut reader = ProbeCurveReader::new(pcurve, probe_batch_enabled());
1696    let mut computed = 0u64;
1697    for &fraction in fractions {
1698        let probe = match memo.as_deref().and_then(|memo| memo.get(&fraction.to_bits())) {
1699            Some(&probe) => probe,
1700            None => {
1701                computed += 1;
1702                let parameter = reader.evaluate(fraction)?;
1703                let image = section_surface_point(surface, parameter.x, parameter.y, true)?;
1704                let on_curve = section_curve_point(curve, t0 + (t1 - t0) * fraction)?;
1705                let foot = crate::projection::project_point_to_surface_from_seed(surface, on_curve, [parameter.x, parameter.y])?;
1706                let tracking = image.sub(foot.point).length();
1707                let deviation = image.sub(on_curve).length();
1708                if !(tracking.is_finite() && deviation.is_finite() && foot.distance.is_finite()) {
1709                    return Err(format!("native read: non-finite reading at fraction {fraction}"));
1710                }
1711                let probe = NativeRead { tracking, deviation, standoff: foot.distance };
1712                if let Some(memo) = memo.as_deref_mut() {
1713                    memo.insert(fraction.to_bits(), probe);
1714                }
1715                probe
1716            }
1717        };
1718        read.tracking = read.tracking.max(probe.tracking);
1719        read.deviation = read.deviation.max(probe.deviation);
1720        read.standoff = read.standoff.max(probe.standoff);
1721    }
1722    crate::work_counts::add(|c| { c.pcurve_native_passes += 1; c.pcurve_native_samples += computed; });
1723    Ok(read)
1724}
1725
1726/// `BREP_PCURVE_READ_MEMO` (default on; `0` reads every probe afresh): the
1727/// standoff-tracking rungs keep each pcurve's probe readings
1728/// ([`native_read_memo`]), so a standing fit is not read again at fractions
1729/// it was already read at.
1730fn pcurve_read_memo_enabled() -> bool {
1731    crate::switch!("BREP_PCURVE_READ_MEMO", true)
1732}
1733
1734/// Whether an off-carrier tracking candidate replaces the standing fit, both
1735/// read at the SAME probes ([`native_probe_fractions`] of both curves): its
1736/// tracking finite, within the unchanged floor and strictly lower, AND its
1737/// same-parameter deviation no worse (the reported total, inherited standoff
1738/// included, must not grow), AND its own refinement fields finite.
1739pub fn standoff_candidate_accepted(standing: NativeRead, candidate: NativeRead, candidate_fields_finite: bool, floor: f64) -> bool {
1740    candidate_fields_finite
1741        && candidate.tracking.is_finite()
1742        && candidate.deviation.is_finite()
1743        && candidate.tracking <= floor
1744        && candidate.tracking < standing.tracking
1745        && candidate.deviation <= standing.deviation
1746}
1747
1748/// [`probe_residual_at`] at [`probe_residual`]'s three quarter-points plus
1749/// [`TRACKING_ACCEPTANCE_POINTS`] evenly spaced interior points of every span
1750/// (nineteen per span): the maximum of the old three-point reading and the
1751/// sixteen-point one. It is the reading a budget-exit tracking candidate is
1752/// accepted on, and the residual it is then reported with.
1753pub fn tracking_acceptance_residual(
1754    surface: &NurbsSurface,
1755    curve: &NurbsCurve,
1756    pcurve: &NurbsCurve,
1757    parameters: &[f64],
1758    domain: [f64; 2],
1759) -> Result<f64, String> {
1760    let locals: Vec<f64> = [0.25, 0.5, 0.75]
1761        .into_iter()
1762        .chain((1..=TRACKING_ACCEPTANCE_POINTS).map(|index| index as f64 / (TRACKING_ACCEPTANCE_POINTS + 1) as f64))
1763        .collect();
1764    probe_residual_at(surface, curve, pcurve, parameters, domain, &locals)
1765}
1766
1767/// Whether a projection-tracking candidate replaces the fit standing in
1768/// [`refine_pcurve`], given the `reading` it is judged on (see
1769/// `judge_tracking_candidate`). `standing_dense` says the standing fit's
1770/// reading is itself a nineteen-point one: a budget-exit candidate was taken.
1771///
1772/// While the standing reading is the fitter's own, a `Converged` candidate is
1773/// taken exactly as before (within the floor, better). A BUDGET exit
1774/// (`SampleCeiling`, `RoundBudget`, `Stalled`, `SpanFloor`) is taken only to
1775/// repair a standing fit that MISSES the floor, and only when its
1776/// nineteen-point reading is finite, within the unchanged floor and strictly
1777/// better. Once the standing reading is a nineteen-point one, every later
1778/// candidate is compared nineteen against nineteen: a Converged one must read
1779/// finite, within the floor and strictly better on the same stencil, and a
1780/// budget exit is never taken (the standing fit is then within the floor).
1781/// The exit label says how the loop stopped, not whether the curve is good: on
1782/// the 15° constructed-cylinder union all six imprint pcurves that shipped
1783/// 1.3e-7..7.0e-6 off had a tracking candidate reading 1.4e-8..9.95e-8 at
1784/// three points per span, discarded for its label (2026-10-04). A standing
1785/// fit already within the floor is never replaced by a budget exit, so every
1786/// in-floor fit is unchanged; a taken candidate keeps its own exit, samples
1787/// and raise, and reports the reading it was taken on.
1788pub fn tracking_candidate_accepted(standing: f64, standing_dense: bool, floor: f64, exit: PcurveFitExit, reading: f64) -> bool {
1789    if exit == PcurveFitExit::Converged && !standing_dense {
1790        return reading <= floor && reading < standing;
1791    }
1792    if exit != PcurveFitExit::Converged && !(standing > floor) {
1793        return false;
1794    }
1795    reading.is_finite() && reading <= floor && reading < standing
1796}
1797
1798
1799pub fn judge_tracking_candidate_with_bounds(
1800    standing: f64,
1801    standing_dense: bool,
1802    floor: f64,
1803    exit: PcurveFitExit,
1804    own: f64,
1805    dense: impl FnOnce() -> Result<f64, String>,
1806    bounds: bool,
1807) -> (Result<Option<f64>, String>, bool) {
1808    // A budget exit's own residual probes the quarter points of every
1809    // returned span. They are a subset of the nineteen-point stencil, so its
1810    // maximum cannot fall below this already over-floor lower bound.
1811    if bounds && exit != PcurveFitExit::Converged && own > floor {
1812        if crate::profile::profile_enabled() { profile_line!("pcurve.reject_bound kind=quarter_residual"); }
1813        return (Ok(Some(own)), false);
1814    }
1815    let reading = if exit == PcurveFitExit::Converged && !standing_dense {
1816        Ok(Some(own))
1817    } else if exit == PcurveFitExit::Converged || standing > floor {
1818        dense().map(Some)
1819    } else {
1820        Ok(None)
1821    };
1822    let accepted = matches!(
1823        reading,
1824        Ok(Some(value)) if tracking_candidate_accepted(standing, standing_dense, floor, exit, value)
1825    );
1826    (reading, accepted)
1827}
1828
1829/// What one call to [`refine_pcurve`] achieved, beside the curve it left in
1830/// place.
1831pub struct Refinement {
1832    pub exit: PcurveFitExit,
1833    pub residual: f64,
1834    pub off_surface: f64,
1835    pub raised: bool,
1836    /// [`PcurveFitReport::clamped_excursion`] and
1837    /// [`PcurveFitReport::clamped_distance`] of the curve left in place.
1838    pub clamped: [f64; 2],
1839}
1840
1841/// Adaptive 3D-residual refinement of an interpolant, with the PER-TRIM sample
1842/// budget. Shared by [`fit_pcurve_on_surface`] (global inversion) and
1843/// [`fit_pcurve_on_surface_marched`] (seeded projection); `insert` is the one
1844/// step that differs — given a probe station's fraction, the current pcurve's
1845/// parameter there and the edge point, it returns the surface parameter to
1846/// interpolate through (or `None` to decline the station) and the distance
1847/// from the edge point to the surface at that station, its GAP.
1848///
1849/// **First pass.** Four rounds at [`MAX_PCURVE_SAMPLES`], each probing the
1850/// quarter-points of every span wider than 1e-3 of the parameter range and
1851/// inserting the stations over `floor`. Byte-for-byte the pre-2026-09-12
1852/// loop; every exit is classified ([`PcurveFitExit`]) and the residual is
1853/// measured on the RETURNED curve — over every span, unless the final round
1854/// probed every span, in which case that round's maximum already is.
1855///
1856/// **The raise.** A [`PcurveFitExit::SampleCeiling`] exit re-enters the four
1857/// rounds ONCE with [`PCURVE_RAISED_SAMPLES`], continuing from the samples it
1858/// has, when the residual exceeds `off_surface` by more than the floor — the
1859/// returned curve is worse than the edge curve's own distance from the
1860/// surface, so more samples CAN improve it. Measured on `25_cube_pierce_solid`
1861/// (2026-09-12): the edge curves there sit off their surfaces by up to 1.9e-4,
1862/// four of the eight ceiling exits already read their gap to four digits, and
1863/// raising those spent 900 inversions each for no change in the swept
1864/// residual. The raised pass therefore inserts only where the pcurve's surface
1865/// point is further than the floor from the PROJECTION of the edge point — its
1866/// tracking error, which the inversion just computed: it stops when the pcurve
1867/// tracks the surface's nearest point to the floor, which is the best any
1868/// pcurve can do, and reports [`PcurveFitExit::Stalled`] with the deviation it
1869/// actually reached when that is still over the floor. The limit of that pass
1870/// as the floor tightens is the projected edge curve itself, so a volume built
1871/// on it can be shown to converge; the deviation test alone cannot say that on
1872/// off-surface input. Grow-once, capped, deterministic.
1873#[allow(clippy::too_many_arguments)]
1874pub fn refine_pcurve(
1875    surface: &NurbsSurface,
1876    curve: &NurbsCurve,
1877    domain: [f64; 2],
1878    u_domain: [f64; 2],
1879    v_domain: [f64; 2],
1880    floor: f64,
1881    joins: &[f64],
1882    parameters: &mut Vec<f64>,
1883    raw: &mut Vec<[f64; 2]>,
1884    pcurve: &mut NurbsCurve,
1885    off_surface: f64,
1886    clamped: [f64; 2],
1887    mut insert: impl FnMut(f64, Vec3, Vec3) -> Result<(Option<[f64; 2]>, f64), String>,
1888) -> Result<Refinement, String> {
1889    // Trace only (`BREP_DEBUG_PCURVE_FIT`): reads values the passes already
1890    // computed and decides nothing.
1891    let trace = env_read!("BREP_DEBUG_PCURVE_FIT").is_some();
1892    let call = if trace {
1893        PCURVE_TRACK_CALL.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1
1894    } else {
1895        0
1896    };
1897    let reject_bounds = PCURVE_REJECT_BOUNDS.with(|state| state.get());
1898    let best = refine_pcurve_pass(surface, curve, domain, u_domain, v_domain,
1899        floor, joins, parameters, raw, pcurve, off_surface, clamped, false, 1.0, false, &mut insert, false)?;
1900    if trace {
1901        eprintln!(
1902            "PCURVE-TRACK call={call} first-pass exit={:?} residual={:e} floor={floor:e} off_surface={:e} samples={} raised={} tracking={}",
1903            best.exit,
1904            best.residual,
1905            best.off_surface,
1906            parameters.len(),
1907            best.raised,
1908            if best.off_surface <= floor { "eligible" } else { "standoff-tracking" }
1909        );
1910    }
1911    if best.off_surface > floor {
1912        // The edge curve itself stands off the carrier by more than the floor
1913        // (its INHERITED standoff), so no pcurve can bring the image within the
1914        // floor of the edge point. What a pcurve CAN improve is its tracking
1915        // error: the image's distance from the edge point's foot. Measured
1916        // 2026-10-04 (15-degree crossing, turn 295): a first pass
1917        // ended RoundBudget at 6.726e-6 over a 1.316e-7 standoff and every
1918        // tracking pass was skipped. No candidate refinement when the ACTUAL
1919        // tracking request is met: the first pass's own tracking, read on its
1920        // native spans and endpoints (a diagnostic read; it adds no station),
1921        // within the floor ([`standoff_tracking_rungs`]). A total residual
1922        // under standoff + floor does not prove that: a tangential slip t over
1923        // a standoff g reads sqrt(g^2 + t^2) < g + t.
1924        // `BREP_PCURVE_STANDOFF_TRACKING=0`: diagnostic A/B hatch, not a
1925        // policy. It restores the earlier answer (before this tracking: an
1926        // off-carrier first pass is returned as it stands) for a same-binary
1927        // attribution of a volume or census delta to this lane. Default (unset
1928        // or any other value) is unchanged. It does not touch the in-floor
1929        // tracking rungs or their raise rule, nor the range lane's end-span
1930        // challenger.
1931        if !standoff_tracking_enabled() {
1932            return Ok(best);
1933        }
1934        return standoff_tracking_rungs(surface, curve, domain, u_domain, v_domain, floor, joins,
1935            parameters, raw, pcurve, best, trace, call, &mut insert);
1936    }
1937    // Each target starts from the same baseline station set: retaining the
1938    // coarser target's inserts can exhaust the cap before the finer target
1939    // places its own error-directed stations. Keep the best rung
1940    // [`tracking_candidate_accepted`] takes.
1941    let baseline_parameters = parameters.clone();
1942    let baseline_raw = raw.clone();
1943    let baseline_curve = pcurve.clone();
1944    let baseline_off_surface = best.off_surface;
1945    let baseline_clamped = best.clamped;
1946    // Whether the first pass MISSED the floor: only then may a tracking
1947    // candidate that reaches the sample ceiling still missing its request take
1948    // the existing one-time raise (2026-10-04, 20-degree crossing, turn 295:
1949    // a 1.964e-6 first pass, a candidate at 600 samples reading 1.068e-7,
1950    // declined; the raise needed residual > off_surface + floor). A first pass
1951    // within the floor keeps exactly the work it did before.
1952    // (On this path the edge stands within the floor of the carrier, so a
1953    // first pass over the floor is a tracking miss, not inherited standoff.)
1954    let standing_misses = best.residual > floor;
1955    Ok(tracking_rungs(
1956        best,
1957        floor,
1958        trace,
1959        call,
1960        true,
1961        |fraction| {
1962            let mut refined_parameters = baseline_parameters.clone();
1963            let mut refined_raw = baseline_raw.clone();
1964            let mut refined_curve = baseline_curve.clone();
1965            let candidate = refine_pcurve_pass(surface, curve, domain, u_domain, v_domain,
1966                floor, joins, &mut refined_parameters, &mut refined_raw, &mut refined_curve,
1967                baseline_off_surface, baseline_clamped, true, fraction, standing_misses, &mut insert, reject_bounds && !standing_misses);
1968            (candidate, (refined_parameters, refined_raw, refined_curve))
1969        },
1970        |state: &RungState| tracking_acceptance_residual(surface, curve, &state.2, &state.0, domain),
1971        |state: &RungState| state.0.len(),
1972        |(refined_parameters, refined_raw, refined_curve): RungState| {
1973            *parameters = refined_parameters;
1974            *raw = refined_raw;
1975            *pcurve = refined_curve;
1976        },
1977    ))
1978}
1979
1980/// A tracking candidate's station parameters, raw surface parameters and
1981/// pcurve, as [`refine_pcurve`] hands them to [`tracking_rungs`].
1982type RungState = (Vec<f64>, Vec<[f64; 2]>, NurbsCurve);
1983
1984/// The tracking rungs of [`refine_pcurve`] after an eligible first pass: for
1985/// each tracking fraction, skip it if the standing fit is already that far
1986/// inside the floor, otherwise run the candidate pass (`run_pass`), judge it
1987/// (`judge_tracking_candidate`, reading `dense` only when needed), trace
1988/// it, and either take it (`adopt` its state; it becomes the standing fit) or
1989/// stop. `samples` is the candidate's station count, for the trace. Separated
1990/// so the accepted-budget state can be driven with scripted passes;
1991/// `thread_dense` is `true` in production and `false` only to show, in a
1992/// test, what dropping the nineteen-point standing flag would take.
1993#[allow(clippy::too_many_arguments)]
1994pub fn tracking_rungs<S>(
1995    mut best: Refinement,
1996    floor: f64,
1997    trace: bool,
1998    call: u64,
1999    thread_dense: bool,
2000    mut run_pass: impl FnMut(f64) -> (Result<Refinement, String>, S),
2001    mut dense: impl FnMut(&S) -> Result<f64, String>,
2002    samples: impl Fn(&S) -> usize,
2003    mut adopt: impl FnMut(S),
2004) -> Refinement {
2005    // Whether the standing reading is a nineteen-point one (a budget-exit
2006    // candidate was taken); every later candidate is then judged on it.
2007    let mut standing_dense = false;
2008    let reject_bounds = PCURVE_REJECT_BOUNDS.with(|state| state.get());
2009    for fraction in [0.1, 0.01] {
2010        if best.residual <= floor * fraction {
2011            if trace {
2012                eprintln!(
2013                    "PCURVE-TRACK call={call} candidate fraction={fraction} skipped best_residual={:e} <= {:e}",
2014                    best.residual,
2015                    floor * fraction
2016                );
2017            }
2018            continue;
2019        }
2020        let (candidate, state) = run_pass(fraction);
2021        // The reading the candidate is judged on and the decision (see
2022        // judge_tracking_candidate); an unreadable read declines like a
2023        // failed pass.
2024        let judged_dense = matches!(&candidate, Ok(seen) if seen.exit != PcurveFitExit::Converged || standing_dense);
2025        let (effective, accepted) = match &candidate {
2026            Ok(seen) => judge_tracking_candidate_with_bounds(best.residual, standing_dense, floor, seen.exit, seen.residual, || {
2027                dense(&state)
2028            }, reject_bounds),
2029            Err(_) => (Ok(None), false),
2030        };
2031        if trace {
2032            let judged_on = match &effective {
2033                Ok(Some(reading)) => format!("{reading:e}"),
2034                Ok(None) => "-".to_string(),
2035                Err(message) => format!("error:{message:?}"),
2036            };
2037            match &candidate {
2038                Ok(seen) => eprintln!(
2039                    "PCURVE-TRACK call={call} candidate fraction={fraction} exit={:?} residual={:e} judged_on={judged_on} standing_dense={standing_dense} floor={floor:e} off_surface={:e} samples={} raised={} residual_meets_floor={} decision={}",
2040                    seen.exit,
2041                    seen.residual,
2042                    seen.off_surface,
2043                    samples(&state),
2044                    seen.raised,
2045                    seen.residual <= floor,
2046                    if accepted { "accept" } else { "decline-stop" }
2047                ),
2048                Err(message) => eprintln!(
2049                    "PCURVE-TRACK call={call} candidate fraction={fraction} error={message:?} decision=decline-stop"
2050                ),
2051            }
2052        }
2053        match candidate {
2054            Ok(mut candidate) if accepted => {
2055                // Report the reading it was taken on (its own, if Converged).
2056                if let Ok(Some(reading)) = effective {
2057                    candidate.residual = reading;
2058                }
2059                // From here on the standing reading is a nineteen-point one.
2060                if thread_dense {
2061                    standing_dense |= judged_dense;
2062                }
2063                adopt(state);
2064                best = candidate;
2065            }
2066            _ => break,
2067        }
2068    }
2069    best
2070}
2071
2072/// Whether [`refine_pcurve`] takes [`standoff_tracking_rungs`] for an
2073/// off-carrier first pass: true unless `BREP_PCURVE_STANDOFF_TRACKING=0`
2074/// (diagnostic A/B hatch, read once per process).
2075fn standoff_tracking_enabled() -> bool {
2076    switch!("BREP_PCURVE_STANDOFF_TRACKING", true)
2077}
2078
2079/// The tracking rungs for an edge curve that stands OFF its carrier by more
2080/// than the floor ([`refine_pcurve`]). The first pass is read natively
2081/// ([`native_read`] on its own knot spans and endpoints); when its tracking is
2082/// within the floor, or the read fails, nothing more is done. Otherwise each
2083/// candidate pass (fractions 0.1 then 0.01 of the floor, from the same
2084/// baseline stations, taking the one-time raise when its own tracking target
2085/// is cut short by the ceiling) is read with the standing fit at the SAME
2086/// probes (both curves' native spans and endpoints) and taken only per
2087/// [`standoff_candidate_accepted`]: tracking finite, within the unchanged
2088/// floor and strictly lower, same-parameter deviation no worse, refinement
2089/// fields finite. A taken fit is REPORTED with its same-probe deviation
2090/// (inherited standoff included, so still over the floor) and with an
2091/// `off_surface` that is the larger of its station reading and the probes'
2092/// standoff. Any error, or a candidate that does not qualify, stops the loop
2093/// and keeps the standing curve and report.
2094#[allow(clippy::too_many_arguments)]
2095fn standoff_tracking_rungs(
2096    surface: &NurbsSurface,
2097    curve: &NurbsCurve,
2098    domain: [f64; 2],
2099    u_domain: [f64; 2],
2100    v_domain: [f64; 2],
2101    floor: f64,
2102    joins: &[f64],
2103    parameters: &mut Vec<f64>,
2104    raw: &mut Vec<[f64; 2]>,
2105    pcurve: &mut NurbsCurve,
2106    mut best: Refinement,
2107    trace: bool,
2108    call: u64,
2109    insert: &mut impl FnMut(f64, Vec3, Vec3) -> Result<(Option<[f64; 2]>, f64), String>,
2110) -> Result<Refinement, String> {
2111    // Each pcurve's probe readings, kept while it is the standing fit or the
2112    // candidate (`BREP_PCURVE_READ_MEMO`).
2113    let memoise = pcurve_read_memo_enabled();
2114    let mut standing_memo = NativeReadMemo::default();
2115    let first = native_probe_fractions(&[&*pcurve])
2116        .and_then(|probes| native_read_memo(surface, curve, pcurve, domain, &probes, memoise.then_some(&mut standing_memo)));
2117    if trace {
2118        eprintln!("PCURVE-TRACK call={call} standoff-tracking first-pass native={first:?} floor={floor:e}");
2119    }
2120    let Ok(first) = first else { return Ok(best) };
2121    if first.tracking <= floor {
2122        return Ok(best);
2123    }
2124    let baseline_parameters = parameters.clone();
2125    let baseline_raw = raw.clone();
2126    let baseline_curve = pcurve.clone();
2127    for fraction in [0.1, 0.01] {
2128        let mut refined_parameters = baseline_parameters.clone();
2129        let mut refined_raw = baseline_raw.clone();
2130        let mut refined_curve = baseline_curve.clone();
2131        let candidate = refine_pcurve_pass(surface, curve, domain, u_domain, v_domain, floor, joins,
2132            &mut refined_parameters, &mut refined_raw, &mut refined_curve, best.off_surface, best.clamped,
2133            true, fraction, true, &mut *insert, false);
2134        let mut candidate_memo = NativeReadMemo::default();
2135        let reads = candidate.as_ref().ok().map(|_| {
2136            native_probe_fractions(&[&*pcurve, &refined_curve]).and_then(|probes| {
2137                Ok((
2138                    native_read_memo(surface, curve, pcurve, domain, &probes, memoise.then_some(&mut standing_memo))?,
2139                    native_read_memo(surface, curve, &refined_curve, domain, &probes, memoise.then_some(&mut candidate_memo))?,
2140                ))
2141            })
2142        });
2143        let fields_finite = matches!(&candidate, Ok(seen) if seen.residual.is_finite() && seen.off_surface.is_finite());
2144        let decision = match &reads {
2145            Some(Ok((standing, read))) => standoff_rung_decision(*standing, *read, fields_finite, floor),
2146            _ => RungDecision::Stop,
2147        };
2148        if trace {
2149            eprintln!(
2150                "PCURVE-TRACK call={call} standoff-tracking fraction={fraction} candidate={} reads={reads:?} decision={}",
2151                match &candidate { Ok(seen) => format!("{:?}/{:e}/raised={}", seen.exit, seen.residual, seen.raised), Err(message) => format!("error:{message:?}") },
2152                match decision { RungDecision::Accept => "accept", RungDecision::Continue => "decline-continue", RungDecision::Stop => "decline-stop" }
2153            );
2154        }
2155        let (Ok(mut taken), Some(Ok((_, read))), RungDecision::Accept) = (candidate, reads, decision) else {
2156            if decision == RungDecision::Continue {
2157                continue;
2158            }
2159            break;
2160        };
2161        taken.residual = read.deviation;
2162        taken.off_surface = taken.off_surface.max(read.standoff);
2163        *parameters = refined_parameters;
2164        *raw = refined_raw;
2165        *pcurve = refined_curve;
2166        // The candidate is the standing fit now: its readings come with it.
2167        standing_memo = candidate_memo;
2168        best = taken;
2169        if read.tracking <= floor * 0.01 {
2170            break;
2171        }
2172    }
2173    Ok(best)
2174}
2175
2176/// What one off-carrier tracking rung does with its candidate
2177/// ([`standoff_tracking_rungs`]).
2178#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2179pub enum RungDecision {
2180    /// Taken ([`standoff_candidate_accepted`]).
2181    Accept,
2182    /// Not taken, but it read finite and LOWER tracking than the standing fit
2183    /// while over the floor: the finer fraction is still tried from the same
2184    /// baseline (fixture 25: one use read 2.33e-7 at 0.1 and
2185    /// stopped while its partner was taken at 9.0e-9).
2186    Continue,
2187    /// Not taken and not improving (or unreadable): the rungs end.
2188    Stop,
2189}
2190
2191pub fn standoff_rung_decision(standing: NativeRead, candidate: NativeRead, fields_finite: bool, floor: f64) -> RungDecision {
2192    if standoff_candidate_accepted(standing, candidate, fields_finite, floor) {
2193        RungDecision::Accept
2194    } else if candidate.tracking.is_finite() && candidate.tracking < standing.tracking {
2195        RungDecision::Continue
2196    } else {
2197        RungDecision::Stop
2198    }
2199}
2200
2201/// The one-time raise decision of [`refine_pcurve_pass`]: a ceiling exit not
2202/// yet raised, when the returned curve is worse than the edge's own gap by
2203/// more than the floor (the original rule), or when a tracking pass for an
2204/// unmet first pass returned a curve whose own tracking still misses the
2205/// pass's target (`unmet_tracking`, read on the returned curve). Nothing else
2206/// raises.
2207pub fn takes_raise(exit: PcurveFitExit, raised: bool, residual: f64, off_surface: f64, floor: f64, unmet_tracking: bool) -> bool {
2208    exit == PcurveFitExit::SampleCeiling && !raised && (residual > off_surface + floor || unmet_tracking)
2209}
2210
2211pub fn refine_pcurve_pass(
2212    surface: &NurbsSurface,
2213    curve: &NurbsCurve,
2214    [t0, t1]: [f64; 2],
2215    [u0, u1]: [f64; 2],
2216    [v0, v1]: [f64; 2],
2217    floor: f64,
2218    joins: &[f64],
2219    parameters: &mut Vec<f64>,
2220    raw: &mut Vec<[f64; 2]>,
2221    pcurve: &mut NurbsCurve,
2222    mut off_surface: f64,
2223    mut clamped: [f64; 2],
2224    track_projection: bool,
2225    tracking_fraction: f64,
2226    raise_unmet_tracking: bool,
2227    mut insert: impl FnMut(f64, Vec3, Vec3) -> Result<(Option<[f64; 2]>, f64), String>,
2228    reject_budget: bool,
2229) -> Result<Refinement, String> {
2230    let _clock = PcurvePhaseClock::new("refinement", parameters.len(), track_projection);
2231    let tracking_floor = if track_projection { floor * tracking_fraction } else { floor };
2232    let mut max_samples = MAX_PCURVE_SAMPLES;
2233    let mut raised = false;
2234    loop {
2235        // Every way out of this loop is CLASSIFIED (`PcurveFitExit`); a budget
2236        // exit returns the curve it built, but says so. Falling off the end
2237        // after a fourth round of inserts is the round-budget exit.
2238        let mut exit = PcurveFitExit::RoundBudget;
2239        let mut residual = None;
2240        for round in 0..4 {
2241            crate::work_counts::add(|c| c.refinement_rounds += 1);
2242            if parameters.len() >= max_samples {
2243                exit = PcurveFitExit::SampleCeiling;
2244                break;
2245            }
2246            let mut inserts = Vec::new();
2247            let mut round_max = 0.0_f64;
2248            let mut truncated = false;
2249            let mut skipped_narrow = false;
2250            let mut reader = ProbeCurveReader::new(pcurve, probe_batch_enabled());
2251            for index in 0..parameters.len() - 1 {
2252                if parameters.len() + inserts.len() >= max_samples {
2253                    truncated = true;
2254                    break;
2255                }
2256                let start = parameters[index];
2257                let end = parameters[index + 1];
2258                // Keep construction's existing first-pass policy. Extended
2259                // residual probes must not silently change its station ladder;
2260                // projection tracking retains its established finer floor.
2261                if end - start < if track_projection { SPAN_FLOOR } else { 1e-3 } {
2262                    skipped_narrow = true;
2263                    continue;
2264                }
2265                for local_fraction in [0.25, 0.5, 0.75] {
2266                    if parameters.len() + inserts.len() >= max_samples {
2267                        truncated = true;
2268                        break;
2269                    }
2270                    let fraction = start + (end - start) * local_fraction;
2271                    let parameter = reader.evaluate(fraction)?;
2272                    let on_surface =
2273                        section_surface_point(surface, parameter.x, parameter.y, true)?;
2274                    let on_curve = section_curve_point(curve, t0 + (t1 - t0) * fraction)?;
2275                    let deviation = on_surface.sub(on_curve).length();
2276                    // A non-finite distance must not reach `f64::max` (which
2277                    // drops NaN) or the classification below, where a round
2278                    // with an unreadable station could still exit Converged on
2279                    // its readable ones. Fail closed: a first pass's error
2280                    // goes to its caller, a tracking candidate's declines it.
2281                    if !deviation.is_finite() {
2282                        return Err(format!(
2283                            "refine_pcurve_pass: non-finite station distance {deviation} at fraction {fraction}"
2284                        ));
2285                    }
2286                    round_max = round_max.max(deviation);
2287                    if deviation <= tracking_floor {
2288                        continue;
2289                    }
2290                    let (surface_parameter, gap) = insert(fraction, parameter, on_curve)?;
2291                    off_surface = off_surface.max(gap);
2292                    if let Some(surface_parameter) = surface_parameter {
2293                        // The raised pass stops where the pcurve TRACKS the
2294                        // edge curve's projection to the floor — the best any
2295                        // pcurve can do at this station. Not `deviation - gap`:
2296                        // a surface point at tangential distance d from the
2297                        // projection of a point g off the surface is only
2298                        // d^2/(2g) further from it, so the deviation test is
2299                        // quadratically blind to sideways error on off-surface
2300                        // input (6e-6 of slop at g = 1.9e-4, floor 1e-7).
2301                        if raised || track_projection {
2302                            let projected =
2303                                section_surface_point(surface, surface_parameter[0], surface_parameter[1], false)?;
2304                            if on_surface.sub(projected).length() <= tracking_floor {
2305                                continue;
2306                            }
2307                        }
2308                        inserts.push((index + 1, fraction, surface_parameter));
2309                    }
2310                }
2311            }
2312            if inserts.is_empty() {
2313                // Nothing to insert: every probed station is within the floor
2314                // (converged — unless a narrow span was skipped, in which case
2315                // the sweep below decides), or the ones over it could not be
2316                // improved (stalled — the edge curve is off the surface there).
2317                exit = if truncated {
2318                    PcurveFitExit::SampleCeiling
2319                } else if round_max > floor {
2320                    PcurveFitExit::Stalled
2321                } else if skipped_narrow {
2322                    PcurveFitExit::SpanFloor
2323                } else {
2324                    residual = Some(round_max);
2325                    PcurveFitExit::Converged
2326                };
2327                break;
2328            }
2329            // With inserts still needed after the fourth non-truncated
2330            // round, this exit is RoundBudget. An in-floor standing fit
2331            // never adopts any budget exit; rebuilding and probing this
2332            // discarded candidate cannot affect its curve or report.
2333            if reject_budget && round == 3 && !truncated {
2334                if crate::profile::profile_enabled() { profile_line!("pcurve.reject_bound kind=fifth_round"); }
2335                return Err("pcurve tracking candidate requires a fifth round".into());
2336            }
2337            for (at, fraction, surface_parameter) in inserts.into_iter().rev() {
2338                parameters.insert(at, fraction);
2339                raw.insert(at, surface_parameter);
2340            }
2341            let (rebuilt, excursion, distance) = build_interpolant_joined(surface, raw, parameters, joins)?;
2342            *pcurve = rebuilt;
2343            clamped = [excursion, distance];
2344            if truncated {
2345                exit = PcurveFitExit::SampleCeiling;
2346                break;
2347            }
2348        }
2349        let residual = match residual {
2350            Some(measured) => measured,
2351            // A budget exit never re-checked the curve it is returning, and a
2352            // converged round that skipped narrow spans never checked those:
2353            // measure every span.
2354            None => probe_residual(
2355                surface,
2356                curve,
2357                pcurve,
2358                parameters,
2359                [t0, t1],
2360                [u0, u1],
2361                [v0, v1],
2362            )?,
2363        };
2364        if exit == PcurveFitExit::SpanFloor && residual <= floor {
2365            exit = PcurveFitExit::Converged;
2366        }
2367        // The per-trim budget decision. Deterministic, grow-once, capped (I3):
2368        // the ceiling bound and the returned curve is worse than the edge
2369        // curve's own gap from the surface by more than the floor, so samples
2370        // can still buy accuracy. A curve already at its gap stops here —
2371        // reported, not retried.
2372        // A TRACKING pass for a standing fit that missed the floor (and only
2373        // then) also takes the same one-time raise when it hits the ceiling
2374        // still over the floor: its request is the projection's tracking, and
2375        // the ceiling cut it short. The raised maximum itself is unchanged.
2376        // The added raise serves a TRACKING pass for an unmet first pass whose
2377        // RETURNED curve still misses the pass's own target: its tracking (the
2378        // image against the projected foot, read natively on its own knot spans
2379        // and endpoints) over the tracking floor (floor x fraction). Reaching
2380        // the ceiling alone is exhaustion, not a miss, and the inherited
2381        // standoff never triggers it. Read only at a ceiling exit not yet
2382        // raised; an unreadable read does not raise.
2383        let unmet_tracking = track_projection
2384            && raise_unmet_tracking
2385            && exit == PcurveFitExit::SampleCeiling
2386            && !raised
2387            && native_probe_fractions(&[&*pcurve])
2388                .and_then(|probes| native_read(surface, curve, pcurve, [t0, t1], &probes))
2389                .is_ok_and(|read| read.tracking > tracking_floor);
2390        if takes_raise(exit, raised, residual, off_surface, floor, unmet_tracking) {
2391            raised = true;
2392            max_samples = PCURVE_RAISED_SAMPLES;
2393            continue;
2394        }
2395        return Ok(Refinement {
2396            exit,
2397            residual,
2398            off_surface,
2399            raised,
2400            clamped,
2401        });
2402    }
2403}
2404
2405/// The exact inverse of an affine carrier's parameterization.
2406///
2407/// An affine patch (2x2 net, degree 1 both ways, equal weights) maps `uv` to 3D
2408/// by an affine map, so the inverse — a 3D point to the `uv` of its orthogonal
2409/// projection — is affine too. An affine map commutes with the rational basis:
2410/// sending a curve's control points through it and keeping the weights
2411/// produces the EXACT image of that curve in parameter space, not a fit of it.
2412struct AffineInversion {
2413    origin: Vec3,
2414    du: Vec3,
2415    dv: Vec3,
2416    u0: f64,
2417    v0: f64,
2418    uu: f64,
2419    uv: f64,
2420    vv: f64,
2421    determinant: f64,
2422}
2423
2424impl AffineInversion {
2425    /// `None` when `surface` is not affine, or when its two directions are
2426    /// parallel enough that the inverse is not determined. The caller decides
2427    /// what that means: a refusal on the whole-curve lane, the sampled lane on
2428    /// the range lane.
2429    fn of(surface: &NurbsSurface) -> Result<Option<Self>, String> {
2430        if !surface.is_affine()? {
2431            return Ok(None);
2432        }
2433        let ([u0, _], [v0, _]) = surface_domains(surface)?;
2434        let (origin, du, dv) = surface.deriv1(u0, v0)?;
2435        let uu = du.dot(du);
2436        let uv = du.dot(dv);
2437        let vv = dv.dot(dv);
2438        let determinant = uu * vv - uv * uv;
2439        if determinant.abs() <= 1e-18 {
2440            return Ok(None);
2441        }
2442        Ok(Some(Self {
2443            origin,
2444            du,
2445            dv,
2446            u0,
2447            v0,
2448            uu,
2449            uv,
2450            vv,
2451            determinant,
2452        }))
2453    }
2454
2455    fn uv_of(&self, point: Vec3) -> [f64; 2] {
2456        let delta = point.sub(self.origin);
2457        let along_u = delta.dot(self.du);
2458        let along_v = delta.dot(self.dv);
2459        [
2460            self.u0 + (along_u * self.vv - along_v * self.uv) / self.determinant,
2461            self.v0 + (along_v * self.uu - along_u * self.uv) / self.determinant,
2462        ]
2463    }
2464
2465    /// The exact image of `curve` in this carrier's parameter space, with the
2466    /// curve's own degree, knots and weights.
2467    fn image_of(&self, curve: &NurbsCurve) -> Result<NurbsCurve, String> {
2468        let control_points = curve
2469            .control_points
2470            .iter()
2471            .map(|control| {
2472                let [u, v] = self.uv_of(control.point()?);
2473                Ok(Vec4::from_point(Vec3::new(u, v, 0.0), control.w))
2474            })
2475            .collect::<Result<Vec<_>, String>>()?;
2476        NurbsCurve::new(curve.degree, curve.knots.clone(), control_points)
2477    }
2478}
2479
2480fn sphere_iso_enabled() -> bool {
2481    env_read!("BREP_PCURVE_SPHERE_ISO").is_none_or(|mode| mode != "0")
2482}
2483
2484/// A complete native meridian with the same rational basis as the section.
2485/// Equal positive weights and affinely identical knots make its image minus
2486/// the section a convex combination of control-point differences. Thus their
2487/// maximum norm bounds the whole curve, including the pole endpoints. This
2488/// avoids fitting an arbitrary longitude at a pole into a meridian's interior.
2489/// Every failed recognition retains the ordinary fitter and its diagnostics.
2490pub fn sphere_iso_fit(surface: &NurbsSurface, curve: &NurbsCurve) -> Option<PcurveFit> {
2491    // Native sphere recognition requires quadratic u. Avoid warming other
2492    // carriers, and validate before recognition indexes a deserialized net.
2493    if surface.degree_u != 2 { return None; }
2494    let [t0, t1] = curve.domain().ok()?;
2495    let [u0, u1] = surface.domain_u().ok()?;
2496    let [v0, v1] = surface.domain_v().ok()?;
2497    if !matches!(surface.analytic(), Some(AnalyticSurface::Sphere { .. })) { return None; }
2498    let middle = curve.evaluate(t0 + (t1 - t0) * 0.5).ok()?;
2499    let projected = project_point_to_surface(surface, middle).ok()?;
2500    let mut candidates = vec![projected.u];
2501    // Cardinal meridians can invert an ulp beside their native knot. A snap
2502    // is only a candidate: the complete control-net bound below must hold.
2503    for &knot in &surface.knots_u {
2504        if (knot - projected.u).abs() <= 1e-12 && !candidates.contains(&knot) { candidates.push(knot); }
2505    }
2506    for u in candidates {
2507        if !(u >= u0 && u <= u1) { continue; }
2508        let iso = surface.iso_curve_u(u).ok()?;
2509        if iso.degree != curve.degree || iso.knots.len() != curve.knots.len()
2510            || iso.control_points.len() != curve.control_points.len() { continue; }
2511        for reverse in [false, true] {
2512            let n = iso.control_points.len();
2513            // Rounded quotient equality alone does not prove equal bases.
2514            // TwoDiff proves the subtractions exact; FMA then proves that
2515            // each normalized knot times its span equals the exact offset.
2516            // Conservative magnitude bounds keep all product residuals well
2517            // above underflow. Unusual domains simply use the ordinary fit.
2518            fn exact_difference(a: f64, b: f64) -> Option<f64> {
2519                if !(a.is_finite() && b.is_finite()) || a.abs().max(b.abs()) > 1e100 { return None; }
2520                let x = a - b;
2521                let bv = a - x;
2522                let av = x + bv;
2523                let error = (a - av) + (bv - b);
2524                (error == 0.).then_some(x)
2525            }
2526            fn exact_fraction(offset: f64, span: f64) -> Option<f64> {
2527                if !(1e-100..=1e100).contains(&span) { return None; }
2528                let ratio = offset / span;
2529                if !(0.0..=1.0).contains(&ratio) || (ratio != 0. && ratio < 1e-100) { return None; }
2530                (ratio.mul_add(span, -offset) == 0.).then_some(ratio)
2531            }
2532            let knots_match = (|| {
2533                let section_span = exact_difference(t1, t0)?;
2534                let native_span = exact_difference(v1, v0)?;
2535                for (i, &knot) in curve.knots.iter().enumerate() {
2536                    let section = exact_difference(knot, t0)?;
2537                    let native = if reverse { exact_difference(v1, iso.knots[iso.knots.len() - 1 - i])? }
2538                        else { exact_difference(iso.knots[i], v0)? };
2539                    if exact_fraction(section, section_span)? != exact_fraction(native, native_span)? { return None; }
2540                }
2541                Some(())
2542            })().is_some();
2543            if !knots_match { continue; }
2544            let mut bound = 0.0_f64;
2545            let mut matches = true;
2546            for (i, control) in curve.control_points.iter().enumerate() {
2547                let native = &iso.control_points[if reverse { n - 1 - i } else { i }];
2548                if !(control.w > 0.) || control.w != native.w { matches = false; break; }
2549                let distance = control.point().ok()?.sub(native.point().ok()?).length();
2550                if !distance.is_finite() { matches = false; break; }
2551                bound = bound.max(distance);
2552            }
2553            if !matches || bound > PCURVE_REFINEMENT_TOLERANCE * 0.0625 { continue; }
2554            let (start, end) = if reverse { (v1, v0) } else { (v0, v1) };
2555            let pcurve = NurbsCurve::new(1, vec![0., 0., 1., 1.], vec![
2556                Vec4::from_point(Vec3::new(u, start, 0.), 1.),
2557                Vec4::from_point(Vec3::new(u, end, 0.), 1.),
2558            ]).ok()?;
2559            // Confirm the actual floating-point evaluation too, on the
2560            // ordinary first pass's 24 intervals and quarter stations. The
2561            // control-net proof covers between probes; these reads guard
2562            // roundoff from differing surface/curve evaluation orders.
2563            for i in 0..=96 {
2564                let fraction = i as f64 / 96.;
2565                let uv = pcurve.evaluate(fraction).ok()?;
2566                let image = surface.evaluate(uv.x, uv.y).ok()?;
2567                let on_curve = curve.evaluate(t0 + (t1 - t0) * fraction).ok()?;
2568                let error = image.sub(on_curve).length();
2569                if !error.is_finite() { matches = false; break; }
2570                bound = bound.max(error);
2571            }
2572            if !matches || bound > PCURVE_REFINEMENT_TOLERANCE * 0.0625 { continue; }
2573            crate::work_counts::constructed("analytic_certified", 0, pcurve.control_points.len());
2574            return Some(PcurveFit { curve: pcurve, report: PcurveFitReport {
2575                residual: bound, floor: PCURVE_REFINEMENT_TOLERANCE, samples: 2,
2576                exit: PcurveFitExit::Converged, off_surface: bound, raised: false,
2577                clamped_excursion: 0., clamped_distance: 0.,
2578            } });
2579        }
2580    }
2581    None
2582}
2583
2584/// Build a parameter-space curve for a 3D curve lying on a surface, and say
2585/// what the fit achieved.
2586///
2587/// This mirrors the reference imprint implementation: affine patches map
2588/// homogeneous control points exactly; general patches use sampled inversion,
2589/// periodic seam unwrapping, and adaptive 3D residual refinement. The report
2590/// beside the curve carries the residual the RETURNED curve reaches and why
2591/// refinement stopped ([`PcurveFitReport`]); the curve itself is what
2592/// [`build_pcurve_on_surface`] has always returned.
2593pub fn fit_pcurve_on_surface(
2594    surface: &NurbsSurface,
2595    curve: &NurbsCurve,
2596) -> Result<PcurveFit, String> {
2597    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::FIT);
2598    crate::work_counts::add(|c| c.fit_calls += 1);
2599    if sphere_iso_enabled() {
2600        if let Some(fit) = sphere_iso_fit(surface, curve) { return Ok(fit); }
2601    }
2602    let mode = env_read!("BREP_PCURVE_EVAL_CACHE").unwrap_or_default();
2603    let bounds = env_read!("BREP_PCURVE_REJECT_BOUNDS").unwrap_or_else(|| "on".into());
2604    let stack = env_read!("BREP_PCURVE_STACK_POINT").unwrap_or_else(|| "on".into());
2605    if mode == "check" || bounds == "check" || stack == "check" {
2606        let old = fit_pcurve_on_surface_cached(surface, curve, false, false, false)?;
2607        if matches!(surface.analytic(), Some(AnalyticSurface::Sphere { .. })) {
2608            let candidate = fit_pcurve_on_surface_cached(surface, curve, mode == "check" || mode == "on" || mode == "1", bounds == "check" || bounds == "on" || bounds == "1", stack == "check" || stack == "on" || stack == "1");
2609            let identical = candidate.as_ref().is_ok_and(|new| {
2610                old.curve.degree == new.curve.degree
2611                    && old.curve.knots.len() == new.curve.knots.len()
2612                    && old.curve.knots.iter().zip(&new.curve.knots).all(|(a, b)| a.to_bits() == b.to_bits())
2613                    && old.curve.control_points.len() == new.curve.control_points.len()
2614                    && old.curve.control_points.iter().zip(&new.curve.control_points).all(|(a, b)| {
2615                        [a.x.to_bits(), a.y.to_bits(), a.z.to_bits(), a.w.to_bits()]
2616                            == [b.x.to_bits(), b.y.to_bits(), b.z.to_bits(), b.w.to_bits()]
2617                    }) && old.report == new.report
2618            });
2619            if let Ok(path) = std::env::var("BREP_PCURVE_EVAL_CENSUS") {
2620                use std::io::Write;
2621                if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
2622                    let _ = writeln!(file, "pcurve.eval_census identical={identical} controls={} samples={}", old.curve.control_points.len(), old.report.samples);
2623                }
2624            }
2625        }
2626        return Ok(old);
2627    }
2628    fit_pcurve_on_surface_cached(surface, curve, mode == "1" || mode == "on", bounds == "1" || bounds == "on", stack == "1" || stack == "on")
2629}
2630
2631pub fn fit_pcurve_on_surface_cached(surface: &NurbsSurface, curve: &NurbsCurve, enabled: bool, bounds: bool, stack: bool) -> Result<PcurveFit, String> {
2632    let _stack = PcurveStackPointScope::open(stack && matches!(surface.analytic(), Some(AnalyticSurface::Sphere { .. })));
2633    // Non-sphere refinement repeats expensive global inversions and surface
2634    // probes. Retain successful exact inputs for this immutable fit only.
2635    // The older sphere-global experiment keeps its existing opt-in policy.
2636    let _samples = PcurveSampleScope::open(surface, curve, enabled
2637        || !matches!(surface.analytic(), Some(AnalyticSurface::Sphere { .. })));
2638    let _bounds = PcurveRejectScope::open(bounds && matches!(surface.analytic(), Some(AnalyticSurface::Sphere { .. })));
2639    let [t0, t1] = curve.domain()?;
2640    if surface.is_affine()? {
2641        let Some(inversion) = AffineInversion::of(surface)? else {
2642            return Err("build_pcurve_on_surface: singular affine parameterization".into());
2643        };
2644        let pcurve = inversion.image_of(curve)?;
2645        crate::work_counts::constructed("affine", 0, pcurve.control_points.len());
2646        return Ok(PcurveFit {
2647            report: PcurveFitReport {
2648                residual: 0.0,
2649                floor: PCURVE_REFINEMENT_TOLERANCE,
2650                samples: pcurve.control_points.len(),
2651                exit: PcurveFitExit::Converged,
2652                off_surface: 0.0,
2653                raised: false,
2654                clamped_excursion: 0.0,
2655                clamped_distance: 0.0,
2656            },
2657            curve: pcurve,
2658        });
2659    }
2660
2661    let scale = 1.0 + curve.evaluate((t0 + t1) / 2.0)?.length();
2662    let drop_tolerance = 1e-4 * scale;
2663    let endpoint_tolerance = 1e-3 * scale;
2664    let refinement_tolerance = PCURVE_REFINEMENT_TOLERANCE;
2665    let ([u0, u1], [v0, v1]) = surface_domains(surface)?;
2666    let invert =
2667        |fraction: f64| invert_checked(surface, section_curve_point(curve, t0 + (t1 - t0) * fraction)?);
2668
2669    let mut parameters = Vec::with_capacity(25);
2670    let mut raw_surface_parameters = Vec::with_capacity(25);
2671    // The edge curve's own distance from the surface at every station inverted,
2672    // accepted or not: the floor below which no pcurve can bring the residual.
2673    let mut off_surface = 0.0_f64;
2674    // The edge's own C0 knots must remain corners of its parameter image.
2675    // Plant those stations before inversion; refinement retains their joins.
2676    let corners = range_breaks(curve, t0, t1, true);
2677    let mut stations: Vec<f64> = (0..=24).map(|index| index as f64 / 24.0).collect();
2678    // Replace nearby uniform seeds, never the native corner itself. Keep
2679    // endpoints and other native corners even when their spans are short.
2680    stations.retain(|station| {
2681        *station == 0.0 || *station == 1.0 || corners.contains(station)
2682            || !corners.iter().any(|corner| (*station - corner).abs() <= SPAN_FLOOR)
2683    });
2684    for &corner in &corners {
2685        let at = stations.partition_point(|value| *value < corner);
2686        if stations.get(at) != Some(&corner) {
2687            stations.insert(at, corner);
2688        }
2689    }
2690    let joins = corners;
2691    for (index, &fraction) in stations.iter().enumerate() {
2692        let (parameter, distance) = invert(fraction)?;
2693        off_surface = off_surface.max(distance);
2694        if distance > drop_tolerance && index != 0 && index != stations.len() - 1 {
2695            continue;
2696        }
2697        if distance > endpoint_tolerance {
2698            if std::env::var("BREP_DEBUG_PCURVE").is_ok() {
2699                let p3 = curve.evaluate(t0 + (t1 - t0) * fraction).ok();
2700                let p0 = curve.evaluate(t0).ok();
2701                let p1 = curve.evaluate(t1).ok();
2702                eprintln!(
2703                    "PCURVE-FAIL idx={index} frac={fraction} dist={distance} endpt_tol={endpoint_tolerance} scale={scale}\n  curve3D@frac={p3:?}\n  curve3D@t0={p0:?} curve3D@t1={p1:?}\n  surf_domain=u[{u0},{u1}] v[{v0},{v1}] invpar={parameter:?}\n  surf@invpar={:?}",
2704                    surface.evaluate(parameter[0], parameter[1]).ok()
2705                );
2706            }
2707            return Err(format!(
2708                "build_pcurve_on_surface: endpoint projection failed (distance={distance})"
2709            ));
2710        }
2711        parameters.push(fraction);
2712        raw_surface_parameters.push(parameter);
2713    }
2714
2715    let (mut pcurve, excursion, distance) =
2716        build_interpolant_joined(surface, &raw_surface_parameters, &parameters, &joins)?;
2717    let refinement = refine_pcurve(
2718        surface,
2719        curve,
2720        [t0, t1],
2721        [u0, u1],
2722        [v0, v1],
2723        refinement_tolerance,
2724        &joins,
2725        &mut parameters,
2726        &mut raw_surface_parameters,
2727        &mut pcurve,
2728        off_surface,
2729        [excursion, distance],
2730        |fraction, _parameter, _on_curve| {
2731            let (surface_parameter, distance) = invert(fraction)?;
2732            Ok((
2733                (distance <= drop_tolerance).then_some(surface_parameter),
2734                distance,
2735            ))
2736        },
2737    )?;
2738    crate::work_counts::constructed("projected_global", parameters.len(), pcurve.control_points.len());
2739    Ok(PcurveFit {
2740        curve: pcurve,
2741        report: PcurveFitReport {
2742            residual: refinement.residual,
2743            floor: refinement_tolerance,
2744            samples: parameters.len(),
2745            exit: refinement.exit,
2746            off_surface: refinement.off_surface,
2747            raised: refinement.raised,
2748            clamped_excursion: refinement.clamped[0],
2749            clamped_distance: refinement.clamped[1],
2750        },
2751    })
2752}
2753
2754/// [`fit_pcurve_on_surface`] for the callers that only need the curve. The
2755/// report is not dropped: it is tallied on the open [`PcurveFitScope`], if any,
2756/// so the operation that owns this fit can say in its diagnostics whether every
2757/// trim reached the floor.
2758pub fn build_pcurve_on_surface(
2759    surface: &NurbsSurface,
2760    curve: &NurbsCurve,
2761) -> Result<NurbsCurve, String> {
2762    let fit = fit_pcurve_on_surface(surface, curve)?;
2763    record_fit(&fit.report);
2764    Ok(fit.curve)
2765}
2766
2767/// Optional section-fit clock; records every early fallback without changing it.
2768struct SectionFitClock {
2769    started: Option<web_time::Instant>,
2770    global: std::time::Duration,
2771    seeded: bool,
2772}
2773impl SectionFitClock {
2774    fn new() -> Self {
2775        Self { started: crate::profile::profile_enabled().then(web_time::Instant::now),
2776            global: std::time::Duration::ZERO, seeded: false }
2777    }
2778}
2779impl Drop for SectionFitClock {
2780    fn drop(&mut self) {
2781        if let Some(started) = self.started {
2782            crate::profile::profile_emit(format_args!("pcurve.section_time global={:.3} seeded={:.3} result={}",
2783                self.global.as_secs_f64() * 1000.0,
2784                started.elapsed().saturating_sub(self.global).as_secs_f64() * 1000.0,
2785                if self.seeded { "seeded" } else { "global" }));
2786        }
2787    }
2788}
2789
2790/// SECTION-PCURVE SEEDED MARCH (t222: cone × ABC 00000327, non-integral genus).
2791///
2792/// `build_pcurve_on_surface` inverts every sample by GLOBAL closest point. Where
2793/// the carrier surface is COMPRESSED / self-overlapping along the row the
2794/// section rides, the global search aliases interior samples onto a DISTANT
2795/// preimage sheet, folding the pcurve out past the trim boundary and re-crossing
2796/// it. The arrangement then splits the shared section at that phantom crossing,
2797/// while the mate face (whose carrier is not folded there) keeps the section
2798/// whole — so the two operands' fragments disagree and the section strands
2799/// one-use (non-integral genus). Ground truth for t222: 00000327 face 496's
2800/// v≈0.7875 row maps u∈[0.55,0.81] into a ~0.18mm neighbourhood of the section
2801/// endpoint A; the global pcurve for piece 9 folded out to u=0.806 and back,
2802/// re-crossing trim edge 349 at v≈0.784, 0.003 below the corner vertex A.
2803///
2804/// This marches the interior inversions with each seeded from the PREVIOUS
2805/// accepted parameters, so a marched sample
2806/// adopts the nearby branch instead of the momentarily-closest distant sheet.
2807/// The two ENDPOINT samples keep the deterministic global inversion (they are
2808/// the piece's shared junction vertices — same reasoning as
2809/// `repair_branch_jumps`). Additive + fail-soft: the marched chain is used ONLY
2810/// when it CLOSES onto the global far endpoint (its last interior sample is
2811/// parameter-adjacent to it, measured against the chain's own median step);
2812/// otherwise the plain global build is returned byte-for-byte. A single-preimage
2813/// carrier (the cone side of the same section) marches to the same samples the
2814/// global search already had. Use the analytic-aware seeded projector for both
2815/// the march and inserted stations: raw Newton stops at 1e-7 even on an exact
2816/// cylinder, introducing avoidable trim error. General folded carriers retain
2817/// their local seeded Newton path; analytic carriers take their closed form.
2818///
2819/// Escape hatch: `BREP_SECTION_PCURVE_MARCH=0`.
2820pub fn fit_pcurve_on_surface_marched(
2821    surface: &NurbsSurface,
2822    curve: &NurbsCurve,
2823) -> Result<PcurveFit, String> {
2824    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::FIT);
2825    crate::work_counts::add(|c| c.fit_calls += 1);
2826    fn run(surface: &NurbsSurface, curve: &NurbsCurve, eager: bool) -> Result<PcurveFit, String> {
2827        // The global fallback owns a nested scope; it cannot populate or
2828        // invalidate the marched fit's immutable carrier/curve entries.
2829        let _samples = PcurveSampleScope::open(surface, curve, true);
2830        let mut clock = SectionFitClock::new();
2831        // The global builder owns only scoped sample caches. Its fit/report is
2832        // discarded on a successful seeded route; do that work on fallback only.
2833        // Profile phase/sample lines for the discarded global fit disappear ON.
2834        let mut fallback = || {
2835            let started = clock.started.map(|_| web_time::Instant::now());
2836            let fit = fit_pcurve_on_surface(surface, curve);
2837            if let Some(started) = started { clock.global += started.elapsed(); }
2838            fit
2839        };
2840        let global = if eager { Some(fallback()?) } else { None };
2841        // The global builder's first fallible geometry read validates the
2842        // curve domain. Preserve that error priority before the affine probe
2843        // when the unused global fit is deferred (both inputs may be invalid).
2844        if !eager { curve.domain()?; }
2845        if env_read!("BREP_SECTION_PCURVE_MARCH").as_deref() == Some("0") || surface.is_affine()? {
2846            return global.map_or_else(&mut fallback, Ok);
2847        }
2848        let [t0, t1] = curve.domain()?;
2849        // A closed (ring) section has no distinct endpoints to anchor the march;
2850        // leave it to the existing path (closed rings are handled elsewhere).
2851        if curve.evaluate(t0)?.sub(curve.evaluate(t1)?).length() <= 1e-6 {
2852            return global.map_or_else(&mut fallback, Ok);
2853        }
2854        const SAMPLES: usize = 24;
2855        let fractions: Vec<f64> = (0..=SAMPLES).map(|i| i as f64 / SAMPLES as f64).collect();
2856        let edge: Vec<Vec3> = fractions
2857            .iter()
2858            .map(|fraction| curve.evaluate(t0 + (t1 - t0) * fraction))
2859            .collect::<Result<Vec<_>, _>>()?;
2860        let scale = 1.0 + curve.evaluate((t0 + t1) / 2.0)?.length();
2861        let endpoint_tolerance = 1e-3 * scale;
2862        let (first, first_distance) = invert_checked(surface, edge[0])?;
2863        let (last, last_distance) = invert_checked(surface, edge[SAMPLES])?;
2864        if first_distance > endpoint_tolerance || last_distance > endpoint_tolerance {
2865            return global.map_or_else(&mut fallback, Ok);
2866        }
2867        // The edge curve's distance from the surface at every station this chain
2868        // inverts — on the MARCHED branch, which is the one being fitted.
2869        let mut off_surface = first_distance.max(last_distance);
2870        let ([u0, u1], [v0, v1]) = surface_domains(surface)?;
2871        let u_span = (u1 - u0).abs().max(EPSILON);
2872        let v_span = (v1 - v0).abs().max(EPSILON);
2873        let (closed_u, closed_v) = surface_closedness(surface)?;
2874        let norm_step = |a: [f64; 2], b: [f64; 2]| -> f64 {
2875            let mut du = a[0] - b[0];
2876            if closed_u {
2877                while du > 0.5 * u_span {
2878                    du -= u_span;
2879                }
2880                while du < -0.5 * u_span {
2881                    du += u_span;
2882                }
2883            }
2884            let mut dv = a[1] - b[1];
2885            if closed_v {
2886                while dv > 0.5 * v_span {
2887                    dv -= v_span;
2888                }
2889                while dv < -0.5 * v_span {
2890                    dv += v_span;
2891                }
2892            }
2893            ((du / u_span).powi(2) + (dv / v_span).powi(2)).sqrt()
2894        };
2895        // Forward seeded march over the interior samples.
2896        let mut raw = vec![first];
2897        let mut previous = first;
2898        for index in 1..SAMPLES {
2899            let seeded =
2900                crate::projection::project_point_to_surface_from_seed(surface, edge[index], previous)?;
2901            let (_, global_distance) = invert_checked(surface, edge[index])?;
2902            // The seeded footpoint must still sit on the surface — as tight as the
2903            // fit band or the global answer already had it. If it fell off (the
2904            // seed led Newton into a valley), abandon the march and keep global.
2905            if seeded.distance > 4.0 * global_distance + endpoint_tolerance {
2906                return global.map_or_else(&mut fallback, Ok);
2907            }
2908            off_surface = off_surface.max(seeded.distance);
2909            previous = [seeded.u, seeded.v];
2910            raw.push(previous);
2911        }
2912        raw.push(last);
2913        // CLOSURE GATE: the last marched interior sample must be parameter-adjacent
2914        // to the global far endpoint — the march stayed on ONE branch the whole way.
2915        // Measure the endpoint gap against the chain's OWN median step so a genuine
2916        // long edge is not rejected while a sheet-hop (which leaves a big gap to the
2917        // endpoint) is.
2918        let mut steps: Vec<f64> = (1..raw.len())
2919            .map(|i| norm_step(raw[i], raw[i - 1]))
2920            .collect();
2921        let endpoint_gap = steps.pop().unwrap_or(0.0);
2922        steps.sort_by(f64::total_cmp);
2923        let median = steps
2924            .get(steps.len() / 2)
2925            .copied()
2926            .unwrap_or(0.0)
2927            .max(EPSILON);
2928        if endpoint_gap > (4.0 * median).max(0.05) {
2929            return global.map_or_else(&mut fallback, Ok);
2930        }
2931        // Build the interpolant from the marched samples, then refine — re-projecting
2932        // each insert SEEDED from the interpolant (already on the marched branch), so
2933        // a mid-refinement global inversion cannot re-alias onto the far sheet.
2934        let mut parameters = fractions;
2935        let (mut pcurve, excursion, distance) = build_interpolant(surface, &raw, &parameters)?;
2936        let refinement_tolerance = PCURVE_REFINEMENT_TOLERANCE;
2937        // Same classified exits and budget ladder as `fit_pcurve_on_surface`. A
2938        // seeded insert always lands, so this loop cannot stall.
2939        let refinement = refine_pcurve(
2940            surface,
2941            curve,
2942            [t0, t1],
2943            [u0, u1],
2944            [v0, v1],
2945            refinement_tolerance,
2946            &[],
2947            &mut parameters,
2948            &mut raw,
2949            &mut pcurve,
2950            off_surface,
2951            [excursion, distance],
2952            |_fraction, seed, on_curve| {
2953                let seeded = crate::projection::project_point_to_surface_from_seed(surface, on_curve, [seed.x, seed.y])?;
2954                Ok((Some([seeded.u, seeded.v]), seeded.distance))
2955            },
2956        )?;
2957        clock.seeded = true;
2958        crate::work_counts::constructed("projected_seeded", parameters.len(), pcurve.control_points.len());
2959        Ok(PcurveFit {
2960            curve: pcurve,
2961            report: PcurveFitReport {
2962                residual: refinement.residual,
2963                floor: refinement_tolerance,
2964                samples: parameters.len(),
2965                exit: refinement.exit,
2966                off_surface: refinement.off_surface,
2967                raised: refinement.raised,
2968                clamped_excursion: refinement.clamped[0],
2969                clamped_distance: refinement.clamped[1],
2970            },
2971        })
2972    }
2973
2974    let mode = match std::env::var("BREP_PCURVE_LAZY_GLOBAL") {
2975        Ok(mode) => mode,
2976        Err(std::env::VarError::NotPresent) => "on".to_owned(),
2977        Err(std::env::VarError::NotUnicode(_)) => String::new(),
2978    };
2979    if mode != "check" {
2980        return run(surface, curve, !matches!(mode.as_str(), "1" | "on"));
2981    }
2982    // Clone BEFORE eager evaluation: lazy must start with the same carrier
2983    // cache state, rather than benefiting from eager's recognition/projection.
2984    let lazy_surface = surface.clone();
2985    let lazy_curve = curve.clone();
2986    let eager = run(surface, curve, true);
2987    let lazy = run(&lazy_surface, &lazy_curve, false);
2988    let identical = match (&eager, &lazy) {
2989        (Ok(a), Ok(b)) => {
2990            a.curve.degree == b.curve.degree
2991                && a.curve.knots.len() == b.curve.knots.len()
2992                && a.curve.knots.iter().zip(&b.curve.knots).all(|(a,b)| a.to_bits() == b.to_bits())
2993                && a.curve.control_points.len() == b.curve.control_points.len()
2994                && a.curve.control_points.iter().zip(&b.curve.control_points).all(|(a,b)| {
2995                    [a.x.to_bits(),a.y.to_bits(),a.z.to_bits(),a.w.to_bits()]
2996                        == [b.x.to_bits(),b.y.to_bits(),b.z.to_bits(),b.w.to_bits()]
2997                })
2998                && a.report == b.report
2999                && [a.report.residual, a.report.floor, a.report.off_surface,
3000                    a.report.clamped_excursion, a.report.clamped_distance].map(f64::to_bits)
3001                    == [b.report.residual, b.report.floor, b.report.off_surface,
3002                        b.report.clamped_excursion, b.report.clamped_distance].map(f64::to_bits)
3003        }
3004        (Err(a), Err(b)) => a == b,
3005        _ => false,
3006    };
3007    if let Ok(path) = std::env::var("BREP_PCURVE_LAZY_GLOBAL_CENSUS") {
3008        use std::io::Write;
3009        let mut file = std::fs::OpenOptions::new().create(true).append(true).open(path)
3010            .expect("open lazy-global differential ledger");
3011        writeln!(file, "pcurve.lazy_global identical={identical} eager_ok={} lazy_ok={} degree={} controls={}",
3012            eager.is_ok(), lazy.is_ok(), curve.degree, curve.control_points.len())
3013            .expect("append lazy-global differential ledger");
3014    }
3015    assert!(identical, "lazy global pcurve fallback changed the curve, report or error");
3016    eager
3017}
3018
3019/// [`fit_pcurve_on_surface_marched`] for the callers that only need the curve;
3020/// the report is tallied on the open [`PcurveFitScope`] exactly as
3021/// [`build_pcurve_on_surface`] does.
3022pub fn build_pcurve_on_surface_marched(
3023    surface: &NurbsSurface,
3024    curve: &NurbsCurve,
3025) -> Result<NurbsCurve, String> {
3026    let fit = fit_pcurve_on_surface_marched(surface, curve)?;
3027    record_fit(&fit.report);
3028    Ok(fit.curve)
3029}
3030
3031/// Build a pcurve for a represented subrange of a larger edge curve.
3032///
3033/// On an affine carrier the answer is exact and is taken as such
3034/// (`affine_pcurve_on_range`). Otherwise this samples only the represented
3035/// interval, which is essential when off-interval control points do not lie on
3036/// the target carrier — the exact lane restricts the net by knot insertion
3037/// first, so those control points are removed rather than ignored.
3038pub fn fit_pcurve_on_surface_range(
3039    surface: &NurbsSurface,
3040    curve: &NurbsCurve,
3041    edge_start: f64,
3042    edge_end: f64,
3043    forward: bool,
3044    tolerance: f64,
3045) -> Result<PcurveFit, String> {
3046    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::FIT);
3047    crate::work_counts::add(|c| c.fit_calls += 1);
3048    if let Some(exact) =
3049        affine_pcurve_on_range(surface, curve, edge_start, edge_end, forward, tolerance)?
3050    {
3051        return Ok(exact);
3052    }
3053    fit_pcurve_on_surface_range_dense(
3054        surface, curve, edge_start, edge_end, forward, tolerance, 64, 3, 513,
3055    )
3056}
3057
3058/// Refine a derived import trim against projected feet independently of normal
3059/// standoff. The existing fit budgets and common-probe acceptance rule apply;
3060/// a candidate that does not demonstrably improve the locus is discarded.
3061pub fn refine_import_projected_range(
3062    surface: &NurbsSurface,
3063    curve: &NurbsCurve,
3064    edge_start: f64,
3065    edge_end: f64,
3066    forward: bool,
3067    legacy: PcurveFit,
3068) -> PcurveFit {
3069    let _feet = FootMemoScope::precision(surface);
3070    let evaluate = |fraction: f64| {
3071        let along = if forward { fraction } else { 1.0 - fraction };
3072        curve.evaluate(edge_start + (edge_end - edge_start) * along)
3073    };
3074    let Ok(fixed) = range_use_probes(&[&legacy.curve], curve, edge_start, edge_end, forward) else { return legacy };
3075    let Ok((old, _)) = common_station_read_with_excess(surface, &evaluate, &legacy.curve, &legacy.curve, &fixed) else { return legacy };
3076    if old[0] <= PCURVE_REFINEMENT_TOLERANCE { return legacy; }
3077    let breaks = range_breaks(curve, edge_start, edge_end, forward);
3078    // A minimum parameter span protects the deviation fitter from chasing
3079    // inherited standoff. Tracking does not chase that standoff. If that span
3080    // alone blocks a verified candidate, retry once with finer construction
3081    // resolution, retaining the same budgets and final physical acceptance bar.
3082    for span_floor in [SPAN_FLOOR, SPAN_FLOOR * 0.01] {
3083        let Ok(candidate) = fit_station_pcurve_mode(surface, &evaluate, &breaks, &breaks,
3084            PCURVE_REFINEMENT_TOLERANCE * 0.1, 64, 3, 513, span_floor, true, Some(&legacy.curve), &fixed) else { return legacy };
3085        let Ok(probes) = range_use_probes(&[&legacy.curve, &candidate.curve], curve, edge_start, edge_end, forward) else { return legacy };
3086        let readings = common_station_read_with_excess(surface, &evaluate, &legacy.curve, &candidate.curve, &probes);
3087        let accepted = matches!(&readings, Ok((old, new)) if floor_admits(*old, *new));
3088        if station_fit_tracing() {
3089            eprintln!("STATION-FIT import projected challenger: span_floor={span_floor:e} old={:?} candidate={:?} common={readings:?} accepted={accepted}", legacy.report, candidate.report);
3090        }
3091        if accepted { return candidate; }
3092        if candidate.report.exit != PcurveFitExit::SpanFloor { break; }
3093    }
3094    legacy
3095}
3096
3097/// [`fit_pcurve_on_surface_range`] for the callers that only need the curve:
3098/// the fit is ACCEPTED or REFUSED on its bar (`accept_fit`), never returned
3099/// off it.
3100pub fn build_pcurve_on_surface_range(
3101    surface: &NurbsSurface,
3102    curve: &NurbsCurve,
3103    edge_start: f64,
3104    edge_end: f64,
3105    forward: bool,
3106    tolerance: f64,
3107) -> Result<NurbsCurve, String> {
3108    accept_fit(fit_pcurve_on_surface_range(
3109        surface, curve, edge_start, edge_end, forward, tolerance,
3110    )?)
3111}
3112
3113/// `BREP_DEBUG_STATION_FIT`: trace every station fit round by round, and the
3114/// stations around the worst span of a fit off its bar. Read once per process.
3115fn station_fit_tracing() -> bool {
3116    debug_flag!("BREP_DEBUG_STATION_FIT")
3117}
3118
3119/// Narrowest span, as a fraction of the parameter range, that
3120/// [`fit_pcurve_on_surface_stations`] subdivides. `refine_pcurve` floors at
3121/// 1e-3 from 25 base samples; this fitter starts from 64 and quarters, so a
3122/// floor of 1e-3 bound on its first pass and refused 67 of the 57-document
3123/// corpus's bodies (measured 2026-09-26). 1e-6 admits every halving a real
3124/// trim needs and stops the runaway that fits stations 4e-7 apart.
3125pub const SPAN_FLOOR: f64 = 1e-6;
3126
3127/// Rounds the raised pass of [`fit_pcurve_on_surface_stations`] may spend:
3128/// enough halvings for any span the sample cap can resolve.
3129const RAISED_ROUNDS: usize = 40;
3130
3131/// The refusal every station builder returns for a fit off its bar.
3132pub const PCURVE_OFF_BAR: &str = "pcurve fit refused: the trim misses its stations by";
3133
3134/// The one acceptance decision behind [`build_pcurve_on_surface_range`],
3135/// [`build_pcurve_on_surface_range_dense`] and
3136/// [`build_pcurve_on_surface_stations`]: a fit on its bar
3137/// ([`PcurveFitReport::on_bar`]) is the curve, a fit off it is a refusal that
3138/// names the residual, the bar, what was asked, how far the stations stand off
3139/// the carrier and why refinement stopped.
3140///
3141/// Until 2026-09-26 these builders returned whatever their last round built
3142/// without measuring it (the 2026-09-18 census: 4564 of 54556 imported pcurves
3143/// over the ask they were built to, 2072 of them at a station the refinement
3144/// itself had tested and given up on). Nothing here widens a band: the bar is
3145/// the caller's own ask plus what the input makes unreachable.
3146fn accept_fit(fit: PcurveFit) -> Result<NurbsCurve, String> {
3147    let report = fit.report;
3148    if report.on_bar() {
3149        return Ok(fit.curve);
3150    }
3151    Err(off_bar_message(&report))
3152}
3153
3154fn off_bar_message(report: &PcurveFitReport) -> String {
3155    format!(
3156        "{PCURVE_OFF_BAR} {:.3e} out of sample against a bar of {:.3e} (asked {:.1e}, the \
3157         stations stand {:.3e} off the carrier; {:?} at {} samples{}{})",
3158        report.residual,
3159        report.floor + report.off_surface,
3160        report.floor,
3161        report.off_surface,
3162        report.exit,
3163        report.samples,
3164        if report.raised { ", after the raise" } else { "" },
3165        if report.clamped_excursion > 0.0 {
3166            format!(
3167                "; clamped into the chart by {:.3e} in parameter, {:.3e} in 3D",
3168                report.clamped_excursion, report.clamped_distance
3169            )
3170        } else {
3171            String::new()
3172        },
3173    )
3174}
3175
3176/// The class slug of a pcurve fit refused off its bar
3177/// ([`crate::RefusalClass::NonConvergence`]): minted by
3178/// [`build_pcurve_on_surface_range_classed`] and read by
3179/// [`is_pcurve_off_bar`], so a dispatcher decides on the class, never on the
3180/// message text.
3181pub const PCURVE_OFF_BAR_WHAT: &str = "pcurve_fit_off_bar";
3182
3183/// Whether `refusal` is a pcurve fit that could not reach its bar.
3184pub fn is_pcurve_off_bar(refusal: &crate::KernelRefusal) -> bool {
3185    matches!(&refusal.class, crate::RefusalClass::NonConvergence { what } if what == PCURVE_OFF_BAR_WHAT)
3186}
3187
3188/// [`build_pcurve_on_surface_range`] with a typed refusal: a fit off its bar
3189/// is `NonConvergence { what: PCURVE_OFF_BAR_WHAT }` at `stage`, with the same
3190/// message; any other failure of the fit is `Internal` under `what`.
3191pub fn build_pcurve_on_surface_range_classed(
3192    surface: &NurbsSurface,
3193    curve: &NurbsCurve,
3194    edge_start: f64,
3195    edge_end: f64,
3196    forward: bool,
3197    tolerance: f64,
3198    stage: KernelStage,
3199    what: &'static str,
3200) -> Result<NurbsCurve, crate::KernelRefusal> {
3201    use crate::OrRefuse;
3202    let fit = fit_pcurve_on_surface_range(surface, curve, edge_start, edge_end, forward, tolerance)
3203        .or_refuse(stage, what)?;
3204    accept_fit_classed(fit, stage)
3205}
3206
3207/// [`accept_fit`] with the refusal typed: `NonConvergence { what:
3208/// PCURVE_OFF_BAR_WHAT }` at `stage`, the message unchanged.
3209pub fn accept_fit_classed(fit: PcurveFit, stage: KernelStage) -> Result<NurbsCurve, crate::KernelRefusal> {
3210    if fit.report.on_bar() {
3211        return Ok(fit.curve);
3212    }
3213    Err(crate::KernelRefusal {
3214        class: crate::RefusalClass::NonConvergence { what: PCURVE_OFF_BAR_WHAT.into() },
3215        stage,
3216        message: off_bar_message(&fit.report),
3217    })
3218}
3219
3220/// The EXACT pcurve for a coedge's subrange of `curve` on an affine carrier,
3221/// or `None` when there is no such answer and the sampled lane must run.
3222///
3223/// [`fit_pcurve_on_surface`] has always mapped a WHOLE curve's control net
3224/// exactly on an affine carrier. A coedge's trim is that same curve restricted
3225/// to `[edge_start, edge_end]` and oriented by `forward`, and both operations
3226/// are exact on a NURBS: [`NurbsCurve::split`] subdivides by knot insertion,
3227/// [`NurbsCurve::reversed`] mirrors the net, and rescaling the knots to
3228/// `[0, 1]` is affine in the edge's own parameter — which is precisely the
3229/// fraction convention the sampled lane uses, so the pcurve's correspondence
3230/// with the edge is the same one either lane produces.
3231///
3232/// Sampling where an exact answer exists leaves a real error: measured
3233/// 2026-09-17, a booleaned band rim's two planar trims sat 2.379e-4 and
3234/// 2.395e-4 off their edges, where this lane lands 1.4e-13 off.
3235///
3236/// The image is verified against the caller's own `tolerance` before it is
3237/// returned. The exact image of a curve that does NOT lie on this carrier is
3238/// its orthogonal projection, which is not that coedge's trim, so every such
3239/// case falls through to the sampled lane and keeps the refusals that lane
3240/// makes today.
3241pub fn affine_pcurve_on_range(
3242    surface: &NurbsSurface,
3243    curve: &NurbsCurve,
3244    edge_start: f64,
3245    edge_end: f64,
3246    forward: bool,
3247    tolerance: f64,
3248) -> Result<Option<PcurveFit>, String> {
3249    // Opt-out for A/B bisection of this lane against the sampled one, in the
3250    // shape of the two hatches beside it (`BREP_NO_PCURVE_REPAIR`,
3251    // `BREP_SECTION_PCURVE_MARCH`). It is what showed that the boolean's
3252    // planar residuals do NOT come through here: the same binary with this set
3253    // and unset read identically to every digit on 21_band_rim.
3254    if std::env::var("BREP_AFFINE_RANGE_PCURVE").as_deref() == Ok("0") {
3255        return Ok(None);
3256    }
3257    let Some(inversion) = AffineInversion::of(surface)? else {
3258        return Ok(None);
3259    };
3260    if !(edge_start.is_finite() && edge_end.is_finite() && edge_start < edge_end) {
3261        // The sampled lane owns this refusal; it is not this lane's to reword.
3262        return Ok(None);
3263    }
3264    let [t0, t1] = curve.domain()?;
3265    let start = edge_start.max(t0);
3266    let end = edge_end.min(t1);
3267    // A range narrower than the knot identity tolerance cannot be split onto
3268    // its own endpoints at all.
3269    if end - start <= 2.0 * KNOT_IDENTITY_TOL {
3270        return Ok(None);
3271    }
3272    let mut restricted = curve.clone();
3273    if end < t1 - KNOT_IDENTITY_TOL {
3274        restricted = restricted.split(end)?.0;
3275    }
3276    if start > t0 + KNOT_IDENTITY_TOL {
3277        restricted = restricted.split(start)?.1;
3278    }
3279    let mut pcurve = inversion.image_of(&restricted)?;
3280    if !forward {
3281        pcurve = pcurve.reversed()?;
3282    }
3283    let first = pcurve.knots[0];
3284    let last = pcurve.knots[pcurve.knots.len() - 1];
3285    if !(last - first > 0.0) {
3286        return Ok(None);
3287    }
3288    let knots = pcurve
3289        .knots
3290        .iter()
3291        .map(|knot| (knot - first) / (last - first))
3292        .collect::<Vec<_>>();
3293    let pcurve = NurbsCurve::new(pcurve.degree, knots, pcurve.control_points.clone())?;
3294
3295    // Verify against the range the CALLER asked for, not the one the
3296    // restriction produced: `split` snaps onto a nearby knot, so a snap that
3297    // moved the correspondence reads here as a deviation. Sampling at
3298    // fractions that are not the stations any lane interpolates through keeps
3299    // this a check on the whole trim rather than on its endpoints.
3300    let scale = 1.0 + curve.evaluate((start + end) / 2.0)?.length();
3301    let bar = tolerance.max(1e-11 * scale);
3302    let mut residual = 0.0_f64;
3303    for index in 0..=32 {
3304        let fraction = index as f64 / 32.0;
3305        let uv = pcurve.evaluate(fraction)?;
3306        // `evaluate` CLAMPS out-of-domain uv. A planar carrier's domain is a
3307        // bounding rectangle that a booleaned trim can leave, and an affine
3308        // patch's extension is the same plane, so read it unclamped.
3309        let on_carrier = surface.evaluate_extended(uv.x, uv.y)?;
3310        let edge_fraction = if forward { fraction } else { 1.0 - fraction };
3311        let on_edge = curve.evaluate(start + (end - start) * edge_fraction)?;
3312        residual = residual.max(on_carrier.sub(on_edge).length());
3313        if residual > bar {
3314            return Ok(None);
3315        }
3316    }
3317    let samples = pcurve.control_points.len();
3318    crate::work_counts::constructed("affine_range", 0, pcurve.control_points.len());
3319    Ok(Some(PcurveFit {
3320        curve: pcurve,
3321        report: PcurveFitReport {
3322            residual,
3323            // The floor this lane VERIFIED against: the caller's ask, or the
3324            // floating-point floor of an exact map on a part this size. An
3325            // exact image is on its bar by construction; a caller asking for
3326            // less than the map's own precision is not refused for it.
3327            floor: bar,
3328            samples,
3329            exit: PcurveFitExit::Converged,
3330            off_surface: 0.0,
3331            raised: false,
3332            clamped_excursion: 0.0,
3333            clamped_distance: 0.0,
3334        },
3335    }))
3336}
3337
3338pub fn align_collapsed_endpoints(surface: &NurbsSurface, raw: &mut [[f64; 2]]) -> Result<(), String> {
3339    let anchor = surface.control_points[0][0].point()?;
3340    let mut extent = 0.0_f64;
3341    for control in surface.control_points.iter().flatten() {
3342        extent = extent.max(control.point()?.sub(anchor).length());
3343    }
3344    // This is a geometric identity check, independent of the fitting allowance
3345    // and of world position. Positive rational weights keep the whole iso-curve
3346    // inside the convex hull of its Euclidean controls. Cap the size coupling
3347    // at the linear tolerance so a large patch cannot erase a thin finite row.
3348    let pole_band = (1e-10 * (1.0 + extent)).min(LINEAR_TOLERANCE);
3349    for (endpoint, neighbor) in [(0, 1), (raw.len() - 1, raw.len() - 2)] {
3350        let point = surface.evaluate(raw[endpoint][0], raw[endpoint][1])?;
3351        for axis in 0..2 {
3352            let mut candidate = raw[endpoint];
3353            candidate[axis] = raw[neighbor][axis];
3354            if candidate == raw[endpoint]
3355                || surface
3356                    .evaluate(candidate[0], candidate[1])?
3357                    .sub(point)
3358                    .length()
3359                    > pole_band
3360            {
3361                continue;
3362            }
3363            let row = if axis == 0 {
3364                surface.iso_curve_v(raw[endpoint][1])?
3365            } else {
3366                surface.iso_curve_u(raw[endpoint][0])?
3367            };
3368            let mut collapsed = true;
3369            for control in &row.control_points {
3370                if control.point()?.sub(point).length() > pole_band {
3371                    collapsed = false;
3372                    break;
3373                }
3374            }
3375            if collapsed {
3376                raw[endpoint] = candidate;
3377            }
3378        }
3379    }
3380    Ok(())
3381}
3382
3383/// Re-seat any raw inversion sample that BRANCH-JUMPED — snapped to a distant
3384/// fold of a self-overlapping general carrier — back onto the branch traced by
3385/// its neighbours.
3386///
3387/// Each entry in `raw` is an INDEPENDENT global closest-point inversion of the
3388/// corresponding 3D edge sample. Every one is geometrically valid (on the
3389/// surface, at the edge), but they need not be CONTIGUOUS: where a rational
3390/// B-spline surface folds back over the small trimmed patch it carries, the
3391/// momentarily-closest fold flips from one sample to the next, so the raw
3392/// polygon zig-zags across the whole domain and self-crosses — and the region
3393/// its interpolant bounds no longer covers the true face (its surface flux can
3394/// exceed its own area). We anchor on the LONGEST run of mutually-continuous
3395/// samples — the fold the trimmed patch actually lies on, since a small face
3396/// lives on ONE fold and the jumped samples are the minority the global search
3397/// snapped elsewhere — then walk outward in both directions, re-seeding Newton
3398/// from the last good parameters and adopting the continuous footpoint whenever
3399/// it is geometrically as valid as the global one. Anchoring on consensus (not
3400/// blindly on sample 0, which can itself be an outlier that would drag the
3401/// whole edge onto the wrong branch and tear the loop open at its endpoint)
3402/// leaves continuous nonsingular fits unchanged. Certified collapsed endpoint
3403/// rows first adopt their neighbour's branch; a bad seed in the subsequent
3404/// jump repair cannot make a sample worse than the global search already had it.
3405fn repair_branch_jumps(
3406    surface: &NurbsSurface,
3407    edge_points: &[Vec3],
3408    raw: &mut [[f64; 2]],
3409    tolerance: f64,
3410) -> Result<(), String> {
3411    if raw.len() < 3 {
3412        return Ok(());
3413    }
3414    // Affine carriers invert linearly and exactly — no folds, nothing to chase.
3415    // Checked first so the common planar/affine face never touches the env.
3416    if surface.is_affine()? {
3417        return Ok(());
3418    }
3419    // Opt-out for A/B bisection of a STEP-import regression against this repair.
3420    if std::env::var("BREP_NO_PCURVE_REPAIR").is_ok() {
3421        return Ok(());
3422    }
3423    // A pole has no unique coordinate along its collapsed row. Continuing the
3424    // adjacent sample's branch is safe only when the ENTIRE row is collapsed;
3425    // coincident points across an ordinary seam or fold are not enough.
3426    align_collapsed_endpoints(surface, raw)?;
3427    let ([u0, u1], [v0, v1]) = surface_domains(surface)?;
3428    let u_span = (u1 - u0).abs().max(EPSILON);
3429    let v_span = (v1 - v0).abs().max(EPSILON);
3430    let (closed_u, closed_v) = surface_closedness(surface)?;
3431    // Normalised, seam-aware step between two parameter samples. Wrapping the
3432    // closed directions keeps a legitimate seam crossing SMALL, so the seam /
3433    // periodic-unwrap machinery elsewhere is never disturbed by this repair.
3434    let norm_step = |a: [f64; 2], b: [f64; 2]| -> f64 {
3435        let mut du = a[0] - b[0];
3436        if closed_u {
3437            while du > 0.5 * u_span {
3438                du -= u_span;
3439            }
3440            while du < -0.5 * u_span {
3441                du += u_span;
3442            }
3443        }
3444        let mut dv = a[1] - b[1];
3445        if closed_v {
3446            while dv > 0.5 * v_span {
3447                dv -= v_span;
3448            }
3449            while dv < -0.5 * v_span {
3450                dv += v_span;
3451            }
3452        }
3453        ((du / u_span).powi(2) + (dv / v_span).powi(2)).sqrt()
3454    };
3455    // A jump crosses a large fraction of the WHOLE domain — orders above the
3456    // per-sample motion of any real (even domain-spanning) edge, which advances
3457    // ~1/N of its traversal between consecutive stations.
3458    const JUMP_THRESHOLD: f64 = 0.2;
3459    let count = raw.len();
3460
3461    // Locate the longest maximal run of consecutive continuous samples — the
3462    // branch to anchor on. If nothing jumps, this spans [0, count-1] and both
3463    // re-seat passes below are empty, leaving `raw` untouched.
3464    let (mut best_start, mut best_len, mut run_start) = (0usize, 1usize, 0usize);
3465    for index in 1..count {
3466        if norm_step(raw[index], raw[index - 1]) > JUMP_THRESHOLD {
3467            if index - run_start > best_len {
3468                best_len = index - run_start;
3469                best_start = run_start;
3470            }
3471            run_start = index;
3472        }
3473    }
3474    if count - run_start > best_len {
3475        best_len = count - run_start;
3476        best_start = run_start;
3477    }
3478    let (spine_lo, spine_hi) = (best_start, best_start + best_len - 1);
3479
3480    // Adopt the continuous footpoint only when it (a) still sits on the surface
3481    // — as tight as the fit band or the global answer — and (b) genuinely
3482    // closes the jump rather than trading it for another. Returns the parameter
3483    // to carry forward as the next seed (the repaired one, or the untouched
3484    // global when no repair applies).
3485    let reseat = |edge_point: Vec3,
3486                  previous: [f64; 2],
3487                  global: [f64; 2]|
3488     -> Result<[f64; 2], String> {
3489        let global_step = norm_step(global, previous);
3490        if global_step <= JUMP_THRESHOLD {
3491            return Ok(global);
3492        }
3493        let seeded =
3494            project_point_to_surface_seeded(surface, edge_point, previous[0], previous[1])?;
3495        let candidate = [seeded.u, seeded.v];
3496        let global_residual = surface
3497            .evaluate(global[0], global[1])?
3498            .sub(edge_point)
3499            .length();
3500        let on_surface = seeded.distance <= 4.0 * global_residual + tolerance.max(1e-12);
3501        if on_surface && norm_step(candidate, previous) < 0.5 * global_step {
3502            if std::env::var("BREP_DEBUG_PCURVE").is_ok() {
3503                eprintln!(
3504                    "pcurve repair: jump {global_step:.4} ({global:?}) -> {:.4} ({candidate:?}) res {:.2e}->{:.2e}",
3505                    norm_step(candidate, previous),
3506                    global_residual,
3507                    seeded.distance
3508                );
3509            }
3510            Ok(candidate)
3511        } else {
3512            Ok(global)
3513        }
3514    };
3515
3516    // Walk forward off the spine's high end, then backward off its low end,
3517    // chaining each repaired sample as the next seed so continuity propagates.
3518    //
3519    // Apart from the certified collapsed rows above, the two ENDPOINT samples
3520    // (fraction 0 and 1) are NEVER moved: they are the
3521    // edge's shared loop vertices. The global inversion is deterministic, so the
3522    // two coedges meeting at a vertex land it at the SAME parameters even when
3523    // that vertex sits on a fold reachable from two branches — moving one side
3524    // to a different branch tears the loop open there (`synthesize_pole_edge`
3525    // then rejects the non-collapsed gap). A vertex's genuine fold transition
3526    // (an edge whose interior rides u≈0.08 but whose endpoint must meet its
3527    // neighbour at u≈0.95) is exactly this case and must be preserved, not
3528    // "continuity-repaired" back onto the interior branch.
3529    let mut previous = raw[spine_hi];
3530    for index in (spine_hi + 1)..count.saturating_sub(1) {
3531        raw[index] = reseat(edge_points[index], previous, raw[index])?;
3532        previous = raw[index];
3533    }
3534    let mut previous = raw[spine_lo];
3535    for index in (1..spine_lo).rev() {
3536        raw[index] = reseat(edge_points[index], previous, raw[index])?;
3537        previous = raw[index];
3538    }
3539    Ok(())
3540}
3541
3542/// Range fitter with explicit sampling knobs, reporting what the fit achieved.
3543/// [`fit_pcurve_on_surface_range`] keeps the long-standing (base 64, 3
3544/// refinement rounds, 513 cap) budget; a fit that binds at that cap with the
3545/// bar unmet grows once to `PCURVE_RAISED_SAMPLES`
3546/// ([`fit_pcurve_on_surface_stations`]).
3547///
3548/// NOTE (2026-09-03): this comment used to say "STEP import retries failed fits
3549/// with a denser budget". No caller passes these knobs any more — that retry
3550/// was removed and the sentence outlived it. The knobs are kept because they
3551/// are the honest way to ASK whether a fit had headroom left, which is what
3552/// `examples/pcurve_residual_probe.rs` uses them for: on every ABC corpus
3553/// coedge that failed `validate`'s pcurve check, budgets up to (512, 8, 8193)
3554/// with a 1000x tighter target reproduced the coarse fit's deviation to six
3555/// decimals, because that deviation is the edge-vs-surface closest-point
3556/// residual and a curve ON the surface cannot beat it.
3557#[allow(clippy::too_many_arguments)]
3558pub fn fit_pcurve_on_surface_range_dense(
3559    surface: &NurbsSurface,
3560    curve: &NurbsCurve,
3561    edge_start: f64,
3562    edge_end: f64,
3563    forward: bool,
3564    tolerance: f64,
3565    base_samples: usize,
3566    refinement_rounds: usize,
3567    parameter_cap: usize,
3568) -> Result<PcurveFit, String> {
3569    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::FIT);
3570    crate::work_counts::add(|c| c.fit_calls += 1);
3571    if !(edge_start.is_finite() && edge_end.is_finite() && edge_start < edge_end) {
3572        return Err("build_pcurve_on_surface_range: invalid edge interval".into());
3573    }
3574    let evaluate_edge = |fraction: f64| {
3575        let edge_fraction = if forward { fraction } else { 1.0 - fraction };
3576        curve.evaluate(edge_start + (edge_end - edge_start) * edge_fraction)
3577    };
3578    let breaks = range_breaks(curve, edge_start, edge_end, forward);
3579    let ask = tolerance.max(PCURVE_REFINEMENT_TOLERANCE);
3580    let fit = fit_station_pcurve(
3581        surface,
3582        &evaluate_edge,
3583        &breaks,
3584        &breaks,
3585        ask,
3586        base_samples,
3587        refinement_rounds,
3588        parameter_cap,
3589        SPAN_FLOOR,
3590    )?;
3591    end_span_challenger(surface, curve, &evaluate_edge, edge_start, edge_end, forward, &breaks, ask, base_samples, refinement_rounds, parameter_cap, fit)
3592}
3593
3594/// The edge curve's OWN distinct interior knots inside `[edge_start,
3595/// edge_end]`, mapped through the trim's range and sense to coedge
3596/// fractions, that fall inside `pcurve`'s FIRST or LAST span (between the
3597/// domain end and its nearest interior knot), sorted.
3598pub fn native_end_knot_fractions(curve: &NurbsCurve, edge_start: f64, edge_end: f64, forward: bool, pcurve: &NurbsCurve) -> Result<Vec<f64>, String> {
3599    let [q0, q1] = pcurve.domain()?;
3600    let mut interior: Vec<f64> = pcurve.knots.iter().copied().filter(|k| *k > q0 && *k < q1).collect();
3601    interior.dedup();
3602    let (Some(&first), Some(&last)) = (interior.first(), interior.last()) else { return Ok(Vec::new()) };
3603    let (low, high) = (edge_start.min(edge_end), edge_start.max(edge_end));
3604    let span = edge_end - edge_start;
3605    let mut fractions: Vec<f64> = curve
3606        .knots
3607        .iter()
3608        .copied()
3609        .filter(|k| *k > low && *k < high)
3610        .map(|k| {
3611            let along = (k - edge_start) / span;
3612            if forward { along } else { 1.0 - along }
3613        })
3614        .filter(|f| f.is_finite() && ((*f > q0 && *f < first) || (*f > last && *f < q1)))
3615        .collect();
3616    fractions.sort_by(f64::total_cmp);
3617    fractions.dedup();
3618    Ok(fractions)
3619}
3620
3621/// The admission rule for a foot read against an edge point: finite distance,
3622/// finite point, finite (u, v) inside the native domain. Shared by
3623/// [`common_station_read`] and the station fitter's tracking mode.
3624pub fn foot_admitted(foot: &crate::SurfaceProjection, [u0, u1]: [f64; 2], [v0, v1]: [f64; 2]) -> bool {
3625    let finite = |p: Vec3| p.x.is_finite() && p.y.is_finite() && p.z.is_finite();
3626    foot.distance.is_finite() && finite(foot.point) && foot.u.is_finite() && foot.v.is_finite() && (u0..=u1).contains(&foot.u) && (v0..=v1).contains(&foot.v)
3627}
3628
3629/// The tracking mode's verification probes: the current pcurve's native probes
3630/// ([`native_probe_fractions`]: endpoints, quarters and 16 interior points of
3631/// each knot span), its EXACT knots (the final common read includes them, and
3632/// the native probes do not), and the caller's fixed fractions; finite, in
3633/// [0, 1], sorted, deduplicated.
3634pub fn verification_fractions(pcurve: &NurbsCurve, verify: &[f64]) -> Result<Vec<f64>, String> {
3635    let mut fractions = native_probe_fractions(&[pcurve])?;
3636    fractions.extend(pcurve.knots.iter().copied());
3637    fractions.extend(verify.iter().copied());
3638    fractions.retain(|f| f.is_finite() && (0.0..=1.0).contains(f));
3639    fractions.sort_by(f64::total_cmp);
3640    fractions.dedup();
3641    Ok(fractions)
3642}
3643
3644/// The off-carrier candidate admission, at the same probes and shared feet
3645/// (`[tracking, deviation, excess]` per curve, [`common_station_read_with_excess`]):
3646/// every reading finite, the candidate's tracking strictly lower, and EITHER
3647/// its maximum deviation no worse than the legacy's (the original rule) OR the
3648/// candidate meeting the ORIGINAL floors outright, tracking and excess both
3649/// within `PCURVE_REFINEMENT_TOLERANCE` (1e-7).
3650///
3651/// Why the second branch: for fits whose images follow the shared admitted
3652/// feet, the maximum deviation can be dominated by the edge's standoff.
3653/// Their measured maxima can then differ by rounding while tracking improves.
3654/// This does not assert that the admitted foot is a certified global nearest
3655/// point or that an arbitrary pcurve has the same maximum deviation.
3656/// next5 fixture 25 (BREP_DEBUG_STATION_FIT): every tracking candidate reached
3657/// the floor (9.52e-8 .. 9.94e-8 tracking) and was declined on a deviation
3658/// 1.2e-14 .. 6.7e-13 above the legacy's at 2.1e-5 .. 9.0e-4 standoffs, while
3659/// the legacy kept 5.9e-7 .. 8.5e-5 tracking. A candidate within the original
3660/// floors on both readings is what those controls require; it is not a
3661/// standoff allowance and no bar moves.
3662pub fn floor_admits(old: [f64; 3], new: [f64; 3]) -> bool {
3663    let floor = PCURVE_REFINEMENT_TOLERANCE;
3664    old.iter().chain(new.iter()).all(|v| v.is_finite())
3665        && new[0] < old[0]
3666        && (new[1] <= old[1] || (new[0] <= floor && new[2] <= floor))
3667}
3668
3669/// The common reader's foot: the NEAREST admitted ([`foot_admitted`]) of the
3670/// global projection, the projection seeded at the reference (legacy) uv and
3671/// the one seeded at the candidate (image) uv, in THAT order, so that between
3672/// admitted feet at equal distance the first in this order is taken
3673/// (`min_by` keeps the first minimum). [`common_station_read`] and the station
3674/// fitter's tracking mode both take their foot here, so an equal-distance tie
3675/// resolves to the same foot in both.
3676pub fn common_foot(
3677    global: Option<crate::SurfaceProjection>,
3678    reference: Option<crate::SurfaceProjection>,
3679    candidate: Option<crate::SurfaceProjection>,
3680    domain_u: [f64; 2],
3681    domain_v: [f64; 2],
3682) -> Option<crate::SurfaceProjection> {
3683    [global, reference, candidate]
3684        .into_iter()
3685        .flatten()
3686        .filter(|f| foot_admitted(f, domain_u, domain_v))
3687        .min_by(|a, b| a.distance.total_cmp(&b.distance))
3688}
3689
3690/// The probes a RANGE trim is read at by the common reader: `curves`'
3691/// native spans (endpoints, quarters and 16 interior points of each knot
3692/// span) and exact knots, plus the edge curve's own knots CLIPPED to
3693/// `[t0, t1]` (with the range ends) and the same 19 points on every clipped
3694/// span, mapped through the coedge's sense to fractions; finite, in [0, 1],
3695/// sorted, deduplicated.
3696pub fn range_use_probes(curves: &[&NurbsCurve], edge_curve: &NurbsCurve, t0: f64, t1: f64, forward: bool) -> Result<Vec<f64>, String> {
3697    let mut probes = native_probe_fractions(curves)?;
3698    for curve in curves {
3699        probes.extend(curve.knots.iter().copied());
3700    }
3701    let span = t1 - t0;
3702    if span.is_finite() && span != 0.0 {
3703        let (low, high) = (t0.min(t1), t0.max(t1));
3704        let mut knots: Vec<f64> = edge_curve.knots.iter().copied().filter(|k| *k >= low && *k <= high).collect();
3705        knots.push(low);
3706        knots.push(high);
3707        knots.sort_by(f64::total_cmp);
3708        knots.dedup();
3709        let locals: Vec<f64> = [0.25, 0.5, 0.75]
3710            .into_iter()
3711            .chain((1..=TRACKING_ACCEPTANCE_POINTS).map(|index| index as f64 / (TRACKING_ACCEPTANCE_POINTS + 1) as f64))
3712            .collect();
3713        let mut ts = knots.clone();
3714        for pair in knots.windows(2).filter(|w| w[1] > w[0]) {
3715            for &local in &locals {
3716                ts.push(pair[0] + (pair[1] - pair[0]) * local);
3717            }
3718        }
3719        for t in ts {
3720            let along = (t - t0) / span;
3721            probes.push(if forward { along } else { 1.0 - along });
3722        }
3723    }
3724    probes.retain(|f| f.is_finite() && (0.0..=1.0).contains(f));
3725    probes.sort_by(f64::total_cmp);
3726    probes.dedup();
3727    Ok(probes)
3728}
3729
3730/// [`common_station_read`] for two RANGE trims of one coedge (`old`, `new`,
3731/// both on the coedge fraction domain [0, 1]) against the edge curve over
3732/// `[t0, t1]` in the coedge's sense, at [`range_use_probes`] of both: the same
3733/// probes and one shared admitted foot per probe, finite or an error. A trim
3734/// not on [0, 1] is an error.
3735// Unused by the import lane since the tracking trigger and keep were withdrawn
3736// for this merge; kept, with its controls, for their re-proposal.
3737#[cfg_attr(not(test), allow(dead_code))]
3738pub fn range_common_read(
3739    surface: &NurbsSurface,
3740    edge_curve: &NurbsCurve,
3741    t0: f64,
3742    t1: f64,
3743    forward: bool,
3744    old: &NurbsCurve,
3745    new: &NurbsCurve,
3746) -> Result<((f64, f64), (f64, f64)), String> {
3747    let (o, n) = range_common_read_with_excess(surface, edge_curve, t0, t1, forward, old, new)?;
3748    Ok(((o[0], o[1]), (n[0], n[1])))
3749}
3750
3751/// [`range_common_read`] with each trim's maximum pointwise excess over the
3752/// shared admitted foot's own distance: `[tracking, deviation, excess]` per
3753/// trim ([`common_station_read_with_excess`]).
3754// Unused by the import lane since the tracking trigger and keep were withdrawn
3755// for this merge; kept, with its controls, for their re-proposal.
3756#[cfg_attr(not(test), allow(dead_code))]
3757pub fn range_common_read_with_excess(
3758    surface: &NurbsSurface,
3759    edge_curve: &NurbsCurve,
3760    t0: f64,
3761    t1: f64,
3762    forward: bool,
3763    old: &NurbsCurve,
3764    new: &NurbsCurve,
3765) -> Result<([f64; 3], [f64; 3]), String> {
3766    for curve in [old, new] {
3767        if !matches!(curve.domain(), Ok([a, b]) if a == 0.0 && b == 1.0) {
3768            return Err("range common read: a trim not on [0, 1]".into());
3769        }
3770    }
3771    let probes = range_use_probes(&[old, new], edge_curve, t0, t1, forward)?;
3772    let evaluate = |fraction: f64| -> Result<Vec3, String> {
3773        let along = if forward { fraction } else { 1.0 - fraction };
3774        edge_curve.evaluate(t0 + (t1 - t0) * along)
3775    };
3776    common_station_read_with_excess(surface, &evaluate, old, new, &probes)
3777}
3778
3779/// The legacy and candidate pcurves read against the edge at the SAME probes
3780/// and against the SAME foot per probe: at each fraction, the edge point's
3781/// foot is the NEAREST admitted one among the global projection and the
3782/// projections seeded at the legacy and the candidate image's (u, v). A foot
3783/// is admitted with a finite distance and point and a finite (u, v) inside the
3784/// native domain. Both images are then measured against that one shared foot
3785/// (TRACKING) and against the edge point (same-parameter DEVIATION). The
3786/// shared foot is the nearest of these three, not a certified global nearest.
3787/// Any non-finite image, point or distance, or a probe with no admitted foot,
3788/// is an error (the caller keeps the legacy fit). Returns
3789/// ((legacy tracking, legacy deviation), (candidate tracking, candidate
3790/// deviation)), maxima over the probes.
3791pub fn common_station_read(
3792    surface: &NurbsSurface,
3793    evaluate_edge: &dyn Fn(f64) -> Result<Vec3, String>,
3794    legacy: &NurbsCurve,
3795    candidate: &NurbsCurve,
3796    probes: &[f64],
3797) -> Result<((f64, f64), (f64, f64)), String> {
3798    let (old, new) = common_station_read_with_excess(surface, evaluate_edge, legacy, candidate, probes)?;
3799    Ok(((old[0], old[1]), (new[0], new[1])))
3800}
3801
3802/// [`common_station_read`] that also returns, per curve, the maximum
3803/// pointwise EXCESS: the same-parameter deviation minus the shared admitted
3804/// foot's own distance at that probe (the part over the edge's standoff
3805/// there, which the every-use controls bar at the original 1e-7). Returns
3806/// `[tracking, deviation, excess]` for the legacy and the candidate.
3807/// `BREP_TRACKING_CLOSED_FOOT` (default on, `=0` restores the seeded Newton
3808/// feet): [`common_station_read_with_excess`] reads a curve against itself on
3809/// an analytic carrier at the closed-form foot when that foot is admitted.
3810fn tracking_closed_foot_enabled() -> bool {
3811    let enabled = crate::switch!("BREP_TRACKING_CLOSED_FOOT", true);
3812    enabled
3813}
3814
3815
3816pub fn common_station_read_with_excess(
3817    surface: &NurbsSurface,
3818    evaluate_edge: &dyn Fn(f64) -> Result<Vec3, String>,
3819    legacy: &NurbsCurve,
3820    candidate: &NurbsCurve,
3821    probes: &[f64],
3822) -> Result<([f64; 3], [f64; 3]), String> {
3823    let (domain_u, domain_v) = surface_domains(surface)?;
3824    let finite = |p: Vec3| p.x.is_finite() && p.y.is_finite() && p.z.is_finite();
3825    // [tracking, deviation, excess] per curve; the excess (deviation minus
3826    // the shared foot's distance, per probe) starts at -inf, so a read with no
3827    // probe is not finite and admits nothing.
3828    let mut read = ([0.0_f64, 0.0, f64::NEG_INFINITY], [0.0_f64, 0.0, f64::NEG_INFINITY]);
3829    // Reading ONE curve against itself (`legacy` and `candidate` the same
3830    // object, as a tracking read and a trigger's read are): the candidate's
3831    // parameter, image and seeded projection are the reference's on identical
3832    // inputs, so each is computed once (same results, same tie order).
3833    let same = std::ptr::eq(legacy, candidate);
3834    // On an affine-sphere carrier with no analytic kind, the global projector
3835    // and the seeded one both return the ellipsoid's closed form whenever it
3836    // answers (`projection::project_point_to_surface` and
3837    // `project_point_to_surface_seeded`), whatever the seed: one closed form
3838    // stands for all three feet (2026-11-03: two thirds of the
3839    // elephant's tracking projections).
3840    let ellipsoid = if same && surface.analytic().is_none() { surface.affine_sphere() } else { None };
3841    // On a recognised analytic carrier the global projector IS the closed
3842    // form (`projection::project_point_to_surface`), the exact nearest point,
3843    // and the seeded Newton converges to that same foot (the carriers' feet are
3844    // unique off their focal sets, where the closed form declines), so it can
3845    // only win `common_foot`'s minimum by rounding. A self-read
3846    // therefore takes the closed form for all three feet when it is admitted, and
3847    // otherwise reads as before. brep-bench boolean/cross-drilled-cube: every
3848    // cylinder-cylinder crossing an operand hands on is read once, 11 000
3849    // probes of a 480-control pcurve, a seeded Newton each (5.2 s of 20 s).
3850    // `BREP_TRACKING_CLOSED_FOOT` (default on; `=0` restores the Newton feet).
3851    // Curved carriers only: a plane's Newton foot is cheap, and on a weighted
3852    // plane far from the origin its two evaluation paths part by more than the
3853    // floor (`step_import::builder::loops::derived_floor_tracking_tests`).
3854    // On a curved carrier a self-read is no longer the two-object read of the
3855    // same trim to the bit; the two differ by the Newton feet's rounding.
3856    let analytic = if same && ellipsoid.is_none() && tracking_closed_foot_enabled() {
3857        surface.analytic().filter(|analytic| !matches!(analytic, crate::AnalyticSurface::Plane { .. }))
3858    } else {
3859        None
3860    };
3861    for &fraction in probes {
3862        let point = evaluate_edge(fraction)?;
3863        let old_uv = legacy.evaluate(fraction)?;
3864        let new_uv = if same { old_uv } else { candidate.evaluate(fraction)? };
3865        let old_image = surface.evaluate_extended(old_uv.x, old_uv.y)?;
3866        let new_image = if same { old_image } else { surface.evaluate_extended(new_uv.x, new_uv.y)? };
3867        if !(finite(point) && finite(old_image) && finite(new_image)) {
3868            return Err(format!("common station read: non-finite point at fraction {fraction}"));
3869        }
3870        let closed_form = ellipsoid.and_then(|ellipsoid| ellipsoid.project(surface, point)).or_else(|| {
3871            analytic
3872                .and_then(|analytic| analytic.project(surface, point))
3873                .filter(|foot| foot_admitted(foot, domain_u, domain_v))
3874        });
3875        let foot = if let Some(foot) = closed_form {
3876            common_foot(Some(foot), Some(foot), Some(foot), domain_u, domain_v)
3877        } else {
3878            let reference_foot = memo_seeded_foot(surface, point, old_uv.x, old_uv.y);
3879            let candidate_foot = if same {
3880                reference_foot
3881            } else {
3882                memo_seeded_foot(surface, point, new_uv.x, new_uv.y)
3883            };
3884            common_foot(
3885                memo_global_foot(surface, point),
3886                reference_foot,
3887                candidate_foot,
3888                domain_u,
3889                domain_v,
3890            )
3891        }
3892        .ok_or_else(|| format!("common station read: no admitted foot at fraction {fraction}"))?;
3893        let values = [
3894            old_image.sub(foot.point).length(),
3895            old_image.sub(point).length(),
3896            new_image.sub(foot.point).length(),
3897            new_image.sub(point).length(),
3898        ];
3899        if values.iter().any(|v| !v.is_finite()) {
3900            return Err(format!("common station read: non-finite distance at fraction {fraction}"));
3901        }
3902        if !foot.distance.is_finite() {
3903            return Err(format!("common station read: non-finite foot distance at fraction {fraction}"));
3904        }
3905        read.0[0] = read.0[0].max(values[0]);
3906        read.0[1] = read.0[1].max(values[1]);
3907        read.0[2] = read.0[2].max(values[1] - foot.distance);
3908        read.1[0] = read.1[0].max(values[2]);
3909        read.1[1] = read.1[1].max(values[3]);
3910        read.1[2] = read.1[2].max(values[3] - foot.distance);
3911    }
3912    Ok(read)
3913}
3914
3915/// The interior probe fractions of the edge curve's own FIRST and LAST native
3916/// knot spans inside `[edge_start, edge_end]` (quarter points and 16 interior
3917/// points of each), mapped through the trim's range and sense to coedge
3918/// fractions in [0, 1].
3919pub fn edge_end_span_fractions(curve: &NurbsCurve, edge_start: f64, edge_end: f64, forward: bool) -> Vec<f64> {
3920    let (low, high) = (edge_start.min(edge_end), edge_start.max(edge_end));
3921    let mut knots: Vec<f64> = curve.knots.iter().copied().filter(|k| *k > low && *k < high).collect();
3922    knots.dedup();
3923    let spans = match (knots.first(), knots.last()) {
3924        (Some(&first), Some(&last)) => vec![(low, first), (last, high)],
3925        _ => vec![(low, high)],
3926    };
3927    let span = edge_end - edge_start;
3928    let mut out = Vec::new();
3929    for (a, b) in spans {
3930        if !(b > a) {
3931            continue;
3932        }
3933        for local in [0.25, 0.5, 0.75].into_iter().chain((1..=TRACKING_ACCEPTANCE_POINTS).map(|index| index as f64 / (TRACKING_ACCEPTANCE_POINTS + 1) as f64)) {
3934            let along = (a + (b - a) * local - edge_start) / span;
3935            let fraction = if forward { along } else { 1.0 - along };
3936            if fraction.is_finite() && (0.0..=1.0).contains(&fraction) {
3937                out.push(fraction);
3938            }
3939        }
3940    }
3941    out.sort_by(f64::total_cmp);
3942    out.dedup();
3943    out
3944}
3945
3946/// At most this many of the legacy pcurve's worst spans are seeded.
3947const WORST_SPANS: usize = 4;
3948/// Interior stations seeded in each of them.
3949const WORST_SPAN_SEEDS: usize = 7;
3950
3951/// The seed fractions of [`end_span_challenger`]'s worst-span source: the
3952/// legacy pcurve's own spans (between its distinct knots) whose same-parameter
3953/// deviation, read at the quarter points and 16 interior points, and at any of
3954/// `extra_probes` (the edge's own end-span interior points mapped to coedge
3955/// fractions) that fall inside the span, exceeds
3956/// `bar`, worst first, at most [`WORST_SPANS`] of them, each seeded with
3957/// [`WORST_SPAN_SEEDS`] evenly spaced interior fractions. Fails closed on any
3958/// non-finite reading.
3959pub fn legacy_worst_span_seeds(
3960    evaluate_edge: &dyn Fn(f64) -> Result<Vec3, String>,
3961    surface: &NurbsSurface,
3962    pcurve: &NurbsCurve,
3963    bar: f64,
3964    extra_probes: &[f64],
3965) -> Result<Vec<f64>, String> {
3966    let [q0, q1] = pcurve.domain()?;
3967    let mut knots: Vec<f64> = pcurve.knots.iter().copied().filter(|k| *k >= q0 && *k <= q1).collect();
3968    knots.dedup();
3969    let locals: Vec<f64> = [0.25, 0.5, 0.75]
3970        .into_iter()
3971        .chain((1..=TRACKING_ACCEPTANCE_POINTS).map(|index| index as f64 / (TRACKING_ACCEPTANCE_POINTS + 1) as f64))
3972        .collect();
3973    let mut over: Vec<(f64, f64, f64)> = Vec::new();
3974    for span in knots.windows(2).filter(|w| w[1] > w[0]) {
3975        let mut worst = 0.0_f64;
3976        let inside = extra_probes.iter().copied().filter(|f| *f > span[0] && *f < span[1]);
3977        for fraction in locals.iter().map(|local| span[0] + (span[1] - span[0]) * local).chain(inside) {
3978            let uv = pcurve.evaluate(fraction)?;
3979            let deviation = surface.evaluate_extended(uv.x, uv.y)?.sub(evaluate_edge(fraction)?).length();
3980            if !deviation.is_finite() {
3981                return Err(format!("worst-span read: non-finite deviation at fraction {fraction}"));
3982            }
3983            worst = worst.max(deviation);
3984        }
3985        if worst > bar {
3986            over.push((worst, span[0], span[1]));
3987        }
3988    }
3989    over.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.total_cmp(&b.1)));
3990    over.truncate(WORST_SPANS);
3991    Ok(over
3992        .into_iter()
3993        .flat_map(|(_, lo, hi)| (1..=WORST_SPAN_SEEDS).map(move |index| lo + (hi - lo) * index as f64 / (WORST_SPAN_SEEDS + 1) as f64))
3994        .collect())
3995}
3996
3997/// Why the range lane's [`end_span_challenger`] runs.
3998#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3999pub enum ChallengerTrigger {
4000    /// The legacy residual misses `ask + standoff` (the original trigger).
4001    Deviation,
4002    /// The legacy residual is within `ask + standoff`, the edge stands off its
4003    /// carrier by more than the ask, and the legacy fit's COMMON tracking
4004    /// (`common_station_read` at the fixed probes) misses the ask.
4005    Tracking,
4006}
4007
4008/// The challenger's trigger. The original rule reads the same-parameter
4009/// DEVIATION against `ask + standoff`; over a standoff `g` a tangential slip
4010/// `d` adds only about d²/(2g) to it, so a slip up to sqrt(ask² + 2·ask·g)
4011/// never triggers (about 1.3e-5 at g = 9e-4, the fixture-25 inherited edges).
4012/// When the deviation rule does not fire and the edge stands off its carrier
4013/// by more than the ask (the same gate `refine_pcurve` takes its
4014/// standoff-tracking lane on), the legacy fit's common tracking is read
4015/// (`tracking`, called only then): over the ask, the challenger runs on
4016/// tracking. An unread tracking (None or non-finite) never triggers.
4017pub fn challenger_trigger(residual: f64, off_surface: f64, ask: f64, tracking: impl FnOnce() -> Option<f64>) -> Option<ChallengerTrigger> {
4018    if residual > ask + off_surface {
4019        return Some(ChallengerTrigger::Deviation);
4020    }
4021    if !(off_surface > ask) {
4022        return None;
4023    }
4024    match tracking() {
4025        Some(value) if value.is_finite() && value > ask => Some(ChallengerTrigger::Tracking),
4026        _ => None,
4027    }
4028}
4029
4030/// The END-SPAN CHALLENGER of the range lane (2026-10-05, the four original
4031/// fitter rows of `abc_00000011/12` edges 7 and 243). Before this, their worst
4032/// excess (4.58e-6 and 5.14e-6) sat in the installed pcurve's LAST span, at the
4033/// edge's start, where the edge curve's own first knot span is only 4.5e-6
4034/// (e7) and 1.2e-4 (e243) wide while the fitter's end span was 1.4e-4 wide at
4035/// its cap. It runs when [`challenger_trigger`] fires: the legacy fit misses
4036/// its bar (residual over the ask plus its standoff), or, on an edge standing
4037/// off its carrier by more than the ask, its common tracking misses the ask.
4038/// It refits with the edge's own interior knots that
4039/// fall inside the legacy pcurve's first or last span as additional stations
4040/// (not joins; corners stay the legacy ones), through the same fitter with the
4041/// unchanged ask, SPAN_FLOOR, cap and rounds. The candidate replaces the legacy
4042/// fit only when both, read at COMMON probes (both pcurves' own knot spans,
4043/// knots and endpoints, plus the edge's own knots and knot spans mapped to
4044/// fractions) against one SHARED foot per probe ([`common_station_read`]),
4045/// read finite, the candidate's tracking is strictly lower and its
4046/// same-parameter deviation no worse. Otherwise, or on any error or unreadable read, the legacy fit
4047/// stands exactly.
4048#[allow(clippy::too_many_arguments)]
4049pub fn end_span_challenger(
4050    surface: &NurbsSurface,
4051    curve: &NurbsCurve,
4052    evaluate_edge: &dyn Fn(f64) -> Result<Vec3, String>,
4053    edge_start: f64,
4054    edge_end: f64,
4055    forward: bool,
4056    breaks: &[f64],
4057    ask: f64,
4058    base_samples: usize,
4059    refinement_rounds: usize,
4060    parameter_cap: usize,
4061    legacy: PcurveFit,
4062) -> Result<PcurveFit, String> {
4063    // On the bar by deviation: nothing is read (the original zero-work
4064    // path). The TRACKING trigger (an off-carrier edge on its
4065    // deviation bar challenged on its common tracking) is withdrawn from this
4066    // merge (Claude master's ruling, 2026-10-05): bisected as the first commit
4067    // that moved step_import's a_trim_off_its_bar_is_accepted_and_named, and
4068    // the four original fitter rows do not need it (they enter on the
4069    // deviation trigger).
4070    if !(legacy.report.residual > ask + legacy.report.off_surface) {
4071        return Ok(legacy);
4072    }
4073    // The trigger read, the candidate's tracking verification and the final
4074    // read project the same edge points again: memoized, same answers.
4075    let _feet = FootMemoScope::open(surface);
4076    let Ok(end_knots) = native_end_knot_fractions(curve, edge_start, edge_end, forward, &legacy.curve) else { return Ok(legacy) };
4077    // The legacy fit's own WORST native spans (2026-10-05, root's boundary
4078    // audit of the four rows): the e90 witnesses read a 4.58e-6 / 5.14e-6
4079    // pointwise excess at q 0.99996 inside the closed native domain, in the
4080    // legacy pcurve's last span, where no edge knot falls. Each span between the
4081    // legacy pcurve's own distinct knots is read at its 19 probes; the spans
4082    // whose same-parameter deviation exceeds the ask plus the legacy standoff,
4083    // worst first and at most WORST_SPANS of them, each get WORST_SPAN_SEEDS
4084    // evenly spaced interior stations. Unreadable reads decline.
4085    // The edge's OWN first and last native knot spans, read at their quarter
4086    // points and 16 interior points, mapped through the trim's range and sense
4087    // to coedge fractions (e7's first edge span [0, 4.496e-6] of a
4088    // 0.018661-long trim maps reversed to q in [0.99976, 1], overlapping the
4089    // legacy pcurve's last span [0.99986, 1]).
4090    let edge_end_probes = edge_end_span_fractions(curve, edge_start, edge_end, forward);
4091    // The FIXED part of the common probe set, known before the candidate is
4092    // fitted: the legacy pcurve's own spans, endpoints and knots, and the
4093    // edge's own end-span probes, knot-span quarters and knots (every probe
4094    // that could have TRIGGERED the challenger among them). The candidate fit
4095    // verifies against these as well as its own spans, so it stops on the
4096    // reader that judges it.
4097    let Ok(mut fixed) = native_probe_fractions(&[&legacy.curve]) else { return Ok(legacy) };
4098    fixed.extend(edge_end_probes.iter().copied());
4099    let (low, high) = (edge_start.min(edge_end), edge_start.max(edge_end));
4100    let mut edge_knots: Vec<f64> = curve.knots.iter().copied().filter(|k| *k >= low && *k <= high).collect();
4101    edge_knots.push(low);
4102    edge_knots.push(high);
4103    edge_knots.sort_by(f64::total_cmp);
4104    edge_knots.dedup();
4105    let to_fraction = |t: f64| {
4106        let along = (t - edge_start) / (edge_end - edge_start);
4107        if forward { along } else { 1.0 - along }
4108    };
4109    for span in edge_knots.windows(2).filter(|w| w[1] > w[0]) {
4110        for local in [0.25, 0.5, 0.75] {
4111            fixed.push(to_fraction(span[0] + (span[1] - span[0]) * local));
4112        }
4113    }
4114    fixed.extend(edge_knots.iter().map(|&t| to_fraction(t)));
4115    fixed.extend(end_knots.iter().copied());
4116    fixed.extend(legacy.curve.knots.iter().copied());
4117    fixed.retain(|f| f.is_finite() && (0.0..=1.0).contains(f));
4118    fixed.sort_by(f64::total_cmp);
4119    fixed.dedup();
4120    let trigger = challenger_trigger(legacy.report.residual, legacy.report.off_surface, ask, || {
4121        common_station_read(surface, evaluate_edge, &legacy.curve, &legacy.curve, &fixed).ok().map(|((tracking, _), _)| tracking)
4122    });
4123    let Some(trigger) = trigger else { return Ok(legacy) };
4124    let Ok(worst_seeds) = legacy_worst_span_seeds(evaluate_edge, surface, &legacy.curve, ask + legacy.report.off_surface, &edge_end_probes) else { return Ok(legacy) };
4125    // The original guard holds for the deviation trigger only: a tracking
4126    // trigger needs no added station (the tracking mode and its verification
4127    // read the fixed probes).
4128    if trigger == ChallengerTrigger::Deviation && end_knots.is_empty() && worst_seeds.is_empty() {
4129        return Ok(legacy);
4130    }
4131    let mut stations: Vec<f64> = breaks.iter().copied().chain(end_knots.iter().copied()).chain(worst_seeds.iter().copied()).collect();
4132    stations.sort_by(f64::total_cmp);
4133    stations.dedup();
4134    // The fitter's cap is max(requested cap, initial station count): the added
4135    // stations must not raise it. Decline when the merged initial count
4136    // (base stations plus every break and end knot) could exceed the
4137    // requested cap.
4138    let initial = base_samples.max(1).checked_add(1).and_then(|count| count.checked_add(stations.len()));
4139    if initial.is_none_or(|count| count > parameter_cap) {
4140        return Ok(legacy);
4141    }
4142    let Ok(candidate) = fit_station_pcurve_mode(surface, evaluate_edge, &stations, breaks, ask, base_samples, refinement_rounds, parameter_cap, SPAN_FLOOR, true, Some(&legacy.curve), &fixed) else {
4143        return Ok(legacy);
4144    };
4145    if !(candidate.report.residual.is_finite() && candidate.report.off_surface.is_finite() && candidate.report.clamped_excursion.is_finite() && candidate.report.clamped_distance.is_finite()) {
4146        return Ok(legacy);
4147    }
4148    // Common probes: the fixed set plus the candidate's own knot spans,
4149    // endpoints and knots (the same set as both curves' native probes plus
4150    // the edge's, as before).
4151    let Ok(mut probes) = native_probe_fractions(&[&candidate.curve]) else { return Ok(legacy) };
4152    probes.extend(fixed.iter().copied());
4153    probes.extend(candidate.curve.knots.iter().copied());
4154    probes.retain(|f| f.is_finite() && (0.0..=1.0).contains(f));
4155    probes.sort_by(f64::total_cmp);
4156    probes.dedup();
4157    let readings = common_station_read_with_excess(surface, evaluate_edge, &legacy.curve, &candidate.curve, &probes);
4158    let accepted = matches!(&readings, Ok((old, new)) if floor_admits(*old, *new));
4159    if station_fit_tracing() {
4160        eprintln!(
4161            "STATION-FIT end-span challenger: trigger={trigger:?} end_knots={} worst_span_seeds={} edge_end_probes={} legacy={:?}/{:e} candidate={:?}/{:e} common={readings:?} decision={}",
4162            end_knots.len(), worst_seeds.len(), edge_end_probes.len(), legacy.report.exit, legacy.report.residual, candidate.report.exit, candidate.report.residual,
4163            if accepted { "candidate" } else { "legacy" }
4164        );
4165    }
4166    Ok(if accepted { candidate } else { legacy })
4167}
4168
4169
4170/// [`fit_pcurve_on_surface_range_dense`] for the callers that only need the
4171/// curve, accepted or refused on its bar (`accept_fit`).
4172#[allow(clippy::too_many_arguments)]
4173pub fn build_pcurve_on_surface_range_dense(
4174    surface: &NurbsSurface,
4175    curve: &NurbsCurve,
4176    edge_start: f64,
4177    edge_end: f64,
4178    forward: bool,
4179    tolerance: f64,
4180    base_samples: usize,
4181    refinement_rounds: usize,
4182    parameter_cap: usize,
4183) -> Result<NurbsCurve, String> {
4184    accept_fit(fit_pcurve_on_surface_range_dense(
4185        surface,
4186        curve,
4187        edge_start,
4188        edge_end,
4189        forward,
4190        tolerance,
4191        base_samples,
4192        refinement_rounds,
4193        parameter_cap,
4194    )?)
4195}
4196
4197/// The fractions of `[edge_start, edge_end]`, walked in the coedge's sense, at
4198/// which `curve` is not C2: interior knots of multiplicity at least its
4199/// degree. A rational-quadratic arc past a quarter turn is two segments joined
4200/// at a double knot, and an interpolant through uniform samples across that
4201/// joint cannot represent the second-derivative jump: on the 2026-09-18 import
4202/// census 1511 of the 2979 arc trims blamed on the fitter had their worst
4203/// miss at fraction 0.49–0.51, the mid double knot, exactly as the fillet's
4204/// corner patch had measured (`blend/track_fit.rs::curve_breaks`, which this
4205/// mirrors for a range).
4206pub fn range_breaks(
4207    curve: &NurbsCurve,
4208    edge_start: f64,
4209    edge_end: f64,
4210    forward: bool,
4211) -> Vec<f64> {
4212    let mut fractions = Vec::new();
4213    let span = edge_end - edge_start;
4214    if !(span.abs() > 0.0) {
4215        return fractions;
4216    }
4217    let (low, high) = (edge_start.min(edge_end), edge_start.max(edge_end));
4218    let mut index = 0;
4219    while index < curve.knots.len() {
4220        let value = curve.knots[index];
4221        let run = curve.knots[index..]
4222            .iter()
4223            .take_while(|knot| **knot == value)
4224            .count();
4225        if value > low && value < high && run >= curve.degree.max(1) {
4226            let along = (value - edge_start) / span;
4227            fractions.push(if forward { along } else { 1.0 - along });
4228        }
4229        index += run;
4230    }
4231    fractions.sort_by(f64::total_cmp);
4232    fractions
4233}
4234
4235/// The body of [`fit_pcurve_on_surface_range_dense`], parameterized by the
4236/// 3D station the pcurve must pass through at each coedge fraction instead of
4237/// by an edge curve and a range.
4238///
4239/// The station supplier is the whole difference between deriving a pcurve and
4240/// reading one. `fit_pcurve_on_surface_range_dense` supplies points off the
4241/// edge's own 3D curve, so the answer is "the nearest point of the carrier",
4242/// which is ambiguous exactly where a trim is interesting — a seam branch, a
4243/// near-tangential approach, a pole. The STEP importer's supplied-pcurve lane
4244/// supplies points off the VENDOR's stated trim instead, and the ambiguity is
4245/// gone because the vendor resolved it.
4246///
4247/// `stations(fraction)` must be continuous in `fraction` over `[0, 1]` and land
4248/// on (or very near) `surface`; `breaks` are the fractions at which it is not
4249/// C2 (`range_breaks`), each of which becomes a station so no kink sits
4250/// between two nodes. Everything else — inversion, branch repair, refinement
4251/// and the measurement — is shared with the derived lane by construction.
4252///
4253/// The SURFACE's knot-line crossings are deliberately not stations here,
4254/// although `blend/track_fit.rs` makes them so. Measured 2026-09-26 over the
4255/// 57-document import corpus: with each crossing bisected on the fraction and
4256/// projected seeded from the left station, 34 bodies refused (19 with a foot
4257/// that misses its global distance rejected) against 15 without the pass —
4258/// every extra refusal a fit stalled around a crossing station, on
4259/// `AssemblyExample-Assembly` and `abc_00000014` among others. The raised
4260/// pass resolves the O(h²) tail across a crossing on its own.
4261///
4262/// # What the fit is measured against, and when it stops
4263///
4264/// The stations' own standoff from the carrier is read FIRST, from the base
4265/// inversions, and the refinement target is the ask plus that standoff
4266/// ([`PcurveFitReport::on_bar`]): a station standing `g` off the surface
4267/// cannot be imaged closer than `g`, so chasing it to the ask alone spends the
4268/// whole budget for nothing (the 2026-09-18 census: 2052 imported pcurves at
4269/// the 513 cap, 1958 of them on a curve that is not on its carrier).
4270///
4271/// Every probe and the final measurement read the carrier through
4272/// `evaluate_extended`: a pcurve riding a periodic seam legitimately carries
4273/// parameters past the domain, and the clamped `evaluate` this loop used until
4274/// 2026-09-26 read every such station as a gross miss — an insert per round
4275/// until the cap, on a trim that was right.
4276///
4277/// The RETURNED curve is measured out of sample — at the quarter points of
4278/// every span between its nodes, where an interpolant is exact at the nodes
4279/// and extremal between — unless its last round probed every span and found
4280/// nothing to insert, in which case that round's maximum already is that
4281/// measurement. A fit that binds at `parameter_cap` or spends its rounds with
4282/// the bar still unmet grows ONCE to `PCURVE_RAISED_SAMPLES` (deterministic).
4283/// The report says which exit it took and what it reached; the `build_*`
4284/// wrappers refuse over the bar, this function never does.
4285#[allow(clippy::too_many_arguments)]
4286pub fn fit_pcurve_on_surface_stations(
4287    surface: &NurbsSurface,
4288    stations: &dyn Fn(f64) -> Result<Vec3, String>,
4289    breaks: &[f64],
4290    tolerance: f64,
4291    base_samples: usize,
4292    refinement_rounds: usize,
4293    parameter_cap: usize,
4294) -> Result<PcurveFit, String> {
4295    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::FIT);
4296    crate::work_counts::add(|c| c.fit_calls += 1);
4297    let fit = fit_station_pcurve(
4298        surface, stations, breaks, &[], tolerance.max(PCURVE_REFINEMENT_TOLERANCE),
4299        base_samples, refinement_rounds, parameter_cap, SPAN_FLOOR,
4300    )?;
4301    // Tallied on the open scope like the curve builders' fits, so a station
4302    // fit's clamp reaches the operation's ledger (`pcurve.clamped`).
4303    record_fit(&fit.report);
4304    Ok(fit)
4305}
4306
4307/// Precision construction for stations on recognized analytic carriers. Unlike
4308/// general projection, their inverse maps reach floating point accuracy. This
4309/// is an explicit construction contract, not a change to general fit policy.
4310pub fn analytic_station_pcurve(
4311    surface: &NurbsSurface,
4312    stations: &dyn Fn(f64) -> Result<Vec3, String>,
4313    tolerance: f64,
4314) -> Result<NurbsCurve, String> {
4315    if surface.analytic().is_none() {
4316        return Err("analytic pcurve requires an analytic carrier".into());
4317    }
4318    let mut breaks = Vec::new();
4319    for _ in 0..4 {
4320        let fit = fit_station_pcurve(surface, stations, &breaks, &[], tolerance, 64, 64, 8192, 1e-10)?;
4321        if fit.report.residual > tolerance || fit.report.off_surface > tolerance {
4322            return Err(format!(
4323                "analytic pcurve construction missed its contract: {:?}",
4324                fit.report
4325            ));
4326        }
4327        let mut failed = Vec::new();
4328        // Independent Gauss stations in every returned knot span, rather than
4329        // re-reading the interpolation nodes or the fitter's quarter stations.
4330        for pair in fit.curve.knots.windows(2) {
4331            if pair[1] <= pair[0] {
4332                continue;
4333            }
4334            for local in [
4335                0.06943184420297371,
4336                0.33000947820757187,
4337                0.6699905217924281,
4338                0.9305681557970262,
4339            ] {
4340                let t = pair[0] + (pair[1] - pair[0]) * local;
4341                let uv = fit.curve.evaluate(t)?;
4342                if surface
4343                    .evaluate_extended(uv.x, uv.y)?
4344                    .sub(stations(t)?)
4345                    .length()
4346                    > tolerance
4347                {
4348                    failed.push(t);
4349                }
4350            }
4351        }
4352        if failed.is_empty() {
4353            return Ok(fit.curve);
4354        }
4355        if breaks.len() + failed.len() > 8192 {
4356            break;
4357        }
4358        breaks.extend(failed);
4359        breaks.sort_by(f64::total_cmp);
4360        breaks.dedup();
4361    }
4362    Err("analytic pcurve failed independent knot-span witnesses".into())
4363}
4364
4365#[allow(clippy::too_many_arguments)]
4366thread_local! {
4367    /// Profile only: the station fitter's time by phase (setup, probes,
4368    /// inserts, repair, interpolant, residual, other), ms.
4369    static STATION_LAPS: std::cell::Cell<[f64; 7]> = const { std::cell::Cell::new([0.0; 7]) };
4370}
4371
4372fn station_lap(slot: usize, lap: &mut Option<web_time::Instant>) {
4373    let Some(started) = *lap else { return };
4374    let now = web_time::Instant::now();
4375    STATION_LAPS.with(|laps| {
4376        let mut all = laps.get();
4377        all[slot] += (now - started).as_secs_f64() * 1e3;
4378        laps.set(all);
4379    });
4380    *lap = Some(now);
4381}
4382
4383/// Profile only: take and reset the station fitter's phase totals.
4384#[doc(hidden)]
4385pub fn take_station_fit_laps() -> [f64; 7] {
4386    STATION_LAPS.with(|laps| laps.replace([0.0; 7]))
4387}
4388
4389#[allow(clippy::too_many_arguments)]
4390pub fn fit_station_pcurve(
4391    surface: &NurbsSurface,
4392    stations: &dyn Fn(f64) -> Result<Vec3, String>,
4393    breaks: &[f64],
4394    corners: &[f64],
4395    tolerance: f64,
4396    base_samples: usize,
4397    refinement_rounds: usize,
4398    parameter_cap: usize,
4399    span_floor: f64,
4400) -> Result<PcurveFit, String> {
4401    fit_station_pcurve_mode(surface, stations, breaks, corners, tolerance, base_samples, refinement_rounds, parameter_cap, span_floor, false, None, &[])
4402}
4403
4404/// [`fit_station_pcurve`] with an optional TRACKING mode, taken only by the
4405/// range lane's [`end_span_challenger`]; every other caller keeps the legacy
4406/// mode byte for byte. The legacy fitter probes, ranks and stops on the
4407/// image's same-parameter DEVIATION from the edge point. On an edge standing
4408/// off its carrier that deviation never falls under the ask, so every probe is
4409/// a candidate, the cap goes to the probes with the largest STANDOFF, and a
4410/// tangential slip of `d` adds only about d²/(2g) to a deviation over a
4411/// standoff `g`: the four original rows' challenger met its standoff (4.670e-6)
4412/// and kept a common tracking of 1.434e-6 (root's e24 run, 2026-10-05). In
4413/// tracking mode each probe reads its TRACKING, the image against the edge
4414/// point's foot (the nearer admitted one of the global projection and the
4415/// projection seeded at the image's uv: finite, inside the native domain, as
4416/// [`common_station_read`] admits). A probe is a candidate only over the ask,
4417/// the cap goes to the worst TRACKING first, and the one raise is taken when
4418/// the last round's tracking still misses the ask. The reported residual
4419/// stays the same-parameter deviation (standoff included). A probe with no
4420/// admitted foot is an error, which the challenger turns into the exact legacy
4421/// fit.
4422#[allow(clippy::too_many_arguments)]
4423pub fn fit_station_pcurve_mode(
4424    surface: &NurbsSurface,
4425    stations: &dyn Fn(f64) -> Result<Vec3, String>,
4426    breaks: &[f64],
4427    corners: &[f64],
4428    tolerance: f64,
4429    base_samples: usize,
4430    refinement_rounds: usize,
4431    parameter_cap: usize,
4432    span_floor: f64,
4433    track_projection: bool,
4434    reference: Option<&NurbsCurve>,
4435    verify: &[f64],
4436) -> Result<PcurveFit, String> {
4437    // Read only in tracking mode: the legacy mode makes no extra call.
4438    let domains = if track_projection { Some(surface_domains(surface)?) } else { None };
4439    // The tracking reading at one fraction, by the SAME foot rule as
4440    // [`common_station_read`], the reader the challenger accepts on: the
4441    // nearest admitted foot among the global projection and the projections
4442    // seeded at this image's uv and at the reference (legacy) pcurve's uv at
4443    // the same fraction. Returns the tracking and that foot (uv, distance),
4444    // which is where a tracking insert is placed.
4445    let tracking_of = |represented: Vec3, edge_point: Vec3, uv: Vec3, fraction: f64| -> Result<(f64, [f64; 2], f64), String> {
4446        let (domain_u, domain_v) = domains.ok_or_else(|| "station tracking: legacy mode".to_string())?;
4447        let finite = |p: Vec3| p.x.is_finite() && p.y.is_finite() && p.z.is_finite();
4448        let reference_seed = match reference {
4449            Some(curve) => curve.evaluate(fraction).ok().and_then(|seed| memo_seeded_foot(surface, edge_point, seed.x, seed.y)),
4450            None => None,
4451        };
4452        // The common reader's order (global, reference, candidate), so an
4453        // equal-distance tie takes the same foot here as there.
4454        let foot = common_foot(
4455            memo_global_foot(surface, edge_point),
4456            reference_seed,
4457            memo_seeded_foot(surface, edge_point, uv.x, uv.y),
4458            domain_u,
4459            domain_v,
4460        )
4461        .ok_or_else(|| "station tracking: no admitted foot".to_string())?;
4462        let tracking = represented.sub(foot.point).length();
4463        if !(finite(represented) && tracking.is_finite()) {
4464            return Err("station tracking: non-finite reading".into());
4465        }
4466        Ok((tracking, [foot.u, foot.v], foot.distance))
4467    };
4468    // The last round's tracking missed the ask (tracking mode only).
4469    let mut tracking_unmet = false;
4470    let evaluate_edge = stations;
4471    let base_samples = base_samples.max(1);
4472    // The general caller floors its ask: its projector places a foot
4473    // to about `LINEAR_TOLERANCE` (1e-7), so a caller asking for 1e-9 asks for
4474    // more than any station can deliver. Chased to such an ask the fit spends
4475    // its cap and reads its own noise — the direct-edit heals asked 1e-9 on
4476    // stations 9.9e-8 off their carrier and were refused by 8.5e-9
4477    // (2026-09-26). The floor is the ask's floor; the report says what was
4478    // reached against it.
4479
4480    let mut parameters = (0..=base_samples)
4481        .map(|index| index as f64 / base_samples as f64)
4482        .collect::<Vec<_>>();
4483    // A break within the span floor of a station IS that station: two nodes
4484    // closer than that make the interpolant swing between them, and over a
4485    // stretch that short the kink moves the fit by nothing a bar can read.
4486    // `abc_00000011` face #549's curve carries a triple knot 4e-7 before its
4487    // end; as a station it put the cubic 1.594e-2 off between it and the last
4488    // one (measured 2026-09-26), where the file's curve sits 1e-7 off.
4489    // A break that is a CORNER of the curve (`corners`, a subset of
4490    // `breaks`: the range lane passes its curve's knots of multiplicity >=
4491    // degree as both) is a C0 JOIN of the interpolant
4492    // (`build_interpolant_joined`): one cubic through the corner overshoots
4493    // on both sides whatever is inserted. A break that is only a station
4494    // (an analytic witness, a caller's own marker) joins nothing.
4495    let mut joins = Vec::with_capacity(corners.len());
4496    for &fraction in breaks {
4497        if !(fraction > 0.0 && fraction < 1.0) {
4498            continue;
4499        }
4500        let corner = corners.contains(&fraction);
4501        let at = parameters.partition_point(|parameter| *parameter < fraction);
4502        let near_left = at > 0 && fraction - parameters[at - 1] <= span_floor;
4503        let near_right = at < parameters.len() && parameters[at] - fraction <= span_floor;
4504        if near_left || near_right {
4505            // The break IS that station (a corner at a base station, e.g.
4506            // the midpoint of a two-piece curve at 32/64): no insert, but the
4507            // station is still the join.
4508            if corner {
4509                joins.push(if near_right { parameters[at] } else { parameters[at - 1] });
4510            }
4511            continue;
4512        }
4513        parameters.insert(at, fraction);
4514        if corner {
4515            joins.push(fraction);
4516        }
4517    }
4518    // The 3D edge point behind each raw inversion sample, kept parallel so the
4519    // continuity repair can re-seed a jumped station from its own footpoint.
4520    let mut lap = crate::profile::profile_enabled().then(web_time::Instant::now);
4521    let mut edge_points = parameters
4522        .iter()
4523        .map(|fraction| evaluate_edge(*fraction))
4524        .collect::<Result<Vec<_>, _>>()?;
4525    // The stations' standoff from the carrier: the part of every residual no
4526    // pcurve can remove, known before a single probe is spent.
4527    let mut off_surface = 0.0_f64;
4528    let mut raw = Vec::with_capacity(edge_points.len());
4529    let mut gaps = Vec::with_capacity(edge_points.len());
4530    for point in &edge_points {
4531        let (parameter, gap) = if track_projection && precision_trim_feet(surface) {
4532            let foot = memo_global_foot(surface, *point).ok_or("precision trim has no foot")?;
4533            ([foot.u, foot.v], foot.distance)
4534        } else { invert_checked(surface, *point)? };
4535        off_surface = off_surface.max(gap);
4536        raw.push(parameter);
4537        gaps.push(gap);
4538    }
4539    repair_branch_jumps(surface, &edge_points, &mut raw, tolerance)?;
4540    let (mut pcurve, mut excursion, mut distance) =
4541        build_interpolant_joined(surface, &raw, &parameters, &joins)?;
4542
4543    station_lap(0, &mut lap);
4544    let mut cap = parameter_cap.max(parameters.len());
4545    let mut rounds = refinement_rounds;
4546    let mut raised = false;
4547    loop {
4548        let mut exit = PcurveFitExit::RoundBudget;
4549        let mut converged_max = None;
4550        // This pass's last round probed every span (none narrow, none
4551        // truncated) and every probe tracked within the ask (tracking mode).
4552        let mut tracking_met = false;
4553        for _ in 0..rounds {
4554            if parameters.len() >= cap {
4555                exit = PcurveFitExit::SampleCeiling;
4556                break;
4557            }
4558            // The target is the ASK, bare: a station standing off the carrier
4559            // is chased to the foot it projects to, as the fitter has always
4560            // done. A target of ask + standoff (one landing, 2026-09-26) let
4561            // such a fit stop at its base stations with the interpolant
4562            // wandering between them, folded a molex wall's mesh and put a
4563            // trim of abc_00000023 2.2e-5 off its own parameter; the bar
4564            // below still reads what it reached.
4565            let target = tolerance;
4566            let mut candidates = Vec::new();
4567            let mut round_max = 0.0_f64;
4568            let mut truncated = false;
4569            let mut skipped_narrow = false;
4570            let worst_first = worst_first();
4571            'spans: for index in 0..parameters.len() - 1 {
4572                // The loop's own resolution floor: a span narrower than this
4573                // is not subdivided. Without it the
4574                // raised pass inserted into a vanishing span at a trim's end
4575                // until the cap — `abc_00000011` face #549's last stations sat
4576                // 4e-7 apart with their feet clamped at the patch edge, and the
4577                // cubic through them swung 1.594e-2 off between them (measured
4578                // 2026-09-26). A miss that survives only inside such a span is
4579                // reported as [`PcurveFitExit::SpanFloor`].
4580                if parameters[index + 1] - parameters[index] < span_floor {
4581                    skipped_narrow = true;
4582                    continue;
4583                }
4584                for local in [0.25, 0.5, 0.75] {
4585                    if !worst_first && parameters.len() + candidates.len() >= cap {
4586                        truncated = true;
4587                        break 'spans;
4588                    }
4589                    let fraction =
4590                        parameters[index] + (parameters[index + 1] - parameters[index]) * local;
4591                    let uv = pcurve.evaluate(fraction)?;
4592                    let represented = surface.evaluate_extended(uv.x, uv.y)?;
4593                    let edge_point = evaluate_edge(fraction)?;
4594                    let deviation = represented.sub(edge_point).length();
4595                    // The probe's reading: its deviation (legacy), or its
4596                    // tracking against the admitted foot (tracking mode).
4597                    let (reading, foot) = if track_projection {
4598                        let (tracking, foot_uv, foot_gap) = tracking_of(represented, edge_point, uv, fraction)?;
4599                        (tracking, Some((foot_uv, foot_gap)))
4600                    } else {
4601                        (deviation, None)
4602                    };
4603                    round_max = round_max.max(reading);
4604                    if reading <= target {
4605                        continue;
4606                    }
4607                    candidates.push((index, fraction, edge_point, uv, reading, foot));
4608                }
4609            }
4610            // Tracking mode's VERIFICATION, before it may stop: a round whose
4611            // quarter probes all track within the ask is read again at the
4612            // probes the challenger's acceptance reads, the current pcurve's
4613            // own knot spans (endpoints, quarters and 16 interior points: the
4614            // interpolant's knots are averages of three stations, not the
4615            // stations) and the caller's fixed fractions (the legacy pcurve's
4616            // spans and the edge's own). A probe over the ask becomes a
4617            // candidate at its own fraction, placed at its own foot. One
4618            // within the span floor of a station cannot be inserted: it is
4619            // counted, and the fit may not report its tracking as met. On e24
4620            // the four rows stopped on their quarter probes and read 1.144e-7 /
4621            // 1.590e-7 at the common probes (2026-10-05).
4622            let mut verify_blocked = false;
4623            if track_projection && candidates.is_empty() && !truncated && !skipped_narrow {
4624                for fraction in verification_fractions(&pcurve, verify)? {
4625                    let index = parameters.partition_point(|parameter| *parameter <= fraction).saturating_sub(1).min(parameters.len() - 2);
4626                    let uv = pcurve.evaluate(fraction)?;
4627                    let represented = surface.evaluate_extended(uv.x, uv.y)?;
4628                    let edge_point = evaluate_edge(fraction)?;
4629                    let (tracking, foot_uv, foot_gap) = tracking_of(represented, edge_point, uv, fraction)?;
4630                    round_max = round_max.max(tracking);
4631                    if tracking <= target {
4632                        continue;
4633                    }
4634                    if fraction - parameters[index] <= span_floor || parameters[index + 1] - fraction <= span_floor {
4635                        verify_blocked = true;
4636                        continue;
4637                    }
4638                    // Two over-ask probes closer than the span floor in one
4639                    // span: keep the worse, so no near-duplicate stations.
4640                    if let Some(last) = candidates.last_mut() {
4641                        if last.0 == index && fraction - last.1 <= span_floor {
4642                            if tracking > last.4 {
4643                                *last = (index, fraction, edge_point, uv, tracking, Some((foot_uv, foot_gap)));
4644                            }
4645                            continue;
4646                        }
4647                    }
4648                    candidates.push((index, fraction, edge_point, uv, tracking, Some((foot_uv, foot_gap))));
4649                }
4650            }
4651            station_lap(if track_projection { 6 } else { 1 }, &mut lap);
4652            tracking_unmet = track_projection && round_max > target;
4653            // A round with more candidates than the cap has room for spends
4654            // that room on its WORST probes, kept in curve order, rather than
4655            // on the first spans in order: truncating in span order left the
4656            // late spans of an off-carrier ring at their base spacing and its
4657            // image 1.523e-6 off its feet; worst first reaches 5.84e-8 on the
4658            // same 513 samples. An even stride along the curve reached 2.87e-7
4659            // there but diluted the inserts a local miss needs and lost fits
4660            // over the corpus (a 1.3e-5 trim of `abc_00000011` fell back to its
4661            // 4.4e-4 size-ask fit), measured 2026-09-27.
4662            let room = cap.saturating_sub(parameters.len());
4663            if candidates.len() > room {
4664                truncated = true;
4665                let mut order: Vec<usize> = (0..candidates.len()).collect();
4666                order.sort_by(|&a, &b| candidates[b].4.total_cmp(&candidates[a].4).then(a.cmp(&b)));
4667                order.truncate(room);
4668                order.sort_unstable();
4669                candidates = order.into_iter().map(|index| candidates[index]).collect();
4670            }
4671            let mut inserts = Vec::with_capacity(candidates.len());
4672            for (index, fraction, edge_point, uv, _, foot) in candidates {
4673                // A tracking candidate is placed at the very foot it was read
4674                // against, so the node's image IS that foot; the legacy
4675                // inversion is unchanged.
4676                let (parameter, gap) = match foot {
4677                    Some(placed) => placed,
4678                    None => invert_near(surface, edge_point, [uv.x, uv.y], gaps[index].max(gaps[index + 1]))?,
4679                };
4680                inserts.push((index + 1, fraction, edge_point, parameter, gap));
4681            }
4682            station_lap(2, &mut lap);
4683            if station_fit_tracing() {
4684                eprintln!(
4685                    "STATION-FIT round: samples={} target={target:.3e} round_max={round_max:.3e} inserts={} truncated={truncated}{}",
4686                    parameters.len(),
4687                    inserts.len(),
4688                    // Tracking mode's round_max is a TRACKING reading.
4689                    if track_projection { " mode=tracking" } else { "" }
4690                );
4691            }
4692            if inserts.is_empty() {
4693                exit = if truncated {
4694                    PcurveFitExit::SampleCeiling
4695                } else if skipped_narrow {
4696                    // Every probed span is within the target; the narrow ones
4697                    // were not probed, and the sweep below measures them.
4698                    PcurveFitExit::SpanFloor
4699                } else if track_projection {
4700                    // Every probe TRACKS within the ask, but round_max is a
4701                    // tracking reading, not the deviation the report carries.
4702                    // The exit is Stalled (no probe can be improved; the
4703                    // residual measured below is the edge's own standoff),
4704                    // and it becomes Converged below only if that measured
4705                    // deviation itself meets the floor. A verification probe
4706                    // over the ask that could not be inserted leaves the
4707                    // tracking UNMET.
4708                    tracking_met = !verify_blocked;
4709                    PcurveFitExit::Stalled
4710                } else {
4711                    converged_max = Some(round_max);
4712                    PcurveFitExit::Converged
4713                };
4714                break;
4715            }
4716            for (index, fraction, edge_point, parameter, gap) in inserts.into_iter().rev() {
4717                parameters.insert(index, fraction);
4718                edge_points.insert(index, edge_point);
4719                raw.insert(index, parameter);
4720                gaps.insert(index, gap);
4721                off_surface = off_surface.max(gap);
4722            }
4723            // Inserts are independent global inversions too — re-run the repair
4724            // so a fold-flip introduced mid-refinement cannot poison the next
4725            // round's deviation interpolant.
4726            repair_branch_jumps(surface, &edge_points, &mut raw, tolerance)?;
4727            station_lap(3, &mut lap);
4728            let rebuilt = build_interpolant_joined(surface, &raw, &parameters, &joins)?;
4729            station_lap(4, &mut lap);
4730            pcurve = rebuilt.0;
4731            excursion = rebuilt.1;
4732            distance = rebuilt.2;
4733            if truncated {
4734                exit = PcurveFitExit::SampleCeiling;
4735                break;
4736            }
4737        }
4738        station_lap(5, &mut lap);
4739        let residual = match converged_max {
4740            Some(measured) => measured,
4741            None => {
4742                station_residual(surface, evaluate_edge, &pcurve, &parameters, tolerance, &mut off_surface)?
4743            }
4744        };
4745        station_lap(5, &mut lap);
4746        if station_fit_tracing() {
4747            eprintln!(
4748                "STATION-FIT pass raised={raised} exit={exit:?} samples={} residual={residual:.3e} off_surface={off_surface:.3e}",
4749                parameters.len()
4750            );
4751            if residual > tolerance + off_surface && (exit == PcurveFitExit::Converged || raised) {
4752                // Where the miss sits, and the uv track around it: the trace a
4753                // refusal needs to be attributed to a fold, a seam or the file.
4754                let (mut worst, mut at) = (0.0f64, 0usize);
4755                for (index, span) in parameters.windows(2).enumerate() {
4756                    let fraction = 0.5 * (span[0] + span[1]);
4757                    let uv = pcurve.evaluate(fraction)?;
4758                    let deviation = surface.evaluate_extended(uv.x, uv.y)?.sub(evaluate_edge(fraction)?).length();
4759                    if deviation > worst {
4760                        worst = deviation;
4761                        at = index;
4762                    }
4763                }
4764                let ([u0, u1], [v0, v1]) = surface_domains(surface)?;
4765                let (closed_u, closed_v) = surface_closedness(surface)?;
4766                eprintln!(
4767                    "STATION-FIT OFF BAR: worst {worst:.3e} between stations {at} and {}; surface degree {}x{} net {}x{} domain u[{u0},{u1}] v[{v0},{v1}] closed ({closed_u},{closed_v}) analytic {:?}",
4768                    at + 1,
4769                    surface.degree_u,
4770                    surface.degree_v,
4771                    surface.control_points.len(),
4772                    surface.control_points[0].len(),
4773                    surface.analytic().map(|_| "yes").unwrap_or("no")
4774                );
4775                {
4776                    let fraction = 0.5 * (parameters[at] + parameters[at + 1]);
4777                    let uv = pcurve.evaluate(fraction)?;
4778                    let image = surface.evaluate_extended(uv.x, uv.y)?;
4779                    let station = evaluate_edge(fraction)?;
4780                    let foot = project_point_to_surface(surface, station)?;
4781                    let seeded = project_point_to_surface_seeded(surface, station, raw[at][0], raw[at][1])?;
4782                    eprintln!(
4783                        "    at the worst midpoint: deviation {:.4e}, station gap {:.4e} (seeded {:.4e}), image-to-foot {:.4e} (to seeded foot {:.4e}), foot uv ({:.7}, {:.7}) seeded ({:.7}, {:.7}) image uv ({:.7}, {:.7})",
4784                        image.sub(station).length(), foot.distance, seeded.distance, image.sub(foot.point).length(), image.sub(seeded.point).length(), foot.u, foot.v, seeded.u, seeded.v, uv.x, uv.y
4785                    );
4786                }
4787                let lo = at.saturating_sub(3);
4788                let hi = (at + 4).min(parameters.len() - 1);
4789                for index in lo..=hi {
4790                    eprintln!(
4791                        "    station {index}: fraction {:.6} uv ({:.6}, {:.6}) point ({:.4}, {:.4}, {:.4})",
4792                        parameters[index], raw[index][0], raw[index][1], edge_points[index].x, edge_points[index].y, edge_points[index].z
4793                    );
4794                }
4795            }
4796        }
4797        // Legacy only: a SpanFloor exit whose measured DEVIATION is on the
4798        // bar is promoted. In tracking mode the deviation sits at the standoff
4799        // whatever the unprobed narrow spans' TRACKING is, so SpanFloor stays
4800        // SpanFloor (unread); a tracking-mode fit is Converged only when every
4801        // span was probed within the ask AND the measured deviation meets the
4802        // floor (the exit's documented meaning, never the standoff bar).
4803        if !track_projection && exit == PcurveFitExit::SpanFloor && residual <= tolerance + off_surface {
4804            exit = PcurveFitExit::Converged;
4805        }
4806        if tracking_met && residual <= tolerance {
4807            exit = PcurveFitExit::Converged;
4808        }
4809        if exit != PcurveFitExit::Converged
4810            && !raised
4811            && (residual > tolerance + off_surface || tracking_unmet)
4812            && cap < PCURVE_RAISED_SAMPLES
4813        {
4814            raised = true;
4815            cap = PCURVE_RAISED_SAMPLES;
4816            // The raised pass is bounded by SAMPLES, not rounds: a kink
4817            // converges O(h²), a round per halving, and the three rounds of
4818            // the first pass are what left the 2026-09-18 census's fits over
4819            // their ask with budget to spare (RoundBudget at 158–400 of 2000
4820            // samples, measured 2026-09-26). Forty rounds cover every halving
4821            // the cap admits; a fit that is not converging stalls out first.
4822            rounds = RAISED_ROUNDS;
4823            continue;
4824        }
4825        crate::work_counts::constructed("station_fit", parameters.len(), pcurve.control_points.len());
4826        return Ok(PcurveFit {
4827            curve: pcurve,
4828            report: PcurveFitReport {
4829                residual,
4830                floor: tolerance,
4831                samples: parameters.len(),
4832                exit,
4833                off_surface,
4834                raised,
4835                clamped_excursion: excursion,
4836                clamped_distance: distance,
4837            },
4838        });
4839    }
4840}
4841
4842/// [`fit_pcurve_on_surface_stations`] for the callers that only need the
4843/// curve, accepted or refused on its bar (`accept_fit`).
4844pub fn build_pcurve_on_surface_stations(
4845    surface: &NurbsSurface,
4846    stations: &dyn Fn(f64) -> Result<Vec3, String>,
4847    breaks: &[f64],
4848    tolerance: f64,
4849    base_samples: usize,
4850    refinement_rounds: usize,
4851    parameter_cap: usize,
4852) -> Result<NurbsCurve, String> {
4853    accept_fit(fit_pcurve_on_surface_stations(
4854        surface,
4855        stations,
4856        breaks,
4857        tolerance,
4858        base_samples,
4859        refinement_rounds,
4860        parameter_cap,
4861    )?)
4862}
4863
4864/// The largest 3D distance between `pcurve`'s image and its stations at the
4865/// quarter points of every span of `parameters` — out of sample by
4866/// construction, since the interpolant is exact at its nodes. Unclamped
4867/// evaluations; a station read over the running bar is inverted so that
4868/// `off_surface` covers the standoff AT the stations the residual is taken at,
4869/// not only at the nodes (a curve lifted off its plane by a bump stands
4870/// further off between two nodes than at either).
4871fn station_residual(
4872    surface: &NurbsSurface,
4873    stations: &dyn Fn(f64) -> Result<Vec3, String>,
4874    pcurve: &NurbsCurve,
4875    parameters: &[f64],
4876    tolerance: f64,
4877    off_surface: &mut f64,
4878) -> Result<f64, String> {
4879    let mut worst = 0.0_f64;
4880    let mut read = |fraction: f64| -> Result<(), String> {
4881        let uv = pcurve.evaluate(fraction)?;
4882        let represented = surface.evaluate_extended(uv.x, uv.y)?;
4883        let station = stations(fraction)?;
4884        let deviation = represented.sub(station).length();
4885        worst = worst.max(deviation);
4886        if deviation > tolerance + *off_surface {
4887            *off_surface = off_surface.max(invert_checked(surface, station)?.1);
4888        }
4889        Ok(())
4890    };
4891    for span in parameters.windows(2) {
4892        for local in [0.25, 0.5, 0.75] {
4893            read(span[0] + (span[1] - span[0]) * local)?;
4894        }
4895    }
4896    Ok(worst)
4897}
4898
4899
4900
4901