Skip to main content

brep_geometry/intersect/
curve_surface_intersection.rs

1use crate::curve::interior_knot_count;
2use crate::{project_point_to_surface, NurbsCurve, NurbsSurface, Vec3};
3use serde::Serialize;
4
5const EPSILON: f64 = crate::tolerance::FP_FLOOR;
6
7use crate::spatial::Aabb as Bounds;
8
9
10/// The box of the carrier's control points, in their order; the first control
11/// point that is not a point is the error. Read without collecting them: it
12/// is paid on every call, and a view ray through a fitted carrier of a gear
13/// asks it thousands of times.
14fn surface_bounds(surface: &NurbsSurface) -> Result<Bounds, String> {
15    let mut bounds = Bounds::from_points([]);
16    for point in surface.control_points.iter().flatten() {
17        let point = point.point()?;
18        bounds.minimum.x = bounds.minimum.x.min(point.x);
19        bounds.minimum.y = bounds.minimum.y.min(point.y);
20        bounds.minimum.z = bounds.minimum.z.min(point.z);
21        bounds.maximum.x = bounds.maximum.x.max(point.x);
22        bounds.maximum.y = bounds.maximum.y.max(point.y);
23        bounds.maximum.z = bounds.maximum.z.max(point.z);
24    }
25    Ok(bounds)
26}
27
28
29/// The box of each knot-span patch's control points: the surface over span
30/// `[u_i, u_i+1) x [v_j, v_j+1)` lies in the convex hull of the
31/// `(p + 1) x (q + 1)` control points that support it (positive weights), so
32/// a curve segment clear of every span box is clear of the surface.
33///
34/// The whole-net box cannot say that for a carrier that winds: an eight-turn
35/// helical tube's box is the whole coil, every sample segment of a ray through
36/// the coil passes it, and every one seeded a Newton that starts from a global
37/// projection onto a 1280-point net — 21 of the 26 s the 2026-09-26 coil
38/// fillet report's interference check took, for about one hit in forty seeds.
39fn span_bounds(surface: &NurbsSurface) -> Result<Vec<Bounds>, String> {
40    let (p, q) = (surface.degree_u, surface.degree_v);
41    let rows = surface.control_points.len();
42    let columns = surface.control_points.first().map_or(0, Vec::len);
43    let spans = |knots: &[f64], degree: usize, count: usize| -> Vec<usize> {
44        (degree..count).filter(|&i| i + 1 < knots.len() && knots[i] < knots[i + 1]).collect()
45    };
46    let (spans_u, spans_v) = (spans(&surface.knots_u, p, rows), spans(&surface.knots_v, q, columns));
47    // A malformed net has no span structure to trust: the whole-net box stands.
48    if spans_u.is_empty() || spans_v.is_empty() {
49        return Ok(vec![surface_bounds(surface)?]);
50    }
51    let mut boxes = Vec::with_capacity(spans_u.len() * spans_v.len());
52    for &i in &spans_u {
53        for &j in &spans_v {
54            let mut bounds = Bounds::from_points([]);
55            for row in &surface.control_points[i - p..=i] {
56                for control in &row[j - q..=j] {
57                    let point = control.point()?;
58                    bounds.minimum.x = bounds.minimum.x.min(point.x);
59                    bounds.minimum.y = bounds.minimum.y.min(point.y);
60                    bounds.minimum.z = bounds.minimum.z.min(point.z);
61                    bounds.maximum.x = bounds.maximum.x.max(point.x);
62                    bounds.maximum.y = bounds.maximum.y.max(point.y);
63                    bounds.maximum.z = bounds.maximum.z.max(point.z);
64                }
65            }
66            boxes.push(bounds);
67        }
68    }
69    Ok(boxes)
70}
71
72fn fit_parameter(value: f64, minimum: f64, maximum: f64, closed: bool) -> f64 {
73    crate::projection::fit_parameter(value, minimum, maximum, closed)
74}
75
76fn solve_three(matrix: [[f64; 3]; 3], rhs: Vec3) -> Option<[f64; 3]> {
77    let a = matrix;
78    let determinant = a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
79        - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
80        + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]);
81    let scale: f64 = a.iter().flatten().map(|value| value.abs()).sum();
82    if determinant.abs() <= 1e-14 * scale.max(1.0).powi(3) {
83        return None;
84    }
85    let x = (rhs.x * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
86        - a[0][1] * (rhs.y * a[2][2] - a[1][2] * rhs.z)
87        + a[0][2] * (rhs.y * a[2][1] - a[1][1] * rhs.z))
88        / determinant;
89    let y = (a[0][0] * (rhs.y * a[2][2] - a[1][2] * rhs.z)
90        - rhs.x * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
91        + a[0][2] * (a[1][0] * rhs.z - rhs.y * a[2][0]))
92        / determinant;
93    let z = (a[0][0] * (a[1][1] * rhs.z - rhs.y * a[2][1])
94        - a[0][1] * (a[1][0] * rhs.z - rhs.y * a[2][0])
95        + rhs.x * (a[1][0] * a[2][1] - a[1][1] * a[2][0]))
96        / determinant;
97    Some([x, y, z])
98}
99
100/// `BREP_CS_NEWTON_LOCAL_START` (default on; =0 opens from the global foot): on a classifier's ray
101/// ([`intersect_ray_surface`]), each seed's Newton opens from
102/// the local foot of its curve point ([`crate::projection::project_point_to_surface_local`]:
103/// Newton from the seed grid's nearest sample) instead of the nearest point of
104/// the whole surface. The opening foot is only a start: the Newton then solves
105/// curve = surface on its own, and the gap filter and duplicate guard read its
106/// answer as before. On a ray through a winding carrier the global stage was
107/// nine tenths of each Newton's cost.
108pub fn newton_local_start_enabled() -> bool {
109    switch!("BREP_CS_NEWTON_LOCAL_START", true)
110}
111
112/// `BREP_CS_NEWTON_LOCAL_START_CHECK=1` (with the start switch on): solve every
113/// call from both starts, return the local one's answer, and count (and print)
114/// each opening foot more than the model tolerance from the global one's and
115/// each call whose hits differ ([`newton_start_check_counts`]).
116fn newton_local_start_check() -> bool {
117    switch!("BREP_CS_NEWTON_LOCAL_START_CHECK", false)
118}
119
120static START_CHECK_CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
121static START_CHECK_FEET: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
122static START_CHECK_FOOT_DISAGREEMENTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
123static START_CHECK_HIT_DISAGREEMENTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
124
125/// What the check mode has compared in this process: `(calls, opening feet,
126/// feet apart by more than the model tolerance, calls whose hits differ)`.
127pub fn newton_start_check_counts() -> (u64, u64, u64, u64) {
128    use std::sync::atomic::Ordering::Relaxed;
129    (
130        START_CHECK_CALLS.load(Relaxed),
131        START_CHECK_FEET.load(Relaxed),
132        START_CHECK_FOOT_DISAGREEMENTS.load(Relaxed),
133        START_CHECK_HIT_DISAGREEMENTS.load(Relaxed),
134    )
135}
136
137/// The Newton's opening foot of `point`: local or the whole surface's nearest.
138/// In check mode the local start also reads the global foot and counts the two
139/// apart by more than the model tolerance.
140fn opening_foot(surface: &NurbsSurface, point: Vec3, local: bool, check: bool) -> Result<[f64; 2], String> {
141    if !local {
142        let projection = project_point_to_surface(surface, point)?;
143        return Ok([projection.u, projection.v]);
144    }
145    let projection = crate::projection::project_point_to_surface_local(surface, point)?;
146    if check {
147        use std::sync::atomic::Ordering::Relaxed;
148        START_CHECK_FEET.fetch_add(1, Relaxed);
149        let nearest = project_point_to_surface(surface, point)?;
150        let apart = projection.point.sub(nearest.point).length();
151        if apart > crate::tolerance::DEFAULT_MODEL {
152            START_CHECK_FOOT_DISAGREEMENTS.fetch_add(1, Relaxed);
153            eprintln!(
154                "cs newton start check: foot apart {apart:.3e} (local {:.3e} at ({:.9},{:.9}), nearest {:.3e} at ({:.9},{:.9}))",
155                projection.distance, projection.u, projection.v, nearest.distance, nearest.u, nearest.v
156            );
157        }
158    }
159    Ok([projection.u, projection.v])
160}
161
162fn newton_curve_surface(
163    curve: &NurbsCurve,
164    surface: &NurbsSurface,
165    seed: f64,
166    local_start: bool,
167    check: bool,
168) -> Result<[f64; 3], String> {
169    let [t0, t1] = curve.domain()?;
170    let [u0, u1] = surface.domain_u()?;
171    let [v0, v1] = surface.domain_v()?;
172    let (closed_u, closed_v) = surface.closed_directions()?;
173    let mut t = seed;
174    let [mut u, mut v] = opening_foot(surface, curve.evaluate(t)?, local_start, check)?;
175    for _ in 0..60 {
176        let (curve_point, tangent) = curve.deriv1(t)?;
177        let (surface_point, du, dv) = surface.deriv1(u, v)?;
178        let residual = curve_point.sub(surface_point);
179        if residual.length() <= EPSILON {
180            return Ok([t, u, v]);
181        }
182        let Some([mut step_t, mut step_u, mut step_v]) = solve_three(
183            [
184                [tangent.x, -du.x, -dv.x],
185                [tangent.y, -du.y, -dv.y],
186                [tangent.z, -du.z, -dv.z],
187            ],
188            residual.scale(-1.0),
189        ) else {
190            if tangent.length_squared() <= EPSILON {
191                return Ok([t, u, v]);
192            }
193            let next_t = (t - residual.dot(tangent) / tangent.length_squared()).clamp(t0, t1);
194            if (next_t - t).abs() <= 1e-15 * (t1 - t0) {
195                return Ok([t, u, v]);
196            }
197            t = next_t;
198            // The next iterate's foot, continued from this one's: the Newton
199            // is on ONE sheet, and the nearest point of the whole surface to
200            // the stepped curve point can be on another.
201            let projection =
202                crate::projection::project_point_to_surface_from_seed(surface, curve.evaluate(t)?, [u, v])?;
203            u = projection.u;
204            v = projection.v;
205            continue;
206        };
207        step_t = step_t.clamp(-(t1 - t0) / 4.0, (t1 - t0) / 4.0);
208        step_u = step_u.clamp(-(u1 - u0) / 4.0, (u1 - u0) / 4.0);
209        step_v = step_v.clamp(-(v1 - v0) / 4.0, (v1 - v0) / 4.0);
210        let next_t = (t + step_t).clamp(t0, t1);
211        let next_u = fit_parameter(u + step_u, u0, u1, closed_u);
212        let next_v = fit_parameter(v + step_v, v0, v1, closed_v);
213        let stalled = (next_t - t).abs() <= 1e-15 * (t1 - t0)
214            && (next_u - u).abs() <= 1e-15 * (u1 - u0)
215            && (next_v - v).abs() <= 1e-15 * (v1 - v0);
216        t = next_t;
217        u = next_u;
218        v = next_v;
219        if stalled {
220            return Ok([t, u, v]);
221        }
222    }
223    Ok([t, u, v])
224}
225
226#[derive(Clone, Copy, Debug, Serialize)]
227pub struct CurveSurfaceIntersection {
228    pub t: f64,
229    pub u: f64,
230    pub v: f64,
231    pub point: Vec3,
232    pub gap: f64,
233    pub tangential: bool,
234}
235
236/// Whether the duplicate guard's parameter tolerance is capped by the curve's
237/// domain. `BREP_CS_DUPLICATE_CAP=0` restores the uncapped tolerance, which at
238/// a stationary parameter is 1e6 and swallows every other hit on the curve.
239fn duplicate_cap_enabled() -> bool {
240    switch!("BREP_CS_DUPLICATE_CAP", true)
241}
242
243pub fn intersect_curve_surface(
244    curve: &NurbsCurve,
245    surface: &NurbsSurface,
246    tolerance: f64,
247) -> Result<Vec<CurveSurfaceIntersection>, String> {
248    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_INTERSECT_CURVE_SURFACE, surface);
249    let seeds = sampled_seeds(curve, surface, tolerance)?;
250    intersect_curve_surface_from_seeds(curve, surface, tolerance, seeds)
251}
252
253/// The general search's Newton seeds: the midpoint of every sample segment
254/// of the curve whose box meets the surface's box and one of its span boxes.
255fn sampled_seeds(curve: &NurbsCurve, surface: &NurbsSurface, tolerance: f64) -> Result<Vec<f64>, String> {
256    let [t0, t1] = curve.domain()?;
257    let surface_box = surface_bounds(surface)?.expanded(tolerance * 10.0);
258    let sample_count =
259        32usize.max((interior_knot_count(&curve.knots, curve.degree) + 1) * (curve.degree + 1) * 4);
260    let mut samples = Vec::with_capacity(sample_count + 1);
261    for index in 0..=sample_count {
262        let t = t0 + (t1 - t0) * index as f64 / sample_count as f64;
263        samples.push((t, curve.evaluate(t)?));
264    }
265    let span_boxes = span_bounds(surface)?;
266    let mut seeds = Vec::new();
267    for pair in samples.windows(2) {
268        let segment_box = Bounds::from_points([pair[0].1, pair[1].1]).expanded(tolerance * 10.0);
269        if segment_box.intersects_exact(surface_box)
270            && span_boxes.iter().any(|span_box| segment_box.intersects_exact(span_box.expanded(tolerance * 10.0)))
271        {
272            seeds.push((pair[0].0 + pair[1].0) * 0.5);
273        }
274    }
275    Ok(seeds)
276}
277
278/// [`intersect_curve_surface`] from the caller's own Newton seeds (curve
279/// parameters): the same Newton, gap filter, duplicate guard and tangency
280/// reading as the general search, only the seeds differ. The classifier's
281/// exact ray lane (`crate::exact_line_surface`) seeds it with the closed-form
282/// roots of a straight segment against an analytic carrier.
283pub fn intersect_curve_surface_from_seeds(
284    curve: &NurbsCurve,
285    surface: &NurbsSurface,
286    tolerance: f64,
287    seeds: Vec<f64>,
288) -> Result<Vec<CurveSurfaceIntersection>, String> {
289    solve_counted(curve, surface, tolerance, &seeds, false)
290}
291
292/// [`intersect_curve_surface`] for a point classifier's ray: the same search,
293/// with each Newton opened from the local foot when
294/// `BREP_CS_NEWTON_LOCAL_START` is on. Only a ray caller may take it: it reads
295/// the parity of transversal crossings and casts another direction on a
296/// grazing hit, so a cluster of roots where a curve runs along the surface (an
297/// edge on a face, where the two starts can keep different members of the
298/// cluster) never decides its answer.
299pub fn intersect_ray_surface(
300    curve: &NurbsCurve,
301    surface: &NurbsSurface,
302    tolerance: f64,
303) -> Result<Vec<CurveSurfaceIntersection>, String> {
304    let _lap = crate::projection_profile::Lap::enter(crate::projection_profile::LANE_INTERSECT_CURVE_SURFACE, surface);
305    let seeds = sampled_seeds(curve, surface, tolerance)?;
306    solve_counted(curve, surface, tolerance, &seeds, true)
307}
308
309fn solve_counted(
310    curve: &NurbsCurve,
311    surface: &NurbsSurface,
312    tolerance: f64,
313    seeds: &[f64],
314    ray: bool,
315) -> Result<Vec<CurveSurfaceIntersection>, String> {
316    if !ray || !newton_local_start_enabled() {
317        return solve_from_seeds(curve, surface, tolerance, seeds, false, false);
318    }
319    if !newton_local_start_check() {
320        return solve_from_seeds(curve, surface, tolerance, seeds, true, false);
321    }
322    let local = solve_from_seeds(curve, surface, tolerance, seeds, true, true)?;
323    let global = solve_from_seeds(curve, surface, tolerance, seeds, false, false)?;
324    START_CHECK_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
325    if !same_hits(&local, &global, tolerance) {
326        START_CHECK_HIT_DISAGREEMENTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
327        let read = |hits: &[CurveSurfaceIntersection]| hits.iter().map(|hit| hit.t).collect::<Vec<_>>();
328        eprintln!(
329            "cs newton start check: hits differ: local t {:?} global t {:?}",
330            read(&local),
331            read(&global)
332        );
333    }
334    Ok(local)
335}
336
337/// The two starts read the same hits: as many, each at the same place within
338/// the duplicate guard's chord (`tolerance * 10`), with the same tangency.
339fn same_hits(first: &[CurveSurfaceIntersection], second: &[CurveSurfaceIntersection], tolerance: f64) -> bool {
340    first.len() == second.len()
341        && first.iter().zip(second).all(|(a, b)| {
342            a.point.sub(b.point).length() <= tolerance * 10.0 && a.tangential == b.tangential
343        })
344}
345
346fn solve_from_seeds(
347    curve: &NurbsCurve,
348    surface: &NurbsSurface,
349    tolerance: f64,
350    seeds: &[f64],
351    local_start: bool,
352    check: bool,
353) -> Result<Vec<CurveSurfaceIntersection>, String> {
354    let [t0, t1] = curve.domain()?;
355    let mut results: Vec<CurveSurfaceIntersection> = Vec::new();
356    for &seed in seeds {
357        let [t, u, v] = newton_curve_surface(curve, surface, seed, local_start, check)?;
358        let on_curve = curve.evaluate(t)?;
359        let on_surface = surface.evaluate(u, v)?;
360        let gap = on_curve.sub(on_surface).length();
361        if gap > tolerance {
362            continue;
363        }
364        let tangent = curve.deriv1(t)?.1;
365        // Two hits are the SAME hit when they are at the same PLACE, and the
366        // chord test below is what measures that. This parameter test only has
367        // to absorb two seeds landing on one root a few ulps apart — and it
368        // converts the caller's 3D tolerance into a parameter tolerance by
369        // dividing by the curve's speed, a quotient that is unbounded where the
370        // speed is not. At a stationary parameter the `EPSILON` floor makes it
371        // `1e-7 / 1e-12 * 10 = 1e6`, wider than any curve's domain, so every
372        // earlier hit on the curve reads as a duplicate and a legitimate
373        // intersection AT a cusp is discarded unless it happens to be first.
374        // An involute flank's speed is `r_base * t`, so a gear profile carries
375        // one such cusp per flank per tooth: this is the 2026-09-14 herringbone
376        // report's root cause one lane over, where it is silent rather than
377        // loud.
378        //
379        // The cap is the curve's OWN domain, which is the only scale this test
380        // has: 1e-6 of it keeps the ulp-absorbing job (nine orders above the
381        // `1e-15 * (t1 - t0)` stall the Newton above exits on, three above the
382        // 1e-9 floor this rule already had) and drops the unbounded one. Two
383        // seeds on the same cusp root can land further apart than that in
384        // parameter, but not in space, and the chord test catches them.
385        // Escape hatch for tamper-verification:
386        // BREP_CS_DUPLICATE_CAP=0 restores the uncapped tolerance.
387        let uncapped = ((tolerance / tangent.length().max(EPSILON)) * 10.0).max((t1 - t0) * 1e-9);
388        let capped = uncapped.min((t1 - t0) * 1e-6);
389        let parameter_tolerance = if duplicate_cap_enabled() { capped } else { uncapped };
390        if let Some(result) = results.iter().find(|result| {
391            (result.t - t).abs() <= parameter_tolerance
392                || result.point.sub(on_curve).length() <= tolerance * 10.0
393        }) {
394            // The only drops the cap changes: a PARAMETER-only match (the two
395            // hits are apart in space) that the capped tolerance would keep. A
396            // hit dropped here leaves no trace anywhere else, so name it when
397            // asked: `BREP_DEBUG_CS_DUPLICATE=1`. With the cap on this prints
398            // nothing by construction; under `BREP_CS_DUPLICATE_CAP=0` it counts
399            // what the cap recovers.
400            let chord = result.point.sub(on_curve).length();
401            let gap = (result.t - t).abs();
402            if chord > tolerance * 10.0
403                && gap > capped
404                && std::env::var("BREP_DEBUG_CS_DUPLICATE").is_ok()
405            {
406                eprintln!(
407                    "cs-duplicate: dropped t={t:.12} against t={:.12} gap={gap:.6e} ptol={parameter_tolerance:.6e} \
408                     chord={chord:.6e} |tangent|={:.6e} domain=[{t0:.6},{t1:.6}] tolerance={tolerance:.3e}",
409                    result.t,
410                    tangent.length(),
411                );
412            }
413            continue;
414        }
415        let normal = surface.normal(u, v).ok();
416        let tangential = normal
417            .and_then(|normal| {
418                tangent
419                    .normalized()
420                    .ok()
421                    .map(|unit| normal.dot(unit).abs() <= 1e-3)
422            })
423            .unwrap_or(false);
424        results.push(CurveSurfaceIntersection {
425            t,
426            u,
427            v,
428            point: on_curve.add(on_surface).scale(0.5),
429            gap,
430            tangential,
431        });
432    }
433    results.sort_by(|a, b| a.t.total_cmp(&b.t));
434    Ok(results)
435}
436