Skip to main content

brep_geometry/geometry/
projection.rs

1use crate::curve::interior_knots;
2pub use crate::{NurbsCurve, NurbsSurface, Vec3, Vec4};
3use serde::Serialize;
4
5const EPSILON: f64 = crate::tolerance::FP_FLOOR;
6const LINEAR_TOLERANCE: f64 = crate::tolerance::DEFAULT_MODEL;
7const MAX_NEWTON_ITERATIONS: usize = 50;
8
9#[derive(Clone, Copy, Debug, Serialize)]
10pub struct CurveProjection {
11    pub u: f64,
12    pub point: Vec3,
13    pub distance: f64,
14}
15
16#[derive(Clone, Copy, Debug, Serialize)]
17pub struct SurfaceProjection {
18    pub u: f64,
19    pub v: f64,
20    pub point: Vec3,
21    pub distance: f64,
22}
23
24pub fn fit_parameter(value: f64, minimum: f64, maximum: f64, closed: bool) -> f64 {
25    if closed {
26        let period = maximum - minimum;
27        (value - minimum).rem_euclid(period) + minimum
28    } else {
29        value.clamp(minimum, maximum)
30    }
31}
32
33/// Escape hatch for tamper-verification: `BREP_PROJECTION_WITNESS=0` restores
34/// the pre-2026-09-14 answer — the Newton walk from the nearest seed and
35/// nothing else — so a fixture that depends on the rescue can be shown to
36/// depend on it. Read once; the projector is called about a million times in
37/// one boolean.
38fn witness_rescue_enabled() -> bool {
39    switch!("BREP_PROJECTION_WITNESS", true)
40}
41
42/// Squared distance from `point` to the SEGMENT `a`-`b`.
43///
44/// The seed sweep's consecutive samples are the segments of a polyline that
45/// approximates the curve, and this is how far that polyline passes from the
46/// query — the witness the rescue below reads.
47fn point_segment_distance_squared(point: Vec3, a: Vec3, b: Vec3) -> f64 {
48    point.distance_to_segment_squared(a, b)
49}
50
51/// One Newton refinement of the foot parameter, seeded at `seed`.
52///
53/// `best_u` / `best_distance_squared` carry the best answer found SO FAR and
54/// every iterate is compared against them, so a run that diverges or stalls can
55/// only leave the answer where it was. The returned parameter is where the
56/// iteration exited, which the caller still has to evaluate: the stall branch
57/// takes its last step without evaluating it.
58#[allow(clippy::too_many_arguments)]
59fn curve_newton(
60    curve: &NurbsCurve,
61    point: Vec3,
62    seed: f64,
63    start: f64,
64    end: f64,
65    closed: bool,
66    best_u: &mut f64,
67    best_distance_squared: &mut f64,
68) -> Result<f64, String> {
69    let (last, nearest, squared) = curve_foot_newton_state(curve, point, seed, [start, end],
70        CurveFootPolicy {
71            domain: if closed { FootDomain::Wrap } else { FootDomain::Clamp },
72            iterations: MAX_NEWTON_ITERATIONS,
73            slope_guard: EPSILON,
74            step_limit: (end - start) / 4.0,
75            parameter_tolerance: 1e-15 * (end - start),
76            mode: FootMode::Witness,
77        })?;
78    if squared < *best_distance_squared {
79        *best_distance_squared = squared;
80        *best_u = nearest;
81    }
82    Ok(last)
83}
84
85/// The parameter in `[low, high]` nearest `point`, by golden-section search on
86/// the SQUARED distance.
87///
88/// Reads no derivative, so it is the one lane that still works where the
89/// tangent vanishes, and it can never return a point farther than the bracket's
90/// own ends. It assumes ONE minimum inside the bracket — true of a seed
91/// interval, which is one sample step of a single knot span wide.
92fn bracketed_nearest(curve: &NurbsCurve, point: Vec3, low: f64, high: f64) -> Result<f64, String> {
93    // 1/φ. 64 contractions take a bracket to 2.5e-14 of its width, below the
94    // parameter resolution the Newton polish that follows needs from a seed.
95    const CONTRACTION: f64 = 0.618_033_988_749_894_9;
96    const CONTRACTIONS: usize = 64;
97    let width = high - low;
98    if !(width > 0.0) {
99        return Ok(low);
100    }
101    let (mut low, mut high) = (low, high);
102    let mut c = high - CONTRACTION * (high - low);
103    let mut d = low + CONTRACTION * (high - low);
104    let mut value_c = curve.evaluate(c)?.sub(point).length_squared();
105    let mut value_d = curve.evaluate(d)?.sub(point).length_squared();
106    for _ in 0..CONTRACTIONS {
107        if high - low <= 1e-15 * width {
108            break;
109        }
110        if value_c < value_d {
111            high = d;
112            d = c;
113            value_d = value_c;
114            c = high - CONTRACTION * (high - low);
115            value_c = curve.evaluate(c)?.sub(point).length_squared();
116        } else {
117            low = c;
118            c = d;
119            value_c = value_d;
120            d = low + CONTRACTION * (high - low);
121            value_d = curve.evaluate(d)?.sub(point).length_squared();
122        }
123    }
124    Ok((low + high) * 0.5)
125}
126
127pub fn project_point_to_curve(curve: &NurbsCurve, point: Vec3) -> Result<CurveProjection, String> {
128    if projection_memo_enabled() {
129        if let Some(key) = straight_projection_key(curve, point) {
130            if let Some(hit) = PROJECTION_MEMO.with(|memo| memo.borrow().get(&key).copied()) {
131                return Ok(hit);
132            }
133            let projection = project_point_to_curve_uncached(curve, point)?;
134            PROJECTION_MEMO.with(|memo| {
135                let mut memo = memo.borrow_mut();
136                if memo.len() >= PROJECTION_MEMO_ENTRIES {
137                    memo.clear();
138                }
139                memo.insert(key, projection);
140            });
141            return Ok(projection);
142        }
143    }
144    project_point_to_curve_uncached(curve, point)
145}
146
147/// PROJECTION MEMO (lane O row 22, 2026-10-29; on by default since the batch 6
148/// promotion, `BREP_PROJECTION_MEMO=0` projects every call). The projector is a pure function of the curve's net and the
149/// point. On the D2 outward shells every one of its 512 calls a shell call
150/// projects onto a straight two-point edge, and 209 of them repeat a call
151/// already made (the section's pierces, its ambiguity reads and the endpoint
152/// exchange re-project the same points; counted, cad-bot). A straight curve's
153/// whole net and the point make a 16-word key compared exactly, so a hit
154/// returns the very answer the projector computed.
155const PROJECTION_MEMO_ENTRIES: usize = 4096;
156
157thread_local! {
158    static PROJECTION_MEMO: std::cell::RefCell<rustc_hash::FxHashMap<[u64; 16], CurveProjection>> = Default::default();
159}
160
161pub fn straight_projection_key(curve: &NurbsCurve, point: Vec3) -> Option<[u64; 16]> {
162    if curve.degree != 1 || curve.control_points.len() != 2 || curve.knots.len() != 4 {
163        return None;
164    }
165    let [a, b] = [curve.control_points[0], curve.control_points[1]];
166    let k = &curve.knots;
167    Some([
168        1, k[0].to_bits(), k[1].to_bits(), k[2].to_bits(), k[3].to_bits(),
169        a.x.to_bits(), a.y.to_bits(), a.z.to_bits(), a.w.to_bits(),
170        b.x.to_bits(), b.y.to_bits(), b.z.to_bits(), b.w.to_bits(),
171        point.x.to_bits(), point.y.to_bits(), point.z.to_bits(),
172    ])
173}
174
175fn projection_memo_enabled() -> bool {
176    switch!("BREP_PROJECTION_MEMO", true)
177}
178
179
180// Immutable slices avoid retaining Vec spare capacity: cached sample payload
181// is at most 8 MiB per thread, plus at most 4096 map entries and Rc headers.
182type CurveSeeds = std::rc::Rc<[(f64, Vec3)]>;
183const CURVE_SEED_BUDGET: usize = 262_144;
184thread_local! {
185    static CURVE_SEEDS: std::cell::RefCell<(rustc_hash::FxHashMap<[u64; 2], CurveSeeds>, usize)> = Default::default();
186}
187
188/// Discard the calling thread's bounded seed geometry at a history boundary.
189/// Other workers retain their own content-keyed entries until local eviction,
190/// an explicit clear on that worker, or thread exit. This is deliberately not
191/// a pool-wide invalidation: curve content fully determines every stored bit.
192/// Each worker retains at most 262,144 samples (8 MiB payload) and 4096 keys;
193/// temporary sampling and an outstanding borrowed snapshot are additional.
194pub fn clear_curve_seed_cache() {
195    CURVE_SEEDS.with(|memo| *memo.borrow_mut() = Default::default());
196}
197
198fn visit_curve_seeds(curve: &NurbsCurve, start: f64, end: f64, mut visit: impl FnMut(f64, Vec3)) -> Result<(), String> {
199    let mut breaks = vec![start];
200    breaks.extend(interior_knots(&curve.knots, curve.degree));
201    breaks.push(end);
202    let samples_per_span = 4usize.max(curve.degree + 2);
203    for pair in breaks.windows(2) {
204        for index in 0..=samples_per_span {
205            let parameter = pair[0] + (pair[1] - pair[0]) * index as f64 / samples_per_span as f64;
206            visit(parameter, curve.evaluate(parameter)?);
207        }
208    }
209    Ok(())
210}
211
212/// Cache only the curve-dependent seed geometry, in its original sequence.
213/// Every query still performs the same distance comparisons, witness search,
214/// Newton iterations and tie breaking. The content key includes every knot
215/// and homogeneous control bit; failed sampling is never retained.
216fn cached_curve_seeds(curve: &NurbsCurve, start: f64, end: f64) -> Result<Option<CurveSeeds>, String> {
217    if !switch!("BREP_CURVE_PROJECTION_SEEDS", true) { return Ok(None); }
218    // Avoid allocating a giant one-off vector even when it would not be kept.
219    let bound = curve.knots.len().saturating_add(1).saturating_mul(4usize.max(curve.degree + 2).saturating_add(1));
220    if bound > CURVE_SEED_BUDGET { return Ok(None); }
221    let mut key = crate::identity_hash::TwoLane::new();
222    crate::identity_hash::hash_curve(&mut key, curve);
223    key.f64(start); key.f64(end);
224    let key = key.finish();
225    if let Some(seeds) = CURVE_SEEDS.with(|memo| memo.borrow().0.get(&key).cloned()) {
226        return Ok(Some(seeds));
227    }
228    let mut seeds = Vec::new();
229    visit_curve_seeds(curve, start, end, |u, point| seeds.push((u, point)))?;
230    let seeds: CurveSeeds = seeds.into();
231    CURVE_SEEDS.with(|memo| {
232        let mut memo = memo.borrow_mut();
233        if memo.0.len() >= PROJECTION_MEMO_ENTRIES || memo.1 + seeds.len() > CURVE_SEED_BUDGET {
234            memo.0.clear(); memo.1 = 0;
235        }
236        memo.1 += seeds.len();
237        memo.0.insert(key, seeds.clone());
238    });
239    Ok(Some(seeds))
240}
241
242fn project_point_to_curve_uncached(curve: &NurbsCurve, point: Vec3) -> Result<CurveProjection, String> {
243    let [start, end] = curve.domain()?;
244    let mut best_u = start;
245    let mut best_distance_squared = f64::INFINITY;
246    // The sweep's FIRST sample is exactly `start` and its LAST is exactly `end`
247    // (`breaks` opens at `start` and closes at `end`, and index 0 / index
248    // `samples_per_span` hit a span's own ends), so closure costs no extra
249    // evaluation: keep those two points and compare them.
250    let mut start_point = None;
251    let mut end_point = None;
252    // The sampled polyline's own nearest approach, and the seed interval that
253    // achieves it. Squared throughout, so the sweep pays no square root.
254    let mut previous: Option<(f64, Vec3)> = None;
255    let mut witness_distance_squared = f64::INFINITY;
256    let mut witness_low = start;
257    let mut witness_high = start;
258    let mut visit = |parameter, sample: Vec3| {
259        if start_point.is_none() {
260            start_point = Some(sample);
261        }
262        end_point = Some(sample);
263        let distance_squared = sample.sub(point).length_squared();
264        if distance_squared < best_distance_squared {
265            best_distance_squared = distance_squared;
266            best_u = parameter;
267        }
268        if let Some((previous_parameter, previous_sample)) = previous {
269            let segment = point_segment_distance_squared(point, previous_sample, sample);
270            if segment < witness_distance_squared {
271                witness_distance_squared = segment;
272                witness_low = previous_parameter;
273                witness_high = parameter;
274            }
275        }
276        previous = Some((parameter, sample));
277    };
278    if let Some(seeds) = cached_curve_seeds(curve, start, end)? {
279        for &(parameter, sample) in seeds.iter() { visit(parameter, sample); }
280    } else {
281        visit_curve_seeds(curve, start, end, visit)?;
282    }
283    // A closed curve's domain is PERIODIC, so Newton must wrap across the seam
284    // rather than stop at it. Clamping made the projector return the seam for
285    // any query whose foot sits within half a seed spacing of it: `start` and
286    // `end` are the same POINT, the sweep keeps the first of equal distances and
287    // so seeds at `start`, and a Newton step toward a foot just BEFORE the seam
288    // is then clamped back to `start`, reads as a zero-length step, and breaks.
289    // Measured on a rational-quadratic circle of radius 20: 4.796 mm out, for a
290    // point taken off the curve itself. Swapping the sweep's tie-break to keep
291    // the LAST equal sample does not fix this — it mirrors it, returning the
292    // same 4.796 mm for queries just AFTER the seam. The surface projector has
293    // always wrapped (`fit_parameter` at the `project_point_to_surface` Newton
294    // step); this is the curve side catching up.
295    const CLOSED_SEAM_TOLERANCE: f64 = 1e-6;
296    let closed = match (start_point, end_point) {
297        (Some(first), Some(last)) => first.sub(last).length() <= CLOSED_SEAM_TOLERANCE,
298        _ => false,
299    };
300
301    let parameter = curve_newton(
302        curve,
303        point,
304        best_u,
305        start,
306        end,
307        closed,
308        &mut best_u,
309        &mut best_distance_squared,
310    )?;
311    for candidate in [start, end, parameter] {
312        let distance_squared = curve.evaluate(candidate)?.sub(point).length_squared();
313        if distance_squared < best_distance_squared {
314            best_distance_squared = distance_squared;
315            best_u = candidate;
316        }
317    }
318    // AN ANSWER THE SEED POLYLINE REFUTES IS NOT AN ANSWER. The sweep's
319    // consecutive samples are a polyline that approximates the curve, so the
320    // nearest that polyline passes to the query is a witness: the curve
321    // demonstrably comes about that close. When the answer is FARTHER than the
322    // witness by more than a factor of two, Newton converged in the wrong basin
323    // and the seed interval the witness names is where the foot really is.
324    //
325    // Two different defects reach here, both of them "a point ON the curve does
326    // not project to its own parameter", and both measured on real geometry:
327    //
328    // * A STATIONARY seed. Newton is a first-order method and
329    //   `f = C'(t) · (C(t) - P)` vanishes at a stationary parameter for EVERY
330    //   `P`, so the iteration reads convergence there whatever the point is, and
331    //   the step it would otherwise take is `-f/f''`, a second-order quantity
332    //   whose sign has nothing to do with where the foot is. The 2026-09-14
333    //   herringbone document is full of them: a flank pcurve is a two-span cubic
334    //   whose first two control points COINCIDE (an involute's speed is
335    //   `r_base * t`, so its Hermite start tangent is exactly zero), the sweep's
336    //   nearest sample to a query near the start IS that cusp, and a point lying
337    //   exactly on the curve at t = 0.125 answered t = 0, 2.159e-2 out in uv.
338    //   That is the wrong answer `build_loop`'s partial-run rescue declined on.
339    // * A seed grid coarser in ONE span than in the rest. An imported pcurve
340    //   from `abc_00000013.step` carries 511 interior knots whose first span is
341    //   eighty times the width of the median, and five samples per span leave
342    //   its samples 4.6e-3 of uv apart — so a point on the curve at fraction
343    //   0.01 read as 3.969e-3 from a DIFFERENT branch at fraction 0.99, which
344    //   was genuinely nearer than any sample of its own.
345    //
346    // The witness refuted both by 71x and by 293000x. Every update below is a
347    // strict improvement on the distance already found, so a rescue that finds
348    // nothing better leaves the answer exactly where it was.
349    const WITNESS_FACTOR: f64 = 2.0;
350    if witness_distance_squared * (WITNESS_FACTOR * WITNESS_FACTOR) < best_distance_squared
351        && witness_rescue_enabled()
352    {
353        let bracketed = bracketed_nearest(curve, point, witness_low, witness_high)?;
354        let polished = curve_newton(
355            curve,
356            point,
357            bracketed,
358            start,
359            end,
360            closed,
361            &mut best_u,
362            &mut best_distance_squared,
363        )?;
364        for candidate in [bracketed, polished] {
365            let distance_squared = curve.evaluate(candidate)?.sub(point).length_squared();
366            if distance_squared < best_distance_squared {
367                best_distance_squared = distance_squared;
368                best_u = candidate;
369            }
370        }
371    }
372    let projected = curve.evaluate(best_u)?;
373    Ok(CurveProjection {
374        u: best_u,
375        point: projected,
376        distance: projected.sub(point).length(),
377    })
378}
379
380fn project_linear_revolution(
381    surface: &NurbsSurface,
382    point: Vec3,
383) -> Result<Option<SurfaceProjection>, String> {
384    let rows = &surface.control_points;
385    if surface.degree_u != 2
386        || surface.degree_v != 1
387        || rows.len() < 5
388        || rows[0].len() != 2
389        || !surface.closed_directions()?.0
390    {
391        return Ok(None);
392    }
393    let base = rows[0][0].point()?.add(rows[4][0].point()?).scale(0.5);
394    let top = rows[0][1].point()?.add(rows[4][1].point()?).scale(0.5);
395    let axis_vector = top.sub(base);
396    let height = axis_vector.length();
397    if height <= EPSILON {
398        return Ok(None);
399    }
400    let axis = axis_vector.normalized()?;
401    let [v0, v1] = surface.domain_v()?;
402    let axial = point.sub(base).dot(axis).clamp(0.0, height);
403    let v = v0 + (v1 - v0) * axial / height;
404    let circle = surface.iso_curve_v(v)?;
405    let projection = project_point_to_curve(&circle, point)?;
406    let [u0, u1] = surface.domain_u()?;
407    let u = projection.u.clamp(u0, u1);
408    let projected = surface.evaluate(u, v)?;
409    Ok(Some(SurfaceProjection {
410        u,
411        v,
412        point: projected,
413        distance: projected.sub(point).length(),
414    }))
415}
416
417#[derive(Clone, Copy)]
418struct NewtonResult {
419    u: f64,
420    v: f64,
421    distance_squared: f64,
422    converged: bool,
423}
424
425fn surface_newton(
426    surface: &NurbsSurface,
427    point: Vec3,
428    seed_u: f64,
429    seed_v: f64,
430    domains: [f64; 4],
431    closed_u: bool,
432    closed_v: bool,
433) -> Result<NewtonResult, String> {
434    surface_newton_impl(surface, point, seed_u, seed_v, domains, closed_u, closed_v,
435        switch!("BREP_PROJECTION_LAZY_DERIVATIVES", false), LINEAR_TOLERANCE)
436}
437
438/// Most seeded verification queries are already on the carrier. Row zero
439/// uses the same basis and rational arithmetic at counts zero and two; read
440/// it first, preserving the best-point and distance exit, and compute the
441/// remaining derivatives only when Newton actually needs to take a step.
442fn surface_newton_impl(
443    surface: &NurbsSurface,
444    point: Vec3,
445    seed_u: f64,
446    seed_v: f64,
447    domains: [f64; 4],
448    closed_u: bool,
449    closed_v: bool,
450    lazy: bool,
451    linear_tolerance: f64,
452) -> Result<NewtonResult, String> {
453    let [u0, u1, v0, v1] = domains;
454    let mut u = seed_u;
455    let mut v = seed_v;
456    let mut converged = false;
457    let mut best = NewtonResult {
458        u,
459        v,
460        distance_squared: surface.evaluate(u, v)?.sub(point).length_squared(),
461        converged,
462    };
463    // A step is a function of (u, v) alone, so an iterate that returns to an
464    // earlier one bit for bit repeats that stretch until the iteration cap:
465    // no exit fires (none did on the first pass through it), the best point
466    // cannot improve (every state of the stretch has been read, and the
467    // comparison is strict), and the state the cap would leave is the stretch's
468    // state at the cap's index. Take that state now instead of walking there
469    // (`BREP_PROJECTION_NEWTON_CYCLE_EXIT`, default on; `=0` walks). Measured
470    // on one import with fitted high-degree carriers and the projected-foot
471    // refine on: about one Newton call in eighteen ran to the cap, those calls
472    // held half of all Newton iterations, and at least three in five of them
473    // were repeating a stretch of eight states or fewer.
474    let cycle_exit = switch!("BREP_PROJECTION_NEWTON_CYCLE_EXIT", true);
475    let mut trail = [(0u64, 0u64); MAX_NEWTON_ITERATIONS];
476    for iteration in 0..MAX_NEWTON_ITERATIONS {
477        if cycle_exit {
478            let state = (u.to_bits(), v.to_bits());
479            if let Some(first) = trail[..iteration].iter().position(|earlier| *earlier == state) {
480                let period = iteration - first;
481                let (last_u, last_v) = trail[first + (MAX_NEWTON_ITERATIONS - first) % period];
482                u = f64::from_bits(last_u);
483                v = f64::from_bits(last_v);
484                crate::work_counts::add(|c| c.newton_iterations += (MAX_NEWTON_ITERATIONS - iteration) as u64);
485                break;
486            }
487            trail[iteration] = state;
488        }
489        crate::work_counts::add(|c| c.newton_iterations += 1);
490        let derivatives = surface.derivatives_small(u, v, if lazy { 0 } else { 2 })?;
491        let residual = derivatives[0][0].sub(point);
492        let distance_squared = residual.length_squared();
493        if distance_squared < best.distance_squared {
494            best.u = u;
495            best.v = v;
496            best.distance_squared = distance_squared;
497        }
498        let residual_length = distance_squared.sqrt();
499        if residual_length <= linear_tolerance {
500            crate::work_counts::add(|c| { c.newton_unused += 1; c.newton_unused_first += u64::from(iteration == 0); });
501            converged = true;
502            break;
503        }
504        let derivatives = if lazy { surface.derivatives_small(u, v, 2)? } else { derivatives };
505        let f = derivatives[1][0].dot(residual);
506        let g = derivatives[0][1].dot(residual);
507        let tangent_u_length = derivatives[1][0].length();
508        let tangent_v_length = derivatives[0][1].length();
509        let cosine_u = if tangent_u_length * residual_length <= EPSILON {
510            0.0
511        } else {
512            f.abs() / (tangent_u_length * residual_length)
513        };
514        let cosine_v = if tangent_v_length * residual_length <= EPSILON {
515            0.0
516        } else {
517            g.abs() / (tangent_v_length * residual_length)
518        };
519        if cosine_u <= 1e-10 && cosine_v <= 1e-10 {
520            converged = true;
521            break;
522        }
523        let j00 = derivatives[2][0].dot(residual) + derivatives[1][0].length_squared();
524        let j01 = derivatives[1][1].dot(residual) + derivatives[1][0].dot(derivatives[0][1]);
525        let j11 = derivatives[0][2].dot(residual) + derivatives[0][1].length_squared();
526        let determinant = j00 * j11 - j01 * j01;
527        if determinant.abs() <= EPSILON {
528            break;
529        }
530        let mut du = (-f * j11 + g * j01) / determinant;
531        let mut dv = (-g * j00 + f * j01) / determinant;
532        du = du.clamp(-(u1 - u0) / 4.0, (u1 - u0) / 4.0);
533        dv = dv.clamp(-(v1 - v0) / 4.0, (v1 - v0) / 4.0);
534        let next_u = fit_parameter(u + du, u0, u1, closed_u);
535        let next_v = fit_parameter(v + dv, v0, v1, closed_v);
536        let stalled =
537            (next_u - u).abs() <= 1e-15 * (u1 - u0) && (next_v - v).abs() <= 1e-15 * (v1 - v0);
538        u = next_u;
539        v = next_v;
540        if stalled {
541            break;
542        }
543    }
544    let final_distance_squared = surface.evaluate(u, v)?.sub(point).length_squared();
545    if final_distance_squared < best.distance_squared {
546        best.u = u;
547        best.v = v;
548        best.distance_squared = final_distance_squared;
549    }
550    best.converged = converged;
551    Ok(best)
552}
553
554/// Refine an existing branch foot for precision trim construction. The normal
555/// projector's distance exit is an on-carrier admission test, not a bound on
556/// tangential placement suitable for interpolating a more accurate trim.
557pub fn refine_trim_foot(
558    surface: &NurbsSurface, point: Vec3, foot: SurfaceProjection,
559) -> Result<SurfaceProjection, String> {
560    let [u0, u1] = surface.domain_u()?;
561    let [v0, v1] = surface.domain_v()?;
562    let (cu, cv) = surface.closed_directions()?;
563    let result = surface_newton_impl(surface, point, foot.u, foot.v,
564        [u0, u1, v0, v1], cu, cv, false, 1e-11)?;
565    let projected = surface.evaluate(result.u, result.v)?;
566    Ok(SurfaceProjection { u: result.u, v: result.v, point: projected,
567        distance: projected.sub(point).length() })
568}
569
570/// The point of `surface` nearest `point`, over the surface's whole domain.
571///
572/// Analytic carriers answer in closed form; every other surface goes through
573/// `project_point_to_surface_general`, which says what it guarantees.
574/// `#[track_caller]` names the call site in the `BREP_PROJECTION_AUDIT` log.
575#[track_caller]
576pub fn project_point_to_surface(
577    surface: &NurbsSurface,
578    point: Vec3,
579) -> Result<SurfaceProjection, String> {
580    crate::work_counts::add(|c| c.projection_global += 1);
581    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_PROJECT, surface);
582    // Recognized analytic carriers (plane / cylinder / cone / sphere /
583    // torus) have exact closed-form projections in the surface's own
584    // rational parameterization — skip grid seeding and Newton entirely.
585    if let Some(analytic) = surface.analytic() {
586        if let Some(projection) = analytic.project(surface, point) {
587            return Ok(projection);
588        }
589    }
590    if let Some(ellipsoid) = surface.affine_sphere() {
591        if let Some(projection) = ellipsoid.project(surface, point) {
592            return Ok(projection);
593        }
594    }
595    project_point_to_surface_general(surface, point)
596}
597
598/// Project a point onto a surface starting Newton from an explicit `(u, v)`
599/// guess, WITHOUT the global grid seed. This is a footpoint refiner for
600/// continuity-preserving curve-on-surface tracing: seeding each edge sample
601/// from its neighbour's parameters keeps the fit on ONE branch of a surface
602/// that folds back over the small trimmed patch, where an independent global
603/// search would snap to whichever fold is momentarily closest and tear the
604/// pcurve into a self-crossing zig-zag. The caller compares the returned
605/// `distance` against the global answer and only adopts this result when it is
606/// geometrically just as valid, so a bad seed can never make a fit worse.
607pub fn project_point_to_surface_seeded(
608    surface: &NurbsSurface,
609    point: Vec3,
610    seed_u: f64,
611    seed_v: f64,
612) -> Result<SurfaceProjection, String> {
613    crate::work_counts::add(|c| c.projection_seeded += 1);
614    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::SEEDED);
615    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_SEEDED, surface);
616    // An ellipsoid's foot is unique off its medial axis: the closed form IS
617    // the branch answer, as it is for the analytic carriers at the seeded
618    // entry (`project_point_to_surface_from_seed`).
619    if let Some(ellipsoid) = surface.affine_sphere() {
620        if let Some(projection) = ellipsoid.project(surface, point) {
621            return Ok(projection);
622        }
623    }
624    let [u0, u1] = surface.domain_u()?;
625    let [v0, v1] = surface.domain_v()?;
626    let (closed_u, closed_v) = surface.closed_directions()?;
627    let result = surface_newton(
628        surface,
629        point,
630        seed_u,
631        seed_v,
632        [u0, u1, v0, v1],
633        closed_u,
634        closed_v,
635    )?;
636    let projected = surface.evaluate(result.u, result.v)?;
637    Ok(SurfaceProjection {
638        u: result.u,
639        v: result.v,
640        point: projected,
641        distance: projected.sub(point).length(),
642    })
643}
644
645/// The foot of `point` on the branch of `seed`: the closed form on an analytic
646/// carrier, otherwise Newton from the caller's own `(u, v)`
647/// ([`project_point_to_surface_seeded`]), WITHOUT the global search.
648///
649/// **Which callers.** One that already holds a foot on this surface from a
650/// geometrically adjacent query and whose output needs continuity with it: a
651/// pcurve's previous sample, a march's previous station, a Newton's previous
652/// iterate. [`project_point_to_surface`] answers a different question — where
653/// on the WHOLE surface the point is nearest — and on a carrier that comes back
654/// near itself, or for an off-surface query about as far from two sheets, that
655/// answer is a foot on another branch: a pcurve sample on the wrong sheet, an
656/// iterate that jumps. A caller with no such foot (a vertex, a probe, the first
657/// station) asks the nearest-point question and calls the projector.
658///
659/// **An analytic carrier** answers in closed form, as the projector does. Its
660/// only places with two equally valid feet are its seam, its poles and its focal
661/// set (axis, centre, tube circle), and the closed form answers those exactly as
662/// the nearest-point query always has; no march on one changes.
663///
664/// **What it does not promise.** It is a local answer: its distance is an upper
665/// bound, and a Newton that stalls returns its best iterate without saying so.
666/// Every caller keeps its own on-surface check.
667///
668/// **Instruments**, each read once. `BREP_PROJECTION_FROM_SEED=0` returns
669/// [`project_point_to_surface`]'s answer at every caller (the reading before
670/// 2026-09-15, for a same-binary A/B); `BREP_PROJECTION_FROM_SEED_SITES=<a,b,…>`
671/// keeps the seeded answer only at the call sites whose `file:line` contains
672/// one of the substrings. Under `BREP_PROJECTION_AUDIT=<dir>` every query whose
673/// seeded foot lies farther than the on-surface floor from the nearest point's
674/// foot appends one line to `<dir>/projection-seed-audit-<pid>.tsv`. That
675/// comparand is the nearest-point projector under the same caller, so its own
676/// replacements land in `projection-audit-<pid>.tsv` at this site's line: they
677/// are the audit's, not an answer the caller took.
678#[track_caller]
679pub fn project_point_to_surface_from_seed(
680    surface: &NurbsSurface,
681    point: Vec3,
682    seed: [f64; 2],
683) -> Result<SurfaceProjection, String> {
684    crate::work_counts::add(|c| c.projection_from_seed += 1);
685    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::SEEDED);
686    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_FROM_SEED, surface);
687    if let Some(analytic) = surface.analytic() {
688        if let Some(projection) = analytic.project(surface, point) {
689            return Ok(projection);
690        }
691    }
692    if let Some(ellipsoid) = surface.affine_sphere() {
693        if let Some(projection) = ellipsoid.project(surface, point) {
694            return Ok(projection);
695        }
696    }
697    let caller = std::panic::Location::caller();
698    if !seeded_answer_admitted(caller) {
699        return project_point_to_surface_general(surface, point);
700    }
701    let seeded = project_point_to_surface_seeded(surface, point, seed[0], seed[1])?;
702    if seed_audit_enabled() {
703        let nearest = project_point_to_surface_general(surface, point)?;
704        if seeded.point.sub(nearest.point).length() > LINEAR_TOLERANCE {
705            seed_audit_record(caller, surface, seed, &seeded, &nearest);
706        }
707    }
708    Ok(seeded)
709}
710
711/// `BREP_PROJECTION_FROM_SEED=0` / `BREP_PROJECTION_FROM_SEED_SITES`: see
712/// [`project_point_to_surface_from_seed`].
713fn seeded_answer_admitted(caller: &std::panic::Location<'_>) -> bool {
714    static SITES: std::sync::OnceLock<Option<Option<Vec<String>>>> = std::sync::OnceLock::new();
715    let sites = SITES.get_or_init(|| {
716        if std::env::var("BREP_PROJECTION_FROM_SEED").as_deref() == Ok("0") {
717            return None;
718        }
719        Some(std::env::var("BREP_PROJECTION_FROM_SEED_SITES").ok().map(|value| {
720            value.split(',').map(str::to_string).filter(|site| !site.is_empty()).collect()
721        }))
722    });
723    match sites {
724        None => false,
725        Some(None) => true,
726        Some(Some(only)) => {
727            let location = format!("{}:{}", caller.file(), caller.line());
728            only.iter().any(|site| location.contains(site.as_str()))
729        }
730    }
731}
732
733fn seed_audit_enabled() -> bool {
734    debug_flag!("BREP_PROJECTION_AUDIT")
735}
736
737/// One line per seeded answer whose foot is not the nearest point's: the call
738/// site, both distances, the seed, both feet's `(u, v)`, the separation of the
739/// two feet and the surface's shape.
740fn seed_audit_record(
741    caller: &std::panic::Location<'_>,
742    surface: &NurbsSurface,
743    seed: [f64; 2],
744    seeded: &SurfaceProjection,
745    nearest: &SurfaceProjection,
746) {
747    use std::io::Write;
748    static SINK: std::sync::OnceLock<Option<std::sync::Mutex<std::fs::File>>> =
749        std::sync::OnceLock::new();
750    let sink = SINK.get_or_init(|| {
751        let directory = std::env::var_os("BREP_PROJECTION_AUDIT")?;
752        let path = std::path::Path::new(&directory)
753            .join(format!("projection-seed-audit-{}.tsv", std::process::id()));
754        std::fs::OpenOptions::new()
755            .create(true)
756            .append(true)
757            .open(path)
758            .ok()
759            .map(std::sync::Mutex::new)
760    });
761    if let Some(file) = sink {
762        if let Ok(mut file) = file.lock() {
763            let _ = writeln!(
764                file,
765                "{}:{}\t{:.6e}\t{:.6e}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{:.6e}\t{}x{} cp {}x{}",
766                caller.file(),
767                caller.line(),
768                seeded.distance,
769                nearest.distance,
770                seed[0],
771                seed[1],
772                seeded.u,
773                seeded.v,
774                nearest.u,
775                nearest.v,
776                seeded.point.sub(nearest.point).length(),
777                surface.degree_u,
778                surface.degree_v,
779                surface.control_points.len(),
780                surface.control_points.first().map(Vec::len).unwrap_or(0),
781            );
782        }
783    }
784}
785
786/// The Newton seed grid for general projection: (u, v, point) samples over
787/// every knot span. A pure function of the surface, cached on it — building
788/// the grid costs hundreds of evaluations and projection is the hottest
789/// entry point in the kernel.
790fn projection_seed_grid(surface: &NurbsSurface) -> Result<&SampleGrid, String> {
791    if let Some(grid) = surface.projection_grid.get() {
792        return Ok(grid);
793    }
794    let [u0, u1] = surface.domain_u()?;
795    let [v0, v1] = surface.domain_v()?;
796    let (closed_u, closed_v) = surface.closed_directions()?;
797    let mut breaks_u = vec![u0];
798    breaks_u.extend(interior_knots(&surface.knots_u, surface.degree_u));
799    breaks_u.push(u1);
800    let mut breaks_v = vec![v0];
801    breaks_v.extend(interior_knots(&surface.knots_v, surface.degree_v));
802    breaks_v.push(v1);
803    let samples_u = if closed_u {
804        8usize.max(surface.degree_u * 4)
805    } else {
806        3usize.max(surface.degree_u + 1)
807    };
808    let samples_v = if closed_v {
809        8usize.max(surface.degree_v * 4)
810    } else {
811        3usize.max(surface.degree_v + 1)
812    };
813    let mut grid = Vec::new();
814    for u_pair in breaks_u.windows(2) {
815        for v_pair in breaks_v.windows(2) {
816            for i in 0..=samples_u {
817                for j in 0..=samples_v {
818                    let u = u_pair[0] + (u_pair[1] - u_pair[0]) * i as f64 / samples_u as f64;
819                    let v = v_pair[0] + (v_pair[1] - v_pair[0]) * j as f64 / samples_v as f64;
820                    grid.push((u, v, surface.evaluate(u, v)?));
821                }
822            }
823        }
824    }
825    Ok(surface.projection_grid.get_or_init(|| SampleGrid::new(grid)))
826}
827
828/// The dense fallback grid for degenerate general projection: (u, v, point)
829/// over a `(count_u+1) × (count_v+1)` lattice with `count_u/count_v` derived
830/// from the surface's knot spans. A pure function of the surface, cached on
831/// it — on metre-unit-mm parts the degenerate fallback fires ~1.7M times and
832/// each re-evaluated all ~561 lattice points; caching them makes the argmin a
833/// pure distance scan over reused points (bit-identical seed).
834fn projection_dense_grid(surface: &NurbsSurface) -> Result<&SampleGrid, String> {
835    if let Some(grid) = surface.projection_dense_grid.get() {
836        return Ok(grid);
837    }
838    let [u0, u1] = surface.domain_u()?;
839    let [v0, v1] = surface.domain_v()?;
840    let mut breaks_u = vec![u0];
841    breaks_u.extend(interior_knots(&surface.knots_u, surface.degree_u));
842    breaks_u.push(u1);
843    let mut breaks_v = vec![v0];
844    breaks_v.extend(interior_knots(&surface.knots_v, surface.degree_v));
845    breaks_v.push(v1);
846    let count_u = 32usize.max((breaks_u.len() - 1) * 8);
847    let count_v = 16usize.max((breaks_v.len() - 1) * 8);
848    let mut grid = Vec::with_capacity((count_u + 1) * (count_v + 1));
849    for i in 0..=count_u {
850        for j in 0..=count_v {
851            let u = u0 + (u1 - u0) * i as f64 / count_u as f64;
852            let v = v0 + (v1 - v0) * j as f64 / count_v as f64;
853            grid.push((u, v, surface.evaluate(u, v)?));
854        }
855    }
856    Ok(surface.projection_dense_grid.get_or_init(|| SampleGrid::with_tree(grid)))
857}
858
859/// Samples per block of a [`SampleGrid`].
860const SAMPLE_BLOCK: usize = 32;
861
862/// Runs per group: the scan's second level, a box over [`GROUP_BLOCKS`]
863/// consecutive runs ([`SampleGrid::groups`]).
864const GROUP_BLOCKS: usize = 32;
865
866/// A cached `(u, v, point)` sample grid, with the axis-aligned box of each run
867/// of [`SAMPLE_BLOCK`] consecutive samples, so the nearest-sample scan
868/// ([`nearest_sample`]) skips a run none of whose samples can beat the answer
869/// it holds.
870#[derive(Clone, Debug)]
871pub struct SampleGrid {
872    samples: Vec<(f64, f64, Vec3)>,
873    blocks: Vec<SampleBlock>,
874    /// The union box of each [`GROUP_BLOCKS`] consecutive runs, prunable only
875    /// when every run in it is. A union box's floor is at most each of its
876    /// runs' floors as computed (the box faces are the runs' own, and the gap
877    /// to a face farther out is no larger, IEEE rounding being monotone).
878    groups: Vec<SampleBlock>,
879    /// The box tree over the runs ([`nearest_sample_tree`]): `tree[0]` boxes
880    /// each [`TREE_FANOUT`] consecutive runs, `tree[k]` each [`TREE_FANOUT`]
881    /// consecutive boxes of `tree[k - 1]`, up to a single root. Built only by
882    /// [`SampleGrid::with_tree`] (the dense grid), and empty when the grid has
883    /// at most one group of runs.
884    tree: Vec<Vec<SampleBlock>>,
885}
886
887/// Children per node of [`SampleGrid::tree`].
888const TREE_FANOUT: usize = 4;
889
890/// The union box of consecutive boxes, prunable only when each of them is.
891fn union_boxes(boxes: &[SampleBlock]) -> Vec<SampleBlock> {
892    boxes
893        .chunks(TREE_FANOUT)
894        .map(|chunk| {
895            let mut union = chunk[0];
896            for block in chunk {
897                union.low = Vec3::new(union.low.x.min(block.low.x), union.low.y.min(block.low.y), union.low.z.min(block.low.z));
898                union.high = Vec3::new(union.high.x.max(block.high.x), union.high.y.max(block.high.y), union.high.z.max(block.high.z));
899                union.prunable &= block.prunable;
900            }
901            union
902        })
903        .collect()
904}
905
906/// One run's box. `prunable` is false when a sample has a non-finite
907/// coordinate: the box says nothing about it, and the run is always scanned.
908#[derive(Clone, Copy, Debug)]
909struct SampleBlock {
910    low: Vec3,
911    high: Vec3,
912    prunable: bool,
913}
914
915impl SampleGrid {
916    fn new(samples: Vec<(f64, f64, Vec3)>) -> Self {
917        let blocks = samples
918            .chunks(SAMPLE_BLOCK)
919            .map(|chunk| {
920                let mut low = chunk[0].2;
921                let mut high = low;
922                let mut prunable = true;
923                for &(_, _, p) in chunk {
924                    prunable &= p.x.is_finite() && p.y.is_finite() && p.z.is_finite();
925                    low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
926                    high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
927                }
928                SampleBlock { low, high, prunable }
929            })
930            .collect::<Vec<_>>();
931        let groups = blocks
932            .chunks(GROUP_BLOCKS)
933            .map(|chunk| {
934                let mut group = chunk[0];
935                for block in chunk {
936                    group.low = Vec3::new(group.low.x.min(block.low.x), group.low.y.min(block.low.y), group.low.z.min(block.low.z));
937                    group.high = Vec3::new(group.high.x.max(block.high.x), group.high.y.max(block.high.y), group.high.z.max(block.high.z));
938                    group.prunable &= block.prunable;
939                }
940                group
941            })
942            .collect();
943        Self { samples, blocks, groups, tree: Vec::new() }
944    }
945
946    /// The grid with its box tree, for a scan that starts from a held answer
947    /// (the dense fallback after a Newton): there the tree reads few floors.
948    /// A scan from no answer reads its bound from a greedy descent, which on a
949    /// surface whose boxes mostly hold the point lands on an arbitrary run;
950    /// ABC 00027566's seed scans took 75 s through the tree against 44 s
951    /// through the groups, so the seed grid keeps the groups.
952    fn with_tree(samples: Vec<(f64, f64, Vec3)>) -> Self {
953        let mut grid = Self::new(samples);
954        if grid.blocks.len() > GROUP_BLOCKS {
955            grid.tree.push(union_boxes(&grid.blocks));
956            while grid.tree.last().is_some_and(|level| level.len() > 1) {
957                let next = union_boxes(grid.tree.last().unwrap());
958                grid.tree.push(next);
959            }
960        }
961        grid
962    }
963}
964
965impl SampleBlock {
966    /// A floor on `sample.sub(point).length_squared()` over the run's samples,
967    /// as COMPUTED, not only as real numbers: per axis the gap from `point` to
968    /// the box is the same subtraction against the box face, and IEEE rounding
969    /// is monotone, so `|fl(s - p)| >= fl(face - p)`; squaring and the same
970    /// left-to-right sum of non-negative terms keep the order (`Vec3::dot`
971    /// has no fused multiply-add). A NaN `point` reads gaps of 0 and every
972    /// distance is NaN, which no scan takes, so skipping changes nothing.
973    fn lower_bound(&self, point: Vec3) -> f64 {
974        let gap = |p: f64, low: f64, high: f64| {
975            if p < low {
976                low - p
977            } else if p > high {
978                p - high
979            } else {
980                0.0
981            }
982        };
983        let x = gap(point.x, self.low.x, self.high.x);
984        let y = gap(point.y, self.low.y, self.high.y);
985        let z = gap(point.z, self.low.z, self.high.z);
986        x * x + y * y + z * z
987    }
988}
989
990/// `BREP_PROJECTION_PRUNED_SCAN=0` scans every sample, as before 2026-11-10,
991/// for a same-binary A/B. Read once per process.
992fn pruned_scan() -> bool {
993    switch!("BREP_PROJECTION_PRUNED_SCAN", true)
994}
995
996/// Replace `best` with the grid's nearest sample when that is strictly nearer,
997/// the first such in scan order: the bits of the linear scan, which this was
998/// until 2026-11-10. A run is skipped only when its box's floor is not below
999/// the distance held, so none of its samples could have replaced it (the
1000/// strict `<`), or lies above the bound read first ([`bound_first_scan`]),
1001/// and the runs are visited in scan order. ABC 00027566's
1002/// 166-span rational faces take the dense fallback on 71% of their pcurve
1003/// probes (the first Newton not converged), each scanning 22.7k samples: 9.1 s
1004/// of a face's 11.5 s of local answers.
1005fn nearest_sample(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult) {
1006    if !grid.tree.is_empty() && scan_tree() && pruned_scan() && bound_first_scan() {
1007        nearest_sample_tree(grid, point, best);
1008        return;
1009    }
1010    nearest_sample_with(grid, point, best, pruned_scan(), bound_first_scan());
1011}
1012
1013/// `BREP_PROJECTION_SCAN_TREE=0` scans through the two levels of groups and
1014/// runs alone, as before 2026-11-11, for a same-binary A/B. Read once per
1015/// process.
1016///
1017/// With it on, a grid built with a tree ([`SampleGrid::with_tree`]: the dense
1018/// grid, when it has more than one group) is scanned through
1019/// [`SampleGrid::tree`]. ABC 00027566's dense fallback on its 166-span faces
1020/// passed 52 of 287 group boxes per call (a group is a strip across the
1021/// surface, and many strips' boxes hold a point on it) and then read 1680 run
1022/// floors to scan 0.65 runs, never improving the answer it held: 26 s of floors
1023/// at one pcurve site.
1024fn scan_tree() -> bool {
1025    switch!("BREP_PROJECTION_SCAN_TREE", true)
1026}
1027
1028/// `BREP_PROJECTION_SCAN_HINT=0` reads the bound from the descent alone, as
1029/// before 2026-11-11, for a same-binary A/B. Read once per process.
1030///
1031/// With it on, a bound-first scan also reads the run that held the answer of
1032/// the last scan of the same grid on this thread. Consecutive queries are
1033/// mostly neighbours (a pcurve's probes): ABC 00027566's busiest pcurve site
1034/// found its answer in the previous answer's run on 98.8% of seed scans, while
1035/// the descent's run held it on 40%; with the hint the bound is the answer on
1036/// 99.4% and the seed scans there fell from 43.6 s to 18.4 s.
1037fn scan_hint() -> bool {
1038    switch!("BREP_PROJECTION_SCAN_HINT", true)
1039}
1040
1041const HINT_SLOTS: usize = 8;
1042
1043thread_local! {
1044    /// Direct-mapped by grid address: (grid samples address, run of its last answer).
1045    static SCAN_HINTS: std::cell::Cell<[(usize, usize); HINT_SLOTS]> =
1046        const { std::cell::Cell::new([(0, usize::MAX); HINT_SLOTS]) };
1047}
1048
1049fn hint_slot(grid: &SampleGrid) -> (usize, usize) {
1050    let address = grid.samples.as_ptr() as usize;
1051    (address, (address >> 4) % HINT_SLOTS)
1052}
1053
1054/// The bound lowered by the hinted run's samples. The hint is only a run
1055/// index: it is range-checked and read from the grid in hand, so a stale one
1056/// (another grid at a reused address) costs time, never bits. It lowers the
1057/// BOUND alone, never the answer held: each value it can take is a real
1058/// sample distance, at least the grid's least distance `m`, which is all the
1059/// bound-first argument asks of it.
1060fn hinted_bound(grid: &SampleGrid, point: Vec3, mut bound: f64) -> f64 {
1061    if !scan_hint() {
1062        return bound;
1063    }
1064    let (address, slot) = hint_slot(grid);
1065    let (held, run) = SCAN_HINTS.with(|hints| hints.get()[slot]);
1066    if held != address || run >= grid.blocks.len() || !grid.blocks[run].prunable {
1067        return bound;
1068    }
1069    let start = run * SAMPLE_BLOCK;
1070    let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1071    for &(_, _, sample) in &grid.samples[start..end] {
1072        let distance_squared = sample.sub(point).length_squared();
1073        if distance_squared < bound {
1074            bound = distance_squared;
1075        }
1076    }
1077    bound
1078}
1079
1080/// Remember the run that last improved the answer of a scan of `grid`.
1081fn remember_hint(grid: &SampleGrid, run: Option<usize>) {
1082    if let Some(run) = run.filter(|_| scan_hint()) {
1083        let (address, slot) = hint_slot(grid);
1084        SCAN_HINTS.with(|hints| {
1085            let mut all = hints.get();
1086            all[slot] = (address, run);
1087            hints.set(all);
1088        });
1089    }
1090}
1091
1092/// [`nearest_sample_with`]'s bound-first scan over the box tree: the bound is
1093/// read from the run reached by descending from the root through the child of
1094/// lowest floor (a real sample distance, or the incoming one, so never below
1095/// the grid's least distance `m`), then the tree is visited depth first in
1096/// scan order, skipping a box whose floor is at or above the distance held or
1097/// strictly above the bound. A union box's floor is at most each of its
1098/// children's as computed (the box faces are theirs, and IEEE rounding is
1099/// monotone), so a box is skipped only when every run under it would have
1100/// been, and the runs that are read are read in scan order: the bits of the
1101/// linear scan, by the argument [`nearest_sample_with`] gives for its groups.
1102fn nearest_sample_tree(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult) {
1103    let top = grid.tree.len() - 1;
1104    let mut bound = best.distance_squared;
1105    // Descend: at each level the child of lowest floor among the prunable ones.
1106    let mut node = 0usize;
1107    let mut reached = true;
1108    for level in (0..=top).rev() {
1109        let children = |count: usize| node * TREE_FANOUT..((node + 1) * TREE_FANOUT).min(count);
1110        let below = if level == 0 { &grid.blocks } else { &grid.tree[level - 1] };
1111        match lowest_floor(below, children(below.len()), point) {
1112            Some(child) => node = child,
1113            None => {
1114                reached = false;
1115                break;
1116            }
1117        }
1118    }
1119    if reached {
1120        let start = node * SAMPLE_BLOCK;
1121        let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1122        for &(_, _, sample) in &grid.samples[start..end] {
1123            let distance_squared = sample.sub(point).length_squared();
1124            if distance_squared < bound {
1125                bound = distance_squared;
1126            }
1127        }
1128    }
1129    let bound = hinted_bound(grid, point, bound);
1130    let skip = |box_: &SampleBlock, held: f64| {
1131        if !box_.prunable {
1132            return false;
1133        }
1134        let floor = box_.lower_bound(point);
1135        floor >= held || floor > bound
1136    };
1137    let mut answer_run = None;
1138    // Depth first in scan order: (level, index), level 0 of the stack meaning a run.
1139    let mut stack: Vec<(usize, usize)> = Vec::with_capacity(TREE_FANOUT * (top + 2));
1140    stack.push((top + 1, 0));
1141    while let Some((level, index)) = stack.pop() {
1142        if level == 0 {
1143            if skip(&grid.blocks[index], best.distance_squared) {
1144                continue;
1145            }
1146            let start = index * SAMPLE_BLOCK;
1147            let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1148            let held = best.distance_squared;
1149            scan_run(&grid.samples[start..end], point, best);
1150            if best.distance_squared < held {
1151                answer_run = Some(index);
1152            }
1153            continue;
1154        }
1155        if skip(&grid.tree[level - 1][index], best.distance_squared) {
1156            continue;
1157        }
1158        let count = if level == 1 { grid.blocks.len() } else { grid.tree[level - 2].len() };
1159        let children = index * TREE_FANOUT..((index + 1) * TREE_FANOUT).min(count);
1160        // Pushed last-first so they pop in scan order.
1161        for child in children.rev() {
1162            stack.push((level - 1, child));
1163        }
1164    }
1165    remember_hint(grid, answer_run);
1166}
1167
1168/// `BREP_PROJECTION_BOUND_FIRST=0` prunes against the distance held alone, as
1169/// on 2026-11-10 before this pass, for a same-binary A/B. Read once per
1170/// process.
1171///
1172/// With it on, the runs are boxed again in groups of [`GROUP_BLOCKS`]. The scan
1173/// first reads the run of lowest floor inside the group of lowest floor and
1174/// takes the nearest of its samples as a BOUND, then visits the groups and
1175/// their runs in scan order, skipping any whose floor is at or above the
1176/// distance held or strictly above that bound. The runs alone started the seed
1177/// scan from no answer (its incoming distance is infinite), so every run ahead
1178/// of the nearest sample was read before the held distance fell, and every
1179/// scan computed one floor per run: on ABC 00027566 the seed
1180/// scans averaged 63k samples (361 s over 5M calls) and the dense ones 180k
1181/// (167 s over 3.5M), while a bound over the runs alone cut the first to 190 s
1182/// but doubled the second to 311 s with its extra pass of floors.
1183fn bound_first_scan() -> bool {
1184    switch!("BREP_PROJECTION_BOUND_FIRST", true)
1185}
1186
1187/// The scan behind [`nearest_sample`]. With `bound_first`, the bound is the
1188/// smaller of the incoming distance and one real sample distance, so it is
1189/// never below the grid's least distance `m`. The first sample at `m` lies in
1190/// a run whose floor is at most `m`, hence not above the bound and not at or
1191/// above the distance held when the scan reaches it (every sample before it is
1192/// strictly farther than `m`): that run is read and the sample taken, as the
1193/// linear scan takes it, and nothing after it is strictly nearer. A run whose
1194/// floor is above the bound holds no sample at `m`. The bound pass reads only
1195/// prunable runs, and updates on a strict `<`, so a NaN never enters it.
1196fn nearest_sample_with(grid: &SampleGrid, point: Vec3, best: &mut NewtonResult, pruned: bool, bound_first: bool) {
1197    if !(pruned && bound_first) {
1198        for (block, chunk) in grid.blocks.iter().zip(grid.samples.chunks(SAMPLE_BLOCK)) {
1199            if pruned && block.prunable && block.lower_bound(point) >= best.distance_squared {
1200                continue;
1201            }
1202            scan_run(chunk, point, best);
1203        }
1204        return;
1205    }
1206    // The bound: one real sample distance (or the incoming one), from the run
1207    // of lowest floor inside the group of lowest floor.
1208    let mut bound = best.distance_squared;
1209    let lowest_group = lowest_floor(&grid.groups, 0..grid.groups.len(), point);
1210    if let Some(group) = lowest_group {
1211        let runs = group * GROUP_BLOCKS..((group + 1) * GROUP_BLOCKS).min(grid.blocks.len());
1212        if let Some(run) = lowest_floor(&grid.blocks, runs, point) {
1213            let start = run * SAMPLE_BLOCK;
1214            let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1215            for &(_, _, sample) in &grid.samples[start..end] {
1216                let distance_squared = sample.sub(point).length_squared();
1217                if distance_squared < bound {
1218                    bound = distance_squared;
1219                }
1220            }
1221        }
1222    }
1223    let bound = hinted_bound(grid, point, bound);
1224    let skip = |box_: &SampleBlock, held: f64| {
1225        if !box_.prunable {
1226            return false;
1227        }
1228        let floor = box_.lower_bound(point);
1229        floor >= held || floor > bound
1230    };
1231    let mut answer_run = None;
1232    for (group_index, group) in grid.groups.iter().enumerate() {
1233        if skip(group, best.distance_squared) {
1234            continue;
1235        }
1236        let first = group_index * GROUP_BLOCKS;
1237        let last = (first + GROUP_BLOCKS).min(grid.blocks.len());
1238        for run in first..last {
1239            if skip(&grid.blocks[run], best.distance_squared) {
1240                continue;
1241            }
1242            let start = run * SAMPLE_BLOCK;
1243            let end = (start + SAMPLE_BLOCK).min(grid.samples.len());
1244            let held = best.distance_squared;
1245            scan_run(&grid.samples[start..end], point, best);
1246            if best.distance_squared < held {
1247                answer_run = Some(run);
1248            }
1249        }
1250    }
1251    remember_hint(grid, answer_run);
1252}
1253
1254/// The linear scan of one run: strict `<`, so the first of equal samples
1255/// stands.
1256fn scan_run(run: &[(f64, f64, Vec3)], point: Vec3, best: &mut NewtonResult) {
1257    for &(u, v, sample) in run {
1258        let distance_squared = sample.sub(point).length_squared();
1259        if distance_squared < best.distance_squared {
1260            best.u = u;
1261            best.v = v;
1262            best.distance_squared = distance_squared;
1263        }
1264    }
1265}
1266
1267/// The index, within `range`, of the prunable box of least floor (the first
1268/// on a tie), or None when none is prunable.
1269fn lowest_floor(boxes: &[SampleBlock], range: std::ops::Range<usize>, point: Vec3) -> Option<usize> {
1270    let mut lowest: Option<(usize, f64)> = None;
1271    for index in range {
1272        let box_ = &boxes[index];
1273        if !box_.prunable {
1274            continue;
1275        }
1276        let floor = box_.lower_bound(point);
1277        if lowest.is_none_or(|(_, held)| floor < held) {
1278            lowest = Some((index, floor));
1279        }
1280    }
1281    lowest.map(|(index, _)| index)
1282}
1283
1284// Boundary-ring cache geometry: 4 sides × 22 exponents × 33 indices. The scan
1285// positions depend only on the surface domain and these fixed integers, so the
1286// evaluated points are a pure function of the surface and cacheable.
1287const RING_EXPONENTS: usize = 22;
1288const RING_INDICES: usize = 33; // index 0..=32
1289
1290#[inline]
1291fn ring_slot(side: usize, exponent_index: usize, index: usize) -> usize {
1292    (side * RING_EXPONENTS + exponent_index) * RING_INDICES + index
1293}
1294
1295/// The boundary-ring sample points for the degenerate projection fallback,
1296/// flattened by `ring_slot(side, exponent-1, index)`. Sides: 0 = v-low
1297/// (`v = v0 + (v1-v0)·offset`), 1 = v-high (`v1 - (v1-v0)·offset`), 2 = u-low
1298/// (`u0 + (u1-u0)·offset`), 3 = u-high (`u1 - (u1-u0)·offset`), where
1299/// `offset = 1/2^exponent`. A pure function of the surface, cached on it — the
1300/// fallback's boundary ring re-evaluated these on every one of ~1.7M calls.
1301fn projection_ring_grid(surface: &NurbsSurface) -> Result<&[Vec3], String> {
1302    if let Some(grid) = surface.projection_ring_grid.get() {
1303        return Ok(grid);
1304    }
1305    let [u0, u1] = surface.domain_u()?;
1306    let [v0, v1] = surface.domain_v()?;
1307    let mut grid = vec![Vec3::default(); 4 * RING_EXPONENTS * RING_INDICES];
1308    for exponent in 1..=RING_EXPONENTS as i32 {
1309        let offset = 1.0 / 2f64.powi(exponent);
1310        let e = exponent as usize - 1;
1311        let v_lo = v0 + (v1 - v0) * offset;
1312        let v_hi = v1 - (v1 - v0) * offset;
1313        let u_lo = u0 + (u1 - u0) * offset;
1314        let u_hi = u1 - (u1 - u0) * offset;
1315        for index in 0..=32 {
1316            let u = u0 + (u1 - u0) * index as f64 / 32.0;
1317            grid[ring_slot(0, e, index as usize)] = surface.evaluate(u, v_lo)?;
1318            grid[ring_slot(1, e, index as usize)] = surface.evaluate(u, v_hi)?;
1319        }
1320        for index in 0..=32 {
1321            let v = v0 + (v1 - v0) * index as f64 / 32.0;
1322            grid[ring_slot(2, e, index as usize)] = surface.evaluate(u_lo, v)?;
1323            grid[ring_slot(3, e, index as usize)] = surface.evaluate(u_hi, v)?;
1324        }
1325    }
1326    Ok(surface.projection_ring_grid.get_or_init(|| grid))
1327}
1328
1329/// The LOCAL answer: Newton from the seed grid's single nearest sample (or the
1330/// linear-revolution foot), with the degenerate-parameterization fallbacks.
1331///
1332/// This is the whole of what the general projector returned before
1333/// 2026-09-14, and it is a local minimum, not the minimum: on a general patch
1334/// nearly closed in one direction the nearest sample can sit on the far end,
1335/// and Newton converges there (abc_00000026's thread flanks, 2.16e-2 .. 4.1e-2
1336/// against a true 1e-13). [`project_point_to_surface_general`] runs it first
1337/// and keeps its answer wherever no other basin beats it.
1338fn nearest_seed_answer(
1339    surface: &NurbsSurface,
1340    point: Vec3,
1341    [u0, u1, v0, v1]: [f64; 4],
1342    closed_u: bool,
1343    closed_v: bool,
1344) -> Result<NewtonResult, String> {
1345    let mut best = NewtonResult {
1346        u: u0,
1347        v: v0,
1348        distance_squared: f64::INFINITY,
1349        converged: false,
1350    };
1351    nearest_sample(projection_seed_grid(surface)?, point, &mut best);
1352    if let Some(revolution) = project_linear_revolution(surface, point)? {
1353        if revolution.distance * revolution.distance < best.distance_squared {
1354            best.u = revolution.u;
1355            best.v = revolution.v;
1356            best.distance_squared = revolution.distance * revolution.distance;
1357        }
1358    }
1359    let first_newton = surface_newton(
1360        surface,
1361        point,
1362        best.u,
1363        best.v,
1364        [u0, u1, v0, v1],
1365        closed_u,
1366        closed_v,
1367    )?;
1368    if first_newton.distance_squared < best.distance_squared {
1369        best = first_newton;
1370    }
1371    let (_, su, sv) = surface.deriv1(best.u, best.v)?;
1372    let degenerate = su.cross(sv).length() <= 1e-5 * (1.0 + su.length() + sv.length());
1373    if degenerate || !first_newton.converged {
1374        let mut grid = best;
1375        nearest_sample(projection_dense_grid(surface)?, point, &mut grid);
1376        if grid.distance_squared < best.distance_squared {
1377            best = grid;
1378        }
1379        let polished = surface_newton(
1380            surface,
1381            point,
1382            grid.u,
1383            grid.v,
1384            [u0, u1, v0, v1],
1385            closed_u,
1386            closed_v,
1387        )?;
1388        if polished.distance_squared < best.distance_squared {
1389            best = polished;
1390        }
1391
1392        let (_, su, sv) = surface.deriv1(best.u, best.v)?;
1393        if su.cross(sv).length() <= 1e-5 * (1.0 + su.length() + sv.length()) {
1394            let ring_grid = projection_ring_grid(surface)?;
1395            let mut ring = best;
1396            // Read the pre-evaluated ring points at the exact same parameter
1397            // positions the live scans used (side/exponent/index → `ring_slot`),
1398            // preserving scan order and argmin tie-breaking for bit-identity.
1399            let scan = |side: usize,
1400                        exponent_index: usize,
1401                        along_u: bool,
1402                        fixed: f64,
1403                        candidate: &mut NewtonResult| {
1404                for index in 0..=32 {
1405                    let moving = if along_u {
1406                        u0 + (u1 - u0) * index as f64 / 32.0
1407                    } else {
1408                        v0 + (v1 - v0) * index as f64 / 32.0
1409                    };
1410                    let (u, v) = if along_u {
1411                        (moving, fixed)
1412                    } else {
1413                        (fixed, moving)
1414                    };
1415                    let distance_squared = ring_grid
1416                        [ring_slot(side, exponent_index, index as usize)]
1417                    .sub(point)
1418                    .length_squared();
1419                    if distance_squared < candidate.distance_squared {
1420                        candidate.u = u;
1421                        candidate.v = v;
1422                        candidate.distance_squared = distance_squared;
1423                    }
1424                }
1425            };
1426            for exponent in 1..=22 {
1427                let offset = 1.0 / 2f64.powi(exponent);
1428                let e = exponent as usize - 1;
1429                if (best.v - v0).abs() <= (v1 - v0) * 0.02 {
1430                    scan(0, e, true, v0 + (v1 - v0) * offset, &mut ring);
1431                }
1432                if (best.v - v1).abs() <= (v1 - v0) * 0.02 {
1433                    scan(1, e, true, v1 - (v1 - v0) * offset, &mut ring);
1434                }
1435                if (best.u - u0).abs() <= (u1 - u0) * 0.02 {
1436                    scan(2, e, false, u0 + (u1 - u0) * offset, &mut ring);
1437                }
1438                if (best.u - u1).abs() <= (u1 - u0) * 0.02 {
1439                    scan(3, e, false, u1 - (u1 - u0) * offset, &mut ring);
1440                }
1441            }
1442            if ring.distance_squared < best.distance_squared {
1443                best = ring;
1444            }
1445            let polished = surface_newton(
1446                surface,
1447                point,
1448                ring.u,
1449                ring.v,
1450                [u0, u1, v0, v1],
1451                closed_u,
1452                closed_v,
1453            )?;
1454            if polished.distance_squared < best.distance_squared {
1455                best = polished;
1456            }
1457        }
1458    }
1459    Ok(best)
1460}
1461
1462/// Escape hatch for A/B measurement: `BREP_PROJECTION_GLOBAL=0` returns the
1463/// local answer alone ([`nearest_seed_answer`], the pre-2026-09-14 projector),
1464/// so a population run can be repeated with and without the global stage from
1465/// one binary. Read once.
1466fn global_stage_enabled() -> bool {
1467    switch!("BREP_PROJECTION_GLOBAL", true)
1468}
1469
1470/// `BREP_PROJECTION_GLOBAL_SITES=<a,b,…>`: the global stage's answer is kept
1471/// only for call sites whose `file:line` contains one of the comma-separated
1472/// substrings, and the local answer is returned everywhere else — so a result
1473/// that moves can be attributed to the call site that moved it.
1474/// `BREP_PROJECTION_GLOBAL_EXCEPT=<a,b,…>` is the complement: every site but
1475/// those. Unset: every site. Read once.
1476/// Whether a `BREP_PROJECTION_GLOBAL_SITES`/`_EXCEPT` filter is set, i.e.
1477/// whether [`project_point_to_surface`]'s answer can depend on its call site.
1478pub fn global_site_filter_active() -> bool {
1479    // Read once per process, like the site lists `global_answer_admitted`
1480    // reads: the common reader asks this for every probe (two `getenv` calls,
1481    // ~3.7% of the elephant's B12 prefix on the production sampler,
1482    // 2026-11-02), and nothing sets these variables after start-up.
1483    static ACTIVE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1484    *ACTIVE.get_or_init(|| {
1485        std::env::var_os("BREP_PROJECTION_GLOBAL_SITES").is_some() || std::env::var_os("BREP_PROJECTION_GLOBAL_EXCEPT").is_some()
1486    })
1487}
1488
1489fn global_answer_admitted(caller: &std::panic::Location<'_>) -> bool {
1490    fn list(name: &str) -> Option<Vec<String>> {
1491        std::env::var(name)
1492            .ok()
1493            .map(|value| value.split(',').map(str::to_string).filter(|site| !site.is_empty()).collect())
1494    }
1495    static SITES: std::sync::OnceLock<(Option<Vec<String>>, Option<Vec<String>>)> =
1496        std::sync::OnceLock::new();
1497    let (only, except) = SITES.get_or_init(|| {
1498        (list("BREP_PROJECTION_GLOBAL_SITES"), list("BREP_PROJECTION_GLOBAL_EXCEPT"))
1499    });
1500    if only.is_none() && except.is_none() {
1501        return true;
1502    }
1503    let location = format!("{}:{}", caller.file(), caller.line());
1504    let named = |sites: &Vec<String>| sites.iter().any(|site| location.contains(site.as_str()));
1505    only.as_ref().is_none_or(named) && !except.as_ref().is_some_and(named)
1506}
1507
1508/// `BREP_PROJECTION_AUDIT=<dir>`: every query on which the global stage
1509/// replaces the local answer appends one tab-separated line to
1510/// `<dir>/projection-audit-<pid>.tsv` — the call site, the local and the
1511/// global distance, both feet's `(u, v)` and the surface's shape. Per process,
1512/// because the case gate forks a child per case and loses its stderr.
1513fn audit_record(caller: &std::panic::Location<'_>, surface: &NurbsSurface, local: &NewtonResult, global: &NewtonResult) {
1514    use std::io::Write;
1515    static SINK: std::sync::OnceLock<Option<std::sync::Mutex<std::fs::File>>> =
1516        std::sync::OnceLock::new();
1517    let sink = SINK.get_or_init(|| {
1518        let directory = std::env::var_os("BREP_PROJECTION_AUDIT")?;
1519        let path = std::path::Path::new(&directory)
1520            .join(format!("projection-audit-{}.tsv", std::process::id()));
1521        std::fs::OpenOptions::new()
1522            .create(true)
1523            .append(true)
1524            .open(path)
1525            .ok()
1526            .map(std::sync::Mutex::new)
1527    });
1528    if let Some(file) = sink {
1529        if let Ok(mut file) = file.lock() {
1530            let _ = writeln!(
1531                file,
1532                "{}:{}\t{:.6e}\t{:.6e}\t{:.9}\t{:.9}\t{:.9}\t{:.9}\t{}x{} cp {}x{}",
1533                caller.file(),
1534                caller.line(),
1535                local.distance_squared.sqrt(),
1536                global.distance_squared.sqrt(),
1537                local.u,
1538                local.v,
1539                global.u,
1540                global.v,
1541                surface.degree_u,
1542                surface.degree_v,
1543                surface.control_points.len(),
1544                surface.control_points.first().map(Vec::len).unwrap_or(0),
1545            );
1546        }
1547    }
1548}
1549
1550/// The point of a general surface nearest `point`: the least local minimum of
1551/// the distance over the surface's whole domain.
1552///
1553/// **What it does.** First the local answer ([`nearest_seed_answer`]: Newton
1554/// from the nearest seed-grid sample, with its degenerate fallbacks — the whole
1555/// projector before 2026-09-14). Then the global stage ([`global_minimum`]):
1556/// the domain is cut into the cells of the projection lattice (every knot span
1557/// sampled `max(3, degree + 1)` times in an open direction and
1558/// `max(8, 4 × degree)` times in a closed one — the seed grid's own density),
1559/// and each cell is enclosed in a box built from the control points of the
1560/// surface REFINED to that cell. A NURBS patch with positive weights lies in
1561/// the convex hull of the control points that support it, so the distance from
1562/// the query to a cell's box is a rigorous LOWER bound on the distance to every
1563/// surface point of the cell. Every cell whose bound is below the best answer
1564/// so far is a candidate basin, and is refined by a descent confined to the
1565/// cell ([`confined_descent`]: Newton where the Hessian is positive definite,
1566/// the metric-scaled gradient where it is not, halved until the distance does
1567/// not rise, so it can end at a minimum but not at a saddle or a maximum),
1568/// seeded at the cell's nearest lattice node and continued over the domain
1569/// when the cell's least point is on its edge. The least answer wins. A closed
1570/// direction's seam is not special: the lattice spans the whole period, the
1571/// cells on either side of the seam are ordinary cells, and the continuation
1572/// wraps.
1573///
1574/// **What is guaranteed.**
1575/// * The answer is a point ON the surface, so its distance never under-reads.
1576/// * Every cell that could hold a point nearer than the answer by more than the
1577///   resolution has been descended in, unless it already held a verified
1578///   minimum: a cell left out was excluded by its hull bound, which cannot
1579///   over-read. [`GlobalStats::hull_lower_bound`] is that certificate: the
1580///   true distance lies in `[hull_lower_bound, answer]`, always.
1581/// * **The one step not certified in general: one basin in the cell that holds
1582///   the least minimum.** A descent finds the basin of its seed. A second basin
1583///   in any OTHER cell costs nothing — that cell's better basin is still no
1584///   nearer than the least minimum — but a second local minimum in the cell
1585///   holding the least minimum can catch the descent seeded at that cell's
1586///   nearest lattice node, and the least minimum is missed by at most
1587///   `answer − hull_lower_bound`. That takes a query past the focal distance of
1588///   part of the cell (farther than its radius of normal curvature on the
1589///   query's side, where the distance's Hessian `G − d·II` stops being positive
1590///   definite) or a cell whose image turns back toward the query. A descent that
1591///   runs out of iterations without a verified minimum fails the same way, with
1592///   the same bound. Seeding every corner of every candidate cell was measured
1593///   and changed no answer on the bench.
1594/// * **Certified on the analytic carriers** — the sphere, torus, cylinder and
1595///   cone, each a revolution of a circle or a line, and the plane. A lattice cell
1596///   there is an (azimuth × generatrix) rectangle under half a turn wide. In the
1597///   cell holding the least minimum the azimuthal derivative of the squared
1598///   distance, `2 ρ(v) ρ_P sin(λ − λ_P)`, vanishes only on the query's own
1599///   meridian, and moving toward that meridian lowers the distance from every
1600///   other point of the cell, so each local minimum over the cell is a local
1601///   minimum of the planar distance from the query's meridian image to the
1602///   generatrix over the cell's `v` range — exactly one on a circle arc under
1603///   half a turn or on a segment. At the focal sets (the axis, the sphere's
1604///   centre, the tube's centre circle) the minimum is a continuum of equal
1605///   distances and every foot is right. A general profile of revolution and a
1606///   general patch are not certified.
1607/// * Where the local answer is already the least minimum, it is returned
1608///   unchanged, bit for bit: the global stage replaces it only with a point
1609///   nearer by more than the resolution.
1610///
1611/// **The two numbers it reads.** The *on-surface floor* is `LINEAR_TOLERANCE`,
1612/// INHERITED unchanged: it is the local Newton's own stopping residual, and a
1613/// local answer within it of the query is on the surface and nothing is
1614/// searched. The *resolution* is the one new number, and it is the surface's
1615/// own: `(degree_u + 1)(degree_v + 1) · ε · scale`, `scale` the largest
1616/// control-point coordinate magnitude — the rounding of one evaluation, which
1617/// sums that many terms of that size. Every box is grown by it, and no
1618/// improvement finer than it is taken.
1619///
1620/// **What it costs.** A query settled by the floor costs what the local answer
1621/// always cost. Any other query builds the cell enclosure once per surface (one
1622/// knot refinement of the net to the lattice, cached on the surface beside the
1623/// seed grid), walks a bounding-sphere tree over the cells, and runs one
1624/// descent per candidate cell the hull bound does not exclude.
1625#[track_caller]
1626pub fn project_point_to_surface_general(
1627    surface: &NurbsSurface,
1628    point: Vec3,
1629) -> Result<SurfaceProjection, String> {
1630    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_GENERAL, surface);
1631    let [u0, u1] = surface.domain_u()?;
1632    let [v0, v1] = surface.domain_v()?;
1633    let (closed_u, closed_v) = surface.closed_directions()?;
1634    let local = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
1635    let mut best = local;
1636    if global_stage_enabled() {
1637        global_minimum(
1638            surface,
1639            point,
1640            [u0, u1, v0, v1],
1641            (closed_u, closed_v),
1642            &mut best,
1643            &mut GlobalStats::default(),
1644        )?;
1645        if best.u != local.u || best.v != local.v {
1646            let caller = std::panic::Location::caller();
1647            if global_answer_admitted(caller) {
1648                audit_record(caller, surface, &local, &best);
1649            } else {
1650                best = local;
1651            }
1652        }
1653    }
1654    let projected = surface.evaluate(best.u, best.v)?;
1655    Ok(SurfaceProjection {
1656        u: best.u,
1657        v: best.v,
1658        point: projected,
1659        distance: projected.sub(point).length(),
1660    })
1661}
1662
1663/// The single-seed inversion by itself: the closed form on an analytic
1664/// carrier, otherwise [`nearest_seed_answer`] — Newton from the seed grid's
1665/// nearest sample, WITHOUT the global stage. Its distance is an upper bound and
1666/// its foot a local minimum. It is not a nearest-point query: it exists for a
1667/// caller that asks a question ABOUT that inversion, and there is one —
1668/// `joint_branch_pcurves` (`io/step_import/builder/rims.rs`) offers a loop the
1669/// joint branch only when this inversion alternates between branches along it,
1670/// which it does on a carrier that comes back within one seed-grid spacing of
1671/// itself (`abc_00000026`'s nearly closed thread flanks).
1672pub fn project_point_to_surface_from_nearest_seed(
1673    surface: &NurbsSurface,
1674    point: Vec3,
1675) -> Result<SurfaceProjection, String> {
1676    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_FROM_NEAREST_SEED, surface);
1677    if let Some(analytic) = surface.analytic() {
1678        if let Some(projection) = analytic.project(surface, point) {
1679            return Ok(projection);
1680        }
1681    }
1682    if let Some(ellipsoid) = surface.affine_sphere() {
1683        if let Some(projection) = ellipsoid.project(surface, point) {
1684            return Ok(projection);
1685        }
1686    }
1687    let [u0, u1] = surface.domain_u()?;
1688    let [v0, v1] = surface.domain_v()?;
1689    let (closed_u, closed_v) = surface.closed_directions()?;
1690    let local = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
1691    let projected = surface.evaluate(local.u, local.v)?;
1692    Ok(SurfaceProjection {
1693        u: local.u,
1694        v: local.v,
1695        point: projected,
1696        distance: projected.sub(point).length(),
1697    })
1698}
1699
1700/// Both answers for one query, and what the global stage did — the bench's
1701/// seam (`examples/projector_bench.rs`). Not for kernel callers.
1702#[doc(hidden)]
1703pub fn project_point_to_surface_general_lanes(
1704    surface: &NurbsSurface,
1705    point: Vec3,
1706    run_global: bool,
1707) -> Result<(SurfaceProjection, GlobalStats), String> {
1708    let [u0, u1] = surface.domain_u()?;
1709    let [v0, v1] = surface.domain_v()?;
1710    let (closed_u, closed_v) = surface.closed_directions()?;
1711    let mut best = nearest_seed_answer(surface, point, [u0, u1, v0, v1], closed_u, closed_v)?;
1712    let mut stats = GlobalStats::default();
1713    if run_global {
1714        global_minimum(surface, point, [u0, u1, v0, v1], (closed_u, closed_v), &mut best, &mut stats)?;
1715    }
1716    let projected = surface.evaluate(best.u, best.v)?;
1717    Ok((
1718        SurfaceProjection {
1719            u: best.u,
1720            v: best.v,
1721            point: projected,
1722            distance: projected.sub(point).length(),
1723        },
1724        stats,
1725    ))
1726}
1727
1728/// How many basins the cells of one query hold — the bench's measure of the
1729/// global stage's one uncertified step (see [`project_point_to_surface_general`]).
1730#[doc(hidden)]
1731#[derive(Clone, Debug, Default)]
1732pub struct BasinCensus {
1733    /// Cells whose hull bound is below the answer's distance: every cell the
1734    /// global stage could have descended in.
1735    pub cells: usize,
1736    /// Descents run: one from each corner of those cells and one from the middle.
1737    pub descents: usize,
1738    /// Descents that stopped without a verified minimum.
1739    pub unconverged: usize,
1740    /// Cells where two verified minima differ in distance by more than `bar`.
1741    /// Distances within the on-surface floor count as equal: the descent stops
1742    /// there, so two feet under it are one foot polished to different depths.
1743    pub cells_with_two_basins: usize,
1744    /// Of those, cells whose rectangle holds the least foot any descent found:
1745    /// the only cells where a second basin can cost the answer anything.
1746    pub foot_cells_with_two_basins: usize,
1747    /// The least distance any descent reached, and where.
1748    pub least: f64,
1749    pub least_uv: (f64, f64),
1750    /// Every descent in a two-basin cell that holds the least foot: the cell,
1751    /// its rectangle, the seed, where it stopped, its distance, and whether that
1752    /// is a verified minimum.
1753    pub foot_cell_descents: Vec<(usize, [f64; 4], (f64, f64), (f64, f64), f64, bool)>,
1754}
1755
1756/// Descend in every cell whose hull bound is below `answer_distance` from each
1757/// of its corners and its middle, and count the cells whose verified minima
1758/// disagree by more than `bar`. For the bench only: it costs five descents per
1759/// cell, which the projector itself was measured not to need.
1760#[doc(hidden)]
1761pub fn project_point_to_surface_basin_census(
1762    surface: &NurbsSurface,
1763    point: Vec3,
1764    answer_distance: f64,
1765    bar: f64,
1766) -> Result<BasinCensus, String> {
1767    let mut census = BasinCensus {
1768        least: f64::INFINITY,
1769        ..BasinCensus::default()
1770    };
1771    let Some(cells) = projection_cells(surface)? else {
1772        return Ok(census);
1773    };
1774    let columns = cells.vs.len() - 1;
1775    let mut spreads: Vec<(usize, f64)> = Vec::new();
1776    let mut runs: Vec<(usize, [f64; 4], (f64, f64), (f64, f64), f64, bool)> = Vec::new();
1777    for (cell, cell_box) in cells.boxes.iter().enumerate() {
1778        if cell_box.lower_bound(point) >= answer_distance {
1779            continue;
1780        }
1781        census.cells += 1;
1782        let (row, column) = (cell / columns, cell % columns);
1783        let rectangle = [cells.us[row], cells.us[row + 1], cells.vs[column], cells.vs[column + 1]];
1784        let middle = ((rectangle[0] + rectangle[1]) * 0.5, (rectangle[2] + rectangle[3]) * 0.5);
1785        let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
1786        for seed in [
1787            (rectangle[0], rectangle[2]),
1788            (rectangle[1], rectangle[2]),
1789            (rectangle[0], rectangle[3]),
1790            (rectangle[1], rectangle[3]),
1791            middle,
1792        ] {
1793            census.descents += 1;
1794            let (found, _) = confined_descent(surface, point, seed, rectangle, (false, false))?;
1795            let distance = found.distance_squared.sqrt();
1796            runs.push((cell, rectangle, seed, (found.u, found.v), distance, found.converged));
1797            if distance < census.least {
1798                census.least = distance;
1799                census.least_uv = (found.u, found.v);
1800            }
1801            if !found.converged {
1802                census.unconverged += 1;
1803                continue;
1804            }
1805            low = low.min(distance.max(LINEAR_TOLERANCE));
1806            high = high.max(distance.max(LINEAR_TOLERANCE));
1807        }
1808        if high - low > bar {
1809            spreads.push((cell, high - low));
1810        }
1811    }
1812    census.cells_with_two_basins = spreads.len();
1813    let (u, v) = census.least_uv;
1814    let foot_cells: Vec<usize> = spreads
1815        .iter()
1816        .map(|&(cell, _)| cell)
1817        .filter(|&cell| {
1818            let (row, column) = (cell / columns, cell % columns);
1819            cells.us[row] <= u && u <= cells.us[row + 1] && cells.vs[column] <= v && v <= cells.vs[column + 1]
1820        })
1821        .collect();
1822    census.foot_cells_with_two_basins = foot_cells.len();
1823    census.foot_cell_descents = runs.into_iter().filter(|run| foot_cells.contains(&run.0)).collect();
1824    Ok(census)
1825}
1826
1827/// What the global stage did on one query.
1828#[doc(hidden)]
1829#[derive(Clone, Copy, Debug, Default)]
1830pub struct GlobalStats {
1831    /// The local answer was within the on-surface floor; nothing searched.
1832    pub settled_by_floor: bool,
1833    /// Cells whose hull bound admitted them.
1834    pub candidates: usize,
1835    /// Confined Newtons run (candidates not already holding a converged foot).
1836    pub refinements: usize,
1837    /// Continuations across the domain from a cell edge.
1838    pub continuations: usize,
1839    /// The global stage replaced the local answer.
1840    pub replaced: bool,
1841    /// The least hull bound over every cell — the true distance is never
1842    /// below it (0 when the floor settled the query).
1843    pub hull_lower_bound: f64,
1844}
1845
1846/// One lattice cell's enclosure: an oriented box around the control points
1847/// that support the cell, in an orthonormal frame fitted to the cell.
1848#[derive(Clone, Debug)]
1849struct CellBox {
1850    axes: [Vec3; 3],
1851    low: [f64; 3],
1852    high: [f64; 3],
1853}
1854
1855impl CellBox {
1856    /// Distance from `point` to the box: a lower bound on the distance to
1857    /// every surface point of the cell.
1858    fn lower_bound(&self, point: Vec3) -> f64 {
1859        let mut squared = 0.0;
1860        for axis in 0..3 {
1861            let coordinate = point.dot(self.axes[axis]);
1862            let excess = (self.low[axis] - coordinate).max(coordinate - self.high[axis]).max(0.0);
1863            squared += excess * excess;
1864        }
1865        squared.sqrt()
1866    }
1867}
1868
1869/// A node of the bounding-sphere tree over the cells. A leaf names its cell;
1870/// an internal node its two children.
1871#[derive(Clone, Copy, Debug)]
1872struct CellTreeNode {
1873    centre: Vec3,
1874    radius: f64,
1875    children: Option<(u32, u32)>,
1876    cell: u32,
1877}
1878
1879/// The cached enclosure of every projection lattice cell (see
1880/// [`project_point_to_surface_general`]).
1881#[derive(Clone, Debug)]
1882pub struct ProjectionCells {
1883    us: Vec<f64>,
1884    vs: Vec<f64>,
1885    /// `us.len() × vs.len()` lattice points, row-major in u.
1886    nodes: Vec<Vec3>,
1887    /// `(us.len() - 1) × (vs.len() - 1)` cells, row-major in u.
1888    boxes: Vec<CellBox>,
1889    /// The tree's root is the LAST node.
1890    tree: Vec<CellTreeNode>,
1891    /// One box per tree node: a leaf's is its cell's box, an internal node's
1892    /// holds both children's boxes grown by `node_margin` on every side (see
1893    /// [`hull_candidates`]). Empty when the surface has no usable scale.
1894    node_boxes: Vec<CellBox>,
1895    /// The growth of each internal node's box over its children's.
1896    node_margin: f64,
1897    /// The largest control-point coordinate magnitude.
1898    scale: f64,
1899    resolution: f64,
1900}
1901
1902/// The projection lattice's parameters along one direction: every knot span
1903/// cut into `samples` equal pieces, the seed grid's density, shared span ends
1904/// listed once.
1905fn lattice_parameters(knots: &[f64], degree: usize, closed: bool) -> Vec<f64> {
1906    let [start, end] = crate::curve::knot_domain(knots, degree);
1907    let samples = if closed {
1908        8usize.max(degree * 4)
1909    } else {
1910        3usize.max(degree + 1)
1911    };
1912    let mut breaks = vec![start];
1913    breaks.extend(interior_knots(knots, degree));
1914    breaks.push(end);
1915    let mut parameters = Vec::with_capacity((breaks.len() - 1) * samples + 1);
1916    for pair in breaks.windows(2) {
1917        for index in 0..samples {
1918            parameters.push(pair[0] + (pair[1] - pair[0]) * index as f64 / samples as f64);
1919        }
1920    }
1921    parameters.push(end);
1922    parameters
1923}
1924
1925/// Raise every lattice parameter to full multiplicity in the knot vector, so
1926/// each lattice cell is one Bézier piece of the refined net.
1927///
1928/// `net[i]` is the i-th control point along the refined direction, held as a
1929/// row across the other direction, and every row takes the same combination.
1930/// Knot refinement in one pass (Piegl & Tiller, *The NURBS Book*, A5.4), in
1931/// homogeneous coordinates, so a rational net refines exactly and the cost is
1932/// linear in the refined net's size.
1933fn refine_to_lattice(net: &mut Vec<Vec<Vec4>>, knots: &mut Vec<f64>, degree: usize, parameters: &[f64]) {
1934    let p = degree;
1935    let n = net.len() - 1;
1936    let mut inserted = Vec::new();
1937    for &parameter in parameters {
1938        let multiplicity = knots.iter().filter(|&&knot| knot == parameter).count();
1939        for _ in multiplicity..p {
1940            inserted.push(parameter);
1941        }
1942    }
1943    if inserted.is_empty() || p == 0 {
1944        return;
1945    }
1946    inserted.sort_by(f64::total_cmp);
1947    let find_span = |parameter: f64| -> usize {
1948        if parameter >= knots[n + 1] {
1949            return n;
1950        }
1951        (knots.partition_point(|&knot| knot <= parameter) - 1).clamp(p, n)
1952    };
1953    let r = inserted.len() - 1;
1954    let m = n + p + 1;
1955    let a = find_span(inserted[0]);
1956    let b = find_span(inserted[r]) + 1;
1957    let columns = net[0].len();
1958    let blank = vec![
1959        Vec4 {
1960            x: 0.0,
1961            y: 0.0,
1962            z: 0.0,
1963            w: 0.0,
1964        };
1965        columns
1966    ];
1967    let mut refined = vec![blank; n + r + 2];
1968    let mut refined_knots = vec![0.0; m + r + 2];
1969    for j in 0..=a - p {
1970        refined[j] = net[j].clone();
1971    }
1972    for j in b - 1..=n {
1973        refined[j + r + 1] = net[j].clone();
1974    }
1975    refined_knots[..=a].copy_from_slice(&knots[..=a]);
1976    for j in b + p..=m {
1977        refined_knots[j + r + 1] = knots[j];
1978    }
1979    let mut i = b + p - 1;
1980    let mut k = b + p + r;
1981    for j in (0..=r).rev() {
1982        while inserted[j] <= knots[i] && i > a {
1983            refined[k - p - 1] = net[i - p - 1].clone();
1984            refined_knots[k] = knots[i];
1985            k -= 1;
1986            i -= 1;
1987        }
1988        refined[k - p - 1] = refined[k - p].clone();
1989        for l in 1..=p {
1990            let index = k - p + l;
1991            let numerator = refined_knots[k + l] - inserted[j];
1992            if numerator == 0.0 {
1993                refined[index - 1] = refined[index].clone();
1994            } else {
1995                let alpha = numerator / (refined_knots[k + l] - knots[i - p + l]);
1996                let (head, tail) = refined.split_at_mut(index);
1997                for (before, &here) in head[index - 1].iter_mut().zip(&tail[0]) {
1998                    *before = before.scale(alpha).add(here.scale(1.0 - alpha));
1999                }
2000            }
2001        }
2002        refined_knots[k] = inserted[j];
2003        k = k.saturating_sub(1);
2004    }
2005    *net = refined;
2006    *knots = refined_knots;
2007}
2008
2009/// The control-point index range supporting the parameter interval
2010/// `[low, high]`: every basis function non-zero anywhere on it.
2011fn supporting_range(knots: &[f64], degree: usize, count: usize, low: f64, high: f64) -> (usize, usize) {
2012    let first_span = knots.partition_point(|&knot| knot <= low).saturating_sub(1);
2013    let last_span = knots.partition_point(|&knot| knot < high).saturating_sub(1);
2014    (
2015        first_span.saturating_sub(degree).min(count - 1),
2016        last_span.max(first_span).min(count - 1),
2017    )
2018}
2019
2020fn unit_or(vector: Vec3, fallback: Vec3) -> Vec3 {
2021    let length = vector.length();
2022    if length > 0.0 && length.is_finite() {
2023        vector.scale(1.0 / length)
2024    } else {
2025        fallback
2026    }
2027}
2028
2029fn enclosing_sphere(a: (Vec3, f64), b: (Vec3, f64)) -> (Vec3, f64) {
2030    let offset = b.0.sub(a.0);
2031    let separation = offset.length();
2032    if separation + b.1 <= a.1 {
2033        return a;
2034    }
2035    if separation + a.1 <= b.1 {
2036        return b;
2037    }
2038    let radius = (separation + a.1 + b.1) * 0.5;
2039    let centre = a.0.add(offset.scale((radius - a.1) / separation));
2040    (centre, radius)
2041}
2042
2043/// What [`build_cell_tree`] reads besides the spheres: the cells' boxes and
2044/// the lattice points (row-major, `lattice_columns` per row) that frame each
2045/// internal node's box, and the margin each internal box grows by.
2046struct NodeBoxInputs<'a> {
2047    boxes: &'a [CellBox],
2048    nodes: &'a [Vec3],
2049    lattice_columns: usize,
2050    margin: f64,
2051}
2052
2053/// The box of an internal node: framed like a cell's (along u, then the
2054/// normal of the region's lattice corners), spanning every corner of both
2055/// children's boxes, grown by `margin` on every side. Unbounded when a frame or
2056/// an extent is not finite, so it never prunes.
2057fn enclosing_node_box(corners: [Vec3; 4], children: [&CellBox; 2], margin: f64) -> CellBox {
2058    let unbounded = || CellBox {
2059        axes: [Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), Vec3::new(0.0, 0.0, 1.0)],
2060        low: [f64::NEG_INFINITY; 3],
2061        high: [f64::INFINITY; 3],
2062    };
2063    let [c00, c10, c01, c11] = corners;
2064    let along_u = c10.sub(c00).add(c11.sub(c01));
2065    let along_v = c01.sub(c00).add(c11.sub(c10));
2066    let e1 = unit_or(along_u, unit_or(along_v, Vec3::new(1.0, 0.0, 0.0)));
2067    let Ok(fallback) = e1.perpendicular() else {
2068        return unbounded();
2069    };
2070    let normal = unit_or(e1.cross(along_v), fallback);
2071    let e2 = unit_or(normal.cross(e1), fallback);
2072    let e3 = e1.cross(e2);
2073    let axes = [e1, e2, e3];
2074    let mut low = [f64::INFINITY; 3];
2075    let mut high = [f64::NEG_INFINITY; 3];
2076    for child in children {
2077        for corner in 0..8 {
2078            let mut point = Vec3::default();
2079            for axis in 0..3 {
2080                let value = if corner >> axis & 1 == 0 { child.low[axis] } else { child.high[axis] };
2081                point = point.add(child.axes[axis].scale(value));
2082            }
2083            for axis in 0..3 {
2084                let coordinate = point.dot(axes[axis]);
2085                low[axis] = low[axis].min(coordinate);
2086                high[axis] = high[axis].max(coordinate);
2087            }
2088        }
2089    }
2090    for axis in 0..3 {
2091        low[axis] -= margin;
2092        high[axis] += margin;
2093    }
2094    if !low.iter().chain(high.iter()).all(|value| value.is_finite()) {
2095        return unbounded();
2096    }
2097    CellBox { axes, low, high }
2098}
2099
2100fn build_cell_tree(
2101    tree: &mut Vec<CellTreeNode>,
2102    node_boxes: &mut Vec<CellBox>,
2103    inputs: &NodeBoxInputs<'_>,
2104    spheres: &[(Vec3, f64)],
2105    columns: usize,
2106    [row_low, row_high, column_low, column_high]: [usize; 4],
2107) -> u32 {
2108    if row_high - row_low == 1 && column_high - column_low == 1 {
2109        let cell = row_low * columns + column_low;
2110        node_boxes.push(inputs.boxes[cell].clone());
2111        tree.push(CellTreeNode {
2112            centre: spheres[cell].0,
2113            radius: spheres[cell].1,
2114            children: None,
2115            cell: cell as u32,
2116        });
2117        return (tree.len() - 1) as u32;
2118    }
2119    let (first, second) = if row_high - row_low >= column_high - column_low {
2120        let middle = (row_low + row_high) / 2;
2121        (
2122            [row_low, middle, column_low, column_high],
2123            [middle, row_high, column_low, column_high],
2124        )
2125    } else {
2126        let middle = (column_low + column_high) / 2;
2127        (
2128            [row_low, row_high, column_low, middle],
2129            [row_low, row_high, middle, column_high],
2130        )
2131    };
2132    let first = build_cell_tree(tree, node_boxes, inputs, spheres, columns, first);
2133    let second = build_cell_tree(tree, node_boxes, inputs, spheres, columns, second);
2134    let a = tree[first as usize];
2135    let b = tree[second as usize];
2136    let lattice = |row: usize, column: usize| inputs.nodes[row * inputs.lattice_columns + column];
2137    node_boxes.push(enclosing_node_box(
2138        [
2139            lattice(row_low, column_low),
2140            lattice(row_high, column_low),
2141            lattice(row_low, column_high),
2142            lattice(row_high, column_high),
2143        ],
2144        [&node_boxes[first as usize], &node_boxes[second as usize]],
2145        inputs.margin,
2146    ));
2147    // The resolution-inflated leaf spheres already absorb rounding; the merge
2148    // adds one more rounding of the same order, absorbed by growing the radius
2149    // by the larger child's own ulp.
2150    let (centre, radius) = enclosing_sphere((a.centre, a.radius), (b.centre, b.radius));
2151    tree.push(CellTreeNode {
2152        centre,
2153        radius: radius * (1.0 + 4.0 * f64::EPSILON),
2154        children: Some((first, second)),
2155        cell: u32::MAX,
2156    });
2157    (tree.len() - 1) as u32
2158}
2159
2160fn projection_cells(surface: &NurbsSurface) -> Result<Option<&ProjectionCells>, String> {
2161    if let Some(cells) = surface.projection_cells.get() {
2162        return Ok(cells.as_ref());
2163    }
2164    let cells = build_projection_cells(surface)?;
2165    Ok(surface.projection_cells.get_or_init(|| cells).as_ref())
2166}
2167
2168fn build_projection_cells(surface: &NurbsSurface) -> Result<Option<ProjectionCells>, String> {
2169    let (closed_u, closed_v) = surface.closed_directions()?;
2170    let us = lattice_parameters(&surface.knots_u, surface.degree_u, closed_u);
2171    let vs = lattice_parameters(&surface.knots_v, surface.degree_v, closed_v);
2172    if us.len() < 2 || vs.len() < 2 {
2173        return Ok(None);
2174    }
2175    let mut scale = 0.0f64;
2176    for control in surface.control_points.iter().flatten() {
2177        let point = control.point()?;
2178        scale = scale.max(point.x.abs()).max(point.y.abs()).max(point.z.abs());
2179    }
2180    let resolution =
2181        ((surface.degree_u + 1) * (surface.degree_v + 1)) as f64 * f64::EPSILON * scale;
2182
2183    // Refine u (the net's rows), then v (its columns, as rows of the transpose).
2184    let mut net = surface.control_points.clone();
2185    let mut knots_u = surface.knots_u.clone();
2186    refine_to_lattice(&mut net, &mut knots_u, surface.degree_u, &us);
2187    let columns = net.first().map(Vec::len).unwrap_or(0);
2188    let mut transposed: Vec<Vec<Vec4>> =
2189        (0..columns).map(|column| net.iter().map(|row| row[column]).collect()).collect();
2190    let mut knots_v = surface.knots_v.clone();
2191    refine_to_lattice(&mut transposed, &mut knots_v, surface.degree_v, &vs);
2192    let rows = transposed.first().map(Vec::len).unwrap_or(0);
2193    let columns = transposed.len();
2194    if rows == 0 || columns == 0 {
2195        return Ok(None);
2196    }
2197    let mut points = vec![Vec3::default(); rows * columns];
2198    for (column, fibre) in transposed.iter().enumerate() {
2199        for (row, control) in fibre.iter().enumerate() {
2200            points[row * columns + column] = control.point()?;
2201        }
2202    }
2203
2204    let mut nodes = Vec::with_capacity(us.len() * vs.len());
2205    for &u in &us {
2206        for &v in &vs {
2207            nodes.push(surface.evaluate(u, v)?);
2208        }
2209    }
2210
2211    let cell_rows = us.len() - 1;
2212    let cell_columns = vs.len() - 1;
2213    let mut boxes = Vec::with_capacity(cell_rows * cell_columns);
2214    let mut spheres = Vec::with_capacity(cell_rows * cell_columns);
2215    for i in 0..cell_rows {
2216        let (row_low, row_high) =
2217            supporting_range(&knots_u, surface.degree_u, rows, us[i], us[i + 1]);
2218        for j in 0..cell_columns {
2219            let (column_low, column_high) =
2220                supporting_range(&knots_v, surface.degree_v, columns, vs[j], vs[j + 1]);
2221            let at = |row: usize, column: usize| points[row * columns + column];
2222            let c00 = at(row_low, column_low);
2223            let c10 = at(row_high, column_low);
2224            let c01 = at(row_low, column_high);
2225            let c11 = at(row_high, column_high);
2226            let along_u = c10.sub(c00).add(c11.sub(c01));
2227            let along_v = c01.sub(c00).add(c11.sub(c10));
2228            let e1 = unit_or(along_u, unit_or(along_v, Vec3::new(1.0, 0.0, 0.0)));
2229            let normal = unit_or(e1.cross(along_v), e1.perpendicular()?);
2230            let e2 = unit_or(normal.cross(e1), e1.perpendicular()?);
2231            let e3 = e1.cross(e2);
2232            let axes = [e1, e2, e3];
2233            let mut low = [f64::INFINITY; 3];
2234            let mut high = [f64::NEG_INFINITY; 3];
2235            for row in row_low..=row_high {
2236                for column in column_low..=column_high {
2237                    let point = at(row, column);
2238                    for axis in 0..3 {
2239                        let coordinate = point.dot(axes[axis]);
2240                        low[axis] = low[axis].min(coordinate);
2241                        high[axis] = high[axis].max(coordinate);
2242                    }
2243                }
2244            }
2245            for axis in 0..3 {
2246                low[axis] -= resolution;
2247                high[axis] += resolution;
2248            }
2249            let mut centre = Vec3::default();
2250            let mut half_diagonal_squared = 0.0;
2251            for axis in 0..3 {
2252                centre = centre.add(axes[axis].scale((low[axis] + high[axis]) * 0.5));
2253                let half = (high[axis] - low[axis]) * 0.5;
2254                half_diagonal_squared += half * half;
2255            }
2256            if !low.iter().chain(high.iter()).all(|value| value.is_finite()) {
2257                return Ok(None);
2258            }
2259            spheres.push((centre, half_diagonal_squared.sqrt() + resolution));
2260            boxes.push(CellBox { axes, low, high });
2261        }
2262    }
2263    let mut tree = Vec::with_capacity(2 * boxes.len());
2264    let mut node_boxes = Vec::with_capacity(2 * boxes.len());
2265    // Each internal box grows by a billionth of the surface's scale over its
2266    // children: far above the rounding of the corners it spans and of the
2267    // bound read from it, so a box that excludes a point excludes every cell
2268    // under it (see `hull_candidates`).
2269    let node_margin = NODE_BOX_MARGIN * scale;
2270    let inputs = NodeBoxInputs { boxes: &boxes, nodes: &nodes, lattice_columns: vs.len(), margin: node_margin };
2271    build_cell_tree(&mut tree, &mut node_boxes, &inputs, &spheres, cell_columns, [0, cell_rows, 0, cell_columns]);
2272    if !(node_margin > 0.0 && node_margin.is_finite()) {
2273        node_boxes = Vec::new();
2274    }
2275    Ok(Some(ProjectionCells {
2276        us,
2277        vs,
2278        nodes,
2279        boxes,
2280        tree,
2281        node_boxes,
2282        node_margin,
2283        scale,
2284        resolution,
2285    }))
2286}
2287
2288/// First- and second-order optimality of `(u, v)` for the distance over the
2289/// rectangle: stationary on the coordinates the rectangle leaves free (the
2290/// descent's own cosine test), with a positive definite Hessian there. A
2291/// `periodic` direction has no edge to be pinned against: its seam is interior.
2292fn optimality(
2293    derivatives: &[[Vec3; 3]; 3],
2294    point: Vec3,
2295    (u, v): (f64, f64),
2296    [ua, ub, va, vb]: [f64; 4],
2297    periodic: (bool, bool),
2298) -> Optimality {
2299    let residual = derivatives[0][0].sub(point);
2300    let residual_length = residual.length();
2301    let su = derivatives[1][0];
2302    let sv = derivatives[0][1];
2303    let f = su.dot(residual);
2304    let g = sv.dot(residual);
2305    let metric_u = su.length_squared();
2306    let metric_v = sv.length_squared();
2307    let stationary_u = metric_u.sqrt() * residual_length <= EPSILON
2308        || f.abs() <= 1e-10 * metric_u.sqrt() * residual_length;
2309    let stationary_v = metric_v.sqrt() * residual_length <= EPSILON
2310        || g.abs() <= 1e-10 * metric_v.sqrt() * residual_length;
2311    let pinned_u = !periodic.0 && ((u <= ua && f > 0.0) || (u >= ub && f < 0.0));
2312    let pinned_v = !periodic.1 && ((v <= va && g > 0.0) || (v >= vb && g < 0.0));
2313    let j00 = derivatives[2][0].dot(residual) + metric_u;
2314    let j01 = derivatives[1][1].dot(residual) + su.dot(sv);
2315    let j11 = derivatives[0][2].dot(residual) + metric_v;
2316    let determinant = j00 * j11 - j01 * j01;
2317    let convex = match (!pinned_u, !pinned_v) {
2318        (true, true) => j00 > 0.0 && determinant > 0.0,
2319        (true, false) => j00 > 0.0,
2320        (false, true) => j11 > 0.0,
2321        (false, false) => true,
2322    };
2323    Optimality {
2324        residual_length,
2325        gradient: (f, g),
2326        metric: (metric_u, metric_v),
2327        hessian: (j00, j01, j11),
2328        determinant,
2329        pinned: (pinned_u, pinned_v),
2330        convex,
2331        minimum: residual_length <= LINEAR_TOLERANCE
2332            || ((stationary_u || pinned_u) && (stationary_v || pinned_v) && convex),
2333    }
2334}
2335
2336struct Optimality {
2337    residual_length: f64,
2338    gradient: (f64, f64),
2339    metric: (f64, f64),
2340    hessian: (f64, f64, f64),
2341    determinant: f64,
2342    pinned: (bool, bool),
2343    convex: bool,
2344    minimum: bool,
2345}
2346
2347fn is_verified_minimum(
2348    surface: &NurbsSurface,
2349    point: Vec3,
2350    at: (f64, f64),
2351    rectangle: [f64; 4],
2352    periodic: (bool, bool),
2353) -> Result<bool, String> {
2354    let derivatives = surface.derivatives_small(at.0, at.1, 2)?;
2355    Ok(optimality(&derivatives, point, at, rectangle, periodic).minimum)
2356}
2357
2358/// A descent to a local minimum of the distance over the rectangle
2359/// `[ua, ub] × [va, vb]`, from a seed inside it.
2360///
2361/// Newton on the gradient converges to ANY critical point — a saddle or a
2362/// maximum as readily as a minimum — and reads convergence there, so every
2363/// step here must lower the distance: the Newton step where the Hessian is
2364/// positive definite on the free coordinates, the metric-scaled gradient step
2365/// where it is not, halved until the distance does not rise. A coordinate
2366/// pinned at the rectangle's edge by a gradient pointing out of it is held
2367/// there and the other takes the one-dimensional step, so a minimum ON the edge
2368/// converges as one (the Karush-Kuhn-Tucker point) instead of stalling.
2369///
2370/// Returns the best iterate, whether it is a verified minimum (stationary on
2371/// the free coordinates with a positive definite Hessian there, or within the
2372/// on-surface floor), and whether it lies on the rectangle's edge.
2373fn confined_descent(
2374    surface: &NurbsSurface,
2375    point: Vec3,
2376    seed: (f64, f64),
2377    rectangle: [f64; 4],
2378    periodic: (bool, bool),
2379) -> Result<(NewtonResult, bool), String> {
2380    let [ua, ub, va, vb] = rectangle;
2381    let mut u = fit_parameter(seed.0, ua, ub, periodic.0);
2382    let mut v = fit_parameter(seed.1, va, vb, periodic.1);
2383    let mut converged = false;
2384    let mut current = surface.evaluate(u, v)?.sub(point).length_squared();
2385    for _ in 0..MAX_NEWTON_ITERATIONS {
2386        let derivatives = surface.derivatives_small(u, v, 2)?;
2387        let state = optimality(&derivatives, point, (u, v), rectangle, periodic);
2388        current = state.residual_length * state.residual_length;
2389        if state.minimum {
2390            converged = true;
2391            break;
2392        }
2393        let (f, g) = state.gradient;
2394        let (metric_u, metric_v) = state.metric;
2395        let (j00, j01, j11) = state.hessian;
2396        let determinant = state.determinant;
2397        let (free_u, free_v) = (!state.pinned.0, !state.pinned.1);
2398        let (mut du, mut dv) = match (free_u, free_v) {
2399            (true, true) if state.convex => (
2400                (-f * j11 + g * j01) / determinant,
2401                (-g * j00 + f * j01) / determinant,
2402            ),
2403            (true, false) if state.convex => (-f / j00, 0.0),
2404            (false, true) if state.convex => (0.0, -g / j11),
2405            _ => (
2406                if free_u && metric_u > 0.0 { -f / metric_u } else { 0.0 },
2407                if free_v && metric_v > 0.0 { -g / metric_v } else { 0.0 },
2408            ),
2409        };
2410        if !(du.is_finite() && dv.is_finite()) || (du == 0.0 && dv == 0.0) {
2411            break;
2412        }
2413        let mut moved = false;
2414        // The step actually taken, a whole period removed across a seam.
2415        let taken = |next: f64, here: f64, low: f64, high: f64, wraps: bool| {
2416            let raw = next - here;
2417            if wraps {
2418                raw - (high - low) * (raw / (high - low)).round()
2419            } else {
2420                raw
2421            }
2422        };
2423        for _ in 0..40 {
2424            let next_u = fit_parameter(u + du, ua, ub, periodic.0);
2425            let next_v = fit_parameter(v + dv, va, vb, periodic.1);
2426            if next_u == u && next_v == v {
2427                break;
2428            }
2429            let trial = surface.evaluate(next_u, next_v)?.sub(point).length_squared();
2430            if trial <= current {
2431                moved = taken(next_u, u, ua, ub, periodic.0).abs() > 1e-15 * (ub - ua)
2432                    || taken(next_v, v, va, vb, periodic.1).abs() > 1e-15 * (vb - va);
2433                u = next_u;
2434                v = next_v;
2435                current = trial;
2436                break;
2437            }
2438            du *= 0.5;
2439            dv *= 0.5;
2440        }
2441        if !moved {
2442            break;
2443        }
2444    }
2445    let result = NewtonResult {
2446        u,
2447        v,
2448        distance_squared: current,
2449        converged,
2450    };
2451    let on_edge =
2452        (!periodic.0 && (u <= ua || u >= ub)) || (!periodic.1 && (v <= va || v >= vb));
2453    Ok((result, on_edge))
2454}
2455
2456/// The growth of an internal node's box over its children's, per unit of
2457/// the surface's scale.
2458const NODE_BOX_MARGIN: f64 = 1e-9;
2459
2460/// `BREP_PROJECTION_NODE_BOXES` (default on): the cell-tree walk also reads
2461/// each internal node's box, not only its sphere. `=0` walks on spheres alone,
2462/// as before. Read once.
2463fn node_boxes_enabled() -> bool {
2464    switch!("BREP_PROJECTION_NODE_BOXES", true)
2465}
2466
2467/// The walk of the global stage: every cell whose box comes nearer `point`
2468/// than `bound`, with its box bound, in the walk's order, and the least bound
2469/// over everything the walk excluded.
2470///
2471/// A node is excluded when its sphere is no nearer than `bound`, and, with
2472/// `node_boxes`, when its box is not either. Cell spheres are loose on long,
2473/// thin cells (a 16 × 5632 lattice: about 3000 nodes visited and 200 cells
2474/// read per query to admit one), and an internal box is not. The box test
2475/// only removes subtrees whose every cell the cell test would reject, in the
2476/// same order, so the candidates are the same list to the bit with and
2477/// without it. Each internal box holds its children's boxes grown by
2478/// `node_margin` (`m`), and both bounds are read within `e` of their exact
2479/// value, `e` (below) set by the point's and the surface's magnitudes. A
2480/// box read at `b ≥ bound` with `b > 2e` is truly at least `b − e > 0` away,
2481/// so each cell box under it is truly at least `b − e + m` away and reads at
2482/// least `b − 2e + m ≥ bound` whenever `m ≥ 2e`; the test is skipped for a
2483/// point so far out that `4e > m` (beyond about 3·10⁴ scales), keeping half
2484/// of `m` for the rounding of the box corners themselves. Only the excluded
2485/// bound (the certificate in `GlobalStats::hull_lower_bound`) can differ: it
2486/// is still a lower bound, read from a tighter box.
2487fn hull_candidates(cells: &ProjectionCells, point: Vec3, bound: f64, node_boxes: bool) -> (Vec<(f64, usize)>, f64) {
2488    let read_error = 32.0 * f64::EPSILON * (point.x.abs() + point.y.abs() + point.z.abs() + 4.0 * cells.scale);
2489    let boxes = node_boxes && !cells.node_boxes.is_empty() && 4.0 * read_error <= cells.node_margin;
2490    let mut candidates: Vec<(f64, usize)> = Vec::new();
2491    let mut excluded = f64::INFINITY;
2492    let mut stack: Vec<u32> = Vec::with_capacity(64);
2493    stack.push((cells.tree.len() - 1) as u32);
2494    while let Some(index) = stack.pop() {
2495        let node = cells.tree[index as usize];
2496        let sphere_bound = (point.sub(node.centre).length() - node.radius).max(0.0);
2497        if sphere_bound >= bound {
2498            excluded = excluded.min(sphere_bound);
2499            continue;
2500        }
2501        match node.children {
2502            Some((first, second)) => {
2503                if boxes {
2504                    let box_bound = cells.node_boxes[index as usize].lower_bound(point);
2505                    if box_bound >= bound && box_bound > 2.0 * read_error {
2506                        excluded = excluded.min(box_bound);
2507                        continue;
2508                    }
2509                }
2510                stack.push(first);
2511                stack.push(second);
2512            }
2513            None => {
2514                let cell = node.cell as usize;
2515                let box_bound = cells.boxes[cell].lower_bound(point);
2516                if box_bound < bound {
2517                    candidates.push((box_bound, cell));
2518                } else {
2519                    excluded = excluded.min(box_bound);
2520                }
2521            }
2522        }
2523    }
2524    (candidates, excluded)
2525}
2526
2527/// The global stage of [`project_point_to_surface_general`]: replace `best`
2528/// with the least local minimum over every cell the hull bound admits.
2529#[allow(clippy::too_many_arguments)]
2530fn global_minimum(
2531    surface: &NurbsSurface,
2532    point: Vec3,
2533    domains: [f64; 4],
2534    periodic: (bool, bool),
2535    best: &mut NewtonResult,
2536    stats: &mut GlobalStats,
2537) -> Result<(), String> {
2538    if best.distance_squared.sqrt() <= LINEAR_TOLERANCE {
2539        stats.settled_by_floor = true;
2540        return Ok(());
2541    }
2542    let Some(cells) = projection_cells(surface)? else {
2543        return Ok(());
2544    };
2545    let resolution = cells.resolution;
2546    let columns = cells.vs.len() - 1;
2547    let columns_u = cells.us.len() - 1;
2548    let mut bound = best.distance_squared.sqrt() - resolution;
2549
2550    // Every cell whose box comes nearer than the answer; the least bound over
2551    // what the walk excluded is the certificate.
2552    let (mut candidates, excluded) = hull_candidates(cells, point, bound, node_boxes_enabled());
2553    stats.candidates = candidates.len();
2554    candidates.sort_by(|a, b| a.0.total_cmp(&b.0));
2555    stats.hull_lower_bound = candidates
2556        .first()
2557        .map_or(excluded, |&(least, _)| least.min(excluded));
2558
2559    // Cells already holding a verified minimum need no second descent. A foot
2560    // names ONE cell even when it sits on a lattice line shared by up to four:
2561    // a neighbour can hold a better basin of its own in its interior, and it
2562    // was admitted precisely because its bound beat this answer. The local
2563    // answer is one when it passes the same test the descent applies.
2564    let cell_of = |u: f64, v: f64| {
2565        let row = (cells.us.partition_point(|&value| value <= u).max(1) - 1).min(columns_u - 1);
2566        let column = (cells.vs.partition_point(|&value| value <= v).max(1) - 1).min(columns - 1);
2567        row * columns + column
2568    };
2569    let mut settled: Vec<usize> = Vec::new();
2570    if is_verified_minimum(surface, point, (best.u, best.v), domains, periodic)? {
2571        settled.push(cell_of(best.u, best.v));
2572    }
2573    for (cell_bound, cell) in candidates {
2574        if cell_bound >= bound {
2575            break;
2576        }
2577        let row = cell / columns;
2578        let column = cell % columns;
2579        let rectangle = [
2580            cells.us[row],
2581            cells.us[row + 1],
2582            cells.vs[column],
2583            cells.vs[column + 1],
2584        ];
2585        if settled.contains(&cell) {
2586            continue;
2587        }
2588        let mut seed = (rectangle[0], rectangle[2]);
2589        let mut seed_distance = f64::INFINITY;
2590        for (node_row, node_column) in
2591            [(row, column), (row + 1, column), (row, column + 1), (row + 1, column + 1)]
2592        {
2593            let distance = cells.nodes[node_row * cells.vs.len() + node_column]
2594                .sub(point)
2595                .length_squared();
2596            if distance < seed_distance {
2597                seed_distance = distance;
2598                seed = (cells.us[node_row], cells.vs[node_column]);
2599            }
2600        }
2601        stats.refinements += 1;
2602        let (confined, on_edge) = confined_descent(surface, point, seed, rectangle, (false, false))?;
2603        let mut found = confined;
2604        if on_edge && confined.distance_squared.sqrt() < bound {
2605            // The cell's least point is on its edge and beats the answer:
2606            // the basin continues past the cell.
2607            stats.continuations += 1;
2608            let (continued, _) =
2609                confined_descent(surface, point, (confined.u, confined.v), domains, periodic)?;
2610            if continued.distance_squared < found.distance_squared {
2611                found = continued;
2612            }
2613            if continued.converged {
2614                settled.push(cell_of(continued.u, continued.v));
2615            }
2616        }
2617        if found.distance_squared.sqrt() < bound {
2618            *best = found;
2619            bound = best.distance_squared.sqrt() - resolution;
2620            stats.replaced = true;
2621            if best.distance_squared.sqrt() <= LINEAR_TOLERANCE {
2622                return Ok(());
2623            }
2624        }
2625    }
2626    Ok(())
2627}
2628
2629
2630
2631/// Domain handling for a local foot-point Newton walk.
2632#[derive(Clone, Copy)]
2633pub enum FootDomain {
2634    Clamp,
2635    Wrap,
2636    Extended,
2637}
2638
2639#[derive(Clone, Copy)]
2640pub struct CurveFootPolicy {
2641    pub domain: FootDomain,
2642    pub iterations: usize,
2643    pub slope_guard: f64,
2644    pub step_limit: f64,
2645    pub parameter_tolerance: f64,
2646    pub mode: FootMode,
2647}
2648
2649/// Acceptance and convergence differ between a distance minimum and a stationary root.
2650#[derive(Clone, Copy)]
2651pub enum FootMode {
2652    Monotone,
2653    Witness,
2654    Stationary { positive_slope: bool, relative_step: bool },
2655    Backtracked,
2656    Planar,
2657}
2658
2659/// Local Newton foot. Seeding and enumeration of local minima belong to the caller.
2660/// Returns the last parameter, best witnessed parameter, and squared distance.
2661fn curve_foot_newton_state(
2662    curve: &NurbsCurve,
2663    point: Vec3,
2664    seed: f64,
2665    bracket: [f64; 2],
2666    policy: CurveFootPolicy,
2667) -> Result<(f64, f64, f64), String> {
2668    let fit = |u| match policy.domain {
2669        FootDomain::Clamp => fit_parameter(u, bracket[0], bracket[1], false),
2670        FootDomain::Wrap => fit_parameter(u, bracket[0], bracket[1], true),
2671        FootDomain::Extended => u,
2672    };
2673    let extended = matches!(policy.domain, FootDomain::Extended) || matches!(policy.mode, FootMode::Backtracked);
2674    let planar = matches!(policy.mode, FootMode::Planar);
2675    let project = |p: Vec3| if planar { Vec3::new(p.x, p.y, 0.0) } else { p };
2676    let point = project(point);
2677    let distance = |u| -> Result<f64, String> {
2678        let p = if extended { curve.derivatives_extended(u, 0)?[0] } else { curve.evaluate(u)? };
2679        Ok(project(p).sub(point).length())
2680    };
2681    let monotone = matches!(policy.mode, FootMode::Monotone | FootMode::Backtracked);
2682    let witness = matches!(policy.mode, FootMode::Witness);
2683    let mut u = if witness { seed } else { fit(seed) };
2684    let mut nearest_u = seed;
2685    let mut nearest_squared = f64::INFINITY;
2686    let mut best = if monotone { distance(u)? } else { f64::INFINITY };
2687    for _ in 0..policy.iterations {
2688        let derivatives = if extended {
2689            let values = curve.derivatives_extended(u, 2)?;
2690            [values[0], values[1], values[2]]
2691        } else if matches!(policy.mode, FootMode::Stationary { .. })
2692            || (planar && !crate::curve::small_curve_derivatives_enabled()) {
2693            let values = curve.derivatives(u, 2)?;
2694            [values[0], values[1], values[2]]
2695        } else {
2696            curve.derivatives_small(u, 2)?
2697        }.map(project);
2698        let offset = derivatives[0].sub(point);
2699        let numerator = offset.dot(derivatives[1]);
2700        let denominator = derivatives[1].dot(derivatives[1]) + offset.dot(derivatives[2]);
2701        if witness {
2702            let squared = offset.length_squared();
2703            if squared < nearest_squared {
2704                nearest_u = u;
2705                nearest_squared = squared;
2706            }
2707            let residual_length = squared.sqrt();
2708            if residual_length <= LINEAR_TOLERANCE
2709                || numerator.abs() <= EPSILON + 1e-10 * derivatives[1].length() * residual_length {
2710                break;
2711            }
2712        }
2713        let singular = if planar { denominator.abs() < policy.slope_guard }
2714            else { denominator.abs() <= policy.slope_guard };
2715        if singular || (matches!(policy.mode, FootMode::Stationary { positive_slope: true, .. }) && !(denominator > 0.0)) { break; }
2716        let mut step = if matches!(policy.mode, FootMode::Backtracked) && !(denominator > 0.0) {
2717            policy.step_limit.copysign(numerator)
2718        } else {
2719            (numerator / denominator).clamp(-policy.step_limit, policy.step_limit)
2720        };
2721        let mut next = fit(u - step);
2722        let mut next_distance = if monotone { distance(next)? } else { f64::INFINITY };
2723        if matches!(policy.mode, FootMode::Backtracked) {
2724            for _ in 0..30 {
2725                if next_distance < best { break; }
2726                step *= 0.5;
2727                next = fit(u - step);
2728                next_distance = distance(next)?;
2729            }
2730            if !(next_distance < best) { break; }
2731        } else if monotone && next_distance >= best { break; }
2732        let moved = if planar || matches!(policy.domain, FootDomain::Extended) { step }
2733            else if matches!(policy.domain, FootDomain::Wrap) {
2734                let period = bracket[1] - bracket[0];
2735                let raw = next - u;
2736                raw - period * (raw / period).round()
2737            } else { next - u };
2738        let tolerance = if matches!(policy.mode, FootMode::Stationary { relative_step: true, .. }) {
2739            policy.parameter_tolerance * (1.0 + u.abs())
2740        } else { policy.parameter_tolerance };
2741        let small = if planar || matches!(policy.mode, FootMode::Backtracked) { moved.abs() < tolerance }
2742            else { moved.abs() <= tolerance };
2743        if small && matches!(policy.mode, FootMode::Monotone) { break; }
2744        u = next;
2745        best = next_distance;
2746        if small { break; }
2747    }
2748    if witness { return Ok((u, nearest_u, nearest_squared)); }
2749    if !monotone { best = distance(u)?; }
2750    Ok((u, u, best * best))
2751}
2752
2753pub fn curve_foot_newton(
2754    curve: &NurbsCurve, point: Vec3, seed: f64, bracket: [f64; 2], policy: CurveFootPolicy,
2755) -> Result<(f64, f64), String> {
2756    let (_, nearest, squared) = curve_foot_newton_state(curve, point, seed, bracket, policy)?;
2757    Ok((nearest, squared))
2758}
2759
2760
2761