Skip to main content

brep_geometry/intersect/
curve_curve_intersection.rs

1use crate::curve::KNOT_IDENTITY_TOL as KNOT_TOLERANCE;
2use crate::{NurbsCurve, Vec3};
3use serde::Serialize;
4
5const EPSILON: f64 = crate::tolerance::FP_FLOOR;
6
7use crate::spatial::Aabb as Bounds;
8
9
10#[derive(Clone, Copy)]
11struct Segment {
12    start: f64,
13    end: f64,
14    bounds: Bounds,
15}
16
17fn interior_knots(curve: &NurbsCurve) -> Vec<f64> {
18    let start = curve.knots[curve.degree];
19    let end = curve.knots[curve.knots.len() - 1 - curve.degree];
20    let mut result = Vec::new();
21    for &knot in &curve.knots {
22        if knot <= start + KNOT_TOLERANCE || knot >= end - KNOT_TOLERANCE {
23            continue;
24        }
25        if result
26            .last()
27            .is_none_or(|previous: &f64| (*previous - knot).abs() > KNOT_TOLERANCE)
28        {
29            result.push(knot);
30        }
31    }
32    result
33}
34
35/// `segment_boxes` served from a small content-keyed memo: the same curve
36/// content and count give the same boxes to the bit, and the imprint asks for
37/// one section's boxes once per boundary edge it is crossed with (87 times on
38/// the planter's wall, 1660 splits of a 280-control-point curve each, 107 ms
39/// of a 560 ms imprint, 2026-11-02). Eight entries, most
40/// recent first; the key is the curve's knot and control bits and the count.
41fn segment_boxes_memoized(curve: &NurbsCurve, count: usize) -> Result<std::rc::Rc<Vec<Segment>>, String> {
42    thread_local! {
43        static SEGMENT_MEMO: std::cell::RefCell<Vec<([u64; 2], std::rc::Rc<Vec<Segment>>)>> = const { std::cell::RefCell::new(Vec::new()) };
44    }
45    let key = {
46        let mut lane = crate::identity_hash::TwoLane::new();
47        crate::identity_hash::hash_curve(&mut lane, curve);
48        lane.usize(count);
49        lane.finish()
50    };
51    let hit = SEGMENT_MEMO.with(|memo| {
52        let mut memo = memo.borrow_mut();
53        let at = memo.iter().position(|(stored, _)| *stored == key)?;
54        if at != 0 {
55            let entry = memo.remove(at);
56            memo.insert(0, entry);
57        }
58        Some(memo[0].1.clone())
59    });
60    if let Some(boxes) = hit {
61        return Ok(boxes);
62    }
63    let boxes = std::rc::Rc::new(segment_boxes(curve, count)?);
64    SEGMENT_MEMO.with(|memo| {
65        let mut memo = memo.borrow_mut();
66        memo.insert(0, (key, boxes.clone()));
67        memo.truncate(8);
68    });
69    Ok(boxes)
70}
71
72/// The control-point box of each knot span of `curve` (its Bezier pieces,
73/// split at every interior knot): for positive weights each span lies inside
74/// its box, so two curves whose span boxes are pairwise apart on some axis by
75/// more than `d` are more than `d` apart everywhere. `None` when a weight is
76/// not positive (the hull property does not hold).
77pub fn span_boxes(curve: &NurbsCurve) -> Result<Option<Vec<Bounds>>, String> {
78    if !curve.control_points.iter().all(|control| control.w > 0.0) {
79        return Ok(None);
80    }
81    Ok(Some(segment_boxes(curve, 1)?.into_iter().map(|segment| segment.bounds).collect()))
82}
83
84fn segment_boxes(curve: &NurbsCurve, count: usize) -> Result<Vec<Segment>, String> {
85    if crate::switch!(live "BREP_SEGMENT_BOX_WALK", true) {
86        if let Some(segments) = segment_boxes_walk(curve, count)? {
87            return Ok(segments);
88        }
89    }
90    segment_boxes_split(curve, count)
91}
92
93/// SEGMENT-BOX WALK (`BREP_SEGMENT_BOX_WALK`, default on, =0 restores;
94/// 2026-11-03). [`segment_boxes_split`] splits the REMAINDER of the curve at
95/// every parameter, and each `NurbsCurve::split` copies and validates the whole
96/// remainder: O(n) per split, about 2000 splits of a 300-control-point section
97/// (8-9 ms per curve natively; the elephant's and the planter's crossing
98/// searches are 60 and 73 ms of box building). Boehm insertion touches only
99/// the knots and controls around the split, and the remainder's tail is always
100/// the ORIGINAL curve's, bit for bit; so this keeps the remainder as the last
101/// split's right half (a short head) followed by an offset into the original,
102/// and splits a WINDOW of it (the head and the original up to `degree + 1`
103/// knots past the parameter) with [`split_window`], `split`'s own arithmetic
104/// on slices. Every box is the same bits as the split path's; anything this
105/// cannot take (a parameter `split` would refuse) hands the whole curve back to
106/// [`segment_boxes_split`], so errors are the split path's too.
107fn segment_boxes_walk(curve: &NurbsCurve, count: usize) -> Result<Option<Vec<Segment>>, String> {
108    let [start, end] = curve.domain()?;
109    let mut parameters: Vec<f64> = (0..=count)
110        .map(|index| start + (end - start) * index as f64 / count as f64)
111        .collect();
112    parameters.extend(interior_knots(curve));
113    parameters.sort_by(f64::total_cmp);
114    parameters.dedup_by(|a, b| (*a - *b).abs() <= KNOT_TOLERANCE);
115
116    let degree = curve.degree;
117    let (knots, points) = (&curve.knots, &curve.control_points);
118    // The remainder: `head_*` followed by `knots[tail_knot..]`, `points[tail_point..]`.
119    let mut head_knots: Vec<f64> = Vec::new();
120    let mut head_points: Vec<crate::Vec4> = Vec::new();
121    let (mut tail_knot, mut tail_point) = (0usize, 0usize);
122    let mut segments = Vec::new();
123    let mut rest_start = start;
124    for (index, &parameter) in parameters.iter().enumerate().skip(1) {
125        if parameter - rest_start <= KNOT_TOLERANCE {
126            continue;
127        }
128        let knot_count = head_knots.len() + knots.len() - tail_knot;
129        let point_count = head_points.len() + points.len() - tail_point;
130        let rest_knot = |at: usize| if at < head_knots.len() { head_knots[at] } else { knots[tail_knot + at - head_knots.len()] };
131        let rest_point = |at: usize| if at < head_points.len() { head_points[at] } else { points[tail_point + at - head_points.len()] };
132        if index == parameters.len() - 1 {
133            let rest = NurbsCurve::new(degree, (0..knot_count).map(rest_knot).collect(), (0..point_count).map(rest_point).collect())?;
134            segments.push(Segment { start: rest_start, end, bounds: Bounds::from_curve_controls(&rest)? });
135            continue;
136        }
137        // `split`'s own refusal: a parameter not strictly inside the remainder.
138        let (rest_low, rest_high) = (rest_knot(degree), rest_knot(knot_count - 1 - degree));
139        if parameter <= rest_low + KNOT_TOLERANCE || parameter >= rest_high - KNOT_TOLERANCE {
140            return Ok(None);
141        }
142        let mut beyond = degree + 1;
143        while beyond < knot_count && rest_knot(beyond) <= parameter + KNOT_TOLERANCE {
144            beyond += 1;
145        }
146        let window_points = (beyond + degree + 1).max(head_points.len()).min(point_count);
147        let window_knots = window_points + degree + 1;
148        let window_knot_values: Vec<f64> = (0..window_knots).map(rest_knot).collect();
149        let window_point_values: Vec<crate::Vec4> = (0..window_points).map(rest_point).collect();
150        let Some((left_knots, left_points, right_knots, right_points)) =
151            split_window(&window_knot_values, &window_point_values, degree, parameter)
152        else {
153            return Ok(None);
154        };
155        let piece = NurbsCurve::new(degree, left_knots, left_points)?;
156        segments.push(Segment { start: rest_start, end: parameter, bounds: Bounds::from_curve_controls(&piece)? });
157        tail_point += window_points - head_points.len();
158        tail_knot += window_knots - head_knots.len();
159        head_points = right_points;
160        head_knots = right_knots;
161        rest_start = parameter;
162    }
163    Ok(Some(segments))
164}
165
166/// `NurbsCurve::split` (and the `insert_knot` it calls) on the leading
167/// WINDOW of a curve's knots and controls, with the same operations in the
168/// same order: Boehm insertion reads only the knots up to `span + degree` and
169/// the controls up to `span`, the span search finds the one interval holding
170/// the parameter, and the window reaches `degree + 1` knots past it. Returns
171/// the left piece and the window's part of the right piece; `None` where
172/// `split` would refuse.
173#[allow(clippy::type_complexity)]
174fn split_window(
175    knots: &[f64],
176    points: &[crate::Vec4],
177    degree: usize,
178    parameter: f64,
179) -> Option<(Vec<f64>, Vec<crate::Vec4>, Vec<f64>, Vec<crate::Vec4>)> {
180    use crate::curve::{knot_clamp, knot_find_span};
181    let parameter = knots.iter().copied().find(|knot| (knot - parameter).abs() <= KNOT_TOLERANCE).unwrap_or(parameter);
182    let multiplicity = knots.iter().filter(|knot| (**knot - parameter).abs() <= KNOT_TOLERANCE).count();
183    let requested = degree.saturating_sub(multiplicity);
184    // insert_knot(parameter, requested)
185    let inserted = {
186        let at = knot_clamp(knots, degree, parameter);
187        let at = knots.iter().copied().find(|knot| (knot - at).abs() <= KNOT_TOLERANCE).unwrap_or(at);
188        let multiplicity = knots.iter().filter(|knot| (**knot - at).abs() <= KNOT_TOLERANCE).count();
189        let insertion_count = requested.min(degree.saturating_sub(multiplicity));
190        if insertion_count == 0 {
191            (knots.to_vec(), points.to_vec())
192        } else {
193            let span = knot_find_span(knots, degree, at);
194            let last_control = points.len() - 1;
195            let mut refined_knots = Vec::with_capacity(knots.len() + insertion_count);
196            refined_knots.extend_from_slice(&knots[..=span]);
197            refined_knots.extend(std::iter::repeat_n(at, insertion_count));
198            refined_knots.extend_from_slice(&knots[span + 1..]);
199            let mut output = vec![crate::Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 1.0 }; last_control + 1 + insertion_count];
200            output[..=span - degree].copy_from_slice(&points[..=span - degree]);
201            for index in span - multiplicity..=last_control {
202                output[index + insertion_count] = points[index];
203            }
204            let mut affected = vec![crate::Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 1.0 }; degree + 1];
205            affected[..=degree - multiplicity].copy_from_slice(&points[span - degree..=span - multiplicity]);
206            let mut left = 0;
207            for insertion in 1..=insertion_count {
208                left = span - degree + insertion;
209                for index in 0..=degree - insertion - multiplicity {
210                    let denominator = knots[index + span + 1] - knots[left + index];
211                    let alpha = (at - knots[left + index]) / denominator;
212                    affected[index] = affected[index + 1].scale(alpha).add(affected[index].scale(1.0 - alpha));
213                }
214                output[left] = affected[0];
215                output[span + insertion_count - insertion - multiplicity] = affected[degree - insertion - multiplicity];
216            }
217            for index in left + 1..span - multiplicity {
218                output[index] = affected[index - left];
219            }
220            (refined_knots, output)
221        }
222    };
223    let (refined_knots, refined_points) = inserted;
224    let first = refined_knots.iter().position(|knot| (*knot - parameter).abs() <= KNOT_TOLERANCE)?;
225    if first == 0 {
226        return None;
227    }
228    let mut left_knots = refined_knots[..first + degree].to_vec();
229    left_knots.push(parameter);
230    let left_points = refined_points[..first].to_vec();
231    let mut right_knots = vec![parameter; degree + 1];
232    right_knots.extend_from_slice(&refined_knots[first + degree..]);
233    let right_points = refined_points[first - 1..].to_vec();
234    Some((left_knots, left_points, right_knots, right_points))
235}
236
237fn segment_boxes_split(curve: &NurbsCurve, count: usize) -> Result<Vec<Segment>, String> {
238    let [start, end] = curve.domain()?;
239    let mut parameters: Vec<f64> = (0..=count)
240        .map(|index| start + (end - start) * index as f64 / count as f64)
241        .collect();
242    parameters.extend(interior_knots(curve));
243    parameters.sort_by(f64::total_cmp);
244    parameters.dedup_by(|a, b| (*a - *b).abs() <= KNOT_TOLERANCE);
245
246    let mut segments = Vec::new();
247    let mut rest = curve.clone();
248    let mut rest_start = start;
249    for (index, &parameter) in parameters.iter().enumerate().skip(1) {
250        if parameter - rest_start <= KNOT_TOLERANCE {
251            continue;
252        }
253        if index == parameters.len() - 1 {
254            segments.push(Segment {
255                start: rest_start,
256                end,
257                bounds: Bounds::from_curve_controls(&rest)?,
258            });
259        } else {
260            let (piece, remainder) = rest.split(parameter)?;
261            segments.push(Segment {
262                start: rest_start,
263                end: parameter,
264                bounds: Bounds::from_curve_controls(&piece)?,
265            });
266            rest = remainder;
267            rest_start = parameter;
268        }
269    }
270    Ok(segments)
271}
272
273fn newton_closest_pair(
274    first: &NurbsCurve,
275    second: &NurbsCurve,
276    seed_s: f64,
277    seed_t: f64,
278    curvature: bool,
279) -> Result<[f64; 2], String> {
280    let [s0, s1] = first.domain()?;
281    let [t0, t1] = second.domain()?;
282    let mut s = seed_s;
283    let mut t = seed_t;
284    for _ in 0..40 {
285        let first_derivatives = first.derivatives_small(s, 2)?;
286        let second_derivatives = second.derivatives_small(t, 2)?;
287        let residual = first_derivatives[0].sub(second_derivatives[0]);
288        let f = first_derivatives[1].dot(residual);
289        let g = -second_derivatives[1].dot(residual);
290        let j00 = first_derivatives[1].length_squared()
291            + if curvature { first_derivatives[2].dot(residual) } else { 0.0 };
292        let j01 = -first_derivatives[1].dot(second_derivatives[1]);
293        let j10 = -second_derivatives[1].dot(first_derivatives[1]);
294        let j11 = second_derivatives[1].length_squared()
295            - if curvature { second_derivatives[2].dot(residual) } else { 0.0 };
296        let residual_length = residual.length();
297        let converged_first =
298            f.abs() <= EPSILON + 1e-10 * first_derivatives[1].length() * residual_length.max(1e-30);
299        let converged_second = g.abs()
300            <= EPSILON + 1e-10 * second_derivatives[1].length() * residual_length.max(1e-30);
301        if (converged_first && converged_second) || residual_length <= EPSILON {
302            return Ok([s, t]);
303        }
304        let determinant = j00 * j11 - j01 * j10;
305        if determinant.abs() <= EPSILON {
306            return Ok([s, t]);
307        }
308        let mut ds = (-f * j11 + g * j01) / determinant;
309        let mut dt = (-g * j00 + f * j10) / determinant;
310        ds = ds.clamp(-(s1 - s0) / 4.0, (s1 - s0) / 4.0);
311        dt = dt.clamp(-(t1 - t0) / 4.0, (t1 - t0) / 4.0);
312        let next_s = (s + ds).clamp(s0, s1);
313        let next_t = (t + dt).clamp(t0, t1);
314        if (next_s - s).abs() <= 1e-15 * (s1 - s0) && (next_t - t).abs() <= 1e-15 * (t1 - t0) {
315            return Ok([next_s, next_t]);
316        }
317        s = next_s;
318        t = next_t;
319    }
320    Ok([s, t])
321}
322
323fn parameter_tolerance(curve: &NurbsCurve, parameter: f64, tolerance: f64) -> Result<f64, String> {
324    let speed = curve.deriv1(parameter)?.1.length();
325    let [start, end] = curve.domain()?;
326    if speed <= EPSILON {
327        Ok((end - start) * 1e-3)
328    } else {
329        Ok(((tolerance / speed) * 10.0).max((end - start) * 1e-9))
330    }
331}
332
333fn parameter_distance(a: f64, b: f64, start: f64, end: f64, closed: bool) -> f64 {
334    let distance = (a - b).abs();
335    if closed {
336        distance.min(end - start - distance)
337    } else {
338        distance
339    }
340}
341
342#[derive(Clone, Copy, Debug, Serialize)]
343pub struct CurveCurveIntersection {
344    pub s: f64,
345    pub t: f64,
346    pub point: Vec3,
347    pub gap: f64,
348    pub tangential: bool,
349}
350
351/// `BREP_EXACT_LINE_LINE` (lane X row 7): two straight segments that are not
352/// near parallel meet where their exact closest pair says
353/// ([`exact_line_line`]), instead of where Newton runs from box seeds settle.
354/// On by default; `0`/`off` returns to the general search, and `census`
355/// answers by the general search and appends one line per call whose answers
356/// differ to `BREP_EXACT_LINE_LINE_CENSUS`.
357///
358/// Promoted 2026-10-16 on top of the canonical fragment order. 239 documents:
359/// 6,853 calls change, every one with the same hit count; the exact pair
360/// removes residuals up to 2.02e-8, and the per-hit gap goes from a 2.17e-8
361/// maximum to 7.9e-9. The exact pair is exact by construction, and the 1,387
362/// hits whose evaluated gap reads above the general search's, by at most
363/// 1.21e-13 (p50 8.9e-16), are the rounding floor of measuring the gap, not
364/// lost accuracy. 49 documents change bytes; every body is geometrically the
365/// same, with no name moved.
366#[derive(Clone, Copy, PartialEq, Eq)]
367enum LineLineMode {
368    Off,
369    On,
370    Census,
371}
372
373fn line_line_mode() -> LineLineMode {
374    static MODE: std::sync::OnceLock<LineLineMode> = std::sync::OnceLock::new();
375    let mode = *MODE.get_or_init(|| match std::env::var("BREP_EXACT_LINE_LINE").as_deref() {
376        Ok("0") | Ok("off") => LineLineMode::Off,
377        Ok("census") => LineLineMode::Census,
378        _ => LineLineMode::On,
379    });
380    mode
381}
382
383
384/// Lane O batch 22 (tier-3 finding 1, `BREP_CURVE_TANGENT_MERGE_LOCAL`,
385/// default on since batch 27; `1`/`on`, `census`): the duplicate guard's radius for
386/// TANGENTIAL hits and the cluster's representative.
387///
388/// Today a tangential hit merges every other hit within
389/// `sqrt(tolerance)·(1 + |p|)` of it — a radius that grows with the point's
390/// distance from the origin, not with the contact: at |p| ≈ 76 it is 0.24
391/// and swallows every tangential hit of a 3.8e-3-radius pair but one (the
392/// 2026-11-02 conic-conic census, record 6), and the one it keeps is the
393/// first seed's, not the closest (record 54: a 1.1e-7 graze represents a
394/// 9e-14 crossing). `On` derives the radius from the contact itself: the
395/// half-width of the band where the two curves stay within the tolerance,
396/// `min(tolerance / sin θ, sqrt(2·tolerance·ρ))` with θ the tangent angle
397/// and ρ = 1 / |κ₁n₁ − κ₂n₂| the relative curvature radius, CAPPED by
398/// today's radius (never wider; a near-coincident stretch with ρ → ∞ merges
399/// exactly as today) and floored at the transverse 10·tolerance; and a
400/// cluster is represented by its smallest-gap hit. `Census` answers as
401/// today and appends one record per call where the two rules differ in a
402/// merge decision or a representative to the file
403/// `BREP_CURVE_TANGENT_MERGE_CENSUS` names (one write per record).
404#[derive(Clone, Copy, PartialEq, Eq)]
405enum TangentMergeMode {
406    Off,
407    On,
408    Census,
409}
410
411fn tangent_merge_mode() -> TangentMergeMode {
412    static MODE: std::sync::OnceLock<TangentMergeMode> = std::sync::OnceLock::new();
413    // On by default since 2026-11-03 (lane O batch 27); `0`/`off` restores
414    // today's |p|-scaled radius.
415    let mode = *MODE.get_or_init(|| match std::env::var("BREP_CURVE_TANGENT_MERGE_LOCAL").as_deref() {
416        Ok("0") | Ok("off") => TangentMergeMode::Off,
417        Ok("census") => TangentMergeMode::Census,
418        _ => TangentMergeMode::On,
419    });
420    mode
421}
422
423
424/// The contact-derived merge radius at a hit `(s, t)`: the half-width of the
425/// band where `first` and `second` stay within `tolerance` of each other,
426/// `min(tolerance / sin θ, sqrt(2·tolerance·ρ))`, capped by `legacy` (today's
427/// radius) and floored at `10·tolerance`. A hit whose tangents cannot be read
428/// keeps `legacy`.
429fn local_tangent_merge_radius(
430    first: &NurbsCurve,
431    second: &NurbsCurve,
432    s: f64,
433    t: f64,
434    tolerance: f64,
435    legacy: f64,
436) -> Result<(f64, f64, f64), String> {
437    let a = first.derivatives_small(s, 2)?;
438    let b = second.derivatives_small(t, 2)?;
439    let (speed_a, speed_b) = (a[1].length(), b[1].length());
440    if speed_a <= EPSILON || speed_b <= EPSILON {
441        return Ok((legacy, f64::NAN, f64::NAN));
442    }
443    let tangent_a = a[1].scale(1.0 / speed_a);
444    let tangent_b = b[1].scale(1.0 / speed_b);
445    let sin_theta = tangent_a.cross(tangent_b).length().min(1.0);
446    // Curvature vectors κn = (d2 − (d2·t)t) / |d1|²: orientation-free, so the
447    // two curves' traversal senses do not matter.
448    let curvature_a = a[2].sub(tangent_a.scale(a[2].dot(tangent_a))).scale(1.0 / (speed_a * speed_a));
449    let curvature_b = b[2].sub(tangent_b.scale(b[2].dot(tangent_b))).scale(1.0 / (speed_b * speed_b));
450    let relative = curvature_a.sub(curvature_b).length();
451    let mut radius = f64::INFINITY;
452    if sin_theta > 0.0 {
453        radius = radius.min(tolerance / sin_theta);
454    }
455    if relative > 0.0 {
456        radius = radius.min((2.0 * tolerance / relative).sqrt());
457    }
458    Ok((radius.min(legacy).max(10.0 * tolerance), sin_theta, relative))
459}
460
461/// The segment a degree-1 curve of two equal-weight control points traces
462/// linearly over its clamped knots: (start point, end point, domain).
463fn straight_segment(curve: &NurbsCurve) -> Option<(Vec3, Vec3, [f64; 2])> {
464    if curve.degree != 1 || curve.control_points.len() != 2 || curve.knots.len() != 4 {
465        return None;
466    }
467    let k = &curve.knots;
468    if k[0] != k[1] || k[2] != k[3] || !(k[1] < k[2]) {
469        return None;
470    }
471    if curve.control_points[0].w != curve.control_points[1].w {
472        return None;
473    }
474    Some((curve.control_points[0].point().ok()?, curve.control_points[1].point().ok()?, [k[1], k[2]]))
475}
476
477/// The exact meeting of two straight segments that are not near parallel:
478/// their unique closest pair (each parameter clamped to its segment, the
479/// other then re-solved), one transverse hit when its gap is within
480/// `tolerance`, none otherwise. `None` (the general search answers) for
481/// anything else: a curve that is not a straight segment, a degenerate one,
482/// or two directions within the tangential band of `intersect_curves`.
483pub fn exact_line_line(first: &NurbsCurve, second: &NurbsCurve, tolerance: f64) -> Option<Vec<CurveCurveIntersection>> {
484    let (p0, p1, [s0, s1]) = straight_segment(first)?;
485    let (q0, q1, [t0, t1]) = straight_segment(second)?;
486    let d1 = p1.sub(p0);
487    let d2 = q1.sub(q0);
488    let a = d1.dot(d1);
489    let e = d2.dot(d2);
490    if a <= EPSILON || e <= EPSILON {
491        return None;
492    }
493    if d1.cross(d2).length() <= 1e-3_f64.sin() * (a * e).sqrt() {
494        return None;
495    }
496    let r = p0.sub(q0);
497    let b = d1.dot(d2);
498    let c = d1.dot(r);
499    let f = d2.dot(r);
500    let denominator = a * e - b * b;
501    let mut s = ((b * f - c * e) / denominator).clamp(0.0, 1.0);
502    let mut t = (b * s + f) / e;
503    if t < 0.0 {
504        t = 0.0;
505        s = (-c / a).clamp(0.0, 1.0);
506    } else if t > 1.0 {
507        t = 1.0;
508        s = ((b - c) / a).clamp(0.0, 1.0);
509    }
510    let first_point = p0.add(d1.scale(s));
511    let second_point = q0.add(d2.scale(t));
512    let gap = first_point.sub(second_point).length();
513    if gap > tolerance {
514        return Some(Vec::new());
515    }
516    Some(vec![CurveCurveIntersection {
517        s: (s0 + (s1 - s0) * s).clamp(s0, s1),
518        t: (t0 + (t1 - t0) * t).clamp(t0, t1),
519        point: first_point.add(second_point).scale(0.5),
520        gap,
521        tangential: false,
522    }])
523}
524
525/// Closed-form seeds only, with no sampled fallback. Used by reductions
526/// that must decline the entire surface pair when a profile pair is not
527/// covered. Every seed must survive refinement (possibly as a duplicate).
528pub(crate) fn intersect_curves_exact_only(first: &NurbsCurve, second: &NurbsCurve, tolerance: f64) -> Option<Vec<CurveCurveIntersection>> {
529    if let Some(hits) = exact_line_line(first,second,tolerance) { return Some(hits); }
530    let seeds = exact_line_conic_pairs(first,second,tolerance)
531        .or_else(|| exact_conic_conic_pairs(first,second,tolerance))?;
532    let hits = intersect_curves_from_seeds(first,second,tolerance,seeds.clone()).ok()?;
533    for [s,t] in seeds {
534        let a = first.evaluate(s).ok()?;
535        let b = second.evaluate(t).ok()?;
536        if !hits.iter().any(|hit| hit.point.sub(a).length() <= 4.0*tolerance && hit.point.sub(b).length() <= 4.0*tolerance) { return None; }
537    }
538    Some(hits)
539}
540
541pub fn intersect_curves(
542    first: &NurbsCurve,
543    second: &NurbsCurve,
544    tolerance: f64,
545) -> Result<Vec<CurveCurveIntersection>, String> {
546    let mode = line_line_mode();
547    if mode != LineLineMode::Off {
548        if let Some(exact) = exact_line_line(first, second, tolerance) {
549            if mode == LineLineMode::On {
550                return Ok(exact);
551            }
552            let general = intersect_curves_general(first, second, tolerance)?;
553            line_line_census(first, second, tolerance, &general, &exact)?;
554            return Ok(general);
555        }
556    }
557    let mode = line_conic_mode();
558    if mode != LineLineMode::Off {
559        if let Some(seeds) = exact_line_conic_pairs(first, second, tolerance) {
560            let exact = intersect_curves_from_seeds(first, second, tolerance, seeds)?;
561            if mode == LineLineMode::On {
562                return Ok(exact);
563            }
564            let general = intersect_curves_general(first, second, tolerance)?;
565            crossing_census("line-conic", "BREP_EXACT_LINE_CONIC_CENSUS", first, second, tolerance, &general, &exact)?;
566            return Ok(general);
567        }
568    }
569    let mode = conic_conic_mode();
570    if mode != LineLineMode::Off {
571        if let Some(seeds) = exact_conic_conic_pairs(first, second, tolerance) {
572            let exact = intersect_curves_from_seeds(first, second, tolerance, seeds)?;
573            if mode == LineLineMode::On {
574                return Ok(exact);
575            }
576            let general = intersect_curves_general(first, second, tolerance)?;
577            // Self-check (lane O batch 22, finding 2): the 2026-11-02 census
578            // recorded one general crossing for a pair every later replay
579            // answers with two; a second call here, compared by bits, makes
580            // the record say whether the search itself wavered in the run.
581            general_rerun_census("conic-conic", "BREP_EXACT_CONIC_CONIC_CENSUS", first, second, tolerance, &general)?;
582            crossing_census("conic-conic", "BREP_EXACT_CONIC_CONIC_CENSUS", first, second, tolerance, &general, &exact)?;
583            return Ok(general);
584        }
585    }
586    intersect_curves_general(first, second, tolerance)
587}
588
589/// Lane O row 40 (`BREP_EXACT_CONIC_CONIC`, default on since batch 27, `0` restores; `1`/`on` answers by
590/// it, `census` answers by the general search and appends one line per call
591/// whose answers differ to `BREP_EXACT_CONIC_CONIC_CENSUS`): two planar curves
592/// of degree two seed the general search's own Newton, gap filter, duplicate
593/// guard and tangency reading ([`intersect_curves_from_seeds`]) at closed-form
594/// crossings instead of at the midpoints of every overlapping pair of segment
595/// boxes. See [`exact_conic_conic_pairs`].
596fn conic_conic_mode() -> LineLineMode {
597    static MODE: std::sync::OnceLock<LineLineMode> = std::sync::OnceLock::new();
598    // On by default since 2026-11-03 (lane O batch 27); `0`/`off` restores
599    // the general search for two planar conics.
600    let mode = *MODE.get_or_init(|| match std::env::var("BREP_EXACT_CONIC_CONIC").as_deref() {
601        Ok("0") | Ok("off") => LineLineMode::Off,
602        Ok("census") => LineLineMode::Census,
603        _ => LineLineMode::On,
604    });
605    mode
606}
607
608
609/// The plane of a planar curve of degree two with positive finite weights:
610/// a control point, the unit normal of the widest control triangle, and the
611/// net's extent. `None` for collinear controls or a net out of one plane by
612/// more than 1e-12 of its extent (row 28's conic test).
613fn conic_plane(curve: &NurbsCurve) -> Option<(Vec3, Vec3, f64)> {
614    if curve.degree != 2 || curve.control_points.len() < 3 {
615        return None;
616    }
617    if curve.control_points.iter().any(|p| !(p.w > 0.0 && p.w.is_finite())) {
618        return None;
619    }
620    let points = curve.control_points.iter().map(|p| p.point().ok()).collect::<Option<Vec<_>>>()?;
621    let base = points[0];
622    let extent = points.iter().fold(0.0_f64, |m, p| m.max(p.sub(base).length()));
623    if !(extent > 0.0 && extent.is_finite()) {
624        return None;
625    }
626    let mut normal = Vec3::new(0.0, 0.0, 0.0);
627    let mut area = 0.0_f64;
628    for i in 1..points.len() {
629        for j in i + 1..points.len() {
630            let cross = points[i].sub(base).cross(points[j].sub(base));
631            if cross.length() > area {
632                area = cross.length();
633                normal = cross;
634            }
635        }
636    }
637    if !(area > 1e-9 * extent * extent) {
638        return None;
639    }
640    let normal = normal.scale(1.0 / area);
641    if points.iter().any(|p| normal.dot(p.sub(base)).abs() > 1e-12 * extent) {
642        return None;
643    }
644    Some((base, normal, extent))
645}
646
647/// The `[s, t]` Newton seeds of row 40 for two planar curves of degree two;
648/// `None` when the lane declines.
649///
650/// - Planes that cross (more than a milliradian apart): every crossing lies on
651///   the line the planes share, so `first`'s seeds are row 28's crossings of
652///   `first` with that line ([`crate::exact_line_surface::exact_line_conic_seeds`],
653///   grazes within a hundred tolerances included).
654/// - One plane, `second` a circle (recognized to 1e-12 of its size): a curve
655///   in a circle's plane crosses it where it crosses the sphere on that
656///   circle, so `first`'s seeds are row 27's sphere roots
657///   ([`crate::exact_line_surface::exact_curve_sphere_seeds`], which declines
658///   a span on the sphere and a double root). A sample of `first` within a
659///   hundred tolerances of the circle with no seed declines too: a near
660///   graze the general search would report.
661/// - Anything else (parallel planes, an ellipse sharing a plane, a non-planar
662///   net) declines.
663///
664/// Each seed is paired with its point's projection onto `second`; the general
665/// search's Newton and gap filter decide what is a crossing.
666fn exact_conic_conic_pairs(first: &NurbsCurve, second: &NurbsCurve, tolerance: f64) -> Option<Vec<[f64; 2]>> {
667    let (base_a, normal_a, extent_a) = conic_plane(first)?;
668    let (base_b, normal_b, extent_b) = conic_plane(second)?;
669    let extent = extent_a.max(extent_b);
670    let shared = normal_a.cross(normal_b);
671    let seeds = if shared.length() > 1e-3_f64.sin() {
672        // The line both planes hold, through the point of it nearest `base_a`.
673        let direction = shared.scale(1.0 / shared.length());
674        let (h_a, h_b) = (normal_a.dot(base_a), normal_b.dot(base_b));
675        let denominator = shared.dot(shared);
676        let on_line = normal_b.cross(shared).scale(h_a / denominator).add(shared.cross(normal_a).scale(h_b / denominator));
677        let foot = on_line.add(direction.scale(base_a.sub(on_line).dot(direction)));
678        let reach = 2.0 * (extent + base_a.sub(foot).length()).max(1.0);
679        crate::exact_line_surface::exact_line_conic_seeds(foot.sub(direction.scale(reach)), foot.add(direction.scale(reach)), first, tolerance)?
680    } else if normal_a.dot(base_b.sub(base_a)).abs() <= 1e-12 * extent {
681        let [t0, t1] = second.domain().ok()?;
682        let circle = crate::recognize_circle(second, t0, t1, 1e-12 * extent.max(1.0))?;
683        let seeds = crate::exact_line_surface::exact_curve_sphere_seeds(first, circle.centre, circle.radius, tolerance)?;
684        if seeds.is_empty() {
685            let [s0, s1] = first.domain().ok()?;
686            let band = 100.0 * tolerance;
687            for i in 0..=64 {
688                let point = first.evaluate(s0 + (s1 - s0) * i as f64 / 64.0).ok()?;
689                if (point.sub(circle.centre).length() - circle.radius).abs() <= band {
690                    return None;
691                }
692            }
693        }
694        seeds
695    } else {
696        return None;
697    };
698    seeds
699        .into_iter()
700        .map(|s| {
701            let point = first.evaluate(s).ok()?;
702            let projection = crate::project_point_to_curve(second, point).ok()?;
703            Some([s, projection.u])
704        })
705        .collect()
706}
707
708/// Lane O row 28 (`BREP_EXACT_LINE_CONIC`, default on since batch 12; `0`/`off`
709/// restores the general search, `census` answers by it and appends one line per call
710/// whose answers differ to `BREP_EXACT_LINE_CONIC_CENSUS`): a straight
711/// segment against a planar curve of degree two, either order, seeds the
712/// general search's own Newton, gap filter, duplicate guard and tangency
713/// reading ([`intersect_curves_from_seeds`]) at the closed-form crossings of
714/// [`crate::exact_line_surface::exact_line_conic_seeds`] instead of at the
715/// midpoints of every overlapping pair of segment boxes. Each conic seed is
716/// paired with its point's projection onto the segment.
717fn line_conic_mode() -> LineLineMode {
718    static MODE: std::sync::OnceLock<LineLineMode> = std::sync::OnceLock::new();
719    let mode = *MODE.get_or_init(|| match std::env::var("BREP_EXACT_LINE_CONIC").as_deref() {
720        Ok("0") | Ok("off") => LineLineMode::Off,
721        Ok("census") => LineLineMode::Census,
722        _ => LineLineMode::On,
723    });
724    mode
725}
726
727
728/// The `[s, t]` Newton seeds of row 28 for `first` against `second`, when one
729/// is a straight segment and the other a planar curve of degree two; `None`
730/// when the lane declines.
731fn exact_line_conic_pairs(first: &NurbsCurve, second: &NurbsCurve, tolerance: f64) -> Option<Vec<[f64; 2]>> {
732    let (line_first, (p0, p1, [l0, l1]), conic) = match (straight_segment(first), straight_segment(second)) {
733        (Some(segment), None) => (true, segment, second),
734        (None, Some(segment)) => (false, segment, first),
735        _ => return None,
736    };
737    let seeds = crate::exact_line_surface::exact_line_conic_seeds(p0, p1, conic, tolerance)?;
738    let direction = p1.sub(p0);
739    let length_squared = direction.dot(direction);
740    seeds
741        .into_iter()
742        .map(|t| {
743            let point = conic.evaluate(t).ok()?;
744            let along = (point.sub(p0).dot(direction) / length_squared).clamp(0.0, 1.0);
745            let s = l0 + along * (l1 - l0);
746            Some(if line_first { [s, t] } else { [t, s] })
747        })
748        .collect()
749}
750
751/// One census line per call whose general and exact answers differ: both
752/// hit lists, and for each general hit its points' distances from the exact
753/// closest pair (the residual the exact answer removes).
754fn line_line_census(
755    first: &NurbsCurve,
756    second: &NurbsCurve,
757    tolerance: f64,
758    general: &[CurveCurveIntersection],
759    exact: &[CurveCurveIntersection],
760) -> Result<(), String> {
761    crossing_census("line-line", "BREP_EXACT_LINE_LINE_CENSUS", first, second, tolerance, general, exact)
762}
763
764/// Census self-check: the general search run a second time on the same
765/// pair, appended as `<lane> rerun census: … general <n> rerun <m>` with
766/// both hit lists when any hit differs by bits (one write per record).
767fn general_rerun_census(
768    lane: &str,
769    variable: &str,
770    first: &NurbsCurve,
771    second: &NurbsCurve,
772    tolerance: f64,
773    general: &[CurveCurveIntersection],
774) -> Result<(), String> {
775    let Ok(path) = std::env::var(variable) else {
776        return Ok(());
777    };
778    let rerun = intersect_curves_general(first, second, tolerance)?;
779    let same = general.len() == rerun.len()
780        && general.iter().zip(&rerun).all(|(g, r)| g.s.to_bits() == r.s.to_bits() && g.t.to_bits() == r.t.to_bits());
781    if same {
782        return Ok(());
783    }
784    let mut line = format!("{lane} rerun census: tolerance={tolerance:e} general {} rerun {}", general.len(), rerun.len());
785    for g in general {
786        line.push_str(&format!(" | general s={:e} t={:e} gap={:e}", g.s, g.t, g.gap));
787    }
788    for r in &rerun {
789        line.push_str(&format!(" | rerun s={:e} t={:e} gap={:e}", r.s, r.t, r.gap));
790    }
791    if let (Ok(a), Ok(b)) = (serde_json::to_string(first), serde_json::to_string(second)) {
792        line.push_str(&format!(" | curves=[{a},{b}]"));
793    }
794    line.push('\n');
795    use std::io::Write;
796    if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
797        let _ = file.write_all(line.as_bytes());
798    }
799    Ok(())
800}
801
802/// [`line_line_census`] for the lane named `lane`, appending to the file that
803/// `variable` names. The record names the call's tolerance, every exact hit,
804/// and every general hit with its parameter offset and spatial residual from
805/// the nearest exact hit. When the two answers disagree on the hit count, or a
806/// general hit sits further than the tolerance from every exact hit, the
807/// record ends with both curves as JSON (`curves=`) so the pair can be
808/// replayed. One record is one `write` so concurrent callers never splice.
809fn crossing_census(
810    lane: &str,
811    variable: &str,
812    first: &NurbsCurve,
813    second: &NurbsCurve,
814    tolerance: f64,
815    general: &[CurveCurveIntersection],
816    exact: &[CurveCurveIntersection],
817) -> Result<(), String> {
818    let same = general.len() == exact.len()
819        && general.iter().zip(exact).all(|(g, x)| g.s.to_bits() == x.s.to_bits() && g.t.to_bits() == x.t.to_bits());
820    if same {
821        return Ok(());
822    }
823    let Ok(path) = std::env::var(variable) else {
824        return Ok(());
825    };
826    let mut line = format!(
827        "{lane} census: label {} tolerance={:e} general {} exact {}",
828        std::env::var("BREP_CENSUS_LABEL").unwrap_or_default(),
829        tolerance,
830        general.len(),
831        exact.len()
832    );
833    let mut exact_points = Vec::with_capacity(exact.len());
834    for x in exact {
835        exact_points.push((first.evaluate(x.s)?, second.evaluate(x.t)?));
836        line.push_str(&format!(" | exact s={:e} t={:e} gap={:e}", x.s, x.t, x.gap));
837    }
838    let mut unmatched = false;
839    for g in general {
840        let (on_first, on_second) = (first.evaluate(g.s)?, second.evaluate(g.t)?);
841        let nearest = exact
842            .iter()
843            .zip(&exact_points)
844            .map(|(x, (xf, xs))| (on_first.sub(*xf).length().max(on_second.sub(*xs).length()), x))
845            .min_by(|a, b| a.0.total_cmp(&b.0));
846        match nearest {
847            Some((residual, x)) => {
848                unmatched |= residual > tolerance;
849                line.push_str(&format!(
850                    " | general s={:e} t={:e} gap={:e} ds={:e} dt={:e} residual={:e}",
851                    g.s,
852                    g.t,
853                    g.gap,
854                    g.s - x.s,
855                    g.t - x.t,
856                    residual
857                ));
858            }
859            None => {
860                unmatched = true;
861                line.push_str(&format!(" | general s={:e} t={:e} gap={:e}", g.s, g.t, g.gap));
862            }
863        }
864    }
865    if general.len() != exact.len() || unmatched {
866        if let (Ok(a), Ok(b)) = (serde_json::to_string(first), serde_json::to_string(second)) {
867            line.push_str(&format!(" | curves=[{a},{b}]"));
868        }
869    }
870    line.push('\n');
871    use std::io::Write;
872    if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
873        let _ = file.write_all(line.as_bytes());
874    }
875    Ok(())
876}
877
878/// Every `(i, j)` with `first[i].bounds` and `second[j].bounds` within
879/// `tolerance` of each other, in ascending `(i, j)` order — exactly the pairs
880/// and the order the nested loop produced. The second list is sorted by its
881/// boxes' minimum x once; for each first segment the candidates are the
882/// second segments whose minimum x lies at or below the first's maximum x
883/// plus the tolerance (a prefix of the sorted order), filtered by the full
884/// box test. Each pair is tested by the same `Aabb::intersects` as before.
885fn overlapping_segment_pairs(first: &[Segment], second: &[Segment], tolerance: f64) -> Vec<(usize, usize)> {
886    let mut order: Vec<usize> = (0..second.len()).collect();
887    order.sort_by(|&a, &b| second[a].bounds.minimum.x.total_cmp(&second[b].bounds.minimum.x));
888    let minimum_x: Vec<f64> = order.iter().map(|&j| second[j].bounds.minimum.x).collect();
889    let mut pairs = Vec::new();
890    for (i, segment) in first.iter().enumerate() {
891        let limit = segment.bounds.maximum.x + tolerance;
892        // Candidates: the prefix with minimum x <= limit.
893        let end = minimum_x.partition_point(|&x| x <= limit);
894        let mut row: Vec<usize> = order[..end]
895            .iter()
896            .copied()
897            .filter(|&j| segment.bounds.intersects_upper(second[j].bounds, tolerance))
898            .collect();
899        row.sort_unstable();
900        pairs.extend(row.into_iter().map(|j| (i, j)));
901    }
902    pairs
903}
904
905fn intersect_curves_general(
906    first: &NurbsCurve,
907    second: &NurbsCurve,
908    tolerance: f64,
909) -> Result<Vec<CurveCurveIntersection>, String> {
910    let first_segment_count = 8usize.max((interior_knots(first).len() + 1) * (first.degree + 1));
911    let second_segment_count = 8usize.max((interior_knots(second).len() + 1) * (second.degree + 1));
912    let first_segments = segment_boxes_memoized(first, first_segment_count)?;
913    let second_segments = segment_boxes_memoized(second, second_segment_count)?;
914    // The overlapping segment pairs, in the order the nested loop over
915    // `first_segments` then `second_segments` visits them: the seeds' order
916    // decides which of two converging seeds is kept as the hit below, so the
917    // pairs are gathered by a sweep over the x extents (sorted once, a binary
918    // search per first segment) and then put back into that order. Two fitted
919    // sections of two thousand segments each cost four million box tests
920    // a call before (2026-10-17, the shelled-box report's shell: 0.57 s of
921    // `lies_on` spans and 0.55 s of section crossings on three face pairs).
922    let seeds = overlapping_segment_pairs(&first_segments, &second_segments, tolerance)
923        .into_iter()
924        .map(|(i, j)| {
925            [
926                (first_segments[i].start + first_segments[i].end) * 0.5,
927                (second_segments[j].start + second_segments[j].end) * 0.5,
928            ]
929        })
930        .collect::<Vec<_>>();
931    intersect_curves_from_seeds(first, second, tolerance, seeds)
932}
933
934/// The general search past its seeding: a Newton run from each `[s, t]`
935/// seed (a Gauss–Newton retry for those that fail), then the gap filter, the
936/// duplicate guard and the tangency reading, sorted by `s`.
937fn intersect_curves_from_seeds(
938    first: &NurbsCurve,
939    second: &NurbsCurve,
940    tolerance: f64,
941    seeds: Vec<[f64; 2]>,
942) -> Result<Vec<CurveCurveIntersection>, String> {
943    let [s0, s1] = first.domain()?;
944    let [t0, t1] = second.domain()?;
945    let closed_first = first.evaluate(s0)?.sub(first.evaluate(s1)?).length() <= tolerance;
946    let closed_second = second.evaluate(t0)?.sub(second.evaluate(t1)?).length() <= tolerance;
947    // The distance Hessian can lead Newton to a nonzero stationary point
948    // instead of a crossing. For a secant of a closed circle, every box seed
949    // can converge to the circle's seam this way. Retry failed seeds with
950    // the positive-semidefinite Gauss–Newton system (no curvature terms).
951    // Keep the successful Newton candidates first so their established
952    // parameters win deduplication; the retry must meet the same gap test.
953    let mut candidates = Vec::with_capacity(seeds.len());
954    let mut failed = Vec::new();
955    for [seed_s, seed_t] in seeds {
956        let pair = newton_closest_pair(first, second, seed_s, seed_t, true)?;
957        if first.evaluate(pair[0])?.sub(second.evaluate(pair[1])?).length() <= tolerance {
958            candidates.push(pair);
959        } else {
960            failed.push([seed_s, seed_t]);
961        }
962    }
963    for [seed_s, seed_t] in failed {
964        candidates.push(newton_closest_pair(first, second, seed_s, seed_t, false)?);
965    }
966    let mut results: Vec<CurveCurveIntersection> = Vec::new();
967    // The contact radius of each kept TANGENTIAL hit (`BREP_CURVE_TANGENT_MERGE_LOCAL`
968    // on or census), so a later TRANSVERSE candidate near it is judged by that
969    // hit's contact, not only by its own transverse band: the rule is the same
970    // whichever of the two seeds arrives first.
971    let mut kept_radii: Vec<Option<f64>> = Vec::new();
972    for [s, t] in candidates {
973        let first_point = first.evaluate(s)?;
974        let second_point = second.evaluate(t)?;
975        let gap = first_point.sub(second_point).length();
976        if gap > tolerance {
977            continue;
978        }
979        let first_tangent = first.deriv1(s)?.1;
980        let second_tangent = second.deriv1(t)?.1;
981        let tangential = match (first_tangent.normalized(), second_tangent.normalized()) {
982            (Ok(a), Ok(b)) => a.cross(b).length() <= 1e-3_f64.sin(),
983            _ => false,
984        };
985        let point = first_point.add(second_point).scale(0.5);
986        let scale = 1.0 + point.length();
987        let spatial_tolerance = if tangential {
988            tolerance.sqrt() * scale
989        } else {
990            tolerance * 10.0
991        };
992        // Lane O batch 22: the contact-derived tangential radius (see
993        // `TangentMergeMode`). Read only when the rule is on or counted.
994        let merge_mode = tangent_merge_mode();
995        let local = if tangential && merge_mode != TangentMergeMode::Off {
996            Some(local_tangent_merge_radius(first, second, s, t, tolerance, spatial_tolerance)?)
997        } else {
998            None
999        };
1000        let local_tolerance = local.map(|(radius, _, _)| radius).unwrap_or(spatial_tolerance);
1001        // The duplicate each rule finds: today's radius and the local one.
1002        let (mut legacy_duplicate, mut local_duplicate) = (None, None);
1003        for (index, result) in results.iter().enumerate() {
1004            let in_parameter = parameter_distance(result.s, s, s0, s1, closed_first)
1005                <= parameter_tolerance(first, result.s, tolerance)?
1006                && parameter_distance(result.t, t, t0, t1, closed_second)
1007                    <= parameter_tolerance(second, result.t, tolerance)?;
1008            let distance = result.point.sub(point).length();
1009            let either_tangential = result.tangential || tangential;
1010            if legacy_duplicate.is_none()
1011                && (in_parameter || distance <= if either_tangential { spatial_tolerance } else { tolerance * 10.0 })
1012            {
1013                legacy_duplicate = Some(index);
1014            }
1015            // Local: the tangential member's contact radius, the larger of the
1016            // two where both are tangential; a transverse pair keeps 10·tol.
1017            let local_radius = match (tangential, kept_radii.get(index).copied().flatten()) {
1018                (true, Some(kept)) => local_tolerance.max(kept),
1019                (true, None) => local_tolerance,
1020                (false, Some(kept)) => kept,
1021                (false, None) => tolerance * 10.0,
1022            };
1023            if local_duplicate.is_none() && (in_parameter || distance <= local_radius) {
1024                local_duplicate = Some(index);
1025            }
1026            if legacy_duplicate.is_some() && (merge_mode == TangentMergeMode::Off || local_duplicate.is_some()) {
1027                break;
1028            }
1029        }
1030        let candidate = CurveCurveIntersection {
1031            s: s.clamp(s0, s1),
1032            t: t.clamp(t0, t1),
1033            point,
1034            gap,
1035            tangential,
1036        };
1037        let candidate_radius = local.map(|(radius, _, _)| radius);
1038        match merge_mode {
1039            TangentMergeMode::Off => {
1040                if legacy_duplicate.is_some() {
1041                    continue;
1042                }
1043                results.push(candidate);
1044            }
1045            TangentMergeMode::On => match local_duplicate {
1046                // The cluster keeps its smallest-gap hit.
1047                Some(index) => {
1048                    if gap < results[index].gap {
1049                        results[index] = candidate;
1050                        kept_radii[index] = candidate_radius;
1051                    }
1052                }
1053                None => {
1054                    results.push(candidate);
1055                    kept_radii.push(candidate_radius);
1056                }
1057            },
1058            TangentMergeMode::Census => {
1059                // Answer as today; record where the local rule would differ:
1060                // a different merge decision, or a representative the local
1061                // rule would replace by this smaller-gap hit.
1062                let legacy_keeps = legacy_duplicate.is_none();
1063                let local_keeps = local_duplicate.is_none();
1064                let would_replace = local_duplicate.is_some_and(|index| gap < results[index].gap);
1065                if legacy_keeps != local_keeps || would_replace {
1066                    if let Ok(path) = std::env::var("BREP_CURVE_TANGENT_MERGE_CENSUS") {
1067                        let (local_radius, sin_theta, relative) = local.unwrap_or((spatial_tolerance, f64::NAN, f64::NAN));
1068                        let against = legacy_duplicate.or(local_duplicate).map(|index| &results[index]);
1069                        let mut line = format!(
1070                            "tangent-merge census: label {} tolerance={:e} p={:e} legacy_radius={:e} local_radius={:e} sin_theta={:e} relative_curvature={:e} gap={:e} tangential={} legacy_keeps={} local_keeps={} would_replace={}",
1071                            std::env::var("BREP_CENSUS_LABEL").unwrap_or_default(),
1072                            tolerance,
1073                            point.length(),
1074                            spatial_tolerance,
1075                            local_radius,
1076                            sin_theta,
1077                            relative,
1078                            gap,
1079                            tangential,
1080                            legacy_keeps,
1081                            local_keeps,
1082                            would_replace,
1083                        );
1084                        if let Some(other) = against {
1085                            line.push_str(&format!(
1086                                " | against s={:e} t={:e} gap={:e} tangential={} distance={:e}",
1087                                other.s,
1088                                other.t,
1089                                other.gap,
1090                                other.tangential,
1091                                other.point.sub(point).length()
1092                            ));
1093                        }
1094                        if let (Ok(a), Ok(b)) = (serde_json::to_string(first), serde_json::to_string(second)) {
1095                            line.push_str(&format!(" | curves=[{a},{b}]"));
1096                        }
1097                        line.push('\n');
1098                        use std::io::Write;
1099                        if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
1100                            let _ = file.write_all(line.as_bytes());
1101                        }
1102                    }
1103                }
1104                if legacy_duplicate.is_some() {
1105                    continue;
1106                }
1107                results.push(candidate);
1108                kept_radii.push(candidate_radius);
1109            }
1110        }
1111    }
1112    results.sort_by(|a, b| a.s.total_cmp(&b.s));
1113    Ok(results)
1114}
1115
1116
1117