Skip to main content

brep_geometry/geometry/
pcurve.rs

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