Skip to main content

brep_kernel/geometry/analytic_surface/
intersect.rs

1use super::*;
2use super::recognition::{generatrix_is_meridional_half_ray, surface_scale};
3use super::revolution::{intersect_coaxial_revolutions, rotate_curve_about_axis};
4
5/// Exact plane data extracted from an affine patch.
6struct PlaneData {
7    origin: Vec3,
8    normal: Vec3,
9}
10
11fn plane_data(analytic: &AnalyticSurface) -> Option<PlaneData> {
12    match analytic {
13        AnalyticSurface::Plane {
14            origin,
15            u_dir,
16            v_dir,
17            ..
18        } => Some(PlaneData {
19            origin: *origin,
20            normal: u_dir.cross(*v_dir).normalized().ok()?,
21        }),
22        _ => None,
23    }
24}
25
26/// Apply a homogeneous 4x4-style map to a rational curve's control points.
27/// `map` produces the image (x', y', z', w') of each homogeneous control
28/// point; weights must come back strictly one-signed or the section is not
29/// an ellipse/circle and we refuse it.
30fn map_rational_curve(
31    curve: &NurbsCurve,
32    map: impl Fn(crate::Vec4) -> crate::Vec4,
33) -> Option<NurbsCurve> {
34    let mut controls = Vec::with_capacity(curve.control_points.len());
35    let mut sign = 0.0f64;
36    for point in &curve.control_points {
37        let image = map(*point);
38        if image.w == 0.0 || !image.w.is_finite() {
39            return None;
40        }
41        if sign == 0.0 {
42            sign = image.w.signum();
43        } else if image.w.signum() != sign {
44            return None;
45        }
46        controls.push(image);
47    }
48    if sign < 0.0 {
49        for point in &mut controls {
50            point.x = -point.x;
51            point.y = -point.y;
52            point.z = -point.z;
53            point.w = -point.w;
54        }
55    }
56    NurbsCurve::new(curve.degree, curve.knots.clone(), controls).ok()
57}
58
59/// The full u-circle of a revolution surface at radial distance `rho` and
60/// axial height `z`, built with the same arc construction as the surface.
61fn frame_circle(frame: &RevolutionFrame, rho: f64, z: f64) -> Option<NurbsCurve> {
62    make_arc(
63        frame.origin.add(frame.axis.scale(z)),
64        frame.x_axis,
65        frame.y_axis,
66        rho,
67        0.0,
68        std::f64::consts::TAU,
69    )
70    .ok()
71}
72
73/// Exact intersection curves for recognized analytic pairs, or `None` when
74/// the pair is not handled and the caller must fall back to SSI marching.
75/// `Some(vec![])` means "provably empty" and skips marching entirely.
76pub fn intersect_analytic_pair(
77    first: &NurbsSurface,
78    second: &NurbsSurface,
79    tolerance: f64,
80) -> Option<Vec<NurbsCurve>> {
81    if let Some(curves) = intersect_recognized_pair(first, second, tolerance) {
82        return Some(curves);
83    }
84    if let Some(curves) = intersect_coaxial_revolutions(first, second, tolerance) {
85        return Some(curves);
86    }
87    if let Some(curves) = intersect_axial_plane_revolution(first, second, tolerance) {
88        return Some(curves);
89    }
90    intersect_axial_plane_revolution(second, first, tolerance)
91}
92
93/// Exact intersection of a plane CONTAINING the revolution axis with a
94/// surface of revolution: the meridian profile rotated to the (at most
95/// two) angles where the plane crosses the sweep. The marcher fits these
96/// as long noisy polylines otherwise (a revolve's start/end caps against
97/// the other operand's revolved walls in revolve-with-holes booleans).
98fn intersect_axial_plane_revolution(
99    plane_surface: &NurbsSurface,
100    revolved: &NurbsSurface,
101    _tolerance: f64,
102) -> Option<Vec<NurbsCurve>> {
103    let plane = match plane_surface.analytic()? {
104        AnalyticSurface::Plane {
105            origin,
106            u_dir,
107            v_dir,
108            ..
109        } => (*origin, u_dir.cross(*v_dir).normalized().ok()?),
110        _ => return None,
111    };
112    let structure = revolution_structure(revolved)?;
113    if !generatrix_is_meridional_half_ray(&structure.generatrix, &structure.frame) {
114        return None;
115    }
116    let scale = surface_scale(plane_surface)
117        .max(surface_scale(revolved))
118        .max(1.0);
119    let (plane_origin, plane_normal) = plane;
120    if structure.frame.axis.dot(plane_normal).abs() > 1e-9 {
121        return None;
122    }
123    if structure
124        .frame
125        .origin
126        .sub(plane_origin)
127        .dot(plane_normal)
128        .abs()
129        > 1e-9 * scale
130    {
131        return None;
132    }
133    let radial = structure.frame.axis.cross(plane_normal).normalized().ok()?;
134    let tau = std::f64::consts::TAU;
135    let mut curves = Vec::new();
136    for direction in [radial, radial.scale(-1.0)] {
137        let mut angle = direction
138            .dot(structure.frame.y_axis)
139            .atan2(direction.dot(structure.frame.x_axis));
140        if angle < -1e-9 {
141            angle += tau;
142        }
143        if angle <= structure.sweep + 1e-9 {
144            curves.push(rotate_curve_about_axis(
145                &structure.generatrix,
146                structure.frame.origin,
147                structure.frame.axis,
148                angle.clamp(0.0, structure.sweep),
149            )?);
150        }
151    }
152    Some(curves)
153}
154
155fn intersect_recognized_pair(
156    first: &NurbsSurface,
157    second: &NurbsSurface,
158    tolerance: f64,
159) -> Option<Vec<NurbsCurve>> {
160    let a = first.analytic()?;
161    let b = second.analytic()?;
162    if !matches!(b, AnalyticSurface::Plane { .. }) {
163        if let Some(plane) = plane_data(a) {
164            return intersect_plane_quadric(&plane, b, tolerance);
165        }
166    }
167    if !matches!(a, AnalyticSurface::Plane { .. }) {
168        if let Some(plane) = plane_data(b) {
169            return intersect_plane_quadric(&plane, a, tolerance);
170        }
171    }
172    match (a, b) {
173        // Plane×plane is deliberately NOT special-cased: the iso path
174        // already returns axis-aligned box intersections exactly, and a
175        // synthesized over-long line segment interacts poorly with the
176        // shared-parameter pcurve contract in process_curve (the pcurve is
177        // fitted over the face crossing only, so the curve's [t0,t1]
178        // subrange and the pcurve domain drift apart on long overhangs).
179        (AnalyticSurface::Plane { .. }, AnalyticSurface::Plane { .. }) => None,
180        (
181            AnalyticSurface::Sphere {
182                frame: frame_a,
183                radius: radius_a,
184            },
185            AnalyticSurface::Sphere {
186                frame: frame_b,
187                radius: radius_b,
188            },
189        ) => intersect_sphere_sphere(
190            frame_a.origin,
191            *radius_a,
192            frame_b.origin,
193            *radius_b,
194            tolerance,
195        ),
196        _ => None,
197    }
198}
199
200/// Frame/meridian data for any revolution with a straight-line generatrix:
201/// the `RuledRevolution` quadrics themselves, plus partial-sweep
202/// `Revolution`s whose generatrix is a degree-1 unit-weight segment
203/// (fillet cutter walls are quarter cylinders of this shape). The plane
204/// intersectors only need the carrier geometry — the boolean trims the
205/// returned curves to the actual face domains afterwards.
206fn ruled_revolution_data(quadric: &AnalyticSurface) -> Option<(RevolutionFrame, f64, f64, f64)> {
207    match quadric {
208        AnalyticSurface::RuledRevolution {
209            frame,
210            rho0,
211            rho1,
212            height,
213        } => Some((frame.clone(), *rho0, *rho1, *height)),
214        AnalyticSurface::Revolution {
215            frame, generatrix, ..
216        } => {
217            let controls = &generatrix.control_points;
218            if generatrix.degree != 1
219                || controls.len() != 2
220                || (controls[0].w - 1.0).abs() > RECOGNITION_TOLERANCE
221                || (controls[1].w - 1.0).abs() > RECOGNITION_TOLERANCE
222            {
223                return None;
224            }
225            let (_, rho0, z0) = frame.cylindrical(controls[0].point().ok()?);
226            let (_, rho1, z1) = frame.cylindrical(controls[1].point().ok()?);
227            let height = z1 - z0;
228            if height.abs() <= 1e-12 * (1.0 + rho0.abs().max(rho1.abs())) {
229                return None;
230            }
231            let origin = frame.origin.add(frame.axis.scale(z0));
232            Some((
233                RevolutionFrame {
234                    origin,
235                    ..frame.clone()
236                },
237                rho0,
238                rho1,
239                height,
240            ))
241        }
242        _ => None,
243    }
244}
245
246/// TRUE when a recognized frustum's radius drift is below the precision floor
247/// of the cone construction itself, so the plane section must take the
248/// CYLINDER branch. The cone branch builds its conic as a projective image of
249/// a base circle toward the apex at distance ~|height|·max|ρ|/|Δρ|; the map's
250/// floating-point error grows like that distance × machine epsilon, so for a
251/// near-cylinder frustum (t363: Δρ = 2.23e-12 over height 1500, apex ~1.5e16)
252/// the "exact analytic" section comes back up to ~1 mm off BOTH surfaces.
253/// Downstream, `build_pcurve_on_surface` honestly measures that deviation on
254/// the curved operand, drops every interior sample, and collapses the ring's
255/// pcurve to a single point — the face under-splits and the boolean fails
256/// with one-use edges / non-integral genus.
257///
258/// Branch selection by error balance: the cylinder approximation errs by at
259/// most |Δρ|, the cone construction by ~ε·|height|·max|ρ|/|Δρ|; prefer the
260/// cylinder when its error is smaller, i.e. Δρ² ≤ ε·|height|·max|ρ| (with a
261/// modest constant for the map's factors). This is a deterministic choice
262/// between two exact-in-infinite-precision constructions — not a tolerance —
263/// and can only ever pick the MORE accurate branch. The legacy absolute
264/// 1e-12 acceptance remains as a floor at the call site. Escape hatch:
265/// BREP_CONE_APEX_GUARD=0 restores the bare 1e-12 discrimination.
266fn degenerate_apex_frustum(rho0: f64, rho1: f64, height: f64) -> bool {
267    if std::env::var("BREP_CONE_APEX_GUARD").as_deref() == Ok("0") {
268        return false;
269    }
270    let delta = rho1 - rho0;
271    delta * delta <= 64.0 * f64::EPSILON * height.abs() * rho0.abs().max(rho1.abs())
272}
273
274fn intersect_plane_quadric(
275    plane: &PlaneData,
276    quadric: &AnalyticSurface,
277    tolerance: f64,
278) -> Option<Vec<NurbsCurve>> {
279    match quadric {
280        AnalyticSurface::RuledRevolution { .. } | AnalyticSurface::Revolution { .. }
281            if ruled_revolution_data(quadric).is_some() =>
282        {
283            let (frame, rho0, rho1, height) = ruled_revolution_data(quadric)?;
284            let (frame, rho0, rho1, height) = (&frame, &rho0, &rho1, &height);
285            let alignment = plane.normal.dot(frame.axis);
286            if alignment.abs() >= 1.0 - 1e-12 {
287                // Perpendicular plane: one circle at the plane's height.
288                let z = plane.origin.sub(frame.origin).dot(frame.axis);
289                let t = z / height;
290                if !(-1e-9..=1.0 + 1e-9).contains(&t) {
291                    return Some(Vec::new());
292                }
293                let rho = rho0 + (rho1 - rho0) * t.clamp(0.0, 1.0);
294                if rho <= tolerance {
295                    return Some(Vec::new());
296                }
297                return Some(vec![frame_circle(frame, rho, z)?]);
298            }
299            if (rho1 - rho0).abs() <= 1e-12 || degenerate_apex_frustum(*rho0, *rho1, *height) {
300                // Cylinder.
301                if alignment.abs() <= 1e-12 {
302                    // Plane parallel to the axis: zero, one, or two
303                    // generatrix lines at the circle/line crossing angles.
304                    return cylinder_parallel_plane_lines(plane, frame, *rho0, *height, tolerance);
305                }
306                // Oblique section: exact ellipse as the affine image of a
307                // base circle along the axis direction.
308                let circle = frame_circle(frame, *rho0, 0.0)?;
309                let denominator = alignment;
310                let origin_dot = plane.origin.dot(plane.normal);
311                let normal = plane.normal;
312                let axis = frame.axis;
313                let ellipse = map_rational_curve(&circle, |p| {
314                    let t = (origin_dot * p.w - Vec3::new(p.x, p.y, p.z).dot(normal)) / denominator;
315                    crate::Vec4 {
316                        x: p.x + axis.x * t,
317                        y: p.y + axis.y * t,
318                        z: p.z + axis.z * t,
319                        w: p.w,
320                    }
321                })?;
322                if !section_within_band(&ellipse, frame, *height, tolerance) {
323                    return Some(Vec::new());
324                }
325                return Some(vec![ellipse]);
326            }
327            // Cone/frustum: projective image of a base circle toward the
328            // apex. Weight signs flip for parabolic/hyperbolic sections and
329            // map_rational_curve refuses those (marcher fallback).
330            let apex_t = rho0 / (rho0 - rho1);
331            let apex = frame.origin.add(frame.axis.scale(height * apex_t));
332            let reference_rho = if rho0.abs() > rho1.abs() {
333                *rho0
334            } else {
335                *rho1
336            };
337            let reference_z = if rho0.abs() > rho1.abs() {
338                0.0
339            } else {
340                *height
341            };
342            let circle = frame_circle(frame, reference_rho, reference_z)?;
343            let k = plane.origin.sub(apex).dot(plane.normal);
344            if k.abs() <= tolerance {
345                // Plane through the apex: line pair; leave to the marcher.
346                return None;
347            }
348            let normal = plane.normal;
349            let conic = map_rational_curve(&circle, |p| {
350                let relative =
351                    Vec3::new(p.x - p.w * apex.x, p.y - p.w * apex.y, p.z - p.w * apex.z);
352                let w_new = relative.dot(normal);
353                let scaled = relative.scale(k);
354                crate::Vec4 {
355                    x: apex.x * w_new + scaled.x,
356                    y: apex.y * w_new + scaled.y,
357                    z: apex.z * w_new + scaled.z,
358                    w: w_new,
359                }
360            })?;
361            if !section_within_band(&conic, frame, *height, tolerance) {
362                return Some(Vec::new());
363            }
364            Some(vec![conic])
365        }
366        AnalyticSurface::Sphere { frame, radius } => {
367            let distance = frame.origin.sub(plane.origin).dot(plane.normal);
368            if distance.abs() >= radius - tolerance {
369                return Some(Vec::new());
370            }
371            let center = frame.origin.sub(plane.normal.scale(distance));
372            let circle_radius = (radius * radius - distance * distance).sqrt();
373            let x_axis = plane.normal.perpendicular().ok()?;
374            let y_axis = plane.normal.cross(x_axis);
375            Some(vec![make_arc(
376                center,
377                x_axis,
378                y_axis,
379                circle_radius,
380                0.0,
381                std::f64::consts::TAU,
382            )
383            .ok()?])
384        }
385        AnalyticSurface::Torus {
386            frame,
387            major_radius,
388            minor_radius,
389        } => {
390            let alignment = plane.normal.dot(frame.axis);
391            if alignment.abs() < 1.0 - 1e-12 {
392                return None;
393            }
394            let z = plane.origin.sub(frame.origin).dot(frame.axis);
395            if z.abs() >= minor_radius - tolerance {
396                return Some(Vec::new());
397            }
398            let offset = (minor_radius * minor_radius - z * z).sqrt();
399            let mut circles = Vec::new();
400            for rho in [major_radius - offset, major_radius + offset] {
401                if rho > tolerance {
402                    circles.push(frame_circle(frame, rho, z)?);
403                }
404            }
405            Some(circles)
406        }
407        AnalyticSurface::Plane { .. } => None,
408        // General revolutions have no closed-form plane section; the
409        // axial-plane and tangential-contact paths in imprint own them.
410        AnalyticSurface::RuledRevolution { .. } | AnalyticSurface::Revolution { .. } => None,
411    }
412}
413
414/// Reject sections that entirely miss the ruled surface's axial band; the
415/// imprint trimmer would discard them anyway, but skipping early avoids
416/// building pcurves for out-of-band curves.
417///
418/// Uses the convex-hull property of a same-sign-weight rational curve: every
419/// curve point's axial coordinate lies within the [min, max] axial span of the
420/// Cartesian control points. So the section can only miss the band when the
421/// WHOLE control-point span sits above or below it. The earlier `any(CP in
422/// band)` test was wrong for near-axis-parallel oblique sections: the affine
423/// map divides the axial displacement by `alignment`, flinging the rational
424/// control points far to BOTH sides of the band (they straddle it with none
425/// landing inside), so a genuine crossing arc was falsely rejected — the
426/// missing cap∩cylinder imprint behind the curved-primitive open-edge /
427/// non-integral-genus booleans. An interval-overlap test can never falsely
428/// reject (hull property); a false accept is harmless (the imprint trimmer
429/// clips the returned curve to the real face domains regardless).
430fn section_within_band(
431    curve: &NurbsCurve,
432    frame: &RevolutionFrame,
433    height: f64,
434    tolerance: f64,
435) -> bool {
436    let (band_low, band_high) = if height >= 0.0 {
437        (0.0, height)
438    } else {
439        (height, 0.0)
440    };
441    let margin = tolerance.max(1e-9) + 1e-9;
442    let mut min_z = f64::INFINITY;
443    let mut max_z = f64::NEG_INFINITY;
444    for p in &curve.control_points {
445        let z = Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w)
446            .sub(frame.origin)
447            .dot(frame.axis);
448        min_z = min_z.min(z);
449        max_z = max_z.max(z);
450    }
451    // The control-point axial span overlaps the band.
452    max_z >= band_low - margin && min_z <= band_high + margin
453}
454
455fn cylinder_parallel_plane_lines(
456    plane: &PlaneData,
457    frame: &RevolutionFrame,
458    radius: f64,
459    height: f64,
460    tolerance: f64,
461) -> Option<Vec<NurbsCurve>> {
462    // Distance from the axis to the plane, measured in the cross-section.
463    let axis_to_plane = plane.origin.sub(frame.origin).dot(plane.normal);
464    if axis_to_plane.abs() >= radius - tolerance {
465        return Some(Vec::new());
466    }
467    // In-plane offset of the chord from the axis foot.
468    let chord_half = (radius * radius - axis_to_plane * axis_to_plane).sqrt();
469    let chord_direction = frame.axis.cross(plane.normal).normalized().ok()?;
470    let foot = frame.origin.add(plane.normal.scale(axis_to_plane));
471    let mut lines = Vec::new();
472    for sign in [-1.0, 1.0] {
473        let base = foot.add(chord_direction.scale(sign * chord_half));
474        let top = base.add(frame.axis.scale(height));
475        lines.push(crate::make_line(base, top).ok()?);
476    }
477    Some(lines)
478}
479
480fn intersect_sphere_sphere(
481    center_a: Vec3,
482    radius_a: f64,
483    center_b: Vec3,
484    radius_b: f64,
485    tolerance: f64,
486) -> Option<Vec<NurbsCurve>> {
487    let offset = center_b.sub(center_a);
488    let distance = offset.length();
489    if distance <= tolerance {
490        // Concentric: empty or coincident; the cosurface path owns
491        // coincident carriers.
492        return if (radius_a - radius_b).abs() <= tolerance {
493            None
494        } else {
495            Some(Vec::new())
496        };
497    }
498    if distance >= radius_a + radius_b - tolerance
499        || distance <= (radius_a - radius_b).abs() + tolerance
500    {
501        return Some(Vec::new());
502    }
503    let normal = offset.scale(1.0 / distance);
504    let along =
505        (distance * distance + radius_a * radius_a - radius_b * radius_b) / (2.0 * distance);
506    let circle_radius_squared = radius_a * radius_a - along * along;
507    if circle_radius_squared <= tolerance * tolerance {
508        return Some(Vec::new());
509    }
510    let center = center_a.add(normal.scale(along));
511    let x_axis = normal.perpendicular().ok()?;
512    let y_axis = normal.cross(x_axis);
513    Some(vec![make_arc(
514        center,
515        x_axis,
516        y_axis,
517        circle_radius_squared.sqrt(),
518        0.0,
519        std::f64::consts::TAU,
520    )
521    .ok()?])
522}