Skip to main content

brep_geometry/intersect/
surface_surface_intersection.rs

1use crate::curve::interior_knot_count;
2use crate::fit::solve_small;
3use crate::projection::project_point_to_surface_from_seed;
4use crate::{project_point_to_surface, KnotVector, NurbsSurface, Vec3, Vec4};
5use std::collections::HashMap;
6use serde::{Deserialize, Serialize};
7
8const EPSILON: f64 = crate::tolerance::FP_FLOOR;
9const LINEAR_TOLERANCE: f64 = crate::tolerance::DEFAULT_MODEL;
10
11/// Minimum `|n_a × n_b|` at a start point for a trace to begin there — the
12/// gate `intersect_surfaces` applies to explicit seeds and grid starts alike,
13/// and `intersect_surfaces_supplemental` to its own seeds.
14///
15/// Below it the carriers are tangent there to working precision, so the point
16/// sits in a tangency BAND — the set of points within the coincidence
17/// tolerance of both surfaces, about `√(2·R·tol)` wide across a contact of
18/// curvature radius `R` — rather than on a transverse curve.  A trace started
19/// inside the band walks the band's noise: it neither closes nor reaches a
20/// boundary and exhausts its step budget (a corner blend's sphere kissing a
21/// mirrored copy's face plane at one point; the same sphere inscribed in its
22/// own fillet cylinder, kissing it along a circle).  Shared topology at a
23/// tangential contact comes from imprint's boundary-curve exchange, never
24/// from marching ("similar faces we do not intersect" — Golovanov §6.2).
25const TRANSVERSE_START_CROSS: f64 = 1e-2;
26
27/// [`TRANSVERSE_START_CROSS`] under its crate-wide name: the bound at which a
28/// contact stops being a graze and becomes a crossing. `csg::imprint`'s
29/// tangential-only gate asks the same question of a marched point, and must ask
30/// it with the same number the seeds were accepted by.
31pub const TRANSVERSE_SEED_CROSS: f64 = TRANSVERSE_START_CROSS;
32
33/// How much CURVE a trace must be able to reach, as a multiple of the
34/// carriers' shared extent, whatever step ceiling the caller asked for.
35///
36/// `maximum_steps` bounds corrector CALLS; multiplied by the ceiling in force
37/// it bounds the ARC a trace can reach, and that product is the only thing
38/// that decides whether an ordinary section is reachable at all.  At the
39/// marcher's own ceiling (`diagonal / 15`) the default budget reaches 266
40/// extents — no bound in practice.  A caller that asks for a FINER ceiling is
41/// asking for RESOLUTION, and its request silently shortened the reach in the
42/// same proportion: `offset_shell`'s `0.0005 · scale` leaves 2.0 extents, less
43/// than one turn of an ordinary closed section on a part that size, so a
44/// perfectly marched circle died at 4000 steps (2026-09-13: the apex-cone
45/// carrier against its base plane — 42.714 of curve against a 28.844 reach,
46/// every step at the cap, the §4.12 curvature budget permitting 113× more).
47///
48/// That is the 2026-08-06 rule one level up: what a marcher can reach must be
49/// a fixed fraction of the MODEL, never a function of the step the caller
50/// asked for.  So the ceiling is honoured as resolution and the step COUNT is
51/// derived from it — the trace takes however many steps this much curve needs.
52/// Nothing that completes today changes by a single step: the derived count
53/// only ever exceeds the caller's own, and only on the fine-ceiling lane.
54///
55/// It is a FLOOR on the reach, not a bound on how long a section may be — the
56/// default lane keeps its 266 extents.  Sized for the fine-ceiling lane alone,
57/// where the longest section measured over the kernel's 37 631 traces is 1.76
58/// extents (the 2026-09-13 census; 4.43 is the most any capped ceiling reached
59/// before this and 0.13 the least).
60const MARCH_REACH_EXTENTS: f64 = 4.0;
61
62/// Corrector calls a trace may spend: the caller's own budget, or however many
63/// [`MARCH_REACH_EXTENTS`] of curve need at `maximum_step`, whichever is more.
64fn step_budget(maximum_steps: usize, maximum_step: f64, diagonal: f64) -> usize {
65    if !(maximum_step > 0.0) || !diagonal.is_finite() {
66        return maximum_steps;
67    }
68    let needed = (MARCH_REACH_EXTENTS * diagonal / maximum_step).ceil();
69    if !needed.is_finite() || needed <= maximum_steps as f64 {
70        return maximum_steps;
71    }
72    needed as usize
73}
74
75use crate::spatial::Aabb as Bounds;
76
77
78#[derive(Clone, Copy)]
79struct SurfaceInfo<'a> {
80    surface: &'a NurbsSurface,
81    u0: f64,
82    u1: f64,
83    v0: f64,
84    v1: f64,
85    closed_u: bool,
86    closed_v: bool,
87}
88
89fn surface_info(surface: &NurbsSurface) -> Result<SurfaceInfo<'_>, String> {
90    let ku = KnotVector::new(surface.knots_u.clone(), surface.degree_u)?;
91    let kv = KnotVector::new(surface.knots_v.clone(), surface.degree_v)?;
92    let [u0, u1] = ku.domain();
93    let [v0, v1] = kv.domain();
94    let mut closed_u = true;
95    let mut closed_v = true;
96    for fraction in [0.17, 0.5, 0.83] {
97        let v = v0 + (v1 - v0) * fraction;
98        if surface
99            .evaluate(u0, v)?
100            .sub(surface.evaluate(u1, v)?)
101            .length()
102            > LINEAR_TOLERANCE * 10.0
103        {
104            closed_u = false;
105        }
106        let u = u0 + (u1 - u0) * fraction;
107        if surface
108            .evaluate(u, v0)?
109            .sub(surface.evaluate(u, v1)?)
110            .length()
111            > LINEAR_TOLERANCE * 10.0
112        {
113            closed_v = false;
114        }
115    }
116    Ok(SurfaceInfo {
117        surface,
118        u0,
119        u1,
120        v0,
121        v1,
122        closed_u,
123        closed_v,
124    })
125}
126
127fn fit(value: f64, minimum: f64, maximum: f64, closed: bool) -> f64 {
128    crate::projection::fit_parameter(value, minimum, maximum, closed)
129}
130
131
132#[derive(Clone, Copy)]
133struct IntersectionPoint {
134    ua: f64,
135    va: f64,
136    ub: f64,
137    vb: f64,
138    point: Vec3,
139}
140
141fn refine_point(
142    first: SurfaceInfo<'_>,
143    second: SurfaceInfo<'_>,
144    mut ua: f64,
145    mut va: f64,
146    mut ub: f64,
147    mut vb: f64,
148    tolerance: f64,
149) -> Result<Option<IntersectionPoint>, String> {
150    for _ in 0..40 {
151        let da = first.surface.derivatives(ua, va, 1)?;
152        let db = second.surface.derivatives(ub, vb, 1)?;
153        let residual = da[0][0].sub(db[0][0]);
154        if residual.length() <= tolerance * 0.01 + EPSILON {
155            return Ok(Some(IntersectionPoint {
156                ua,
157                va,
158                ub,
159                vb,
160                point: da[0][0].add(db[0][0]).scale(0.5),
161            }));
162        }
163        let columns = [
164            da[1][0],
165            da[0][1],
166            db[1][0].scale(-1.0),
167            db[0][1].scale(-1.0),
168        ];
169        let mut matrix = [[0.0f64; 3]; 3];
170        for column in columns {
171            let values = [column.x, column.y, column.z];
172            for row in 0..3 {
173                for col in 0..3 {
174                    matrix[row][col] += values[row] * values[col];
175                }
176            }
177        }
178        let lambda = match solve_small(matrix, [-residual.x, -residual.y, -residual.z], 3) {
179            Ok(value) => value,
180            Err(_) => return Ok(None),
181        };
182        let multiplier = Vec3::new(lambda[0], lambda[1], lambda[2]);
183        let mut changes = columns.map(|column| column.dot(multiplier));
184        let domains = [
185            first.u1 - first.u0,
186            first.v1 - first.v0,
187            second.u1 - second.u0,
188            second.v1 - second.v0,
189        ];
190        for index in 0..4 {
191            changes[index] = changes[index].clamp(-domains[index] / 4.0, domains[index] / 4.0);
192        }
193        ua = fit(ua + changes[0], first.u0, first.u1, first.closed_u);
194        va = fit(va + changes[1], first.v0, first.v1, first.closed_v);
195        ub = fit(ub + changes[2], second.u0, second.u1, second.closed_u);
196        vb = fit(vb + changes[3], second.v0, second.v1, second.closed_v);
197    }
198    let a = first.surface.evaluate(ua, va)?;
199    let b = second.surface.evaluate(ub, vb)?;
200    if a.sub(b).length() <= tolerance {
201        Ok(Some(IntersectionPoint {
202            ua,
203            va,
204            ub,
205            vb,
206            point: a.add(b).scale(0.5),
207        }))
208    } else {
209        Ok(None)
210    }
211}
212
213fn find_start_points(
214    first: SurfaceInfo<'_>,
215    second: SurfaceInfo<'_>,
216    tolerance: f64,
217    density: f64,
218) -> Result<Vec<IntersectionPoint>, String> {
219    let grid_count = |info: SurfaceInfo<'_>, direction_u: bool| {
220        let (knots, degree) = if direction_u {
221            (&info.surface.knots_u, info.surface.degree_u)
222        } else {
223            (&info.surface.knots_v, info.surface.degree_v)
224        };
225        (8.0_f64)
226            .max(((interior_knot_count(knots, degree) + 1) * (degree + 1)) as f64 * density)
227            .ceil()
228            .min(24.0) as usize
229    };
230    let nu = grid_count(first, true);
231    let nv = grid_count(first, false);
232    let first_box = Bounds::from_surface_controls(first.surface)?;
233    let second_box = Bounds::from_surface_controls(second.surface)?;
234    let gate = first_box.diagonal().min(second_box.diagonal()) * 0.15 + tolerance;
235    let expanded_second = second_box.expanded((tolerance * 100.0).max(gate));
236    let mut starts = Vec::new();
237    for i in 0..=nu {
238        for j in 0..=nv {
239            let ua = first.u0 + (first.u1 - first.u0) * i as f64 / nu as f64;
240            let va = first.v0 + (first.v1 - first.v0) * j as f64 / nv as f64;
241            let point = first.surface.evaluate(ua, va)?;
242            if !expanded_second.contains(point) {
243                continue;
244            }
245            let projection = project_point_to_surface(second.surface, point)?;
246            if projection.distance > gate {
247                continue;
248            }
249            if let Some(refined) =
250                refine_point(first, second, ua, va, projection.u, projection.v, tolerance)?
251            {
252                starts.push(refined);
253            }
254        }
255    }
256    Ok(starts)
257}
258
259/// One knot-span leaf of a carrier: the control box of the span (the patch
260/// lies in it, weights being positive) and the span's parametric centre.
261struct SpanLeaf {
262    bounds: Bounds,
263    centre: [f64; 2],
264}
265
266/// The knot-span leaves of a carrier (A4): one per non-empty span pair, each
267/// boxed by the `(p+1)×(q+1)` control points that influence it. A net whose
268/// span structure cannot be read is one leaf, the whole box.
269/// `BREP_SSI_SEPARATION_PREFILTER` (default on, `0` off): the boolean imprint
270/// culls a face pair whose carriers [`hull_sets_proved_apart`] before its
271/// classification and seeding.
272pub fn separation_prefilter_enabled() -> bool {
273    crate::switch!(live "BREP_SSI_SEPARATION_PREFILTER", true)
274}
275
276/// One knot span of a carrier: its control sub-net's points (the span lies in
277/// their convex hull when every weight is positive), their box, and the
278/// sub-net's corner normal (`None` where the corners do not span a plane).
279struct SpanHull {
280    bounds: Bounds,
281    points: Vec<Vec3>,
282    normal: Option<Vec3>,
283    /// The span's parameter box, `[u0, u1, v0, v1]`.
284    range: [f64; 4],
285    /// The span's homogeneous control net, `(p + 1) x (q + 1)` row-major:
286    /// its own Bezier patch once the carrier is in Bezier form.
287    net: Vec<Vec4>,
288    degrees: (usize, usize),
289}
290
291/// The hull of one Bezier patch's homogeneous net (`(p + 1) x (q + 1)`,
292/// row-major) over the parameter box `range`.
293fn hull_of_net(net: Vec<Vec4>, (p, q): (usize, usize), range: [f64; 4]) -> Option<SpanHull> {
294    let mut points = Vec::with_capacity(net.len());
295    let mut minimum = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
296    let mut maximum = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
297    for control in &net {
298        if !(control.w > 0.0) || !control.w.is_finite() {
299            return None;
300        }
301        let point = control.point().ok()?;
302        // A non-finite point bounds nothing: the hull is unreadable, so the
303        // pair is never proved apart on it.
304        if !(point.x.is_finite() && point.y.is_finite() && point.z.is_finite()) {
305            return None;
306        }
307        minimum = Vec3::new(minimum.x.min(point.x), minimum.y.min(point.y), minimum.z.min(point.z));
308        maximum = Vec3::new(maximum.x.max(point.x), maximum.y.max(point.y), maximum.z.max(point.z));
309        points.push(point);
310    }
311    let at = |r: usize, c: usize| points[r * (q + 1) + c];
312    let du = at(p, 0).add(at(p, q)).sub(at(0, 0)).sub(at(0, q));
313    let dv = at(0, q).add(at(p, q)).sub(at(0, 0)).sub(at(p, 0));
314    let normal = du.cross(dv).normalized().ok();
315    Some(SpanHull { bounds: Bounds { minimum, maximum }, points, normal, range, net, degrees: (p, q) })
316}
317
318/// A Bezier span's four quarters, split at its parameter middle both ways by
319/// de Casteljau on the homogeneous net (exact for a rational patch): the same
320/// patches a full-multiplicity middle knot inserted into the whole carrier
321/// gives, read from this span alone.
322fn quartered(hull: &SpanHull) -> Option<[SpanHull; 4]> {
323    let (p, q) = hull.degrees;
324    // Split a row of `n + 1` homogeneous points at t = 1/2.
325    let split = |row: &[Vec4]| -> (Vec<Vec4>, Vec<Vec4>) {
326        let mut work = row.to_vec();
327        let n = work.len() - 1;
328        let mut left = Vec::with_capacity(n + 1);
329        let mut right = vec![work[n]; n + 1];
330        left.push(work[0]);
331        right[n] = work[n];
332        for level in 1..=n {
333            for k in 0..=n - level {
334                // Halved before the sum: no overflow at extreme weights.
335                work[k] = work[k].scale(0.5).add(work[k + 1].scale(0.5));
336            }
337            left.push(work[0]);
338            right[n - level] = work[n - level];
339        }
340        (left, right)
341    };
342    // In u: split every column (u runs down the rows).
343    let mut low_u = vec![Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 }; (p + 1) * (q + 1)];
344    let mut high_u = low_u.clone();
345    for c in 0..=q {
346        let column: Vec<Vec4> = (0..=p).map(|r| hull.net[r * (q + 1) + c]).collect();
347        let (left, right) = split(&column);
348        for r in 0..=p {
349            low_u[r * (q + 1) + c] = left[r];
350            high_u[r * (q + 1) + c] = right[r];
351        }
352    }
353    // In v: split every row of each half.
354    let halves_v = |net: &[Vec4]| -> (Vec<Vec4>, Vec<Vec4>) {
355        let (mut low, mut high) = (Vec::with_capacity(net.len()), Vec::with_capacity(net.len()));
356        for r in 0..=p {
357            let (left, right) = split(&net[r * (q + 1)..(r + 1) * (q + 1)]);
358            low.extend(left);
359            high.extend(right);
360        }
361        (low, high)
362    };
363    let [u0, u1, v0, v1] = hull.range;
364    let (um, vm) = (0.5 * (u0 + u1), 0.5 * (v0 + v1));
365    let (a, b) = halves_v(&low_u);
366    let (c, d) = halves_v(&high_u);
367    Some([
368        hull_of_net(a, (p, q), [u0, um, v0, vm])?,
369        hull_of_net(b, (p, q), [u0, um, vm, v1])?,
370        hull_of_net(c, (p, q), [um, u1, v0, vm])?,
371        hull_of_net(d, (p, q), [um, u1, vm, v1])?,
372    ])
373}
374
375/// `BREP_SSI_SEPARATION_LOCAL_REFINE` (default on, `0` off): the prefilter's
376/// refinement quarters only the spans of its unproved pairs (de Casteljau on
377/// each span's own Bezier net) instead of halving every span of both whole
378/// carriers at each level. Off, a pair of 22 x 11-span lofted faces that touch
379/// along an edge (never provable) paid ~140 ms building ~15 000 span hulls per
380/// carrier by the third level.
381pub fn separation_local_refine_enabled() -> bool {
382    crate::switch!(live "BREP_SSI_SEPARATION_LOCAL_REFINE", true)
383}
384
385/// Every knot span's hull of `surface`, or `None` when a weight is not
386/// positive (the convex-hull property needs positive weights).
387fn span_hulls(surface: &NurbsSurface) -> Option<Vec<SpanHull>> {
388    let (p, q) = (surface.degree_u, surface.degree_v);
389    let rows = surface.control_points.len();
390    let columns = surface.control_points.first().map_or(0, Vec::len);
391    // A rectangular net whose knot vectors fit it, or nothing is read.
392    if rows == 0
393        || columns == 0
394        || surface.control_points.iter().any(|row| row.len() != columns)
395        || surface.knots_u.len() != rows + p + 1
396        || surface.knots_v.len() != columns + q + 1
397    {
398        return None;
399    }
400    if surface.control_points.iter().flatten().any(|control| !(control.w > 0.0) || !control.w.is_finite()) {
401        return None;
402    }
403    let spans = |knots: &[f64], degree: usize, count: usize| -> Vec<usize> {
404        (degree..count).filter(|&i| i + 1 < knots.len() && knots[i] < knots[i + 1]).collect()
405    };
406    let (spans_u, spans_v) = (spans(&surface.knots_u, p, rows), spans(&surface.knots_v, q, columns));
407    let mut hulls = Vec::with_capacity(spans_u.len() * spans_v.len());
408    for &i in &spans_u {
409        for &j in &spans_v {
410            let net: Vec<Vec4> = surface.control_points[i - p..=i].iter().flat_map(|row| row[j - q..=j].iter().copied()).collect();
411            let range = [surface.knots_u[i], surface.knots_u[i + 1], surface.knots_v[j], surface.knots_v[j + 1]];
412            hulls.push(hull_of_net(net, (p, q), range)?);
413        }
414    }
415    (!hulls.is_empty()).then_some(hulls)
416}
417
418/// Whether `surface`'s net can be read span by span: rectangular, knot vectors
419/// that fit it, finite and non-decreasing, with at least one span each way.
420fn readable_net(surface: &NurbsSurface) -> bool {
421    let (p, q) = (surface.degree_u, surface.degree_v);
422    let rows = surface.control_points.len();
423    let columns = surface.control_points.first().map_or(0, Vec::len);
424    let knots_fit = |knots: &[f64], degree: usize, count: usize| {
425        knots.len() == count + degree + 1
426            && knots.iter().all(|knot| knot.is_finite())
427            && knots.windows(2).all(|pair| pair[0] <= pair[1])
428            && knots[0] < knots[knots.len() - 1]
429    };
430    rows > 0
431        && columns > 0
432        && surface.control_points.iter().all(|row| row.len() == columns)
433        && knots_fit(&surface.knots_u, p, rows)
434        && knots_fit(&surface.knots_v, q, columns)
435}
436
437/// `surface` in Bezier form: every interior knot raised to multiplicity
438/// `degree` (exact), so each span's control sub-net is that span's own
439/// Bezier net and its hull hugs the span (a B-spline span's sub-net reaches
440/// about `degree` spans either side).
441fn bezier_form(surface: &NurbsSurface) -> Option<NurbsSurface> {
442    if !readable_net(surface) {
443        return None;
444    }
445    let raise = |knots: &[f64], degree: usize| -> Vec<f64> {
446        let (first, last) = (knots[0], knots[knots.len() - 1]);
447        let mut inserted = Vec::new();
448        let mut index = 0;
449        while index < knots.len() {
450            let knot = knots[index];
451            let count = knots[index..].iter().take_while(|&&other| other == knot).count();
452            if knot > first && knot < last && count < degree {
453                inserted.extend(std::iter::repeat(knot).take(degree - count));
454            }
455            index += count;
456        }
457        inserted
458    };
459    let in_u = raise(&surface.knots_u, surface.degree_u);
460    let refined = if in_u.is_empty() { surface.clone() } else { surface.refine_knots(crate::KnotDirection::U, &in_u).ok()? };
461    let in_v = raise(&refined.knots_v, refined.degree_v);
462    if in_v.is_empty() { Some(refined) } else { refined.refine_knots(crate::KnotDirection::V, &in_v).ok() }
463}
464
465/// `surface` (in Bezier form) with a full-multiplicity knot at the middle of
466/// every span, both directions: the same surface on Bezier spans half as
467/// wide, whose hulls hug it four times closer.
468fn halved_spans(surface: &NurbsSurface) -> Option<NurbsSurface> {
469    let middles = |knots: &[f64], degree: usize| -> Vec<f64> {
470        knots
471            .windows(2)
472            .filter(|pair| pair[0] < pair[1])
473            .flat_map(|pair| std::iter::repeat(0.5 * (pair[0] + pair[1])).take(degree))
474            .collect()
475    };
476    let refined = surface.refine_knots(crate::KnotDirection::U, &middles(&surface.knots_u, surface.degree_u)).ok()?;
477    refined.refine_knots(crate::KnotDirection::V, &middles(&refined.knots_v, refined.degree_v)).ok()
478}
479
480/// Whether two carriers are PROVED apart by more than `margin`: every pair of
481/// knot spans, one of each, is separated by its control hulls' boxes or by a
482/// plane square to either span's corner normal or to the line between the
483/// hulls' centroids (a span lies in its control hull, so hulls apart by
484/// `margin` along any direction are surfaces apart). A span pair no direction
485/// separates is read again on both carriers with every span halved (exact
486/// knot insertion), its children only, up to three times while at most 64
487/// pairs remain. `false` when anything cannot be read, the span count is
488/// large, or a pair is still not proved apart: the march then runs as before.
489///
490/// Two neighbouring hob cutters (near-parallel lofted flanks a few tenths of
491/// a millimetre apart) seed and refine every overlapping leaf pair to
492/// nothing, because the boxes the seeder grows by a share of the carrier
493/// always overlap there; this test settles such a pair first.
494pub fn carriers_proved_apart(first: &NurbsSurface, second: &NurbsSurface, margin: f64) -> bool {
495    match (SpanHullSet::of(first), SpanHullSet::of(second)) {
496        (Some(a), Some(b)) => hull_sets_proved_apart(&a, &b, margin),
497        _ => false,
498    }
499}
500
501/// A carrier in Bezier form with its span hulls, built once per face so a
502/// face tested against many others ([`hull_sets_proved_apart`]) converts once.
503pub struct SpanHullSet {
504    surface: NurbsSurface,
505    hulls: Vec<SpanHull>,
506}
507
508impl SpanHullSet {
509    /// `None` when the carrier cannot be read (a weight not positive, a ragged
510    /// net): such a face is never proved apart.
511    pub fn of(surface: &NurbsSurface) -> Option<Self> {
512        let surface = bezier_form(surface)?;
513        let hulls = span_hulls(&surface)?;
514        Some(Self { surface, hulls })
515    }
516}
517
518/// [`carriers_proved_apart`] on two prepared hull sets.
519pub fn hull_sets_proved_apart(first: &SpanHullSet, second: &SpanHullSet, margin: f64) -> bool {
520    const PAIR_CAP: usize = 250_000;
521    // A pair that crosses leaves many span pairs unseparated at once: past
522    // this many the pair is given up at the first level, so a crossing pair
523    // pays a partial scan, not refinements.
524    const REFINE_CAP: usize = 64;
525    const LEVELS: usize = 3;
526    if first.hulls.len().saturating_mul(second.hulls.len()) > PAIR_CAP {
527        return false;
528    }
529    let (a, b) = (&first.hulls, &second.hulls);
530    let interval = |points: &[Vec3], normal: Vec3| {
531        points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), point| {
532            let value = point.dot(normal);
533            (low.min(value), high.max(value))
534        })
535    };
536    let centroid = |points: &[Vec3]| points.iter().fold(Vec3::new(0.0, 0.0, 0.0), |sum, p| sum.add(*p)).scale(1.0 / points.len() as f64);
537    let apart = |hull_a: &SpanHull, hull_b: &SpanHull| {
538        if !hull_a.bounds.intersects(hull_b.bounds, margin) {
539            return true;
540        }
541        // The spans' own normals, then the line between the hulls' centroids.
542        let between = centroid(&hull_b.points).sub(centroid(&hull_a.points)).normalized().ok();
543        [hull_a.normal, hull_b.normal, between].into_iter().flatten().any(|normal| {
544            let (low_a, high_a) = interval(&hull_a.points, normal);
545            let (low_b, high_b) = interval(&hull_b.points, normal);
546            low_a > high_b + margin || low_b > high_a + margin
547        })
548    };
549    let mut unproved: Vec<(usize, usize)> = Vec::new();
550    for (ia, hull_a) in a.iter().enumerate() {
551        for (ib, hull_b) in b.iter().enumerate() {
552            if !apart(hull_a, hull_b) {
553                unproved.push((ia, ib));
554                if unproved.len() > REFINE_CAP {
555                    return false;
556                }
557            }
558        }
559    }
560    if separation_local_refine_enabled() {
561        // Each level's hulls are the quarters of the previous level's unproved
562        // spans only; a pair's children are its spans' quarters.
563        let mut level_a: Vec<SpanHull> = Vec::new();
564        let mut level_b: Vec<SpanHull> = Vec::new();
565        let mut first_level = true;
566        for _ in 0..LEVELS {
567            if unproved.is_empty() {
568                break;
569            }
570            let (parents_a, parents_b): (&[SpanHull], &[SpanHull]) =
571                if first_level { (a, b) } else { (&level_a, &level_b) };
572            let mut quarters_a: HashMap<usize, usize> = HashMap::new();
573            let mut quarters_b: HashMap<usize, usize> = HashMap::new();
574            let (mut next_a, mut next_b): (Vec<SpanHull>, Vec<SpanHull>) = (Vec::new(), Vec::new());
575            let mut next: Vec<(usize, usize)> = Vec::new();
576            for &(ia, ib) in &unproved {
577                let start_a = match quarters_a.get(&ia) {
578                    Some(&start) => start,
579                    None => {
580                        let Some(children) = quartered(&parents_a[ia]) else { return false };
581                        let start = next_a.len();
582                        next_a.extend(children);
583                        quarters_a.insert(ia, start);
584                        start
585                    }
586                };
587                let start_b = match quarters_b.get(&ib) {
588                    Some(&start) => start,
589                    None => {
590                        let Some(children) = quartered(&parents_b[ib]) else { return false };
591                        let start = next_b.len();
592                        next_b.extend(children);
593                        quarters_b.insert(ib, start);
594                        start
595                    }
596                };
597                for ka in start_a..start_a + 4 {
598                    for kb in start_b..start_b + 4 {
599                        if !apart(&next_a[ka], &next_b[kb]) {
600                            next.push((ka, kb));
601                            if next.len() > REFINE_CAP {
602                                return false;
603                            }
604                        }
605                    }
606                }
607            }
608            next.sort_unstable();
609            next.dedup();
610            unproved = next;
611            level_a = next_a;
612            level_b = next_b;
613            first_level = false;
614        }
615        if std::env::var_os("BREP_DEBUG_SEPARATION").is_some() {
616            eprintln!("separation (local): unproved after refinement {}", unproved.len());
617        }
618        return unproved.is_empty();
619    }
620    // Each refinement level owns its carriers and hulls; level 0 is the
621    // prepared sets.
622    let within = |child: &[f64; 4], parent: &[f64; 4]| child[0] >= parent[0] && child[1] <= parent[1] && child[2] >= parent[2] && child[3] <= parent[3];
623    let mut levels: Vec<(NurbsSurface, NurbsSurface, Vec<SpanHull>, Vec<SpanHull>)> = Vec::new();
624    for _ in 0..LEVELS {
625        if unproved.is_empty() {
626            break;
627        }
628        let (surface_a, surface_b, parents_a, parents_b) = match levels.last() {
629            Some((sa, sb, ha, hb)) => (sa, sb, ha.as_slice(), hb.as_slice()),
630            None => (&first.surface, &second.surface, a.as_slice(), b.as_slice()),
631        };
632        let (Some(next_a), Some(next_b)) = (halved_spans(surface_a), halved_spans(surface_b)) else { return false };
633        let (Some(hulls_a), Some(hulls_b)) = (span_hulls(&next_a), span_hulls(&next_b)) else { return false };
634        let mut next: Vec<(usize, usize)> = Vec::new();
635        for &(ia, ib) in &unproved {
636            let children_a: Vec<usize> = (0..hulls_a.len()).filter(|&k| within(&hulls_a[k].range, &parents_a[ia].range)).collect();
637            let children_b: Vec<usize> = (0..hulls_b.len()).filter(|&k| within(&hulls_b[k].range, &parents_b[ib].range)).collect();
638            for &ka in &children_a {
639                for &kb in &children_b {
640                    if !apart(&hulls_a[ka], &hulls_b[kb]) {
641                        next.push((ka, kb));
642                        if next.len() > REFINE_CAP {
643                            return false;
644                        }
645                    }
646                }
647            }
648        }
649        next.sort_unstable();
650        next.dedup();
651        unproved = next;
652        levels.push((next_a, next_b, hulls_a, hulls_b));
653    }
654    if std::env::var_os("BREP_DEBUG_SEPARATION").is_some() {
655        let (a, b) = match levels.last() {
656            Some((_, _, ha, hb)) => (ha.as_slice(), hb.as_slice()),
657            None => (a.as_slice(), b.as_slice()),
658        };
659        eprintln!("separation: spans {}x{} unproved after refinement {}", a.len(), b.len(), unproved.len());
660    }
661    unproved.is_empty()
662}
663
664fn span_leaves(info: SurfaceInfo<'_>) -> Result<Vec<SpanLeaf>, String> {
665    let surface = info.surface;
666    let (p, q) = (surface.degree_u, surface.degree_v);
667    let rows = surface.control_points.len();
668    let columns = surface.control_points.first().map_or(0, Vec::len);
669    let spans = |knots: &[f64], degree: usize, count: usize| -> Vec<usize> {
670        (degree..count).filter(|&i| i + 1 < knots.len() && knots[i] < knots[i + 1]).collect()
671    };
672    let (spans_u, spans_v) = (spans(&surface.knots_u, p, rows), spans(&surface.knots_v, q, columns));
673    if spans_u.is_empty() || spans_v.is_empty() {
674        return Ok(vec![SpanLeaf {
675            bounds: Bounds::from_surface_controls(surface)?,
676            centre: [0.5 * (info.u0 + info.u1), 0.5 * (info.v0 + info.v1)],
677        }]);
678    }
679    let mut leaves = Vec::with_capacity(spans_u.len() * spans_v.len());
680    for &i in &spans_u {
681        for &j in &spans_v {
682            let mut minimum = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
683            let mut maximum = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
684            for row in &surface.control_points[i - p..=i] {
685                for control in &row[j - q..=j] {
686                    let point = control.point()?;
687                    minimum.x = minimum.x.min(point.x);
688                    minimum.y = minimum.y.min(point.y);
689                    minimum.z = minimum.z.min(point.z);
690                    maximum.x = maximum.x.max(point.x);
691                    maximum.y = maximum.y.max(point.y);
692                    maximum.z = maximum.z.max(point.z);
693                }
694            }
695            leaves.push(SpanLeaf {
696                bounds: Bounds { minimum, maximum },
697                centre: [
698                    0.5 * (surface.knots_u[i] + surface.knots_u[i + 1]),
699                    0.5 * (surface.knots_v[j] + surface.knots_v[j + 1]),
700                ],
701            });
702        }
703    }
704    Ok(leaves)
705}
706
707/// Above this many overlapping leaf pairs the tree seeding hands back to the
708/// grid: two dense nets that overlap everywhere would otherwise refine tens
709/// of thousands of candidates where the grid's few hundred find the same
710/// curves.
711const TREE_SEED_PAIR_CAP: usize = 4096;
712
713/// A4: interior start candidates from the two carriers' knot-span leaves.
714/// For every pair of leaves whose boxes overlap (each grown by the same gate
715/// the grid uses) two candidates are refined onto both carriers: the first
716/// leaf's parametric centre projected onto the second carrier from the second
717/// leaf's centre, and the converse. `None` when the pair count is over
718/// [`TREE_SEED_PAIR_CAP`], which the caller answers with the grid.
719fn tree_start_points(
720    first: SurfaceInfo<'_>,
721    second: SurfaceInfo<'_>,
722    tolerance: f64,
723) -> Result<Option<(Vec<IntersectionPoint>, usize)>, String> {
724    let first_box = Bounds::from_surface_controls(first.surface)?;
725    let second_box = Bounds::from_surface_controls(second.surface)?;
726    let gate = first_box.diagonal().min(second_box.diagonal()) * 0.15 + tolerance;
727    let grow = (tolerance * 100.0).max(gate);
728    let leaves_a = span_leaves(first)?;
729    let leaves_b = span_leaves(second)?;
730    let mut pairs = Vec::new();
731    for (ia, leaf_a) in leaves_a.iter().enumerate() {
732        for (ib, leaf_b) in leaves_b.iter().enumerate() {
733            if leaf_a.bounds.intersects(leaf_b.bounds, grow) {
734                pairs.push((ia, ib));
735                if pairs.len() > TREE_SEED_PAIR_CAP {
736                    return Ok(None);
737                }
738            }
739        }
740    }
741    let mut starts = Vec::new();
742    for (ia, ib) in &pairs {
743        let (leaf_a, leaf_b) = (&leaves_a[*ia], &leaves_b[*ib]);
744        // A leaf's centre is at most a leaf diagonal from anything in its
745        // box, so a candidate that far from the other carrier is still the
746        // pair's own and is refined; the grid's gate (a fraction of the
747        // whole carrier) would drop every candidate of a leaf pair smaller
748        // than it — a sphere of radius `0.005 L` on an `L` sheet.
749        let reach = gate.max(leaf_a.bounds.diagonal().max(leaf_b.bounds.diagonal()));
750        // The first leaf's centre onto the second carrier, seeded from the
751        // second leaf's centre; then the converse.
752        for (from, onto, from_info, onto_info, from_first) in [
753            (leaf_a, leaf_b, first, second, true),
754            (leaf_b, leaf_a, second, first, false),
755        ] {
756            let point = from_info.surface.evaluate(from.centre[0], from.centre[1])?;
757            let projection = project_point_to_surface_from_seed(onto_info.surface, point, onto.centre)?;
758            if projection.distance > reach {
759                continue;
760            }
761            let refined = if from_first {
762                refine_point(first, second, from.centre[0], from.centre[1], projection.u, projection.v, tolerance)?
763            } else {
764                refine_point(first, second, projection.u, projection.v, from.centre[0], from.centre[1], tolerance)?
765            };
766            if let Some(refined) = refined {
767                starts.push(refined);
768            }
769        }
770    }
771    Ok(Some((starts, pairs.len())))
772}
773
774/// Whether the two carriers CROSS at `point` (`|n_a × n_b|` at or above
775/// [`TRANSVERSE_START_CROSS`]) rather than touch tangentially; a surface
776/// with no normal there counts as not crossing.
777fn transverse_at(
778    first: SurfaceInfo<'_>,
779    second: SurfaceInfo<'_>,
780    point: IntersectionPoint,
781) -> bool {
782    crossing_at(first, second, point) >= TRANSVERSE_START_CROSS
783}
784
785/// `|n_a × n_b|` at `point`; zero where either carrier has no normal there.
786fn crossing_at(
787    first: SurfaceInfo<'_>,
788    second: SurfaceInfo<'_>,
789    point: IntersectionPoint,
790) -> f64 {
791    match (
792        first.surface.normal(point.ua, point.va),
793        second.surface.normal(point.ub, point.vb),
794    ) {
795        (Ok(a), Ok(b)) => a.cross(b).length(),
796        _ => 0.0,
797    }
798}
799
800fn tangent_at(
801    first: SurfaceInfo<'_>,
802    second: SurfaceInfo<'_>,
803    point: IntersectionPoint,
804) -> Result<Option<Vec3>, String> {
805    let first_normal = first.surface.normal(point.ua, point.va).ok();
806    let second_normal = second.surface.normal(point.ub, point.vb).ok();
807    match (first_normal, second_normal) {
808        (Some(a), Some(b)) => {
809            let tangent = a.cross(b);
810            if tangent.length() <= 1e-9 {
811                Ok(None)
812            } else {
813                Ok(Some(tangent.normalized()?))
814            }
815        }
816        _ => Ok(None),
817    }
818}
819
820fn polish_boundary(
821    first: SurfaceInfo<'_>,
822    second: SurfaceInfo<'_>,
823    mut point: IntersectionPoint,
824    tolerance: f64,
825) -> Result<Option<IntersectionPoint>, String> {
826    let free = [
827        first.closed_u || (point.ua > first.u0 && point.ua < first.u1),
828        first.closed_v || (point.va > first.v0 && point.va < first.v1),
829        second.closed_u || (point.ub > second.u0 && point.ub < second.u1),
830        second.closed_v || (point.vb > second.v0 && point.vb < second.v1),
831    ];
832    for _ in 0..40 {
833        let da = first.surface.derivatives(point.ua, point.va, 1)?;
834        let db = second.surface.derivatives(point.ub, point.vb, 1)?;
835        let residual = da[0][0].sub(db[0][0]);
836        if residual.length() <= tolerance {
837            point.point = da[0][0].add(db[0][0]).scale(0.5);
838            return Ok(Some(point));
839        }
840        let all_columns = [
841            da[1][0],
842            da[0][1],
843            db[1][0].scale(-1.0),
844            db[0][1].scale(-1.0),
845        ];
846        let indices: Vec<usize> = (0..4).filter(|index| free[*index]).collect();
847        if indices.is_empty() {
848            return Ok(None);
849        }
850        let mut matrix = [[0.0f64; 4]; 4];
851        let mut rhs = [0.0f64; 4];
852        for (row, &r) in indices.iter().enumerate() {
853            rhs[row] = -all_columns[r].dot(residual);
854            for (column, &c) in indices.iter().enumerate() {
855                matrix[row][column] = all_columns[r].dot(all_columns[c]);
856            }
857        }
858        let changes = match solve_small(matrix, rhs, indices.len()) {
859            Ok(value) => value,
860            Err(_) => return Ok(None),
861        };
862        let mut update = [0.0; 4];
863        for (index, &parameter_index) in indices.iter().enumerate() {
864            update[parameter_index] = changes[index];
865        }
866        point.ua = fit(point.ua + update[0], first.u0, first.u1, first.closed_u);
867        point.va = fit(point.va + update[1], first.v0, first.v1, first.closed_v);
868        point.ub = fit(point.ub + update[2], second.u0, second.u1, second.closed_u);
869        point.vb = fit(point.vb + update[3], second.v0, second.v1, second.closed_v);
870    }
871    Ok(None)
872}
873
874fn correct(
875    first: SurfaceInfo<'_>,
876    second: SurfaceInfo<'_>,
877    from: IntersectionPoint,
878    predicted: Vec3,
879    tangent: Vec3,
880    tolerance: f64,
881) -> Result<Option<(IntersectionPoint, bool)>, String> {
882    let mut point = from;
883    let mut boundary = false;
884    for _ in 0..30 {
885        let da = first.surface.derivatives(point.ua, point.va, 1)?;
886        let db = second.surface.derivatives(point.ub, point.vb, 1)?;
887        let residual = da[0][0].sub(db[0][0]);
888        let plane_residual = da[0][0].sub(predicted).dot(tangent);
889        if residual.length() <= tolerance * 0.01 + EPSILON
890            && plane_residual.abs() <= tolerance * 0.01 + EPSILON
891        {
892            point.point = da[0][0].add(db[0][0]).scale(0.5);
893            return Ok(Some((point, boundary)));
894        }
895        let matrix = [
896            [da[1][0].x, da[0][1].x, -db[1][0].x, -db[0][1].x],
897            [da[1][0].y, da[0][1].y, -db[1][0].y, -db[0][1].y],
898            [da[1][0].z, da[0][1].z, -db[1][0].z, -db[0][1].z],
899            [da[1][0].dot(tangent), da[0][1].dot(tangent), 0.0, 0.0],
900        ];
901        let changes = match solve_small(
902            matrix,
903            [-residual.x, -residual.y, -residual.z, -plane_residual],
904            4,
905        ) {
906            Ok(value) => value,
907            Err(_) => return Ok(None),
908        };
909        let scale = [
910            changes[0].abs() / ((first.u1 - first.u0) / 4.0),
911            changes[1].abs() / ((first.v1 - first.v0) / 4.0),
912            changes[2].abs() / ((second.u1 - second.u0) / 4.0),
913            changes[3].abs() / ((second.v1 - second.v0) / 4.0),
914            1.0,
915        ]
916        .into_iter()
917        .fold(1.0_f64, f64::max);
918        let raw = [
919            point.ua + changes[0] / scale,
920            point.va + changes[1] / scale,
921            point.ub + changes[2] / scale,
922            point.vb + changes[3] / scale,
923        ];
924        let domains = [
925            (first.u0, first.u1, first.closed_u),
926            (first.v0, first.v1, first.closed_v),
927            (second.u0, second.u1, second.closed_u),
928            (second.v0, second.v1, second.closed_v),
929        ];
930        boundary = false;
931        let mut next = [0.0; 4];
932        for index in 0..4 {
933            next[index] = fit(
934                raw[index],
935                domains[index].0,
936                domains[index].1,
937                domains[index].2,
938            );
939            if !domains[index].2
940                && (next[index] == domains[index].0 || next[index] == domains[index].1)
941                && raw[index] != next[index]
942            {
943                boundary = true;
944            }
945        }
946        let old = [point.ua, point.va, point.ub, point.vb];
947        let spans = [
948            first.u1 - first.u0,
949            first.v1 - first.v0,
950            second.u1 - second.u0,
951            second.v1 - second.v0,
952        ];
953        let stalled = (0..4).all(|index| (next[index] - old[index]).abs() <= 1e-14 * spans[index]);
954        point.ua = next[0];
955        point.va = next[1];
956        point.ub = next[2];
957        point.vb = next[3];
958        if stalled {
959            if boundary {
960                if let Some(polished) = polish_boundary(first, second, point, tolerance)? {
961                    return Ok(Some((polished, true)));
962                }
963            }
964            return Ok(None);
965        }
966    }
967    Ok(None)
968}
969
970struct Trace {
971    points: Vec<IntersectionPoint>,
972    /// One unit tangent per point, along the trace direction.
973    tangents: Vec<Vec3>,
974    closed: bool,
975    /// The largest span deviation measured, `0.0` when none was asked for.
976    deviation: f64,
977}
978
979/// A branch assembled from its traces: stations, one tangent per station
980/// along the branch, and the largest span deviation either trace measured.
981struct Spliced {
982    points: Vec<IntersectionPoint>,
983    tangents: Vec<Vec3>,
984    deviation: f64,
985}
986
987impl From<Trace> for Spliced {
988    fn from(trace: Trace) -> Self {
989        Self {
990            points: trace.points,
991            tangents: trace.tangents,
992            deviation: trace.deviation,
993        }
994    }
995}
996
997/// `reverse(backward[1..]) ++ forward`: the backward trace walked the other
998/// way, so its tangents are negated to run along the branch.
999fn splice(backward: Trace, forward: Trace) -> Spliced {
1000    let mut points: Vec<_> = backward.points.into_iter().skip(1).rev().collect();
1001    let mut tangents: Vec<_> = backward
1002        .tangents
1003        .into_iter()
1004        .skip(1)
1005        .rev()
1006        .map(|tangent| tangent.scale(-1.0))
1007        .collect();
1008    points.extend(forward.points);
1009    tangents.extend(forward.tangents);
1010    Spliced {
1011        points,
1012        tangents,
1013        deviation: backward.deviation.max(forward.deviation),
1014    }
1015}
1016
1017/// Preserve complete tangents for UV reuse without asking the marcher to
1018/// measure or change its spans. Deviation remains absent unless measured.
1019fn curve_from(all: Spliced, closed: bool, measured: bool) -> SurfaceIntersectionCurve {
1020    let complete = all.tangents.len() == all.points.len();
1021    SurfaceIntersectionCurve {
1022        points: all.points.iter().map(|point| point.point).collect(),
1023        params_a: all.points.iter().map(|point| [point.ua, point.va]).collect(),
1024        params_b: all.points.iter().map(|point| [point.ub, point.vb]).collect(),
1025        closed,
1026        tangents: (complete && (measured || (crate::carried_uv::carried_uv_enabled() && all.points.len() >= crate::carried_uv::carried_uv_min_stations()))).then_some(all.tangents),
1027        span_deviation: (complete && measured).then_some(all.deviation),
1028        tangent: false,
1029    }
1030}
1031
1032/// The cubic Hermite through `p0` and `p1` with end derivatives `d0`, `d1`,
1033/// at `s` in `[0, 1]`.
1034fn hermite_at(p0: Vec3, d0: Vec3, p1: Vec3, d1: Vec3, s: f64) -> Vec3 {
1035    let s2 = s * s;
1036    let s3 = s2 * s;
1037    p0.scale(2.0 * s3 - 3.0 * s2 + 1.0)
1038        .add(d0.scale(s3 - 2.0 * s2 + s))
1039        .add(p1.scale(-2.0 * s3 + 3.0 * s2))
1040        .add(d1.scale(s3 - s2))
1041}
1042
1043/// A cubic Hermite in one carrier's parameter plane between two stations:
1044/// end parameters, and end derivatives that are the least-squares images of
1045/// the chord-scaled 3D tangents through `[S_u S_v]`. Closed directions are
1046/// unwrapped so the Hermite runs the short way round; [`fit`] wraps the
1047/// samples back.
1048struct ParameterHermite {
1049    p0: [f64; 2],
1050    d0: [f64; 2],
1051    p1: [f64; 2],
1052    d1: [f64; 2],
1053}
1054
1055impl ParameterHermite {
1056    fn new(
1057        info: SurfaceInfo<'_>,
1058        p0: [f64; 2],
1059        t0: Vec3,
1060        p1: [f64; 2],
1061        t1: Vec3,
1062        chord: f64,
1063    ) -> Result<Self, String> {
1064        let image = |uv: [f64; 2], tangent: Vec3| -> Result<[f64; 2], String> {
1065            let d = info.surface.derivatives(uv[0], uv[1], 1)?;
1066            let (su, sv) = (d[1][0], d[0][1]);
1067            let (e, f, g) = (su.dot(su), su.dot(sv), sv.dot(sv));
1068            let (bu, bv) = (su.dot(tangent), sv.dot(tangent));
1069            let det = e * g - f * f;
1070            if det.abs() <= EPSILON * (1.0 + e * g) {
1071                return Ok([0.0, 0.0]);
1072            }
1073            Ok([
1074                (g * bu - f * bv) / det * chord,
1075                (e * bv - f * bu) / det * chord,
1076            ])
1077        };
1078        let mut p1 = p1;
1079        let unwrap = |value: f64, near: f64, closed: bool, minimum: f64, maximum: f64| {
1080            let period = maximum - minimum;
1081            if closed && period > 0.0 && (value - near).abs() > 0.5 * period {
1082                value - period * ((value - near) / period).round()
1083            } else {
1084                value
1085            }
1086        };
1087        p1[0] = unwrap(p1[0], p0[0], info.closed_u, info.u0, info.u1);
1088        p1[1] = unwrap(p1[1], p0[1], info.closed_v, info.v0, info.v1);
1089        Ok(Self {
1090            p0,
1091            d0: image(p0, t0)?,
1092            p1,
1093            d1: image([fit(p1[0], info.u0, info.u1, info.closed_u), fit(p1[1], info.v0, info.v1, info.closed_v)], t1)?,
1094        })
1095    }
1096
1097    fn at(&self, s: f64) -> [f64; 2] {
1098        let s2 = s * s;
1099        let s3 = s2 * s;
1100        let (h00, h10, h01, h11) = (
1101            2.0 * s3 - 3.0 * s2 + 1.0,
1102            s3 - 2.0 * s2 + s,
1103            -2.0 * s3 + 3.0 * s2,
1104            s3 - s2,
1105        );
1106        [
1107            h00 * self.p0[0] + h10 * self.d0[0] + h01 * self.p1[0] + h11 * self.d1[0],
1108            h00 * self.p0[1] + h10 * self.d0[1] + h01 * self.p1[1] + h11 * self.d1[1],
1109        ]
1110    }
1111}
1112
1113/// It is what the emitted span would miss by if the stations were
1114/// interpolated with these tangents, measured against the carriers
1115/// themselves, which no test on the stations alone can see.
1116fn span_deviation(
1117    first: SurfaceInfo<'_>,
1118    second: SurfaceInfo<'_>,
1119    from: IntersectionPoint,
1120    from_tangent: Vec3,
1121    to: IntersectionPoint,
1122    to_tangent: Vec3,
1123) -> Result<f64, String> {
1124    let chord = to.point.sub(from.point).length();
1125    if chord <= EPSILON {
1126        return Ok(0.0);
1127    }
1128    let on_a = ParameterHermite::new(first, [from.ua, from.va], from_tangent, [to.ua, to.va], to_tangent, chord)?;
1129    let on_b = ParameterHermite::new(second, [from.ub, from.vb], from_tangent, [to.ub, to.vb], to_tangent, chord)?;
1130    let (d0, d1) = (from_tangent.scale(chord), to_tangent.scale(chord));
1131    let mut worst: f64 = 0.0;
1132    for s in [0.17, 0.33, 0.5, 0.67, 0.83] {
1133        let c = hermite_at(from.point, d0, to.point, d1, s);
1134        let [ua, va] = on_a.at(s);
1135        let a = first.surface.evaluate(fit(ua, first.u0, first.u1, first.closed_u), fit(va, first.v0, first.v1, first.closed_v))?;
1136        let [ub, vb] = on_b.at(s);
1137        let b = second.surface.evaluate(fit(ub, second.u0, second.u1, second.closed_u), fit(vb, second.v0, second.v1, second.closed_v))?;
1138        worst = worst
1139            .max(a.sub(b).length())
1140            .max(a.sub(c).length())
1141            .max(b.sub(c).length());
1142    }
1143    Ok(worst)
1144}
1145
1146fn vector_angle(a: Vec3, b: Vec3) -> f64 {
1147    (a.dot(b) / (a.length() * b.length()))
1148        .clamp(-1.0, 1.0)
1149        .acos()
1150}
1151
1152/// Predictive step size from the surface-normal turn budget (Golovanov
1153/// §4.12): for each parameter of each surface the permissible parametric
1154/// step is Δα·√g/b (g, b = first/second fundamental form coefficients);
1155/// its 3D advance is Δα·g/b, and the usable step is the smallest advance
1156/// PROJECTED onto the march direction (the displacement sphere of §4.8),
1157/// ignoring parameters that barely move along the curve.  Returns None
1158/// when curvature data is unavailable (degenerate normals) — the caller
1159/// keeps its reactive step then.
1160fn normal_turn_step(
1161    first: SurfaceInfo<'_>,
1162    second: SurfaceInfo<'_>,
1163    point: IntersectionPoint,
1164    tangent: Vec3,
1165    budget: f64,
1166) -> Option<f64> {
1167    let mut best: Option<f64> = None;
1168    for (surface, u, v) in [
1169        (first.surface, point.ua, point.va),
1170        (second.surface, point.ub, point.vb),
1171    ] {
1172        let derivatives = surface.derivatives(u, v, 2).ok()?;
1173        let normal = derivatives[1][0].cross(derivatives[0][1]);
1174        let normal_length = normal.length();
1175        if normal_length <= 1e-12 {
1176            continue;
1177        }
1178        let unit_normal = normal.scale(1.0 / normal_length);
1179        for (first_derivative, second_derivative) in [
1180            (derivatives[1][0], derivatives[2][0]),
1181            (derivatives[0][1], derivatives[0][2]),
1182        ] {
1183            let metric = first_derivative.dot(first_derivative);
1184            if metric <= 1e-16 {
1185                continue;
1186            }
1187            let curvature = second_derivative.dot(unit_normal).abs();
1188            if curvature <= 1e-12 {
1189                continue; // flat along this parameter: no budget limit
1190            }
1191            let advance = budget * metric / curvature;
1192            let alignment = first_derivative
1193                .scale(1.0 / metric.sqrt())
1194                .dot(tangent)
1195                .abs();
1196            if alignment <= 0.1 {
1197                continue; // barely moves along the curve (§4.8)
1198            }
1199            let along = advance * alignment;
1200            if best.map(|value| along < value).unwrap_or(true) {
1201                best = Some(along);
1202            }
1203        }
1204    }
1205    best
1206}
1207
1208/// The switches a trace reads, taken from the environment once per
1209/// intersection call rather than once per trace.
1210#[derive(Clone, Copy)]
1211struct TraceSwitches {
1212    /// `BREP_SSI_FIRST_STEP_BUDGET=0` lets the first step skip the §4.12
1213    /// ceiling, as every trace did before 2026-09-15.
1214    first_step_ceiling: bool,
1215    /// Use orientation changes to trigger a geometric continuation check.
1216    oriented_continuation: bool,
1217    /// `BREP_DEBUG_SSI_TRACE=1`: every start and every accepted station.
1218    debug: bool,
1219}
1220
1221impl TraceSwitches {
1222    fn from_env() -> Self {
1223        Self {
1224            first_step_ceiling: std::env::var("BREP_SSI_FIRST_STEP_BUDGET").as_deref() != Ok("0"),
1225            oriented_continuation: crate::switch!(live "BREP_SSI_ORIENTED_CONTINUATION", true),
1226            debug: std::env::var_os("BREP_DEBUG_SSI_TRACE").is_some(),
1227        }
1228    }
1229}
1230
1231/// Membership of both endpoints does not establish continuation. Read the
1232/// chord interior only when orientation suggests a possible branch jump;
1233/// through a true tangent node the oriented field may reverse legitimately.
1234fn chord_in_carrier_bands(
1235    first: SurfaceInfo<'_>, second: SurfaceInfo<'_>,
1236    start: Vec3, end: Vec3, tolerance: f64,
1237) -> Result<bool, String> {
1238    for fraction in [0.25, 0.5, 0.75] {
1239        let point = start.add(end.sub(start).scale(fraction));
1240        for surface in [first.surface, second.surface] {
1241            let foot = project_point_to_surface(surface, point)?;
1242            if !foot.distance.is_finite() || foot.distance > tolerance { return Ok(false); }
1243        }
1244    }
1245    Ok(true)
1246}
1247
1248#[allow(clippy::too_many_arguments)]
1249fn trace(
1250    first: SurfaceInfo<'_>,
1251    second: SurfaceInfo<'_>,
1252    start: IntersectionPoint,
1253    direction: f64,
1254    tolerance: f64,
1255    initial_step: f64,
1256    minimum_step: f64,
1257    maximum_step: f64,
1258    maximum_steps: usize,
1259    switches: TraceSwitches,
1260    span_budget: Option<f64>,
1261) -> Result<Trace, String> {
1262    let mut points = vec![start];
1263    let mut current = start;
1264    let Some(mut tangent) = tangent_at(first, second, start)? else {
1265        return Ok(Trace {
1266            points,
1267            tangents: Vec::new(),
1268            closed: false,
1269            deviation: 0.0,
1270        });
1271    };
1272    tangent = tangent.scale(direction);
1273    let mut field_direction = direction;
1274    let mut tangents = vec![tangent];
1275    let mut deviation: f64 = 0.0;
1276    // The FIRST step is held to the same §4.12 normal-turn ceiling as every
1277    // later one. The ceiling used to be applied only after a step was accepted,
1278    // so step zero was `diagonal / 100` whatever the curvature — and a step
1279    // that lands on a trim-window boundary ends the branch before the turn
1280    // check below ever reads it. On the rescue pair
1281    // (`boolean_fuzz_corpus/23_section_pcurve_fold_t222`, cone × a 90° pin-wall
1282    // window) that one step was the whole 0.69 and 0.77 of section, turning the
1283    // tangent 0.97 rad where the ceiling allows 1.0e-2 of advance: two
1284    // stations, a four-point fit, and trims 3.0e-2 and 3.8e-2 apart. Escape
1285    // hatch: BREP_SSI_FIRST_STEP_BUDGET=0.
1286    let mut step_size = initial_step.min(maximum_step);
1287    if switches.first_step_ceiling {
1288        if let Some(budget) = normal_turn_step(first, second, start, tangent, 0.1) {
1289            step_size = step_size.min(budget).clamp(minimum_step, maximum_step);
1290        }
1291    }
1292    let mut terminated = false;
1293    for _ in 0..maximum_steps {
1294        let mut accepted = None;
1295        let mut rejected_continuation = false;
1296        while step_size >= minimum_step {
1297            let predicted = current.point.add(tangent.scale(step_size));
1298            if let Some((corrected, boundary)) =
1299                correct(first, second, current, predicted, tangent, tolerance)?
1300            {
1301                let chord = corrected.point.sub(current.point);
1302                // A small residual proves membership of both carriers, not
1303                // continuation of this branch. At a narrow neck a corrector
1304                // can land on the opposite arc with its cross-normal reversed.
1305                // Preserve that evidence instead of aligning away the reversal.
1306                if switches.oriented_continuation && !boundary {
1307                    let next = tangent_at(first, second, corrected)?.map(|t| t.scale(field_direction));
1308                    // Polished parameter-boundary stops terminate the trace;
1309                    // they do not request continuation past a tangent rim.
1310                    // A singular endpoint also retains its termination. For
1311                    // an interior step, orientation only triggers the chord
1312                    // test: it may reverse legitimately at a tangent node.
1313                    let suspect = next.is_some_and(|next| next.dot(tangent) <= 0.0 || chord.dot(next) <= 0.0);
1314                    if suspect && !chord_in_carrier_bands(first, second, current.point, corrected.point, tolerance)? {
1315                        if switches.debug {
1316                            eprintln!("SSI-REJECT boundary={boundary} step={step_size:.8e} field_dot={:?} chord_dot={:?} from={:?} to={:?}",
1317                                next.map(|n| n.dot(tangent)), next.map(|n| chord.dot(n)), current.point, corrected.point);
1318                        }
1319                        rejected_continuation = true;
1320                        step_size /= 2.0;
1321                        continue;
1322                    }
1323                }
1324                if chord.length() <= 2.5 * step_size {
1325                    accepted = Some((corrected, boundary));
1326                    break;
1327                }
1328            }
1329            step_size /= 2.0;
1330        }
1331        let Some((candidate, boundary)) = accepted else {
1332            if rejected_continuation {
1333                return Err(format!("surface intersection continuation unresolved at minimum step {minimum_step:.3e}"));
1334            }
1335            terminated = true;
1336            break;
1337        };
1338        points.push(candidate);
1339        if switches.debug {
1340            // One line per accepted station: the tangent's turn across the
1341            // step, the normal-turn ceiling where it started, the step asked
1342            // for and the distance actually covered.
1343            let turn = tangent_at(first, second, candidate)
1344                .ok()
1345                .flatten()
1346                .map(|next| vector_angle(tangent, if next.dot(tangent) < 0.0 { next.scale(-1.0) } else { next }))
1347                .unwrap_or(f64::NAN);
1348            let budget = normal_turn_step(first, second, current, tangent, 0.1).unwrap_or(f64::NAN);
1349            let at = candidate.point;
1350            eprintln!(
1351                "SSI-TRACE dir {direction} step {step_size:.4e} jump {:.4e} turn {turn:.4} ceiling {budget:.4e} boundary {boundary} p ({:.6},{:.6},{:.6})",
1352                at.sub(current.point).length(),
1353                at.x,
1354                at.y,
1355                at.z
1356            );
1357        }
1358        // A station that ends the trace still gets a tangent (its own where
1359        // one exists, else the previous one carried forward), so the tangent
1360        // list stays parallel to the stations.
1361        let raw_next = tangent_at(first, second, candidate)?;
1362        let next = raw_next.map(|next| {
1363            if next.dot(tangent) < 0.0 { next.scale(-1.0) } else { next }
1364        });
1365        if boundary {
1366            tangents.push(next.unwrap_or(tangent));
1367            terminated = true;
1368            break;
1369        }
1370        let Some(next_tangent) = next else {
1371            tangents.push(tangent);
1372            terminated = true;
1373            break;
1374        };
1375        let angle = vector_angle(tangent, next_tangent);
1376        if angle > 0.35 {
1377            points.pop();
1378            step_size = minimum_step.max(step_size / 2.0);
1379            if step_size <= minimum_step * 1.01 {
1380                points.push(candidate);
1381            } else {
1382                continue;
1383            }
1384        }
1385        // The span test (A1): the span between `current` and `candidate`
1386        // is measured against both carriers; over budget, it is re-stepped
1387        // at half the step, like a turn over 0.35, and accepted at the
1388        // minimum step regardless.
1389        let mut span_fine = true;
1390        if let Some(budget) = span_budget {
1391            let measured = span_deviation(first, second, current, tangent, candidate, next_tangent)?;
1392            if measured > budget && step_size > minimum_step * 1.01 {
1393                points.pop();
1394                step_size = minimum_step.max(step_size / 2.0);
1395                continue;
1396            }
1397            deviation = deviation.max(measured);
1398            span_fine = measured < budget / 8.0;
1399        }
1400        tangents.push(next_tangent);
1401        if let Some(raw) = raw_next {
1402            field_direction = if raw.dot(next_tangent) < 0.0 { -1.0 } else { 1.0 };
1403        }
1404        // §4.12 normal-turn budget on BOTH surfaces as a hard CEILING on
1405        // the reactive controller: growth stays reactive (accelerating
1406        // into under-sampled flats regressed downstream curve fits), but
1407        // the budget stops the step from outrunning surface curvature.
1408        let reactive = if angle < 0.03 && span_fine {
1409            step_size * 1.5
1410        } else if angle > 0.15 {
1411            step_size * 0.6
1412        } else {
1413            step_size
1414        };
1415        step_size = match normal_turn_step(first, second, candidate, next_tangent, 0.1) {
1416            Some(budget) => reactive.min(budget),
1417            None => reactive,
1418        }
1419        .clamp(minimum_step, maximum_step);
1420        if points.len() > 4 && candidate.point.sub(start.point).length() <= step_size * 1.2 {
1421            let to_start = start.point.sub(candidate.point);
1422            // Closure is another span, not permission to jump across a
1423            // nearby neck to the start on the opposite continuation.
1424            let follows_start = next_tangent.dot(tangents[0]) > 0.0
1425                && (to_start.length() <= tolerance || to_start.dot(tangents[0]) > 0.0);
1426            if (to_start.length() <= EPSILON || to_start.dot(next_tangent) >= 0.0)
1427                && (!switches.oriented_continuation || follows_start
1428                    || chord_in_carrier_bands(first, second, candidate.point, start.point, tolerance)?)
1429            {
1430                points.push(start);
1431                tangents.push(tangents[0]);
1432                return Ok(Trace {
1433                    points,
1434                    tangents,
1435                    closed: true,
1436                    deviation,
1437                });
1438            }
1439        }
1440        current = candidate;
1441        tangent = next_tangent;
1442    }
1443    if !terminated {
1444        // The step budget ran out with the curve still going: a silently
1445        // truncated branch flows into topology as if complete, which is far
1446        // worse than a loud failure here.
1447        return Err(format!(
1448            "surface intersection trace exhausted {maximum_steps} steps \
1449             ({} points, step {step_size:.3e}) without reaching a boundary or closure",
1450            points.len()
1451        ));
1452    }
1453    Ok(Trace {
1454        points,
1455        tangents,
1456        closed: false,
1457        deviation,
1458    })
1459}
1460
1461fn point_segment_distance(point: Vec3, start: Vec3, end: Vec3) -> f64 {
1462    point.distance_to_segment(start, end, EPSILON)
1463}
1464
1465#[derive(Clone, Debug, Serialize)]
1466pub struct SurfaceIntersectionCurve {
1467    pub points: Vec<Vec3>,
1468    pub params_a: Vec<[f64; 2]>,
1469    pub params_b: Vec<[f64; 2]>,
1470    pub closed: bool,
1471    /// The section's unit tangent at each station, along the curve's
1472    /// direction; retained for trace-UV reuse or when the march ran with a
1473    /// [`SurfaceIntersectionOptions::span_budget`].
1474    #[serde(skip_serializing_if = "Option::is_none")]
1475    pub tangents: Option<Vec<Vec3>>,
1476    /// The largest span deviation the march measured on this curve;
1477    /// present only when it ran with a `span_budget`.
1478    #[serde(skip_serializing_if = "Option::is_none")]
1479    pub span_deviation: Option<f64>,
1480    /// The curve is a TANGENT section: the carriers touch along it with
1481    /// parallel normals rather than crossing it, so it separates nothing on
1482    /// either face. Only `intersect::tangent_curve` produces one; every
1483    /// marched or supplemental curve reads `false`.
1484    #[serde(skip_serializing_if = "std::ops::Not::not")]
1485    pub tangent: bool,
1486}
1487
1488#[derive(Clone, Debug, Deserialize)]
1489pub struct SurfaceIntersectionOptions {
1490    #[serde(default = "default_tolerance")]
1491    pub tolerance: f64,
1492    #[serde(default = "default_density")]
1493    pub seed_density: f64,
1494    #[serde(default = "default_maximum_steps")]
1495    pub maximum_steps: usize,
1496    pub maximum_step: Option<f64>,
1497    #[serde(default)]
1498    pub seed_points: Vec<Vec3>,
1499    #[serde(default)]
1500    pub seed_only: bool,
1501    pub seed_gate: Option<f64>,
1502    /// When set, every accepted span is re-sampled as the cubic Hermite
1503    /// through its two stations — chord-scaled tangents, in 3D and in each
1504    /// carrier's parameter plane — at five interior parameters, and the
1505    /// span's deviation is the largest distance among the 3D Hermite and
1506    /// the two carriers' images of their parameter Hermites. A span over
1507    /// the budget is rejected and re-stepped at half the step (accepted at
1508    /// the minimum step regardless), and the step grows only while the
1509    /// deviation stays under an eighth of the budget. The curve then
1510    /// reports its station tangents and its largest span deviation.
1511    ///
1512    /// `None`, the default, measures nothing and marches exactly as before.
1513    /// The budget a lane carries is what its FIT can absorb (the imprint's
1514    /// `intersection_fit`), never the corrector's `tolerance`: a cubic
1515    /// Hermite over a circle of radius `r` with step `h` misses by about
1516    /// `r (h/r)^4 / 384`, so a budget of `1e-7` would hold the step near
1517    /// `r/15` and multiply stations on every curved section.
1518    #[serde(default)]
1519    pub span_budget: Option<f64>,
1520    /// Off, the default, keeps the grid-then-seeds order byte for byte.
1521    #[serde(default)]
1522    pub ordered_starts: bool,
1523    /// A3's second half: a start an earlier trace ran through is consumed
1524    /// with a station snapped to it (the start is a refined intersection
1525    /// point, the chord it lies by is not), instead of merely dropped. Off,
1526    /// the default, keeps the first-claimant rule. Measured apart from the
1527    /// ordering because it inserts stations into traced curves.
1528    #[serde(default)]
1529    pub consume_starts: bool,
1530    /// The transverse gate stays. Off, the default, grids as before.
1531    #[serde(default)]
1532    pub tree_seeds: bool,
1533    /// SUB-GATE STARTS (2026-10-17, the revolve-into-bore report): the
1534    /// `|n_a × n_b|` an EXPLICIT seed is admitted at, in place of
1535    /// `TRANSVERSE_START_CROSS`. Grid and tree starts keep the gate: the
1536    /// tangency-band runaway it exists for is theirs (a refined start inside
1537    /// a band is a point no transverse curve passes through). An explicit
1538    /// seed the caller has PROVEN to lie on a crossing — a trim edge of one
1539    /// face that leaves one side of the other carrier for the other at the
1540    /// seed — is a point of a transverse section whatever the angle, and the
1541    /// march from it is sound down to where the corrector can still tell the
1542    /// section from the tangency band: the lateral uncertainty `tol / α` of
1543    /// a crossing at angle `α` against the band's half-width `√(2 R tol)`
1544    /// across a contact of curvature radius `R`, so `α ≥ √(tol / 2R)`; the
1545    /// caller derives the bound from its own tolerance and scale. A seed
1546    /// below it is dropped exactly as before. `None`, the default, keeps the
1547    /// gate byte for byte.
1548    #[serde(default)]
1549    pub seed_start_cross: Option<f64>,
1550}
1551
1552fn default_tolerance() -> f64 {
1553    LINEAR_TOLERANCE
1554}
1555fn default_density() -> f64 {
1556    1.0
1557}
1558fn default_maximum_steps() -> usize {
1559    4000
1560}
1561
1562impl Default for SurfaceIntersectionOptions {
1563    fn default() -> Self {
1564        Self {
1565            tolerance: default_tolerance(),
1566            seed_density: default_density(),
1567            maximum_steps: default_maximum_steps(),
1568            maximum_step: None,
1569            seed_points: Vec::new(),
1570            seed_only: false,
1571            seed_gate: None,
1572            span_budget: None,
1573            ordered_starts: false,
1574            consume_starts: false,
1575            tree_seeds: false,
1576            seed_start_cross: None,
1577        }
1578    }
1579}
1580
1581/// A station used only to construct an emitted section. Refinement preserves
1582/// every supplied station; it never replaces the topology-bearing trace.
1583#[derive(Clone, Copy, Debug)]
1584pub struct EmissionSample {
1585    pub point: Vec3,
1586    pub uv_a: [f64; 2],
1587    pub uv_b: [f64; 2],
1588    pub tangent: Vec3,
1589}
1590
1591/// Subdivide smooth spans locally until their joint 3D/UV Hermites pass the
1592/// existing span check. Failure is a conservative request for the fit route.
1593/// No seed search, branch tracing, clipping, station motion or topology edit.
1594pub fn refine_emission_samples(
1595    first_surface: &NurbsSurface,
1596    second_surface: &NurbsSurface,
1597    samples: &[EmissionSample],
1598    budget: f64,
1599) -> Result<Option<Vec<EmissionSample>>, String> {
1600    if samples.len() < 2 || !(budget > 0.0 && budget.is_finite()) { return Ok(None); }
1601    let first = surface_info(first_surface)?;
1602    let second = surface_info(second_surface)?;
1603    let point = |s: EmissionSample| IntersectionPoint {
1604        point: s.point, ua: s.uv_a[0], va: s.uv_a[1], ub: s.uv_b[0], vb: s.uv_b[1],
1605    };
1606    // Fixed endpoints must themselves meet the emission floor. Refining an
1607    // interior cannot repair an inaccurate endpoint without moving topology.
1608    for s in samples {
1609        if !(first_surface.evaluate(s.uv_a[0], s.uv_a[1])?.sub(s.point).length() <= budget)
1610            || !(second_surface.evaluate(s.uv_b[0], s.uv_b[1])?.sub(s.point).length() <= budget)
1611        { return Ok(None); }
1612    }
1613    let mut pending: Vec<_> = samples.windows(2).rev().map(|p| (p[0], p[1], 0usize)).collect();
1614    let mut out = vec![samples[0]];
1615    let mut inserted = 0;
1616    while let Some((a, b, depth)) = pending.pop() {
1617        let pa = point(a);
1618        let pb = point(b);
1619        if span_deviation(first, second, pa, a.tangent, pb, b.tangent)? <= budget {
1620            out.push(b);
1621            continue;
1622        }
1623        let chord_vector = b.point.sub(a.point);
1624        let chord = chord_vector.length();
1625        if depth >= 8 || inserted >= 4096 || chord <= 4.0 * crate::KNOT_IDENTITY_TOL
1626            || crossing_at(first, second, pa) < 0.05 || crossing_at(first, second, pb) < 0.05
1627            || a.tangent.dot(b.tangent) < 0.5
1628            || a.tangent.dot(chord_vector) <= 0.5 * chord || b.tangent.dot(chord_vector) <= 0.5 * chord
1629        { return Ok(None); }
1630        let ha = ParameterHermite::new(first, a.uv_a, a.tangent, b.uv_a, b.tangent, chord)?;
1631        let hb = ParameterHermite::new(second, a.uv_b, a.tangent, b.uv_b, b.tangent, chord)?;
1632        let ua = ha.at(0.5);
1633        let ub = hb.at(0.5);
1634        let predicted = hermite_at(a.point, a.tangent.scale(chord), b.point, b.tangent.scale(chord), 0.5);
1635        let direction = a.tangent.add(b.tangent).normalized()?;
1636        let seed = IntersectionPoint {
1637            point: predicted,
1638            ua: fit(ua[0], first.u0, first.u1, first.closed_u),
1639            va: fit(ua[1], first.v0, first.v1, first.closed_v),
1640            ub: fit(ub[0], second.u0, second.u1, second.closed_u),
1641            vb: fit(ub[1], second.v0, second.v1, second.closed_v),
1642        };
1643        let Some((mid, boundary)) = correct(first, second, seed, predicted, direction, budget * 0.1)? else { return Ok(None); };
1644        let along = mid.point.sub(a.point).dot(chord_vector) / (chord * chord);
1645        if boundary || mid.point.sub(predicted).length() > 0.25 * chord
1646            || !(0.2..=0.8).contains(&along) || crossing_at(first, second, mid) < 0.05
1647        { return Ok(None); }
1648        let Some(mut tangent) = tangent_at(first, second, mid)? else { return Ok(None); };
1649        if tangent.dot(direction) < 0.0 { tangent = tangent.scale(-1.0); }
1650        if tangent.dot(a.tangent) < 0.5 || tangent.dot(b.tangent) < 0.5 { return Ok(None); }
1651        let m = EmissionSample { point: mid.point, uv_a: [mid.ua, mid.va], uv_b: [mid.ub, mid.vb], tangent };
1652        inserted += 1;
1653        pending.push((m, b, depth + 1));
1654        pending.push((a, m, depth + 1));
1655    }
1656    Ok(Some(out))
1657}
1658
1659/// The march's plane-constrained corrector from given parameters on both
1660/// carriers: the intersection point in the plane through `predicted` square to
1661/// `direction`, with its parameters, at the march residual (`tolerance * 0.01`).
1662/// `None` when the Newton does not converge. For a section lane that bisects a
1663/// span between two stations it already holds (`csg/imprint/hermite.rs`).
1664pub fn correct_in_plane(
1665    first_surface: &NurbsSurface,
1666    second_surface: &NurbsSurface,
1667    uv_a: [f64; 2],
1668    uv_b: [f64; 2],
1669    predicted: Vec3,
1670    direction: Vec3,
1671    tolerance: f64,
1672) -> Result<Option<(Vec3, [f64; 2], [f64; 2])>, String> {
1673    let first = surface_info(first_surface)?;
1674    let second = surface_info(second_surface)?;
1675    let seed = IntersectionPoint {
1676        point: predicted,
1677        ua: fit(uv_a[0], first.u0, first.u1, first.closed_u),
1678        va: fit(uv_a[1], first.v0, first.v1, first.closed_v),
1679        ub: fit(uv_b[0], second.u0, second.u1, second.closed_u),
1680        vb: fit(uv_b[1], second.v0, second.v1, second.closed_v),
1681    };
1682    Ok(correct(first, second, seed, predicted, direction, tolerance)?
1683        .map(|(point, _)| (point.point, [point.ua, point.va], [point.ub, point.vb])))
1684}
1685
1686/// Refine `seed` onto the intersection of `first_surface` and `second_surface`:
1687/// the closest point on each carrier seeds the same Newton the march uses
1688/// ([`refine_point`]), so the answer is an INTERSECTION point at the march's own
1689/// residual (`tolerance * 0.01`), not a projection onto one surface — a point
1690/// merely projected onto one carrier would carry the very bias a section
1691/// refiner exists to remove (2026-09-26, the sphere/bore rim of `BadBoolean`).
1692/// `None` when the Newton does not converge or lands further than `reach` from
1693/// the seed: a refiner must not pull a station onto another branch.
1694pub fn refine_to_intersection(
1695    first_surface: &NurbsSurface,
1696    second_surface: &NurbsSurface,
1697    seed: Vec3,
1698    tolerance: f64,
1699    reach: f64,
1700) -> Result<Option<Vec3>, String> {
1701    let first = surface_info(first_surface)?;
1702    let second = surface_info(second_surface)?;
1703    let on_first = project_point_to_surface(first_surface, seed)?;
1704    let on_second = project_point_to_surface(second_surface, seed)?;
1705    let Some(refined) = refine_point(
1706        first,
1707        second,
1708        on_first.u,
1709        on_first.v,
1710        on_second.u,
1711        on_second.v,
1712        tolerance,
1713    )?
1714    else {
1715        return Ok(None);
1716    };
1717    if refined.point.sub(seed).length() > reach {
1718        return Ok(None);
1719    }
1720    Ok(Some(refined.point))
1721}
1722
1723pub fn intersect_surfaces(
1724    first_surface: &NurbsSurface,
1725    second_surface: &NurbsSurface,
1726    options: &SurfaceIntersectionOptions,
1727) -> Result<Vec<SurfaceIntersectionCurve>, String> {
1728    let check = crate::switch!(live "BREP_SSI_ORIENTED_CONTINUATION_CHECK", false);
1729    let mut switches = TraceSwitches::from_env();
1730    if check { switches.oriented_continuation = true; }
1731    let result = intersect_surfaces_with_switches(first_surface, second_surface, options, switches);
1732    if check {
1733        switches.oriented_continuation = false;
1734        let old = intersect_surfaces_with_switches(first_surface, second_surface, options, switches);
1735        match (&old, &result) {
1736            (Ok(before), Ok(after)) => {
1737                eprintln!("ssi.continuation_check branches {} -> {}", before.len(), after.len());
1738                for i in 0..before.len().max(after.len()) {
1739                    match (before.get(i), after.get(i)) {
1740                        (Some(a), Some(b)) => {
1741                            let changed = a.points.iter().zip(&b.points).position(|(p, q)| p.sub(*q).length() > options.tolerance);
1742                            if changed.is_some() || a.points.len() != b.points.len() || a.closed != b.closed {
1743                                eprintln!("ssi.continuation_check branch={i} stations={}->{} closed={}->{} first_changed={changed:?}", a.points.len(), b.points.len(), a.closed, b.closed);
1744
1745                            }
1746                        }
1747                        _ => eprintln!("ssi.continuation_check branch={i} added_or_removed"),
1748                    }
1749                }
1750            }
1751            _ => eprintln!("ssi.continuation_check old_error={:?} guarded_error={:?}", old.as_ref().err(), result.as_ref().err()),
1752        }
1753    }
1754    result
1755}
1756
1757fn intersect_surfaces_with_switches(
1758    first_surface: &NurbsSurface,
1759    second_surface: &NurbsSurface,
1760    options: &SurfaceIntersectionOptions,
1761    switches: TraceSwitches,
1762) -> Result<Vec<SurfaceIntersectionCurve>, String> {
1763    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::MARCH);
1764    let _lap = crate::projection_profile::Lap::enter_pair(first_surface, second_surface);
1765    let first_box = Bounds::from_surface_controls(first_surface)?;
1766    let second_box = Bounds::from_surface_controls(second_surface)?;
1767    if !first_box.intersects(second_box, options.tolerance * 10.0) {
1768        return Ok(Vec::new());
1769    }
1770    let first = surface_info(first_surface)?;
1771    let second = surface_info(second_surface)?;
1772    let diagonal = first_box.diagonal().min(second_box.diagonal());
1773    let initial_step = diagonal / 100.0;
1774    let minimum_step = (options.tolerance * 100.0).max(diagonal * 1e-6);
1775    let maximum_step = (diagonal / 15.0).min(options.maximum_step.unwrap_or(f64::INFINITY));
1776    let maximum_steps = step_budget(options.maximum_steps, maximum_step, diagonal);
1777    let mut starts = if options.seed_only {
1778        Vec::new()
1779    } else if options.tree_seeds {
1780        // A4: leaf-pair candidates; the grid only when the pair count is
1781        // over the cap.
1782        match tree_start_points(first, second, options.tolerance)? {
1783            Some((starts, _pairs)) => starts,
1784            None => find_start_points(first, second, options.tolerance, options.seed_density)?,
1785        }
1786    } else {
1787        find_start_points(first, second, options.tolerance, options.seed_density)?
1788    };
1789    // A grid start is refined onto both carriers exactly like an explicit
1790    // seed and is held to the same transversality gate: inside a tangency
1791    // band the refinement converges (the band IS within tolerance of both
1792    // surfaces) to a point no transverse curve passes through.
1793    starts.retain(|start| transverse_at(first, second, *start));
1794    let seed_gate = options.seed_gate.unwrap_or(options.tolerance * 100.0);
1795    // A3: explicit seeds are kept apart so they can be traced first.
1796    let grid_count = starts.len();
1797    for seed in &options.seed_points {
1798        let projection_a = project_point_to_surface(first_surface, *seed)?;
1799        if projection_a.distance > seed_gate {
1800            continue;
1801        }
1802        let projection_b = project_point_to_surface(second_surface, *seed)?;
1803        if projection_b.distance > seed_gate {
1804            continue;
1805        }
1806        let Some(refined) = refine_point(
1807            first,
1808            second,
1809            projection_a.u,
1810            projection_a.v,
1811            projection_b.u,
1812            projection_b.v,
1813            options.tolerance,
1814        )?
1815        else {
1816            continue;
1817        };
1818        // The seed's own gate: the caller's sub-gate bound where it vouches
1819        // for the seed, the transversality gate otherwise.
1820        let admitted = match options.seed_start_cross {
1821            Some(bound) => crossing_at(first, second, refined) >= bound.min(TRANSVERSE_START_CROSS),
1822            None => transverse_at(first, second, refined),
1823        };
1824        if !admitted {
1825            continue;
1826        }
1827        starts.push(refined);
1828    }
1829    if options.ordered_starts {
1830        // A3: seeds (trim-boundary pierces) before the interior candidates,
1831        // and within each group the most transverse first; stable, so equal
1832        // crossings keep their discovery order.
1833        let crossing = |start: &IntersectionPoint| -> f64 {
1834            match (
1835                first.surface.normal(start.ua, start.va),
1836                second.surface.normal(start.ub, start.vb),
1837            ) {
1838                (Ok(a), Ok(b)) => a.cross(b).length(),
1839                _ => 0.0,
1840            }
1841        };
1842        let mut seeds = starts.split_off(grid_count);
1843        seeds.sort_by(|a, b| crossing(b).total_cmp(&crossing(a)));
1844        starts.sort_by(|a, b| crossing(b).total_cmp(&crossing(a)));
1845        seeds.append(&mut starts);
1846        starts = seeds;
1847    }
1848
1849    let mut curves: Vec<SurfaceIntersectionCurve> = Vec::new();
1850    for start in starts {
1851        let mut claimed = false;
1852        for curve in &mut curves {
1853            let Some((index, distance)) = curve
1854                .points
1855                .windows(2)
1856                .enumerate()
1857                .map(|(index, segment)| (index, point_segment_distance(start.point, segment[0], segment[1])))
1858                .filter(|(_, distance)| *distance <= initial_step * 1.5)
1859                .min_by(|a, b| a.1.total_cmp(&b.1))
1860            else {
1861                continue;
1862            };
1863            claimed = true;
1864            // A3: a start an earlier trace ran through is consumed with a
1865            // station snapped to it — the start is a refined intersection
1866            // point, the segment it lies by is a chord — unless it sits on a
1867            // station already.
1868            if options.consume_starts
1869                && distance > 0.0
1870                && start.point.sub(curve.points[index]).length() > minimum_step
1871                && start.point.sub(curve.points[index + 1]).length() > minimum_step
1872            {
1873                curve.points.insert(index + 1, start.point);
1874                if let Some(tangents) = curve.tangents.as_mut() {
1875                    let along = curve.points[index + 2].sub(curve.points[index]);
1876                    let tangent = match tangent_at(first, second, start)? {
1877                        Some(tangent) if tangent.dot(along) < 0.0 => tangent.scale(-1.0),
1878                        Some(tangent) => tangent,
1879                        None => tangents[index],
1880                    };
1881                    tangents.insert(index + 1, tangent);
1882                }
1883                if curve.params_a.len() > index + 1 && curve.params_b.len() > index + 1 {
1884                    curve.params_a.insert(index + 1, [start.ua, start.va]);
1885                    curve.params_b.insert(index + 1, [start.ub, start.vb]);
1886                }
1887            }
1888            break;
1889        }
1890        if switches.debug {
1891            let at = start.point;
1892            eprintln!(
1893                "SSI-START claimed {claimed} p ({:.6},{:.6},{:.6}) initial {initial_step:.4e} minimum {minimum_step:.4e} maximum {maximum_step:.4e}",
1894                at.x, at.y, at.z
1895            );
1896        }
1897        if claimed {
1898            continue;
1899        }
1900        let forward = trace(
1901            first,
1902            second,
1903            start,
1904            1.0,
1905            options.tolerance,
1906            initial_step,
1907            minimum_step,
1908            maximum_step,
1909            maximum_steps,
1910            switches,
1911            options.span_budget,
1912        )?;
1913        let (all, closed) = if forward.closed {
1914            (Spliced::from(forward), true)
1915        } else {
1916            let backward = trace(
1917                first,
1918                second,
1919                start,
1920                -1.0,
1921                options.tolerance,
1922                initial_step,
1923                minimum_step,
1924                maximum_step,
1925                maximum_steps,
1926                switches,
1927                options.span_budget,
1928            )?;
1929            (splice(backward, forward), false)
1930        };
1931        if all.points.len() < 2 {
1932            continue;
1933        }
1934        curves.push(curve_from(all, closed, options.span_budget.is_some()));
1935    }
1936    Ok(curves)
1937}
1938
1939/// Minimum |n_a × n_b| for a seed/branch to count as a *transverse* crossing
1940/// rather than a tangential graze — the same threshold `intersect_surfaces`
1941/// applies to its start points.
1942const SUPPLEMENTAL_TRANSVERSE_CROSS: f64 = TRANSVERSE_START_CROSS;
1943
1944/// Gated supplemental SSI **detector** for a pair the coarse pair-classifier
1945/// culled as "tangential-only" (`NearTangent` + `tangential_only`).
1946///
1947/// The 5×5 classification grid can land only on an incidental tangential KISS
1948/// between two curved carriers (e.g. the inner walls / tube tops of two
1949/// overlapping tori) and never sample the transverse loop where their tubes
1950/// actually CROSS, so `tangential_only` is a false positive that would drop a
1951/// real intersection. This routine re-seeds a DENSER grid on BOTH carriers,
1952/// keeps only *transverse* seeds (near-parallel normals rejected up front, so
1953/// the tangency band is never walked), SWALLOWS per-branch trace-exhaustion (a
1954/// genuine tangency band never closes/exits and would otherwise error — here
1955/// it simply means "no transverse curve from this seed"), and returns only
1956/// branches that are genuinely transverse along their length.
1957///
1958/// A *genuinely* tangential pair yields an empty result (every seed rejected /
1959/// every trace fruitless), so the caller skips exactly as before — the common
1960/// intersection path is never touched.
1961///
1962/// NOTE — deferred capability: when this DOES return branches, the true
1963/// intersection is *singular* (the transverse loops meet at tangent nodes,
1964/// e.g. equal-radius torus-torus at `(1.5, ±3.708, ±1.5)`). Imprinting them
1965/// requires 4-valent tangent-vertex ("checkerboard") singular assembly, which
1966/// the kernel does not yet do; until then the caller REFUSES such a pair with
1967/// a clear error rather than silently dropping the geometry or emitting the
1968/// cryptic downstream pcurve/open-loop error. See imprint.rs (tangential-only
1969/// skip) and the project singular-assembly roadmap.
1970pub fn intersect_surfaces_supplemental(
1971    first_surface: &NurbsSurface,
1972    second_surface: &NurbsSurface,
1973    options: &SurfaceIntersectionOptions,
1974) -> Result<Vec<SurfaceIntersectionCurve>, String> {
1975    let _wall = crate::wall_profile::Scope::enter(crate::wall_profile::MARCH);
1976    let first_box = Bounds::from_surface_controls(first_surface)?;
1977    let second_box = Bounds::from_surface_controls(second_surface)?;
1978    if !first_box.intersects(second_box, options.tolerance * 10.0) {
1979        return Ok(Vec::new());
1980    }
1981    let first = surface_info(first_surface)?;
1982    let second = surface_info(second_surface)?;
1983    let diagonal = first_box.diagonal().min(second_box.diagonal());
1984    let initial_step = diagonal / 100.0;
1985    let minimum_step = (options.tolerance * 100.0).max(diagonal * 1e-6);
1986    let maximum_step = (diagonal / 15.0).min(options.maximum_step.unwrap_or(f64::INFINITY));
1987    let maximum_steps = step_budget(options.maximum_steps, maximum_step, diagonal);
1988
1989    // Denser self-seed (≥2× density pushes the ≤24 grid toward its cap so a
1990    // thin transverse overlap the classifier stepped over still gets a start),
1991    // gridding BOTH carriers so an interior loop touching neither trim boundary
1992    // is still hit from whichever surface samples it best.
1993    let density = options.seed_density.max(2.0);
1994    let mut starts: Vec<IntersectionPoint> = Vec::new();
1995    for gridded_second in [false, true] {
1996        let (a, b) = if gridded_second {
1997            (second, first)
1998        } else {
1999            (first, second)
2000        };
2001        for start in find_start_points(a, b, options.tolerance, density)? {
2002            // find_start_points expresses params as (grid surface, projected
2003            // surface); normalise every start to (first, second).
2004            let start = if gridded_second {
2005                IntersectionPoint {
2006                    ua: start.ub,
2007                    va: start.vb,
2008                    ub: start.ua,
2009                    vb: start.va,
2010                    point: start.point,
2011                }
2012            } else {
2013                start
2014            };
2015            starts.push(start);
2016        }
2017    }
2018    // Reject tangential seeds outright: a start whose two surface normals are
2019    // (near-)parallel is on a graze, not a crossing, and marching it walks the
2020    // tangency band.
2021    starts.retain(|start| {
2022        match (
2023            first.surface.normal(start.ua, start.va),
2024            second.surface.normal(start.ub, start.vb),
2025        ) {
2026            (Ok(na), Ok(nb)) => na.cross(nb).length() > SUPPLEMENTAL_TRANSVERSE_CROSS,
2027            _ => false,
2028        }
2029    });
2030
2031    let switches = TraceSwitches::from_env();
2032    let mut curves: Vec<SurfaceIntersectionCurve> = Vec::new();
2033    for start in starts {
2034        let claimed = curves.iter().any(|curve| {
2035            curve.points.windows(2).any(|segment| {
2036                point_segment_distance(start.point, segment[0], segment[1]) <= initial_step * 1.5
2037            })
2038        });
2039        if claimed {
2040            continue;
2041        }
2042        // Swallow trace-exhaustion here (unlike the common path, which errors
2043        // loudly): on this gated path a non-closing branch means the seed sat
2044        // on a tangency band, which we simply drop.
2045        let Ok(forward) = trace(
2046            first,
2047            second,
2048            start,
2049            1.0,
2050            options.tolerance,
2051            initial_step,
2052            minimum_step,
2053            maximum_step,
2054            maximum_steps,
2055            switches,
2056            options.span_budget,
2057        ) else {
2058            continue;
2059        };
2060        let (all, closed) = if forward.closed {
2061            (Spliced::from(forward), true)
2062        } else {
2063            let Ok(backward) = trace(
2064                first,
2065                second,
2066                start,
2067                -1.0,
2068                options.tolerance,
2069                initial_step,
2070                minimum_step,
2071                maximum_step,
2072                maximum_steps,
2073                switches,
2074                options.span_budget,
2075            ) else {
2076                continue;
2077            };
2078            (splice(backward, forward), false)
2079        };
2080        if all.points.len() < 2 {
2081            continue;
2082        }
2083        // Keep only a branch that is genuinely transverse somewhere along its
2084        // length — a final guard against a tangency-band polyline that happened
2085        // to close.
2086        let transverse = all.points.iter().step_by((all.points.len() / 5).max(1)).any(|point| {
2087            match (
2088                first.surface.normal(point.ua, point.va),
2089                second.surface.normal(point.ub, point.vb),
2090            ) {
2091                (Ok(na), Ok(nb)) => na.cross(nb).length() > SUPPLEMENTAL_TRANSVERSE_CROSS,
2092                _ => false,
2093            }
2094        });
2095        if !transverse {
2096            continue;
2097        }
2098        curves.push(curve_from(all, closed, options.span_budget.is_some()));
2099    }
2100    Ok(curves)
2101}
2102