Skip to main content

brep_geometry/geometry/analytic_surface/
intersect.rs

1use super::*;
2pub use super::recognition::{generatrix_is_meridional_half_ray, surface_scale};
3use super::revolution::{intersect_coaxial_revolutions, intersect_cylinder_radius_invariant, 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    intersect_analytic_pair_with(first, second, tolerance, ruled_gate())
82}
83
84/// Which predicate admits a general revolution's generatrix as the straight
85/// line of a cone, frustum or cylinder in [`intersect_analytic_pair`].
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub enum RuledGate {
88    /// The count proxy: degree 1, exactly two control points, unit weights.
89    Count,
90    /// What the section constructions consume: the generatrix's two ends, and
91    /// that the curve between them is the straight segment joining them
92    /// ([`NurbsCurve::straight_segment`]).
93    Geometry,
94}
95
96/// The gate the boolean runs: straightness, which is all the section
97/// constructions read. The count proxy declined a knot-refined, degree-elevated
98/// or re-weighted generatrix of the same cone and sent the pair to the marcher.
99/// Escape hatch for measurement: `BREP_RULED_GATE_GEOMETRY=0` runs the count
100/// gate.
101pub fn ruled_gate() -> RuledGate {
102    if std::env::var("BREP_RULED_GATE_GEOMETRY").as_deref() == Ok("0") {
103        RuledGate::Count
104    } else {
105        RuledGate::Geometry
106    }
107}
108
109/// [`intersect_analytic_pair`] under a named generatrix gate — what the fit
110/// census asks of the gate the boolean does NOT run.
111pub fn intersect_analytic_pair_with(
112    first: &NurbsSurface,
113    second: &NurbsSurface,
114    tolerance: f64,
115    gate: RuledGate,
116) -> Option<Vec<NurbsCurve>> {
117    if let Some(curves) = intersect_recognized_pair(first, second, tolerance, gate) {
118        return Some(curves);
119    }
120    if let Some(curves) = intersect_plane_affine_sphere(first, second, tolerance) {
121        return Some(curves);
122    }
123    if let Some(curves) = intersect_coaxial_revolutions(first, second, tolerance) {
124        return Some(curves);
125    }
126    if coaxial_iso_section_enabled() {
127        if let Some(curves) = intersect_cylinder_radius_invariant(first, second, tolerance) {
128            return Some(curves);
129        }
130        if let Some(curves) = intersect_cylinder_radius_invariant(second, first, tolerance) {
131            return Some(curves);
132        }
133    }
134    // Only under the production gate: the count gate is the escape hatch that
135    // measures the old routing (`ruled_gate_admits_a_straight_generatrix_
136    // whatever_it_counts` reads it sending a re-weighted cone to the marcher).
137    if gate == RuledGate::Geometry && plane_revolution_section_enabled() {
138        if let Some(curves) = intersect_perpendicular_plane_revolution(first, second, tolerance) {
139            return Some(curves);
140        }
141        if let Some(curves) = intersect_perpendicular_plane_revolution(second, first, tolerance) {
142            return Some(curves);
143        }
144    }
145    if let Some(curves) = intersect_axial_plane_revolution(first, second, tolerance) {
146        return Some(curves);
147    }
148    intersect_axial_plane_revolution(second, first, tolerance)
149}
150
151/// `BREP_COAXIAL_ISO_SECTION` (default on; `=0` leaves the pair to the
152/// marcher): a cylinder against a surface
153/// whose radius about its axis is invariant along one parameter
154/// ([`intersect_cylinder_radius_invariant`]).
155fn coaxial_iso_section_enabled() -> bool {
156    crate::switch!("BREP_COAXIAL_ISO_SECTION", true)
157}
158
159/// PLANE x REVOLUTION SECTION (2026-11-06;
160/// `BREP_PLANE_REVOLUTION_SECTION`, default on, `=0` off). A plane square to the axis
161/// of a general surface of revolution (one no quadric arm reads: a revolved
162/// parabola, a revolved spline) meets it in one circle per height at which the
163/// generatrix crosses the plane, over the revolution's sweep. No arm read this
164/// pair, so it went to the marcher, which seeds on a grid and finds no loop
165/// much smaller than the faces: brep-bench
166/// `tangent/paraboloid-tip-a-ten-thousandth-high` (a size-8 paraboloid cut by
167/// z = 1e-4, a rim circle of radius 0.028) read "no boundary faces".
168///
169/// The lane answers only when every crossing is clean: each a sign change of
170/// the generatrix's height over the plane, transversal, and away from the
171/// generatrix's ends and from the axis, and the scan's crossings are as many
172/// as the generatrix's control points change sides of the plane (so none can
173/// hide between two stations). A touching height, a crossing at a
174/// rim the face already has as an edge, or no crossing at all keeps the pair
175/// on the paths it took before (`None`).
176fn plane_revolution_section_enabled() -> bool {
177    crate::switch!("BREP_PLANE_REVOLUTION_SECTION", true)
178}
179
180fn intersect_perpendicular_plane_revolution(
181    plane_surface: &NurbsSurface,
182    revolution: &NurbsSurface,
183    tolerance: f64,
184) -> Option<Vec<NurbsCurve>> {
185    let plane = plane_data(plane_surface.analytic()?)?;
186    if matches!(revolution.analytic(), Some(AnalyticSurface::Plane { .. })) {
187        return None;
188    }
189    let structure = super::revolution::revolution_structure(revolution)?;
190    let frame = &structure.frame;
191    if plane.normal.dot(frame.axis).abs() < 1.0 - 1e-12 {
192        return None;
193    }
194    let generatrix = &structure.generatrix;
195    let [start, end] = generatrix.domain().ok()?;
196    let height = |t: f64| -> Option<f64> { Some(generatrix.evaluate(t).ok()?.sub(plane.origin).dot(plane.normal)) };
197    let scale = surface_scale(revolution).max(1.0);
198    let band = tolerance.max(1e-9 * scale);
199    let spans = generatrix.knots.windows(2).filter(|pair| pair[1] > pair[0]).count().max(1);
200    let stations = 64 * spans;
201    let mut previous_t = start;
202    let mut previous = height(start)?;
203    // A generatrix end ON the plane is a rim the face has as an edge.
204    if previous.abs() <= band || height(end)?.abs() <= band {
205        return None;
206    }
207    let mut roots = Vec::new();
208    for index in 1..=stations {
209        let t = start + (end - start) * index as f64 / stations as f64;
210        let value = height(t)?;
211        if value.abs() <= band && index < stations {
212            // A station on the plane: a touching height or a crossing exactly
213            // here; the bisection below cannot tell them apart.
214            return None;
215        }
216        if (previous < 0.0) != (value < 0.0) {
217            let (mut lo, mut hi, mut lo_value) = (previous_t, t, previous);
218            for _ in 0..200 {
219                let middle = 0.5 * (lo + hi);
220                if middle <= lo || middle >= hi {
221                    break;
222                }
223                let middle_value = height(middle)?;
224                if (middle_value < 0.0) == (lo_value < 0.0) {
225                    lo = middle;
226                    lo_value = middle_value;
227                } else {
228                    hi = middle;
229                }
230            }
231            roots.push(0.5 * (lo + hi));
232        }
233        previous_t = t;
234        previous = value;
235    }
236    if roots.is_empty() {
237        return None;
238    }
239    // The height's numerator `sum w_i ((P_i - o).n) N_i(t)` is a B-spline, so
240    // it has no more roots than its coefficients have sign changes (variation
241    // diminishing). A count above the scan's means two crossings may share a
242    // station, which the scan cannot see: decline rather than drop a circle.
243    let mut coefficient_signs = Vec::new();
244    for control in &generatrix.control_points {
245        if control.w <= 0.0 {
246            return None;
247        }
248        let value = control.point().ok()?.sub(plane.origin).dot(plane.normal);
249        if value.abs() <= band {
250            return None;
251        }
252        coefficient_signs.push(value > 0.0);
253    }
254    let sign_changes = coefficient_signs.windows(2).filter(|pair| pair[0] != pair[1]).count();
255    if sign_changes != roots.len() {
256        return None;
257    }
258    let radius_floor = (tolerance * 10.0).max(1e-9 * scale);
259    let mut curves = Vec::new();
260    for root in roots {
261        let derivatives = generatrix.derivatives(root, 1).ok()?;
262        let tangent = derivatives.get(1)?.normalized().ok()?;
263        if tangent.dot(plane.normal).abs() <= 1e-9 {
264            return None;
265        }
266        let point = generatrix.evaluate(root).ok()?;
267        let (_, radius, axial) = frame.cylindrical(point);
268        if radius <= radius_floor {
269            return None;
270        }
271        let center = frame.origin.add(frame.axis.scale(axial));
272        curves.push(make_arc(center, frame.x_axis, frame.y_axis, radius, 0.0, structure.sweep).ok()?);
273    }
274    Some(curves)
275}
276
277/// Exact intersection of a plane CONTAINING the revolution axis with a
278/// surface of revolution: the meridian profile rotated to the (at most
279/// two) angles where the plane crosses the sweep. The marcher fits these
280/// as long noisy polylines otherwise (a revolve's start/end caps against
281/// the other operand's revolved walls in revolve-with-holes booleans).
282fn intersect_axial_plane_revolution(
283    plane_surface: &NurbsSurface,
284    revolved: &NurbsSurface,
285    _tolerance: f64,
286) -> Option<Vec<NurbsCurve>> {
287    let plane = match plane_surface.analytic()? {
288        AnalyticSurface::Plane {
289            origin,
290            u_dir,
291            v_dir,
292            ..
293        } => (*origin, u_dir.cross(*v_dir).normalized().ok()?),
294        _ => return None,
295    };
296    let structure = revolution_structure(revolved)?;
297    if !generatrix_is_meridional_half_ray(&structure.generatrix, &structure.frame) {
298        return None;
299    }
300    let scale = surface_scale(plane_surface)
301        .max(surface_scale(revolved))
302        .max(1.0);
303    let (plane_origin, plane_normal) = plane;
304    if structure.frame.axis.dot(plane_normal).abs() > 1e-9 {
305        return None;
306    }
307    if structure
308        .frame
309        .origin
310        .sub(plane_origin)
311        .dot(plane_normal)
312        .abs()
313        > 1e-9 * scale
314    {
315        return None;
316    }
317    let radial = structure.frame.axis.cross(plane_normal).normalized().ok()?;
318    let tau = std::f64::consts::TAU;
319    let mut curves = Vec::new();
320    for direction in [radial, radial.scale(-1.0)] {
321        let mut angle = direction
322            .dot(structure.frame.y_axis)
323            .atan2(direction.dot(structure.frame.x_axis));
324        if angle < -1e-9 {
325            angle += tau;
326        }
327        if angle <= structure.sweep + 1e-9 {
328            curves.push(rotate_curve_about_axis(
329                &structure.generatrix,
330                structure.frame.origin,
331                structure.frame.axis,
332                angle.clamp(0.0, structure.sweep),
333            )?);
334        }
335    }
336    Some(curves)
337}
338
339/// Plane x affine sphere (`geometry/affine_sphere.rs`, under
340/// `BREP_AFFINE_SPHERE`): the exact ellipse, either operand order. Nothing
341/// else pairs with an ellipsoid in closed form (sphere, cylinder and cone
342/// sections of it are quartics; the marcher keeps them).
343fn intersect_plane_affine_sphere(
344    first: &NurbsSurface,
345    second: &NurbsSurface,
346    tolerance: f64,
347) -> Option<Vec<NurbsCurve>> {
348    for (plane_surface, other) in [(first, second), (second, first)] {
349        let Some(ellipsoid) = other.affine_sphere() else { continue };
350        let Some(plane) = plane_surface.analytic().and_then(plane_data) else { continue };
351        return ellipsoid.plane_section(plane.origin, plane.normal, tolerance);
352    }
353    None
354}
355
356fn intersect_recognized_pair(
357    first: &NurbsSurface,
358    second: &NurbsSurface,
359    tolerance: f64,
360    gate: RuledGate,
361) -> Option<Vec<NurbsCurve>> {
362    let a = first.analytic()?;
363    let b = second.analytic()?;
364    if !matches!(b, AnalyticSurface::Plane { .. }) {
365        if let Some(plane) = plane_data(a) {
366            return intersect_plane_quadric(&plane, b, tolerance, gate);
367        }
368    }
369    if !matches!(a, AnalyticSurface::Plane { .. }) {
370        if let Some(plane) = plane_data(b) {
371            return intersect_plane_quadric(&plane, a, tolerance, gate);
372        }
373    }
374    // Sphere×sphere, whichever way each sphere is parameterized (a reflected
375    // sphere recognizes as a general `Revolution`; see `sphere_geometry`).
376    if let (Some((center_a, radius_a)), Some((center_b, radius_b))) =
377        (a.sphere_geometry(), b.sphere_geometry())
378    {
379        return intersect_sphere_sphere(center_a, radius_a, center_b, radius_b, tolerance);
380    }
381    // Plane×plane is deliberately NOT special-cased: the iso path
382    // already returns axis-aligned box intersections exactly, and a
383    // synthesized over-long line segment interacts poorly with the
384    // shared-parameter pcurve contract in process_curve (the pcurve is
385    // fitted over the face crossing only, so the curve's [t0,t1]
386    // subrange and the pcurve domain drift apart on long overhangs).
387    None
388}
389
390/// Frame/meridian data for any revolution with a straight-line generatrix:
391/// the `RuledRevolution` quadrics themselves, plus partial-sweep
392/// `Revolution`s whose generatrix the named gate admits as straight (fillet
393/// cutter walls are quarter cylinders of this shape). The plane
394/// intersectors only need the carrier geometry — the boolean trims the
395/// returned curves to the actual face domains afterwards.
396fn ruled_revolution_data(
397    quadric: &AnalyticSurface,
398    tolerance: f64,
399    gate: RuledGate,
400) -> Option<(RevolutionFrame, f64, f64, f64)> {
401    match quadric {
402        AnalyticSurface::RuledRevolution {
403            frame,
404            rho0,
405            rho1,
406            height,
407        } => Some((frame.clone(), *rho0, *rho1, *height)),
408        AnalyticSurface::Revolution {
409            frame, generatrix, ..
410        } => {
411            let (start, end) = match gate {
412                RuledGate::Count => {
413                    let controls = &generatrix.control_points;
414                    if generatrix.degree != 1
415                        || controls.len() != 2
416                        || (controls[0].w - 1.0).abs() > RECOGNITION_TOLERANCE
417                        || (controls[1].w - 1.0).abs() > RECOGNITION_TOLERANCE
418                    {
419                        return None;
420                    }
421                    (controls[0].point().ok()?, controls[1].point().ok()?)
422                }
423                RuledGate::Geometry => generatrix.straight_segment(tolerance)?,
424            };
425            let (_, rho0, z0) = frame.cylindrical(start);
426            let (_, rho1, z1) = frame.cylindrical(end);
427            let height = z1 - z0;
428            if height.abs() <= 1e-12 * (1.0 + rho0.abs().max(rho1.abs())) {
429                return None;
430            }
431            let origin = frame.origin.add(frame.axis.scale(z0));
432            Some((
433                RevolutionFrame {
434                    origin,
435                    ..frame.clone()
436                },
437                rho0,
438                rho1,
439                height,
440            ))
441        }
442        _ => None,
443    }
444}
445
446/// CENSUS ONLY (`BREP_FIT_CENSUS=1`): a description of `surface`'s generatrix
447/// when it is a general revolution the two generatrix gates answer
448/// differently, `None` otherwise.
449pub fn ruled_gate_census(surface: &NurbsSurface, tolerance: f64) -> Option<String> {
450    let quadric = surface.analytic()?;
451    let AnalyticSurface::Revolution { generatrix, .. } = quadric else {
452        return None;
453    };
454    let count = ruled_revolution_data(quadric, tolerance, RuledGate::Count).is_some();
455    let geometry = ruled_revolution_data(quadric, tolerance, RuledGate::Geometry).is_some();
456    if count == geometry {
457        return None;
458    }
459    let controls = &generatrix.control_points;
460    let points: Vec<Vec3> = controls
461        .iter()
462        .map(|control| control.point().unwrap_or_default())
463        .collect();
464    let (first, last) = (points[0], points[points.len() - 1]);
465    let direction = last.sub(first);
466    let length_squared = direction.length_squared();
467    let mut collinearity = 0.0_f64;
468    for point in &points {
469        collinearity = collinearity.max(if length_squared <= 0.0 {
470            point.sub(first).length()
471        } else {
472            let fraction = (point.sub(first).dot(direction) / length_squared).clamp(0.0, 1.0);
473            point.sub(first.add(direction.scale(fraction))).length()
474        });
475    }
476    let unit_weights = controls
477        .iter()
478        .all(|control| (control.w - 1.0).abs() <= RECOGNITION_TOLERANCE);
479    Some(format!(
480        "degree={} controls={} collinearity={collinearity:.3e} unit_weights={unit_weights} \
481         count_gate={count} geometry_gate={geometry}",
482        generatrix.degree,
483        controls.len()
484    ))
485}
486
487/// TRUE when a recognized frustum's radius drift is below the precision floor
488/// of the cone construction itself, so the plane section must take the
489/// CYLINDER branch. The cone branch builds its conic as a projective image of
490/// a base circle toward the apex at distance ~|height|·max|ρ|/|Δρ|; the map's
491/// floating-point error grows like that distance × machine epsilon, so for a
492/// near-cylinder frustum (t363: Δρ = 2.23e-12 over height 1500, apex ~1.5e16)
493/// the "exact analytic" section comes back up to ~1 mm off BOTH surfaces.
494/// Downstream, `build_pcurve_on_surface` honestly measures that deviation on
495/// the curved operand, drops every interior sample, and collapses the ring's
496/// pcurve to a single point — the face under-splits and the boolean fails
497/// with one-use edges / non-integral genus.
498///
499/// Branch selection by error balance: the cylinder approximation errs by at
500/// most |Δρ|, the cone construction by ~ε·|height|·max|ρ|/|Δρ|; prefer the
501/// cylinder when its error is smaller, i.e. Δρ² ≤ ε·|height|·max|ρ| (with a
502/// modest constant for the map's factors). This is a deterministic choice
503/// between two exact-in-infinite-precision constructions — not a tolerance —
504/// and can only ever pick the MORE accurate branch. The legacy absolute
505/// 1e-12 acceptance remains as a floor at the call site. Escape hatch:
506/// BREP_CONE_APEX_GUARD=0 restores the bare 1e-12 discrimination.
507fn degenerate_apex_frustum(rho0: f64, rho1: f64, height: f64) -> bool {
508    if std::env::var("BREP_CONE_APEX_GUARD").as_deref() == Ok("0") {
509        return false;
510    }
511    let delta = rho1 - rho0;
512    delta * delta <= 64.0 * f64::EPSILON * height.abs() * rho0.abs().max(rho1.abs())
513}
514
515/// The EXACT arc of `plane ∩ ruled revolution` spanning a given AZIMUTH range
516/// about the carrier's own frame — the arc-restricted, seam-anchorable form of
517/// the full sections `intersect_plane_quadric` returns.
518///
519/// ADDITION, not a change: `intersect_plane_quadric` is untouched and still
520/// answers every pair it answered before, bit for bit. This function exists
521/// because a direct edit needs the section as an EDGE, not as a carrier
522/// section, and an edge has endpoints: a closed rim must START at the face's
523/// own seam vertex (which need not sit at the carrier's `u = 0` — see the
524/// push-face seam fix), and an open rim is a sub-arc between two re-solved
525/// corners. `intersect_plane_quadric` always returns the whole section anchored
526/// at the frame's `x_axis`, so neither is expressible through it.
527///
528/// Both constructions below are the ones that function already uses, and both
529/// preserve AZIMUTH — the cylinder's map adds only an axial component, the
530/// cone's is a central projection from a point ON the axis — so "the arc from
531/// azimuth `a` through `sweep`" is well defined on the section itself and the
532/// anchoring is exact rather than fitted:
533///
534/// - **Cylinder** (`rho1 ≈ rho0`): the section is the AFFINE image of the base
535///   circle under the axial shear `X ↦ X + axis·(c − n·X)/(n·axis)`, which is
536///   linear in the homogeneous control point, so a rational-quadratic arc maps
537///   to a rational-quadratic arc on the SAME knot vector.
538/// - **Cone/frustum**: the section is the PROJECTIVE image from the apex,
539///   `X ↦ apex + (k/((X−apex)·n))·(X−apex)`, again linear in the homogeneous
540///   control point. Weight signs flip for a parabolic/hyperbolic section (the
541///   arc crosses the apex plane), and those are refused by name rather than
542///   silently mis-built.
543///
544/// `sweep` must be positive and at most a full turn; a reversed rim is built
545/// forward and reversed by the caller, which is what keeps the knot vector the
546/// arc construction's own.
547pub fn plane_ruled_section_arc(
548    plane_origin: Vec3,
549    plane_normal: Vec3,
550    frame: &RevolutionFrame,
551    rho0: f64,
552    rho1: f64,
553    height: f64,
554    start_azimuth: f64,
555    sweep: f64,
556    tolerance: f64,
557) -> Result<NurbsCurve, String> {
558    let tau = std::f64::consts::TAU;
559    if !(start_azimuth.is_finite() && sweep.is_finite()) {
560        return Err("plane_ruled_section_arc: non-finite azimuth range".into());
561    }
562    if sweep <= 1e-12 || sweep > tau + 1e-9 {
563        return Err(format!(
564            "plane_ruled_section_arc: the section arc sweeps {sweep:.6e} rad, which is not a \
565             positive arc of at most one turn — refusing"
566        ));
567    }
568    let normal = plane_normal.normalized()?;
569    let radius_scale = rho0.abs().max(rho1.abs()).max(1.0);
570    let axis = frame.axis;
571    let is_cylinder = (rho1 - rho0).abs() <= 1e-9 * radius_scale
572        || degenerate_apex_frustum(rho0, rho1, height);
573    let curve = if is_cylinder {
574        let alignment = normal.dot(axis);
575        if alignment.abs() <= 1e-12 {
576            return Err(
577                "plane_ruled_section_arc: the plane is parallel to the cylinder axis, so the \
578                 section is a generatrix pair rather than a conic — refusing"
579                    .into(),
580            );
581        }
582        if rho0.abs() <= tolerance {
583            return Err("plane_ruled_section_arc: the cylinder carrier has no radius".into());
584        }
585        let base = make_arc(
586            frame.origin,
587            frame.x_axis,
588            frame.y_axis,
589            rho0.abs(),
590            start_azimuth,
591            start_azimuth + sweep,
592        )?;
593        let origin_dot = plane_origin.dot(normal);
594        map_rational_curve(&base, |p| {
595            let t = (origin_dot * p.w - Vec3::new(p.x, p.y, p.z).dot(normal)) / alignment;
596            crate::Vec4 {
597                x: p.x + axis.x * t,
598                y: p.y + axis.y * t,
599                z: p.z + axis.z * t,
600                w: p.w,
601            }
602        })
603        .ok_or_else(|| {
604            "plane_ruled_section_arc: the cylinder section's weights are not one-signed \
605             — refusing"
606                .to_string()
607        })?
608    } else {
609        let apex = frame.origin.add(axis.scale(height * rho0 / (rho0 - rho1)));
610        let k = plane_origin.sub(apex).dot(normal);
611        if k.abs() <= tolerance {
612            return Err(
613                "plane_ruled_section_arc: the plane passes through the cone apex, so the \
614                 section is a line pair rather than a conic — refusing"
615                    .into(),
616            );
617        }
618        let (reference_rho, reference_z) = if rho0.abs() > rho1.abs() {
619            (rho0.abs(), 0.0)
620        } else {
621            (rho1.abs(), height)
622        };
623        if reference_rho <= tolerance {
624            return Err("plane_ruled_section_arc: the cone carrier degenerates to its apex".into());
625        }
626        let base = make_arc(
627            frame.origin.add(axis.scale(reference_z)),
628            frame.x_axis,
629            frame.y_axis,
630            reference_rho,
631            start_azimuth,
632            start_azimuth + sweep,
633        )?;
634        map_rational_curve(&base, |p| {
635            let relative = Vec3::new(p.x - p.w * apex.x, p.y - p.w * apex.y, p.z - p.w * apex.z);
636            let w_new = relative.dot(normal);
637            let scaled = relative.scale(k);
638            crate::Vec4 {
639                x: apex.x * w_new + scaled.x,
640                y: apex.y * w_new + scaled.y,
641                z: apex.z * w_new + scaled.z,
642                w: w_new,
643            }
644        })
645        .ok_or_else(|| {
646            "plane_ruled_section_arc: the section crosses the cone's apex plane (a parabolic \
647             or hyperbolic branch, whose weights change sign) — refusing"
648                .to_string()
649        })?
650    };
651    // The construction is exact, so this measures rather than fits: every
652    // sample must sit on BOTH carriers, at the carrier's own radius for its own
653    // axial station and on the plane.
654    let [d0, d1] = curve.domain()?;
655    let slope = if height == 0.0 {
656        0.0
657    } else {
658        (rho1 - rho0) / height
659    };
660    for step in 0..=8 {
661        let point = curve.evaluate(d0 + (d1 - d0) * (step as f64 / 8.0))?;
662        let delta = point.sub(frame.origin);
663        let axial = delta.dot(axis);
664        let radial = delta.sub(axis.scale(axial)).length();
665        let off_ruled = (radial - (rho0 + slope * axial)).abs();
666        let off_plane = point.sub(plane_origin).dot(normal).abs();
667        if off_ruled > 10.0 * tolerance || off_plane > 10.0 * tolerance {
668            return Err(format!(
669                "plane_ruled_section_arc: the section does not lie on both carriers (off ruled \
670                 {off_ruled:.3e}, off plane {off_plane:.3e}) — refusing"
671            ));
672        }
673    }
674    Ok(curve)
675}
676
677fn intersect_plane_quadric(
678    plane: &PlaneData,
679    quadric: &AnalyticSurface,
680    tolerance: f64,
681    gate: RuledGate,
682) -> Option<Vec<NurbsCurve>> {
683    match quadric {
684        AnalyticSurface::RuledRevolution { .. } | AnalyticSurface::Revolution { .. }
685            if ruled_revolution_data(quadric, tolerance, gate).is_some() =>
686        {
687            let (frame, rho0, rho1, height) = ruled_revolution_data(quadric, tolerance, gate)?;
688            let (frame, rho0, rho1, height) = (&frame, &rho0, &rho1, &height);
689            let alignment = plane.normal.dot(frame.axis);
690            if alignment.abs() >= 1.0 - 1e-12 {
691                // Perpendicular plane: one circle at the plane's height.
692                let z = plane.origin.sub(frame.origin).dot(frame.axis);
693                let t = z / height;
694                if !(-1e-9..=1.0 + 1e-9).contains(&t) {
695                    return Some(Vec::new());
696                }
697                let rho = rho0 + (rho1 - rho0) * t.clamp(0.0, 1.0);
698                if rho <= tolerance {
699                    return Some(Vec::new());
700                }
701                return Some(vec![frame_circle(frame, rho, z)?]);
702            }
703            if (rho1 - rho0).abs() <= 1e-12 || degenerate_apex_frustum(*rho0, *rho1, *height) {
704                // Cylinder.
705                if alignment.abs() <= 1e-12 {
706                    // Plane parallel to the axis: zero, one, or two
707                    // generatrix lines at the circle/line crossing angles.
708                    return cylinder_parallel_plane_lines(plane, frame, *rho0, *height, tolerance);
709                }
710                // Oblique section: exact ellipse as the affine image of a
711                // base circle along the axis direction.
712                let circle = frame_circle(frame, *rho0, 0.0)?;
713                let denominator = alignment;
714                let origin_dot = plane.origin.dot(plane.normal);
715                let normal = plane.normal;
716                let axis = frame.axis;
717                let ellipse = map_rational_curve(&circle, |p| {
718                    let t = (origin_dot * p.w - Vec3::new(p.x, p.y, p.z).dot(normal)) / denominator;
719                    crate::Vec4 {
720                        x: p.x + axis.x * t,
721                        y: p.y + axis.y * t,
722                        z: p.z + axis.z * t,
723                        w: p.w,
724                    }
725                })?;
726                if !section_within_band(&ellipse, frame, *height, tolerance) {
727                    return Some(Vec::new());
728                }
729                return Some(vec![ellipse]);
730            }
731            // Cone/frustum: projective image of a base circle toward the
732            // apex. Weight signs flip for parabolic/hyperbolic sections and
733            // map_rational_curve refuses those (marcher fallback).
734            let apex_t = rho0 / (rho0 - rho1);
735            let apex = frame.origin.add(frame.axis.scale(height * apex_t));
736            let reference_rho = if rho0.abs() > rho1.abs() {
737                *rho0
738            } else {
739                *rho1
740            };
741            let reference_z = if rho0.abs() > rho1.abs() {
742                0.0
743            } else {
744                *height
745            };
746            let circle = frame_circle(frame, reference_rho, reference_z)?;
747            let k = plane.origin.sub(apex).dot(plane.normal);
748            if k.abs() <= tolerance {
749                // Plane through the apex: line pair; leave to the marcher.
750                return None;
751            }
752            let normal = plane.normal;
753            let conic = map_rational_curve(&circle, |p| {
754                let relative =
755                    Vec3::new(p.x - p.w * apex.x, p.y - p.w * apex.y, p.z - p.w * apex.z);
756                let w_new = relative.dot(normal);
757                let scaled = relative.scale(k);
758                crate::Vec4 {
759                    x: apex.x * w_new + scaled.x,
760                    y: apex.y * w_new + scaled.y,
761                    z: apex.z * w_new + scaled.z,
762                    w: w_new,
763                }
764            })?;
765            if !section_within_band(&conic, frame, *height, tolerance) {
766                return Some(Vec::new());
767            }
768            Some(vec![conic])
769        }
770        AnalyticSurface::Sphere { frame, radius } => {
771            plane_sphere_section(plane, frame.origin, *radius, tolerance)
772        }
773        AnalyticSurface::Torus {
774            frame,
775            major_radius,
776            minor_radius,
777        } => plane_torus_section(plane, frame, *major_radius, *minor_radius, tolerance),
778        AnalyticSurface::Plane { .. } => None,
779        AnalyticSurface::RuledRevolution { .. } => None,
780        // A REFLECTED sphere or torus (mirror feature, negative-determinant
781        // transform) recognizes as a general `Revolution` — same point set,
782        // opposite parameter handedness — and keeps its closed-form sections.
783        // Any other general revolution has none; the axial-plane and
784        // tangential-contact paths in imprint own those.
785        AnalyticSurface::Revolution { .. } => {
786            if let Some((center, radius)) = quadric.sphere_geometry() {
787                return plane_sphere_section(plane, center, radius, tolerance);
788            }
789            if let Some((frame, major_radius, minor_radius)) = quadric.torus_geometry() {
790                return plane_torus_section(plane, &frame, major_radius, minor_radius, tolerance);
791            }
792            None
793        }
794    }
795}
796
797/// Plane × sphere: one circle, or provably empty when the plane misses or
798/// merely TOUCHES the sphere (a point contact imprints nothing).
799fn plane_sphere_section(
800    plane: &PlaneData,
801    center: Vec3,
802    radius: f64,
803    tolerance: f64,
804) -> Option<Vec<NurbsCurve>> {
805    let distance = center.sub(plane.origin).dot(plane.normal);
806    if distance.abs() >= radius - tolerance {
807        return Some(Vec::new());
808    }
809    let circle_center = center.sub(plane.normal.scale(distance));
810    let circle_radius = (radius * radius - distance * distance).sqrt();
811    let x_axis = plane.normal.perpendicular().ok()?;
812    let y_axis = plane.normal.cross(x_axis);
813    Some(vec![make_arc(
814        circle_center,
815        x_axis,
816        y_axis,
817        circle_radius,
818        0.0,
819        std::f64::consts::TAU,
820    )
821    .ok()?])
822}
823
824/// Plane ⟂ torus axis: the two latitude circles at the plane's height (one
825/// when it grazes the tube's inner side), or provably empty above/below the
826/// tube.  `frame.origin` must sit at the tube centre's axial position.  An
827/// oblique plane has no closed form here (`None` → marcher).
828fn plane_torus_section(
829    plane: &PlaneData,
830    frame: &RevolutionFrame,
831    major_radius: f64,
832    minor_radius: f64,
833    tolerance: f64,
834) -> Option<Vec<NurbsCurve>> {
835    let alignment = plane.normal.dot(frame.axis);
836    if alignment.abs() < 1.0 - 1e-12 {
837        return None;
838    }
839    let z = plane.origin.sub(frame.origin).dot(frame.axis);
840    if z.abs() >= minor_radius - tolerance {
841        return Some(Vec::new());
842    }
843    let offset = (minor_radius * minor_radius - z * z).sqrt();
844    let mut circles = Vec::new();
845    for rho in [major_radius - offset, major_radius + offset] {
846        if rho > tolerance {
847            circles.push(frame_circle(frame, rho, z)?);
848        }
849    }
850    Some(circles)
851}
852
853/// Reject sections that entirely miss the ruled surface's axial band; the
854/// imprint trimmer would discard them anyway, but skipping early avoids
855/// building pcurves for out-of-band curves.
856///
857/// Uses the convex-hull property of a same-sign-weight rational curve: every
858/// curve point's axial coordinate lies within the [min, max] axial span of the
859/// Cartesian control points. So the section can only miss the band when the
860/// WHOLE control-point span sits above or below it. The earlier `any(CP in
861/// band)` test was wrong for near-axis-parallel oblique sections: the affine
862/// map divides the axial displacement by `alignment`, flinging the rational
863/// control points far to BOTH sides of the band (they straddle it with none
864/// landing inside), so a genuine crossing arc was falsely rejected — the
865/// missing cap∩cylinder imprint behind the curved-primitive open-edge /
866/// non-integral-genus booleans. An interval-overlap test can never falsely
867/// reject (hull property); a false accept is harmless (the imprint trimmer
868/// clips the returned curve to the real face domains regardless).
869fn section_within_band(
870    curve: &NurbsCurve,
871    frame: &RevolutionFrame,
872    height: f64,
873    tolerance: f64,
874) -> bool {
875    let (band_low, band_high) = if height >= 0.0 {
876        (0.0, height)
877    } else {
878        (height, 0.0)
879    };
880    let margin = tolerance.max(1e-9) + 1e-9;
881    let mut min_z = f64::INFINITY;
882    let mut max_z = f64::NEG_INFINITY;
883    for p in &curve.control_points {
884        let z = Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w)
885            .sub(frame.origin)
886            .dot(frame.axis);
887        min_z = min_z.min(z);
888        max_z = max_z.max(z);
889    }
890    // The control-point axial span overlaps the band.
891    max_z >= band_low - margin && min_z <= band_high + margin
892}
893
894fn cylinder_parallel_plane_lines(
895    plane: &PlaneData,
896    frame: &RevolutionFrame,
897    radius: f64,
898    height: f64,
899    tolerance: f64,
900) -> Option<Vec<NurbsCurve>> {
901    // Distance from the axis to the plane, measured in the cross-section.
902    let axis_to_plane = plane.origin.sub(frame.origin).dot(plane.normal);
903    if axis_to_plane.abs() >= radius - tolerance {
904        return Some(Vec::new());
905    }
906    // In-plane offset of the chord from the axis foot.
907    let chord_half = (radius * radius - axis_to_plane * axis_to_plane).sqrt();
908    let chord_direction = frame.axis.cross(plane.normal).normalized().ok()?;
909    let foot = frame.origin.add(plane.normal.scale(axis_to_plane));
910    let mut lines = Vec::new();
911    for sign in [-1.0, 1.0] {
912        let base = foot.add(chord_direction.scale(sign * chord_half));
913        let top = base.add(frame.axis.scale(height));
914        lines.push(crate::make_line(base, top).ok()?);
915    }
916    Some(lines)
917}
918
919fn intersect_sphere_sphere(
920    center_a: Vec3,
921    radius_a: f64,
922    center_b: Vec3,
923    radius_b: f64,
924    tolerance: f64,
925) -> Option<Vec<NurbsCurve>> {
926    let offset = center_b.sub(center_a);
927    let distance = offset.length();
928    if distance <= tolerance {
929        // Concentric: empty or coincident; the cosurface path owns
930        // coincident carriers.
931        return if (radius_a - radius_b).abs() <= tolerance {
932            None
933        } else {
934            Some(Vec::new())
935        };
936    }
937    if distance >= radius_a + radius_b - tolerance
938        || distance <= (radius_a - radius_b).abs() + tolerance
939    {
940        return Some(Vec::new());
941    }
942    let normal = offset.scale(1.0 / distance);
943    let along =
944        (distance * distance + radius_a * radius_a - radius_b * radius_b) / (2.0 * distance);
945    let circle_radius_squared = radius_a * radius_a - along * along;
946    if circle_radius_squared <= tolerance * tolerance {
947        return Some(Vec::new());
948    }
949    let center = center_a.add(normal.scale(along));
950    let x_axis = normal.perpendicular().ok()?;
951    let y_axis = normal.cross(x_axis);
952    Some(vec![make_arc(
953        center,
954        x_axis,
955        y_axis,
956        circle_radius_squared.sqrt(),
957        0.0,
958        std::f64::consts::TAU,
959    )
960    .ok()?])
961}