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