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/// `BREP_CONE_PLANE_OPEN_SECTION` (default off, `1` on): a plane cutting a
60/// cone or frustum in a parabola or hyperbola is answered with the section's
61/// arcs inside the carrier's axial band ([`cone_plane_open_section`]) instead
62/// of being left to the marcher.
63fn cone_plane_open_section_enabled() -> bool {
64    crate::switch!(live "BREP_CONE_PLANE_OPEN_SECTION", false)
65}
66
67/// A plane's open (parabolic or hyperbolic) section of a cone or frustum,
68/// exactly, over the carrier's axial band. The section point over the base
69/// circle's angle θ is the circle point projected from the apex onto the
70/// plane: homogeneous-linear in (cos θ, sin θ, 1), with weight
71/// `w(θ) = A + B cos θ + C sin θ` and axial coordinate `z_apex + K / w(θ)`
72/// (every base point sits at one height). The band's ends and `w = 0` (the
73/// section's points at infinity) are each `R cos(θ − φ) = c` in closed form;
74/// between consecutive roots `w` keeps its sign, so a base-circle arc there
75/// maps to an exact rational quadratic. The arcs whose middle lies in the band
76/// are returned.
77#[allow(clippy::too_many_arguments)]
78fn cone_plane_open_section(
79    frame: &RevolutionFrame,
80    height: f64,
81    apex: Vec3,
82    reference_rho: f64,
83    reference_z: f64,
84    k: f64,
85    normal: Vec3,
86    tolerance: f64,
87    project: &dyn Fn(crate::Vec4) -> crate::Vec4,
88) -> Option<Vec<NurbsCurve>> {
89    let center = frame.origin.add(frame.axis.scale(reference_z));
90    let a = center.sub(apex).dot(normal);
91    let b = reference_rho * frame.x_axis.dot(normal);
92    let c = reference_rho * frame.y_axis.dot(normal);
93    let r = (b * b + c * c).sqrt();
94    let z_apex = apex.sub(frame.origin).dot(frame.axis);
95    // `K` in z(θ) = z_apex + K / w(θ): k times the base circle's height over the apex.
96    let big_k = k * (reference_z - z_apex);
97    let (band_low, band_high) = (0.0_f64.min(height), 0.0_f64.max(height));
98    let margin = tolerance.max(1e-12);
99    let axial = |theta: f64| -> Option<f64> {
100        let w = a + b * theta.cos() + c * theta.sin();
101        (w.abs() > 1e-300).then(|| z_apex + big_k / w)
102    };
103    let mut roots: Vec<f64> = Vec::new();
104    let mut solve = |target: f64| {
105        // b cos θ + c sin θ = target − a.
106        if r <= 0.0 {
107            return;
108        }
109        let ratio = (target - a) / r;
110        if ratio.abs() > 1.0 {
111            return;
112        }
113        let phi = c.atan2(b);
114        let spread = ratio.acos();
115        for theta in [phi + spread, phi - spread] {
116            roots.push(theta.rem_euclid(std::f64::consts::TAU));
117        }
118    };
119    solve(0.0);
120    for end in [band_low, band_high] {
121        let offset = end - z_apex;
122        if offset.abs() > 1e-300 {
123            solve(big_k / offset);
124        }
125    }
126    roots.sort_by(f64::total_cmp);
127    roots.dedup();
128    if roots.is_empty() {
129        roots.push(0.0);
130    }
131    let mut arcs = Vec::new();
132    for index in 0..roots.len() {
133        let start = roots[index];
134        let mut end = if index + 1 < roots.len() { roots[index + 1] } else { roots[0] + std::f64::consts::TAU };
135        if roots.len() == 1 {
136            end = start + std::f64::consts::TAU;
137        }
138        // Only an empty interval is skipped: a thin one in angle can be a
139        // long branch (a plane close to a large cone's axis); one too thin to
140        // build an arc on refuses below and leaves the pair to the marcher.
141        if !(end > start) {
142            continue;
143        }
144        let middle = 0.5 * (start + end);
145        let Some(z) = axial(middle) else { continue };
146        if z < band_low - margin || z > band_high + margin {
147            continue;
148        }
149        let arc = make_arc(center, frame.x_axis, frame.y_axis, reference_rho, start, end).ok()?;
150        // Within the interval the weight keeps its sign: the image is exact.
151        arcs.push(map_rational_curve(&arc, project)?);
152    }
153    Some(arcs)
154}
155
156/// The full u-circle of a revolution surface at radial distance `rho` and
157/// axial height `z`, built with the same arc construction as the surface.
158fn frame_circle(frame: &RevolutionFrame, rho: f64, z: f64) -> Option<NurbsCurve> {
159    make_arc(
160        frame.origin.add(frame.axis.scale(z)),
161        frame.x_axis,
162        frame.y_axis,
163        rho,
164        0.0,
165        std::f64::consts::TAU,
166    )
167    .ok()
168}
169
170/// Exact intersection curves for recognized analytic pairs, or `None` when
171/// the pair is not handled and the caller must fall back to SSI marching.
172/// `Some(vec![])` means "provably empty" and skips marching entirely.
173pub fn intersect_analytic_pair(
174    first: &NurbsSurface,
175    second: &NurbsSurface,
176    tolerance: f64,
177) -> Option<Vec<NurbsCurve>> {
178    intersect_analytic_pair_with(first, second, tolerance, ruled_gate())
179}
180
181/// Which predicate admits a general revolution's generatrix as the straight
182/// line of a cone, frustum or cylinder in [`intersect_analytic_pair`].
183#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184pub enum RuledGate {
185    /// The count proxy: degree 1, exactly two control points, unit weights.
186    Count,
187    /// What the section constructions consume: the generatrix's two ends, and
188    /// that the curve between them is the straight segment joining them
189    /// ([`NurbsCurve::straight_segment`]).
190    Geometry,
191}
192
193/// The gate the boolean runs: straightness, which is all the section
194/// constructions read. The count proxy declined a knot-refined, degree-elevated
195/// or re-weighted generatrix of the same cone and sent the pair to the marcher.
196/// Escape hatch for measurement: `BREP_RULED_GATE_GEOMETRY=0` runs the count
197/// gate.
198pub fn ruled_gate() -> RuledGate {
199    if std::env::var("BREP_RULED_GATE_GEOMETRY").as_deref() == Ok("0") {
200        RuledGate::Count
201    } else {
202        RuledGate::Geometry
203    }
204}
205
206/// [`intersect_analytic_pair`] under a named generatrix gate — what the fit
207/// census asks of the gate the boolean does NOT run.
208pub fn intersect_analytic_pair_with(
209    first: &NurbsSurface,
210    second: &NurbsSurface,
211    tolerance: f64,
212    gate: RuledGate,
213) -> Option<Vec<NurbsCurve>> {
214    if let Some(curves) = intersect_recognized_pair(first, second, tolerance, gate) {
215        return Some(curves);
216    }
217    if crate::switch!("BREP_EXTRUSION_SECTIONS", true) {
218        for (plane, swept) in [(first,second),(second,first)] {
219            if matches!(swept.analytic(),Some(AnalyticSurface::Plane { .. })) { continue; }
220            if let (Some(plane),Some(extrusion)) = (plane.analytic().and_then(plane_data),swept.linear_extrusion()) {
221                if let Some(curves) = super::plane_extrusion_section(extrusion,plane.origin,plane.normal,tolerance) { return Some(curves); }
222            }
223        }
224        if !matches!(first.analytic(),Some(AnalyticSurface::Plane { .. })) && !matches!(second.analytic(),Some(AnalyticSurface::Plane { .. })) {
225        if let (Some(a),Some(b)) = (first.linear_extrusion(),second.linear_extrusion()) {
226            if let Some(curves) = super::parallel_extrusion_sections(a,b,tolerance) { return Some(curves); }
227        }
228        }
229    }
230    if let Some(curves) = intersect_plane_affine_sphere(first, second, tolerance) {
231        return Some(curves);
232    }
233    if let Some(curves) = intersect_coaxial_revolutions(first, second, tolerance) {
234        return Some(curves);
235    }
236    if coaxial_iso_section_enabled() {
237        if let Some(curves) = intersect_cylinder_radius_invariant(first, second, tolerance) {
238            return Some(curves);
239        }
240        if let Some(curves) = intersect_cylinder_radius_invariant(second, first, tolerance) {
241            return Some(curves);
242        }
243    }
244    // Only under the production gate: the count gate is the escape hatch that
245    // measures the old routing (`ruled_gate_admits_a_straight_generatrix_
246    // whatever_it_counts` reads it sending a re-weighted cone to the marcher).
247    if gate == RuledGate::Geometry && plane_revolution_section_enabled() {
248        if let Some(curves) = intersect_perpendicular_plane_revolution(first, second, tolerance) {
249            return Some(curves);
250        }
251        if let Some(curves) = intersect_perpendicular_plane_revolution(second, first, tolerance) {
252            return Some(curves);
253        }
254    }
255    if let Some(curves) = intersect_axial_plane_revolution(first, second, tolerance) {
256        return Some(curves);
257    }
258    intersect_axial_plane_revolution(second, first, tolerance)
259}
260
261/// `BREP_COAXIAL_ISO_SECTION` (default on; `=0` leaves the pair to the
262/// marcher): a cylinder against a surface
263/// whose radius about its axis is invariant along one parameter
264/// ([`intersect_cylinder_radius_invariant`]).
265fn coaxial_iso_section_enabled() -> bool {
266    crate::switch!("BREP_COAXIAL_ISO_SECTION", true)
267}
268
269/// PLANE x REVOLUTION SECTION (2026-11-06;
270/// `BREP_PLANE_REVOLUTION_SECTION`, default on, `=0` off). A plane square to the axis
271/// of a general surface of revolution (one no quadric arm reads: a revolved
272/// parabola, a revolved spline) meets it in one circle per height at which the
273/// generatrix crosses the plane, over the revolution's sweep. No arm read this
274/// pair, so it went to the marcher, which seeds on a grid and finds no loop
275/// much smaller than the faces: brep-bench
276/// `tangent/paraboloid-tip-a-ten-thousandth-high` (a size-8 paraboloid cut by
277/// z = 1e-4, a rim circle of radius 0.028) read "no boundary faces".
278///
279/// The lane answers only when every crossing is clean: each a sign change of
280/// the generatrix's height over the plane, transversal, and away from the
281/// generatrix's ends and from the axis, and the scan's crossings are as many
282/// as the generatrix's control points change sides of the plane (so none can
283/// hide between two stations). A touching height, a crossing at a
284/// rim the face already has as an edge, or no crossing at all keeps the pair
285/// on the paths it took before (`None`).
286fn plane_revolution_section_enabled() -> bool {
287    crate::switch!("BREP_PLANE_REVOLUTION_SECTION", true)
288}
289
290fn intersect_perpendicular_plane_revolution(
291    plane_surface: &NurbsSurface,
292    revolution: &NurbsSurface,
293    tolerance: f64,
294) -> Option<Vec<NurbsCurve>> {
295    let plane = plane_data(plane_surface.analytic()?)?;
296    if matches!(revolution.analytic(), Some(AnalyticSurface::Plane { .. })) {
297        return None;
298    }
299    let structure = super::revolution::revolution_structure(revolution)?;
300    let frame = &structure.frame;
301    if plane.normal.dot(frame.axis).abs() < 1.0 - 1e-12 {
302        return None;
303    }
304    let generatrix = &structure.generatrix;
305    let [start, end] = generatrix.domain().ok()?;
306    let height = |t: f64| -> Option<f64> { Some(generatrix.evaluate(t).ok()?.sub(plane.origin).dot(plane.normal)) };
307    let scale = surface_scale(revolution).max(1.0);
308    let band = tolerance.max(1e-9 * scale);
309    let spans = generatrix.knots.windows(2).filter(|pair| pair[1] > pair[0]).count().max(1);
310    let stations = 64 * spans;
311    let mut previous_t = start;
312    let mut previous = height(start)?;
313    // A generatrix end ON the plane is a rim the face has as an edge.
314    if previous.abs() <= band || height(end)?.abs() <= band {
315        return None;
316    }
317    let mut roots = Vec::new();
318    for index in 1..=stations {
319        let t = start + (end - start) * index as f64 / stations as f64;
320        let value = height(t)?;
321        if value.abs() <= band && index < stations {
322            // A station on the plane: a touching height or a crossing exactly
323            // here; the bisection below cannot tell them apart.
324            return None;
325        }
326        if (previous < 0.0) != (value < 0.0) {
327            let (mut lo, mut hi, mut lo_value) = (previous_t, t, previous);
328            for _ in 0..200 {
329                let middle = 0.5 * (lo + hi);
330                if middle <= lo || middle >= hi {
331                    break;
332                }
333                let middle_value = height(middle)?;
334                if (middle_value < 0.0) == (lo_value < 0.0) {
335                    lo = middle;
336                    lo_value = middle_value;
337                } else {
338                    hi = middle;
339                }
340            }
341            roots.push(0.5 * (lo + hi));
342        }
343        previous_t = t;
344        previous = value;
345    }
346    if roots.is_empty() {
347        return None;
348    }
349    // The height's numerator `sum w_i ((P_i - o).n) N_i(t)` is a B-spline, so
350    // it has no more roots than its coefficients have sign changes (variation
351    // diminishing). A count above the scan's means two crossings may share a
352    // station, which the scan cannot see: decline rather than drop a circle.
353    let mut coefficient_signs = Vec::new();
354    for control in &generatrix.control_points {
355        if control.w <= 0.0 {
356            return None;
357        }
358        let value = control.point().ok()?.sub(plane.origin).dot(plane.normal);
359        if value.abs() <= band {
360            return None;
361        }
362        coefficient_signs.push(value > 0.0);
363    }
364    let sign_changes = coefficient_signs.windows(2).filter(|pair| pair[0] != pair[1]).count();
365    if sign_changes != roots.len() {
366        return None;
367    }
368    let radius_floor = (tolerance * 10.0).max(1e-9 * scale);
369    let mut curves = Vec::new();
370    for root in roots {
371        let derivatives = generatrix.derivatives(root, 1).ok()?;
372        let tangent = derivatives.get(1)?.normalized().ok()?;
373        if tangent.dot(plane.normal).abs() <= 1e-9 {
374            return None;
375        }
376        let point = generatrix.evaluate(root).ok()?;
377        let (_, radius, axial) = frame.cylindrical(point);
378        if radius <= radius_floor {
379            return None;
380        }
381        let center = frame.origin.add(frame.axis.scale(axial));
382        // The crossing turns from ITS azimuth: zero for a profile in the start
383        // meridian, not for a straight profile skew to the axis (a hyperboloid).
384        let phase = if generatrix_is_meridional_half_ray(generatrix, frame) {
385            0.0
386        } else {
387            let radial = point.sub(center);
388            radial.dot(frame.y_axis).atan2(radial.dot(frame.x_axis))
389        };
390        curves.push(make_arc(center, frame.x_axis, frame.y_axis, radius, phase, phase + structure.sweep).ok()?);
391    }
392    Some(curves)
393}
394
395/// Exact intersection of a plane CONTAINING the revolution axis with a
396/// surface of revolution: the meridian profile rotated to the (at most
397/// two) angles where the plane crosses the sweep. The marcher fits these
398/// as long noisy polylines otherwise (a revolve's start/end caps against
399/// the other operand's revolved walls in revolve-with-holes booleans).
400fn intersect_axial_plane_revolution(
401    plane_surface: &NurbsSurface,
402    revolved: &NurbsSurface,
403    _tolerance: f64,
404) -> Option<Vec<NurbsCurve>> {
405    let plane = match plane_surface.analytic()? {
406        AnalyticSurface::Plane {
407            origin,
408            u_dir,
409            v_dir,
410            ..
411        } => (*origin, u_dir.cross(*v_dir).normalized().ok()?),
412        _ => return None,
413    };
414    let structure = revolution_structure(revolved)?;
415    if !generatrix_is_meridional_half_ray(&structure.generatrix, &structure.frame) {
416        return None;
417    }
418    let scale = surface_scale(plane_surface)
419        .max(surface_scale(revolved))
420        .max(1.0);
421    let (plane_origin, plane_normal) = plane;
422    if structure.frame.axis.dot(plane_normal).abs() > 1e-9 {
423        return None;
424    }
425    if structure
426        .frame
427        .origin
428        .sub(plane_origin)
429        .dot(plane_normal)
430        .abs()
431        > 1e-9 * scale
432    {
433        return None;
434    }
435    let radial = structure.frame.axis.cross(plane_normal).normalized().ok()?;
436    let tau = std::f64::consts::TAU;
437    let mut curves = Vec::new();
438    for direction in [radial, radial.scale(-1.0)] {
439        let mut angle = direction
440            .dot(structure.frame.y_axis)
441            .atan2(direction.dot(structure.frame.x_axis));
442        if angle < -1e-9 {
443            angle += tau;
444        }
445        if angle <= structure.sweep + 1e-9 {
446            curves.push(rotate_curve_about_axis(
447                &structure.generatrix,
448                structure.frame.origin,
449                structure.frame.axis,
450                angle.clamp(0.0, structure.sweep),
451            )?);
452        }
453    }
454    Some(curves)
455}
456
457/// Plane x affine sphere (`geometry/affine_sphere.rs`, under
458/// `BREP_AFFINE_SPHERE`): the exact ellipse, either operand order. Nothing
459/// else pairs with an ellipsoid in closed form (sphere, cylinder and cone
460/// sections of it are quartics; the marcher keeps them).
461fn intersect_plane_affine_sphere(
462    first: &NurbsSurface,
463    second: &NurbsSurface,
464    tolerance: f64,
465) -> Option<Vec<NurbsCurve>> {
466    for (plane_surface, other) in [(first, second), (second, first)] {
467        let Some(ellipsoid) = other.affine_sphere() else { continue };
468        let Some(plane) = plane_surface.analytic().and_then(plane_data) else { continue };
469        return ellipsoid.plane_section(plane.origin, plane.normal, tolerance);
470    }
471    None
472}
473
474fn intersect_recognized_pair(
475    first: &NurbsSurface,
476    second: &NurbsSurface,
477    tolerance: f64,
478    gate: RuledGate,
479) -> Option<Vec<NurbsCurve>> {
480    let a = first.analytic()?;
481    let b = second.analytic()?;
482    if !matches!(b, AnalyticSurface::Plane { .. }) {
483        if let Some(plane) = plane_data(a) {
484            return intersect_plane_quadric(&plane, b, tolerance, gate);
485        }
486    }
487    if !matches!(a, AnalyticSurface::Plane { .. }) {
488        if let Some(plane) = plane_data(b) {
489            return intersect_plane_quadric(&plane, a, tolerance, gate);
490        }
491    }
492    // Sphere×sphere, whichever way each sphere is parameterized (a reflected
493    // sphere recognizes as a general `Revolution`; see `sphere_geometry`).
494    if let (Some((center_a, radius_a)), Some((center_b, radius_b))) =
495        (a.sphere_geometry(), b.sphere_geometry())
496    {
497        return intersect_sphere_sphere(center_a, radius_a, center_b, radius_b, tolerance);
498    }
499    if let Some(curves) = intersect_sphere_coaxial_ruled(a, b, tolerance, gate)
500        .or_else(|| intersect_sphere_coaxial_ruled(b, a, tolerance, gate))
501    {
502        return Some(curves);
503    }
504    if let Some(curves) = intersect_equal_cylinders_meeting_axes(first, second, a, b, tolerance, gate) {
505        return Some(curves);
506    }
507    // The residual conic is cut from the first carrier and checked on the
508    // second; a wide partial cone first can fail where the other order
509    // reads the same section, so both orders are asked.
510    if let Some(curves) = intersect_cones_sharing_a_ruling(a, b, tolerance, gate)
511        .or_else(|| intersect_cones_sharing_a_ruling(b, a, tolerance, gate))
512    {
513        return Some(curves);
514    }
515    // Plane×plane is deliberately NOT special-cased: the iso path
516    // already returns axis-aligned box intersections exactly, and a
517    // synthesized over-long line segment interacts poorly with the
518    // shared-parameter pcurve contract in process_curve (the pcurve is
519    // fitted over the face crossing only, so the curve's [t0,t1]
520    // subrange and the pcurve domain drift apart on long overhangs).
521    None
522}
523
524/// `BREP_SPHERE_CONE_COAXIAL` (default off, `1` on): a sphere against a cone,
525/// frustum or cylinder whose axis passes through the sphere's centre
526/// ([`intersect_sphere_coaxial_ruled`]).
527fn sphere_cone_coaxial_enabled() -> bool {
528    crate::switch!(live "BREP_SPHERE_CONE_COAXIAL", false)
529}
530
531/// A sphere (any carrier [`AnalyticSurface::sphere_geometry`] reads, a partial
532/// sweep included under `BREP_PARTIAL_SPHERE`) against a ruled revolution
533/// whose axis passes through its centre: the pair is coaxial, so the section
534/// is the circles about that axis at the heights `z` where the generatrix's
535/// radius `ρ(z) = ρ₀ + m z` reaches the sphere, `(z − z_c)² + ρ(z)² = r²`, a
536/// quadratic. Roots off the generatrix's own nappe or outside its axial band
537/// are dropped; no real root is a proved-empty pair.
538fn intersect_sphere_coaxial_ruled(
539    sphere: &AnalyticSurface,
540    ruled: &AnalyticSurface,
541    tolerance: f64,
542    gate: RuledGate,
543) -> Option<Vec<NurbsCurve>> {
544    if !sphere_cone_coaxial_enabled() {
545        return None;
546    }
547    let (center, radius) = sphere.sphere_geometry()?;
548    let (frame, rho0, rho1, height) = ruled_revolution_data(ruled, tolerance, gate)?;
549    let offset = center.sub(frame.origin);
550    let center_z = offset.dot(frame.axis);
551    let off_axis = offset.sub(frame.axis.scale(center_z)).length();
552    // Bands relative to the sphere, where the section is: never to the
553    // ruled carrier's length or its distance from its frame origin.
554    // The coaxial test is relative to the sphere; the section's own bands
555    // (a circle's radius, the carrier's axial ends) are the tolerance itself.
556    if off_axis > tolerance.max(1e-12) * (1.0 + radius) {
557        return None;
558    }
559    let margin = tolerance.max(1e-12);
560    let slope = (rho1 - rho0) / height;
561    // In the centre's axial frame, z' = z − z_c, with ρ_c the generatrix's
562    // radius at the centre's height: z'² + (ρ_c + m z')² = r² (no cancellation
563    // against a far frame origin).
564    let rho_center = rho0 + slope * center_z;
565    let a = 1.0 + slope * slope;
566    let b = 2.0 * slope * rho_center;
567    let c = rho_center * rho_center - radius * radius;
568    let discriminant = b * b - 4.0 * a * c;
569    let mut heights = Vec::new();
570    if discriminant > 0.0 {
571        let root = discriminant.sqrt();
572        let q = -0.5 * (b + if b >= 0.0 { root } else { -root });
573        if q != 0.0 {
574            heights.push(center_z + q / a);
575            heights.push(center_z + c / q);
576        } else {
577            heights.push(center_z);
578        }
579    }
580    // A tangent contact (a double root, the generatrix touching the sphere
581    // along a circle) is left to the tangent-contact lanes, which place the
582    // circle's seam and its touching vertices; this lane answers transverse
583    // sections only.
584    // Roots closer than 2e-6 of the radius (√disc / a is their separation)
585    // are a tangency up to round-off, e.g. an equator contact about a
586    // rotated axis: as ill-conditioned as an exact one, so left there too.
587    let separation_bar = 2e-6 * radius * a;
588    if discriminant.abs() <= 1e-9 * (b * b + (4.0 * a * c).abs()).max(radius * radius * 1e-24)
589        || (discriminant > 0.0 && discriminant <= separation_bar * separation_bar)
590    {
591        return None;
592    }
593    let (band_low, band_high) = (0.0_f64.min(height), 0.0_f64.max(height));
594    let mut circles = Vec::new();
595    for z in heights {
596        let rho = rho0 + slope * z;
597        if rho < -margin || z < band_low - margin || z > band_high + margin || rho <= margin {
598            continue;
599        }
600        circles.push(frame_circle(&frame, rho, z)?);
601    }
602    Some(circles)
603}
604
605/// `BREP_CONE_SHARED_RULING` (default off, `1` on): two cones tangent along a
606/// shared ruling ([`intersect_cones_sharing_a_ruling`]).
607fn cone_shared_ruling_enabled() -> bool {
608    crate::switch!(live "BREP_CONE_SHARED_RULING", false)
609}
610
611/// A cone (or frustum) carrier as its double cone: apex, unit axis, and
612/// `cos²` of the half-angle, with the frame and extent it was read from.
613struct ConeData {
614    apex: Vec3,
615    axis: Vec3,
616    cos2: f64,
617    frame: RevolutionFrame,
618    height: f64,
619    /// The swept angle from the frame's x axis (`TAU` for a full revolution).
620    sweep: f64,
621    /// The carrier's own size: its axial extent and largest radius.
622    size: f64,
623}
624
625fn cone_data(quadric: &AnalyticSurface, tolerance: f64, gate: RuledGate) -> Option<ConeData> {
626    let (frame, rho0, rho1, height) = ruled_revolution_data(quadric, tolerance, gate)?;
627    let slope = (rho1 - rho0) / height;
628    if !(slope.is_finite() && slope.abs() > 1e-9) {
629        return None;
630    }
631    let apex = frame.origin.add(frame.axis.scale(-rho0 / slope));
632    let sweep = match quadric {
633        AnalyticSurface::Revolution { sweep, .. } => *sweep,
634        _ => std::f64::consts::TAU,
635    };
636    let size = height.abs().max(rho0.abs()).max(rho1.abs());
637    Some(ConeData { apex, axis: frame.axis, cos2: 1.0 / (1.0 + slope * slope), frame, height, sweep, size })
638}
639
640impl ConeData {
641    /// `((X − A)·d)² − cos²α |X − A|²`: zero on the double cone.
642    fn value(&self, point: Vec3) -> f64 {
643        let d = point.sub(self.apex);
644        let along = d.dot(self.axis);
645        along * along - self.cos2 * d.dot(d)
646    }
647
648    /// The distance from `point` to the double cone, to first order.
649    fn distance(&self, point: Vec3) -> f64 {
650        let d = point.sub(self.apex);
651        let gradient = self.axis.scale(2.0 * d.dot(self.axis)).sub(d.scale(2.0 * self.cos2));
652        let norm = gradient.length();
653        if norm > 0.0 { self.value(point).abs() / norm } else { d.length() }
654    }
655
656    /// The quadric's symmetric 4×4 matrix on homogeneous `(x, 1)`.
657    fn matrix(&self) -> [[f64; 4]; 4] {
658        let d = [self.axis.x, self.axis.y, self.axis.z];
659        let a = [self.apex.x, self.apex.y, self.apex.z];
660        let mut m = [[0.0; 4]; 4];
661        let mut da = [0.0; 3];
662        for i in 0..3 {
663            for j in 0..3 {
664                m[i][j] = d[i] * d[j] - if i == j { self.cos2 } else { 0.0 };
665            }
666        }
667        for i in 0..3 {
668            da[i] = (0..3).map(|j| m[i][j] * a[j]).sum();
669        }
670        for i in 0..3 {
671            m[i][3] = -da[i];
672            m[3][i] = -da[i];
673        }
674        m[3][3] = (0..3).map(|i| a[i] * da[i]).sum();
675        m
676    }
677
678    /// Whether `point`'s azimuth about the axis lies in the swept range (with
679    /// `slack` radians either side); a point on the axis is in every one.
680    fn within_sweep(&self, point: Vec3, slack: f64) -> bool {
681        if self.sweep >= std::f64::consts::TAU - 1e-12 {
682            return true;
683        }
684        match self.frame.cylindrical(point).0 {
685            None => true,
686            Some(theta) => theta <= self.sweep + slack || theta >= std::f64::consts::TAU - slack,
687        }
688    }
689
690    /// Whether `point` lies within the carrier's axial extent (so on its own
691    /// nappe of the double cone), with `slack` either side.
692    fn within_extent(&self, point: Vec3, slack: f64) -> bool {
693        let axial = point.sub(self.frame.origin).dot(self.frame.axis);
694        axial >= 0.0_f64.min(self.height) - slack && axial <= 0.0_f64.max(self.height) + slack
695    }
696
697    /// The parameter range along the line `origin + s·direction` over which
698    /// it lies within this carrier's axial extent.
699    fn extent_along(&self, origin: Vec3, direction: Vec3) -> Option<[f64; 2]> {
700        let rate = direction.dot(self.frame.axis);
701        if rate.abs() <= 1e-12 {
702            return None;
703        }
704        let at = origin.sub(self.frame.origin).dot(self.frame.axis);
705        let (low, high) = (0.0_f64.min(self.height), 0.0_f64.max(self.height));
706        let (s0, s1) = ((low - at) / rate, (high - at) / rate);
707        Some([s0.min(s1), s0.max(s1)])
708    }
709}
710
711/// The pieces of `curve` (rational, degree at most 2) within `cone`'s axial
712/// extent, cut EXACTLY where it crosses either end of the band: within each
713/// knot span the axial coordinate times the homogeneous weight is a
714/// polynomial of degree at most 2 in the parameter, read from three
715/// homogeneous evaluations, so every crossing is a root of a quadratic and no
716/// arc that enters and leaves the band between samples is missed. `None` for a
717/// curve of higher degree or a cut that cannot be made.
718fn pieces_within_extent(curve: &NurbsCurve, cone: &ConeData, slack: f64) -> Option<Vec<NurbsCurve>> {
719    if curve.degree > 2 {
720        return None;
721    }
722    let (low, high) = (0.0_f64.min(cone.height) - slack, 0.0_f64.max(cone.height) + slack);
723    let axial_times_weight = |t: f64, bound: f64| -> Option<f64> {
724        let h = curve.evaluate_homogeneous(t).ok()?;
725        let along = Vec3::new(h.x, h.y, h.z).sub(cone.frame.origin.scale(h.w)).dot(cone.frame.axis);
726        Some(along - bound * h.w)
727    };
728    let mut breaks: Vec<f64> = curve.knots.iter().copied().collect();
729    breaks.sort_by(f64::total_cmp);
730    breaks.dedup();
731    let mut cuts = Vec::new();
732    for pair in breaks.windows(2) {
733        let (t0, t1) = (pair[0], pair[1]);
734        if !(t1 > t0) {
735            continue;
736        }
737        for bound in [low, high] {
738            // f(t) = a s² + b s + c on s ∈ [0, 1] from f(0), f(½), f(1).
739            let (f0, fm, f1) = (axial_times_weight(t0, bound)?, axial_times_weight(0.5 * (t0 + t1), bound)?, axial_times_weight(t1, bound)?);
740            let a = 2.0 * f1 - 4.0 * fm + 2.0 * f0;
741            let b = 4.0 * fm - f1 - 3.0 * f0;
742            let c = f0;
743            let mut roots = Vec::new();
744            if a.abs() <= 1e-14 * (b.abs() + c.abs()).max(1e-300) {
745                if b != 0.0 {
746                    roots.push(-c / b);
747                }
748            } else {
749                let discriminant = b * b - 4.0 * a * c;
750                if discriminant >= 0.0 {
751                    let root = discriminant.sqrt();
752                    let q = -0.5 * (b + b.signum() * root);
753                    if q != 0.0 {
754                        roots.push(q / a);
755                        roots.push(c / q);
756                    }
757                }
758            }
759            // A crossing at a span's end (an internal knot) is a cut too;
760            // the curve's own ends are dropped below.
761            for s in roots {
762                if s >= -1e-12 && s <= 1.0 + 1e-12 {
763                    cuts.push(t0 + s.clamp(0.0, 1.0) * (t1 - t0));
764                }
765            }
766        }
767    }
768    cuts.sort_by(f64::total_cmp);
769    cuts.dedup();
770    let inside = |point: Vec3| cone.within_extent(point, slack);
771    let mut pieces = Vec::new();
772    let mut rest = curve.clone();
773    for cut in cuts {
774        let [r0, r1] = rest.domain().ok()?;
775        if cut <= r0 + 1e-12 * (r1 - r0).abs().max(1.0) || cut >= r1 - 1e-12 * (r1 - r0).abs().max(1.0) {
776            continue;
777        }
778        let (left, right) = rest.split(cut).ok()?;
779        pieces.push(left);
780        rest = right;
781    }
782    pieces.push(rest);
783    let mut kept = Vec::new();
784    for piece in pieces {
785        let [p0, p1] = piece.domain().ok()?;
786        if inside(piece.evaluate(0.5 * (p0 + p1)).ok()?) {
787            kept.push(piece);
788        }
789    }
790    Some(kept)
791}
792
793/// Two cones TANGENT ALONG A SHARED RULING. A ruling of each passes through
794/// its apex, so a shared one is the line through both apexes; it lies on
795/// each double cone when it makes that cone's half-angle with the axis, and
796/// a cone's tangent plane is constant along a ruling, so the cones are
797/// tangent along the whole line when their tangent planes there agree. The
798/// quartic intersection is then the ruling twice and a residual conic: in
799/// the pencil `Q₁ − λQ₂` the member vanishing on the common tangent plane `T`
800/// (λ read at one point of `T` off the ruling, where each cone restricts to
801/// the doubled ruling) is the plane pair `T ∪ π`, and the conic is either cone
802/// cut by `π`. The ruling is returned over both carriers' axial extents and
803/// the conic as the first carrier's plane section, checked on the second.
804/// A pair whose residual section cannot be read is left to the marcher.
805///
806/// A cone filled out to its sphere and the revolves of its half-sections
807/// about a line through the apex plane (brep-bench cone-spun): the cones the
808/// half-section's generators sweep are tangent to the turned cone along the
809/// generators, and the marcher could not settle the tangent pair, so one
810/// union order refused.
811fn intersect_cones_sharing_a_ruling(
812    a: &AnalyticSurface,
813    b: &AnalyticSurface,
814    tolerance: f64,
815    gate: RuledGate,
816) -> Option<Vec<NurbsCurve>> {
817    if !cone_shared_ruling_enabled() {
818        return None;
819    }
820    let (first, second) = (cone_data(a, tolerance, gate)?, cone_data(b, tolerance, gate)?);
821    let between = second.apex.sub(first.apex);
822    let length = between.length();
823    // Bands relative to the carriers' own size, not to where they sit.
824    let scale = 1.0 + first.size.max(second.size);
825    if !(length > 1e-9 * scale) {
826        return None;
827    }
828    let line = between.scale(1.0 / length);
829    // The apex line lies on both double cones.
830    for cone in [&first, &second] {
831        let along = line.dot(cone.axis);
832        if (along * along - cone.cos2).abs() > 1e-9 {
833            return None;
834        }
835    }
836    // Their tangent planes along it agree.
837    let normal_first = first.axis.cross(line).cross(line).normalized().ok()?;
838    let normal_second = second.axis.cross(line).cross(line).normalized().ok()?;
839    if normal_first.cross(normal_second).length() > 1e-9 {
840        return None;
841    }
842    // λ at a point of T off the ruling.
843    let off = first.apex.add(normal_first.cross(line).scale(length.max(1.0)));
844    let (value_first, value_second) = (first.value(off), second.value(off));
845    if !(value_second.abs() > 1e-12 * (1.0 + value_first.abs())) {
846        return None;
847    }
848    let lambda = value_first / value_second;
849    let (m_first, m_second) = (first.matrix(), second.matrix());
850    let mut pencil = [[0.0; 4]; 4];
851    for i in 0..4 {
852        for j in 0..4 {
853            pencil[i][j] = m_first[i][j] - lambda * m_second[i][j];
854        }
855    }
856    let t = [normal_first.x, normal_first.y, normal_first.z, -normal_first.dot(first.apex)];
857    let homogeneous = |point: Vec3| [point.x, point.y, point.z, 1.0];
858    let apply = |m: &[[f64; 4]; 4], x: [f64; 4]| -> [f64; 4] {
859        let mut out = [0.0; 4];
860        for i in 0..4 {
861            out[i] = (0..4).map(|j| m[i][j] * x[j]).sum();
862        }
863        out
864    };
865    let dot4 = |p: [f64; 4], q: [f64; 4]| p[0] * q[0] + p[1] * q[1] + p[2] * q[2] + p[3] * q[3];
866    // π from one point y off T: P y = ½(t (π·y) + π (t·y)).
867    let y = homogeneous(first.apex.add(normal_first.scale(length.max(1.0))));
868    let s = dot4(t, y);
869    if !(s.abs() > 1e-12) {
870        return None;
871    }
872    let py = apply(&pencil, y);
873    let pi_y = dot4(y, py) / s;
874    let mut pi = [0.0; 4];
875    for i in 0..4 {
876        pi[i] = (2.0 * py[i] - t[i] * pi_y) / s;
877    }
878    // The member is that plane pair: its value at a few points is (t·x)(π·x).
879    for probe in [second.apex.add(Vec3::new(0.37, -0.21, 0.53).scale(length)), first.apex.add(Vec3::new(-0.44, 0.61, 0.17).scale(length)), off.add(line.scale(0.3 * length))] {
880        let x = homogeneous(probe);
881        let member = dot4(x, apply(&pencil, x));
882        let pair = dot4(t, x) * dot4(pi, x);
883        if (member - pair).abs() > 1e-8 * (1.0 + member.abs().max(pair.abs())) {
884            return None;
885        }
886    }
887    let mut curves = Vec::new();
888    // The ruling over both carriers' axial extents.
889    if let (Some([a0, a1]), Some([b0, b1])) = (first.extent_along(first.apex, line), second.extent_along(first.apex, line)) {
890        let (s0, s1) = (a0.max(b0), a1.min(b1));
891        let (start, end) = (first.apex.add(line.scale(s0)), first.apex.add(line.scale(s1)));
892        let middle = start.add(end).scale(0.5);
893        if std::env::var_os("BREP_DEBUG_CONE_RULING").is_some() {
894            eprintln!(
895                "cone ruling: s [{s0:.6}, {s1:.6}] from {start:?} to {end:?}; middle theta first {:?} (sweep {:.6}) second {:?} (sweep {:.6})",
896                first.frame.cylindrical(middle).0, first.sweep, second.frame.cylindrical(middle).0, second.sweep
897            );
898        }
899        // A ruling outside a partial revolution's sweep is not on that face.
900        // Any ruling longer than the tolerance itself is a section.
901        if s1 - s0 > tolerance.max(1e-12) && first.within_sweep(middle, 1e-9) && second.within_sweep(middle, 1e-9) {
902            curves.push(crate::make_line(start, end).ok()?);
903        }
904    }
905    // The residual conic on π, when π is a real plane other than T.
906    let pi_normal = Vec3::new(pi[0], pi[1], pi[2]);
907    let pi_length = pi_normal.length();
908    if pi_length > 1e-12 * (1.0 + pi[3].abs()) {
909        let unit = pi_normal.scale(1.0 / pi_length);
910        let origin = pi_normal.scale(-pi[3] / (pi_length * pi_length));
911        let same_as_t = unit.cross(normal_first).length() <= 1e-9 && (unit.dot(first.apex) + pi[3] / pi_length).abs() <= tolerance;
912        if !same_as_t {
913            let plane = PlaneData { origin, normal: unit };
914            let conics = intersect_plane_quadric(&plane, a, tolerance, gate)?;
915            for conic in conics {
916                let [c0, c1] = conic.domain().ok()?;
917                let (mut inside, mut outside) = (0, 0);
918                for k in 0..=32 {
919                    let point = conic.evaluate(c0 + (c1 - c0) * k as f64 / 32.0).ok()?;
920                    if second.distance(point) > 1e3 * tolerance.max(1e-12) * scale {
921                        return None;
922                    }
923                    if first.within_sweep(point, 1e-9) && second.within_sweep(point, 1e-9) {
924                        inside += 1;
925                    } else {
926                        outside += 1;
927                    }
928                }
929                if std::env::var_os("BREP_DEBUG_CONE_RULING").is_some() {
930                    let ends = (conic.evaluate(c0).ok(), conic.evaluate(c1).ok());
931                    eprintln!("cone ruling conic: inside {inside} outside {outside}; ends {ends:?}; sweeps {:.6} {:.6}", first.sweep, second.sweep);
932                }
933                // The sweep counts above are read for the debug line only:
934                // nothing declines on them. The section is of the first
935                // carrier, whose plane section is returned whole once its
936                // band admits it (an ellipse is not cut to the first
937                // carrier's extent); on the second it must also lie on that
938                // carrier's own nappe and axial extent, so the pieces past it
939                // are cut off. A conic past a partial sweep's end continues on
940                // the revolution's own extension; the imprint clips it to the
941                // faces' trims.
942                let slack = tolerance.max(1e-12) * scale;
943                curves.extend(pieces_within_extent(&conic, &second, slack)?);
944            }
945        }
946    }
947    Some(curves)
948}
949
950/// `BREP_EQUAL_CYLINDER_SECTIONS` (default on, `0` off): two cylinders of one
951/// radius whose axes meet ([`intersect_equal_cylinders_meeting_axes`]).
952fn equal_cylinder_sections_enabled() -> bool {
953    crate::switch!(live "BREP_EQUAL_CYLINDER_SECTIONS", true)
954}
955
956/// Two cylinders of ONE radius whose axes meet at a point `C` (not parallel):
957/// a point at distance `r` from both axes lies on one of the two planes
958/// through `C` that bisect the axes (normals `a - b` and `a + b`), so the
959/// intersection is exactly the two plane sections of either cylinder, two
960/// ellipses that cross where the two surfaces are tangent (the points of
961/// the circle of radius `r` about `C` along `a x b`). This is the joint of
962/// two straight slides of one ball-ended tool, whose envelope cylinders
963/// share the joint ball: their crease is the section square to the mean
964/// axis, and at a shallow angle a march seeded at the tangent points reads
965/// the pair as touching only (2026-11-18, the ball-end raster). The sections
966/// are of the first carrier; every station is checked on the second.
967fn intersect_equal_cylinders_meeting_axes(
968    surface_a: &NurbsSurface,
969    surface_b: &NurbsSurface,
970    a: &AnalyticSurface,
971    b: &AnalyticSurface,
972    tolerance: f64,
973    gate: RuledGate,
974) -> Option<Vec<NurbsCurve>> {
975    if !equal_cylinder_sections_enabled() {
976        return None;
977    }
978    let (frame_a, rho0_a, rho1_a, _) = ruled_revolution_data(a, tolerance, gate)?;
979    let (frame_b, rho0_b, rho1_b, _) = ruled_revolution_data(b, tolerance, gate)?;
980    // An absolute band at the caller's tolerance: one radius means one radius
981    // to the tolerance whatever the size (floored at what the radius itself
982    // can represent), never a share of the size or of the distance from the
983    // world origin.
984    let band = tolerance.max(4.0 * f64::EPSILON * 1.0f64.max(rho0_a.abs()).max(rho0_b.abs()));
985    // ONE radius means one radius to round-off, not to the tolerance: two
986    // radii a tolerance apart meet in two branches that pass each other near
987    // the tangent points (a gap of order sqrt(r dr)), not in two crossing
988    // ellipses, and such a pair is the march's.
989    let same_radius = 16.0 * f64::EPSILON * 1.0f64.max(rho0_a.abs()).max(rho0_b.abs());
990    if (rho0_a - rho1_a).abs() > band || (rho0_b - rho1_b).abs() > band || (rho0_a - rho0_b).abs() > same_radius || rho0_a <= band {
991        return None;
992    }
993    let (radius, radius_b) = (rho0_a, rho0_b);
994    let (da, mut db) = (frame_a.axis.normalized().ok()?, frame_b.axis.normalized().ok()?);
995    if da.dot(db) < 0.0 {
996        db = db.scale(-1.0);
997    }
998    let cross = da.cross(db);
999    let sine = cross.length();
1000    // Parallel axes are the coaxial / parallel lanes' business; below this
1001    // angle the meeting point is not determined to `band`.
1002    if sine <= 1e-6 {
1003        return None;
1004    }
1005    // The axes must MEET, to round-off as the radii must agree: axes a
1006    // tolerance apart (skew) give two branches that pass each other near the
1007    // tangent points (a gap of order sqrt(r d)), not crossing ellipses.
1008    let offset = frame_b.origin.sub(frame_a.origin);
1009    let skew = offset.dot(cross.scale(1.0 / sine)).abs();
1010    let meet = 16.0 * f64::EPSILON * 1.0f64.max(rho0_a.abs()).max(frame_a.origin.length()).max(frame_b.origin.length());
1011    if std::env::var_os("BREP_DEBUG_EQUAL_CYLINDERS").is_some() {
1012        eprintln!("equal cylinders: skew {skew:.3e} (round-off bar {meet:.3e}), radii {rho0_a} / {rho0_b}");
1013    }
1014    if skew > meet {
1015        return None;
1016    }
1017    // C = A0 + s da with (A0 + s da - B0) x db = 0: s = ((B0 - A0) x db)·(da x db) / |da x db|^2.
1018    let s = offset.cross(db).dot(cross) / (sine * sine);
1019    let centre = frame_a.origin.add(da.scale(s));
1020    let off_axis = |point: Vec3, origin: Vec3, axis: Vec3, rho: f64| {
1021        let delta = point.sub(origin);
1022        (delta.sub(axis.scale(delta.dot(axis))).length() - rho).abs()
1023    };
1024    // Each CARRIER is the cylinder its recognition names: a straight
1025    // generatrix with equal end radii also describes a hyperboloid (a line
1026    // skew to the axis), which is not this closed form.
1027    for (surface, origin, axis, rho) in [(surface_a, frame_a.origin, da, radius), (surface_b, frame_b.origin, db, radius_b)] {
1028        let ([u0, u1], [v0, v1]) = (surface.domain_u().ok()?, surface.domain_v().ok()?);
1029        for i in 0..=6 {
1030            for j in 0..=6 {
1031                let point = surface.evaluate(u0 + (u1 - u0) * i as f64 / 6.0, v0 + (v1 - v0) * j as f64 / 6.0).ok()?;
1032                if off_axis(point, origin, axis, rho) > band {
1033                    return None;
1034                }
1035            }
1036        }
1037    }
1038    let on_b = |point: Vec3| off_axis(point, frame_b.origin, db, radius_b);
1039    let mut curves = Vec::new();
1040    for normal in [da.sub(db), da.add(db)] {
1041        let normal = normal.normalized().ok()?;
1042        let plane = PlaneData { origin: centre, normal };
1043        for curve in intersect_plane_quadric(&plane, a, tolerance, gate)? {
1044            let [t0, t1] = curve.domain().ok()?;
1045            for index in 0..=16 {
1046                let point = curve.evaluate(t0 + (t1 - t0) * index as f64 / 16.0).ok()?;
1047                if on_b(point) > band * 10.0 {
1048                    return None;
1049                }
1050            }
1051            curves.push(curve);
1052        }
1053    }
1054    Some(curves)
1055}
1056
1057/// Frame/meridian data for any revolution with a straight-line generatrix:
1058/// the `RuledRevolution` quadrics themselves, plus partial-sweep
1059/// `Revolution`s whose generatrix the named gate admits as straight (fillet
1060/// cutter walls are quarter cylinders of this shape). The plane
1061/// intersectors only need the carrier geometry — the boolean trims the
1062/// returned curves to the actual face domains afterwards.
1063fn ruled_revolution_data(
1064    quadric: &AnalyticSurface,
1065    tolerance: f64,
1066    gate: RuledGate,
1067) -> Option<(RevolutionFrame, f64, f64, f64)> {
1068    match quadric {
1069        AnalyticSurface::RuledRevolution {
1070            frame,
1071            rho0,
1072            rho1,
1073            height,
1074        } => Some((frame.clone(), *rho0, *rho1, *height)),
1075        AnalyticSurface::Revolution {
1076            frame, generatrix, ..
1077        } => {
1078            // A straight profile skew to the axis sweeps a hyperboloid, not a
1079            // cone: only a profile in the start meridian reads as one.
1080            if !generatrix_is_meridional_half_ray(generatrix, frame) {
1081                return None;
1082            }
1083            let (start, end) = match gate {
1084                RuledGate::Count => {
1085                    let controls = &generatrix.control_points;
1086                    if generatrix.degree != 1
1087                        || controls.len() != 2
1088                        || (controls[0].w - 1.0).abs() > RECOGNITION_TOLERANCE
1089                        || (controls[1].w - 1.0).abs() > RECOGNITION_TOLERANCE
1090                    {
1091                        return None;
1092                    }
1093                    (controls[0].point().ok()?, controls[1].point().ok()?)
1094                }
1095                RuledGate::Geometry => generatrix.straight_segment(tolerance)?,
1096            };
1097            let (_, rho0, z0) = frame.cylindrical(start);
1098            let (_, rho1, z1) = frame.cylindrical(end);
1099            let height = z1 - z0;
1100            if height.abs() <= 1e-12 * (1.0 + rho0.abs().max(rho1.abs())) {
1101                return None;
1102            }
1103            let origin = frame.origin.add(frame.axis.scale(z0));
1104            Some((
1105                RevolutionFrame {
1106                    origin,
1107                    ..frame.clone()
1108                },
1109                rho0,
1110                rho1,
1111                height,
1112            ))
1113        }
1114        _ => None,
1115    }
1116}
1117
1118/// CENSUS ONLY (`BREP_FIT_CENSUS=1`): a description of `surface`'s generatrix
1119/// when it is a general revolution the two generatrix gates answer
1120/// differently, `None` otherwise.
1121pub fn ruled_gate_census(surface: &NurbsSurface, tolerance: f64) -> Option<String> {
1122    let quadric = surface.analytic()?;
1123    let AnalyticSurface::Revolution { generatrix, .. } = quadric else {
1124        return None;
1125    };
1126    let count = ruled_revolution_data(quadric, tolerance, RuledGate::Count).is_some();
1127    let geometry = ruled_revolution_data(quadric, tolerance, RuledGate::Geometry).is_some();
1128    if count == geometry {
1129        return None;
1130    }
1131    let controls = &generatrix.control_points;
1132    let points: Vec<Vec3> = controls
1133        .iter()
1134        .map(|control| control.point().unwrap_or_default())
1135        .collect();
1136    let (first, last) = (points[0], points[points.len() - 1]);
1137    let direction = last.sub(first);
1138    let length_squared = direction.length_squared();
1139    let mut collinearity = 0.0_f64;
1140    for point in &points {
1141        collinearity = collinearity.max(if length_squared <= 0.0 {
1142            point.sub(first).length()
1143        } else {
1144            let fraction = (point.sub(first).dot(direction) / length_squared).clamp(0.0, 1.0);
1145            point.sub(first.add(direction.scale(fraction))).length()
1146        });
1147    }
1148    let unit_weights = controls
1149        .iter()
1150        .all(|control| (control.w - 1.0).abs() <= RECOGNITION_TOLERANCE);
1151    Some(format!(
1152        "degree={} controls={} collinearity={collinearity:.3e} unit_weights={unit_weights} \
1153         count_gate={count} geometry_gate={geometry}",
1154        generatrix.degree,
1155        controls.len()
1156    ))
1157}
1158
1159/// TRUE when a recognized frustum's radius drift is below the precision floor
1160/// of the cone construction itself, so the plane section must take the
1161/// CYLINDER branch. The cone branch builds its conic as a projective image of
1162/// a base circle toward the apex at distance ~|height|·max|ρ|/|Δρ|; the map's
1163/// floating-point error grows like that distance × machine epsilon, so for a
1164/// near-cylinder frustum (t363: Δρ = 2.23e-12 over height 1500, apex ~1.5e16)
1165/// the "exact analytic" section comes back up to ~1 mm off BOTH surfaces.
1166/// Downstream, `build_pcurve_on_surface` honestly measures that deviation on
1167/// the curved operand, drops every interior sample, and collapses the ring's
1168/// pcurve to a single point — the face under-splits and the boolean fails
1169/// with one-use edges / non-integral genus.
1170///
1171/// Branch selection by error balance: the cylinder approximation errs by at
1172/// most |Δρ|, the cone construction by ~ε·|height|·max|ρ|/|Δρ|; prefer the
1173/// cylinder when its error is smaller, i.e. Δρ² ≤ ε·|height|·max|ρ| (with a
1174/// modest constant for the map's factors). This is a deterministic choice
1175/// between two exact-in-infinite-precision constructions — not a tolerance —
1176/// and can only ever pick the MORE accurate branch. The legacy absolute
1177/// 1e-12 acceptance remains as a floor at the call site. Escape hatch:
1178/// BREP_CONE_APEX_GUARD=0 restores the bare 1e-12 discrimination.
1179fn degenerate_apex_frustum(rho0: f64, rho1: f64, height: f64) -> bool {
1180    if std::env::var("BREP_CONE_APEX_GUARD").as_deref() == Ok("0") {
1181        return false;
1182    }
1183    let delta = rho1 - rho0;
1184    delta * delta <= 64.0 * f64::EPSILON * height.abs() * rho0.abs().max(rho1.abs())
1185}
1186
1187/// The EXACT arc of `plane ∩ ruled revolution` spanning a given AZIMUTH range
1188/// about the carrier's own frame — the arc-restricted, seam-anchorable form of
1189/// the full sections `intersect_plane_quadric` returns.
1190///
1191/// ADDITION, not a change: `intersect_plane_quadric` is untouched and still
1192/// answers every pair it answered before, bit for bit. This function exists
1193/// because a direct edit needs the section as an EDGE, not as a carrier
1194/// section, and an edge has endpoints: a closed rim must START at the face's
1195/// own seam vertex (which need not sit at the carrier's `u = 0` — see the
1196/// push-face seam fix), and an open rim is a sub-arc between two re-solved
1197/// corners. `intersect_plane_quadric` always returns the whole section anchored
1198/// at the frame's `x_axis`, so neither is expressible through it.
1199///
1200/// Both constructions below are the ones that function already uses, and both
1201/// preserve AZIMUTH — the cylinder's map adds only an axial component, the
1202/// cone's is a central projection from a point ON the axis — so "the arc from
1203/// azimuth `a` through `sweep`" is well defined on the section itself and the
1204/// anchoring is exact rather than fitted:
1205///
1206/// - **Cylinder** (`rho1 ≈ rho0`): the section is the AFFINE image of the base
1207///   circle under the axial shear `X ↦ X + axis·(c − n·X)/(n·axis)`, which is
1208///   linear in the homogeneous control point, so a rational-quadratic arc maps
1209///   to a rational-quadratic arc on the SAME knot vector.
1210/// - **Cone/frustum**: the section is the PROJECTIVE image from the apex,
1211///   `X ↦ apex + (k/((X−apex)·n))·(X−apex)`, again linear in the homogeneous
1212///   control point. A parabolic or hyperbolic section is built like an
1213///   elliptic one while the ARC stays clear of the generatrices parallel to the
1214///   plane: every point of it is then a finite image on one nappe and the
1215///   weights keep one sign. An arc that reaches such a generatrix (a closed rim
1216///   always does) has weights that change sign, and is refused by name rather
1217///   than silently mis-built — that generatrix never meets the plane.
1218///
1219/// `sweep` must be positive and at most a full turn; a reversed rim is built
1220/// forward and reversed by the caller, which is what keeps the knot vector the
1221/// arc construction's own.
1222pub fn plane_ruled_section_arc(
1223    plane_origin: Vec3,
1224    plane_normal: Vec3,
1225    frame: &RevolutionFrame,
1226    rho0: f64,
1227    rho1: f64,
1228    height: f64,
1229    start_azimuth: f64,
1230    sweep: f64,
1231    tolerance: f64,
1232) -> Result<NurbsCurve, String> {
1233    let tau = std::f64::consts::TAU;
1234    if !(start_azimuth.is_finite() && sweep.is_finite()) {
1235        return Err("plane_ruled_section_arc: non-finite azimuth range".into());
1236    }
1237    if sweep <= 1e-12 || sweep > tau + 1e-9 {
1238        return Err(format!(
1239            "plane_ruled_section_arc: the section arc sweeps {sweep:.6e} rad, which is not a \
1240             positive arc of at most one turn — refusing"
1241        ));
1242    }
1243    let normal = plane_normal.normalized()?;
1244    let radius_scale = rho0.abs().max(rho1.abs()).max(1.0);
1245    let axis = frame.axis;
1246    let is_cylinder = (rho1 - rho0).abs() <= 1e-9 * radius_scale
1247        || degenerate_apex_frustum(rho0, rho1, height);
1248    let curve = if is_cylinder {
1249        let alignment = normal.dot(axis);
1250        if alignment.abs() <= 1e-12 {
1251            return Err(
1252                "plane_ruled_section_arc: the plane is parallel to the cylinder axis, so the \
1253                 section is a generatrix pair rather than a conic — refusing"
1254                    .into(),
1255            );
1256        }
1257        if rho0.abs() <= tolerance {
1258            return Err("plane_ruled_section_arc: the cylinder carrier has no radius".into());
1259        }
1260        let base = make_arc(
1261            frame.origin,
1262            frame.x_axis,
1263            frame.y_axis,
1264            rho0.abs(),
1265            start_azimuth,
1266            start_azimuth + sweep,
1267        )?;
1268        let origin_dot = plane_origin.dot(normal);
1269        map_rational_curve(&base, |p| {
1270            let t = (origin_dot * p.w - Vec3::new(p.x, p.y, p.z).dot(normal)) / alignment;
1271            crate::Vec4 {
1272                x: p.x + axis.x * t,
1273                y: p.y + axis.y * t,
1274                z: p.z + axis.z * t,
1275                w: p.w,
1276            }
1277        })
1278        .ok_or_else(|| {
1279            "plane_ruled_section_arc: the cylinder section's weights are not one-signed \
1280             — refusing"
1281                .to_string()
1282        })?
1283    } else {
1284        let apex = frame.origin.add(axis.scale(height * rho0 / (rho0 - rho1)));
1285        let k = plane_origin.sub(apex).dot(normal);
1286        if k.abs() <= tolerance {
1287            return Err(
1288                "plane_ruled_section_arc: the plane passes through the cone apex, so the \
1289                 section is a line pair rather than a conic — refusing"
1290                    .into(),
1291            );
1292        }
1293        let (reference_rho, reference_z) = if rho0.abs() > rho1.abs() {
1294            (rho0.abs(), 0.0)
1295        } else {
1296            (rho1.abs(), height)
1297        };
1298        if reference_rho <= tolerance {
1299            return Err("plane_ruled_section_arc: the cone carrier degenerates to its apex".into());
1300        }
1301        let base = make_arc(
1302            frame.origin.add(axis.scale(reference_z)),
1303            frame.x_axis,
1304            frame.y_axis,
1305            reference_rho,
1306            start_azimuth,
1307            start_azimuth + sweep,
1308        )?;
1309        map_rational_curve(&base, |p| {
1310            let relative = Vec3::new(p.x - p.w * apex.x, p.y - p.w * apex.y, p.z - p.w * apex.z);
1311            let w_new = relative.dot(normal);
1312            let scaled = relative.scale(k);
1313            crate::Vec4 {
1314                x: apex.x * w_new + scaled.x,
1315                y: apex.y * w_new + scaled.y,
1316                z: apex.z * w_new + scaled.z,
1317                w: w_new,
1318            }
1319        })
1320        .ok_or_else(|| {
1321            "plane_ruled_section_arc: the section crosses the cone's apex plane (a parabolic \
1322             or hyperbolic branch, whose weights change sign) — refusing"
1323                .to_string()
1324        })?
1325    };
1326    // The construction is exact, so this measures rather than fits: every
1327    // sample must sit on BOTH carriers, at the carrier's own radius for its own
1328    // axial station and on the plane.
1329    let [d0, d1] = curve.domain()?;
1330    let slope = if height == 0.0 {
1331        0.0
1332    } else {
1333        (rho1 - rho0) / height
1334    };
1335    for step in 0..=8 {
1336        let point = curve.evaluate(d0 + (d1 - d0) * (step as f64 / 8.0))?;
1337        let delta = point.sub(frame.origin);
1338        let axial = delta.dot(axis);
1339        let radial = delta.sub(axis.scale(axial)).length();
1340        let off_ruled = (radial - (rho0 + slope * axial)).abs();
1341        let off_plane = point.sub(plane_origin).dot(normal).abs();
1342        if off_ruled > 10.0 * tolerance || off_plane > 10.0 * tolerance {
1343            return Err(format!(
1344                "plane_ruled_section_arc: the section does not lie on both carriers (off ruled \
1345                 {off_ruled:.3e}, off plane {off_plane:.3e}) — refusing"
1346            ));
1347        }
1348    }
1349    Ok(curve)
1350}
1351
1352fn intersect_plane_quadric(
1353    plane: &PlaneData,
1354    quadric: &AnalyticSurface,
1355    tolerance: f64,
1356    gate: RuledGate,
1357) -> Option<Vec<NurbsCurve>> {
1358    match quadric {
1359        AnalyticSurface::RuledRevolution { .. } | AnalyticSurface::Revolution { .. }
1360            if ruled_revolution_data(quadric, tolerance, gate).is_some() =>
1361        {
1362            let (frame, rho0, rho1, height) = ruled_revolution_data(quadric, tolerance, gate)?;
1363            let (frame, rho0, rho1, height) = (&frame, &rho0, &rho1, &height);
1364            let alignment = plane.normal.dot(frame.axis);
1365            if alignment.abs() >= 1.0 - 1e-12 {
1366                // Perpendicular plane: one circle at the plane's height.
1367                let z = plane.origin.sub(frame.origin).dot(frame.axis);
1368                let t = z / height;
1369                if !(-1e-9..=1.0 + 1e-9).contains(&t) {
1370                    return Some(Vec::new());
1371                }
1372                let rho = rho0 + (rho1 - rho0) * t.clamp(0.0, 1.0);
1373                if rho <= tolerance {
1374                    return Some(Vec::new());
1375                }
1376                return Some(vec![frame_circle(frame, rho, z)?]);
1377            }
1378            if (rho1 - rho0).abs() <= 1e-12 || degenerate_apex_frustum(*rho0, *rho1, *height) {
1379                // Cylinder.
1380                if alignment.abs() <= 1e-12 {
1381                    // Plane parallel to the axis: zero, one, or two
1382                    // generatrix lines at the circle/line crossing angles.
1383                    return cylinder_parallel_plane_lines(plane, frame, *rho0, *height, tolerance);
1384                }
1385                // Oblique section: exact ellipse as the affine image of a
1386                // base circle along the axis direction.
1387                let circle = frame_circle(frame, *rho0, 0.0)?;
1388                let denominator = alignment;
1389                let origin_dot = plane.origin.dot(plane.normal);
1390                let normal = plane.normal;
1391                let axis = frame.axis;
1392                let ellipse = map_rational_curve(&circle, |p| {
1393                    let t = (origin_dot * p.w - Vec3::new(p.x, p.y, p.z).dot(normal)) / denominator;
1394                    crate::Vec4 {
1395                        x: p.x + axis.x * t,
1396                        y: p.y + axis.y * t,
1397                        z: p.z + axis.z * t,
1398                        w: p.w,
1399                    }
1400                })?;
1401                if !section_within_band(&ellipse, frame, *height, tolerance) {
1402                    return Some(Vec::new());
1403                }
1404                return Some(vec![ellipse]);
1405            }
1406            // Cone/frustum: projective image of a base circle toward the
1407            // apex. Weight signs flip for parabolic/hyperbolic sections and
1408            // map_rational_curve refuses those (marcher fallback).
1409            let apex_t = rho0 / (rho0 - rho1);
1410            let apex = frame.origin.add(frame.axis.scale(height * apex_t));
1411            let reference_rho = if rho0.abs() > rho1.abs() {
1412                *rho0
1413            } else {
1414                *rho1
1415            };
1416            let reference_z = if rho0.abs() > rho1.abs() {
1417                0.0
1418            } else {
1419                *height
1420            };
1421            let circle = frame_circle(frame, reference_rho, reference_z)?;
1422            let k = plane.origin.sub(apex).dot(plane.normal);
1423            if k.abs() <= tolerance {
1424                // Plane through the apex: line pair; leave to the marcher.
1425                return None;
1426            }
1427            let normal = plane.normal;
1428            let project = |p: crate::Vec4| {
1429                let relative =
1430                    Vec3::new(p.x - p.w * apex.x, p.y - p.w * apex.y, p.z - p.w * apex.z);
1431                let w_new = relative.dot(normal);
1432                let scaled = relative.scale(k);
1433                crate::Vec4 {
1434                    x: apex.x * w_new + scaled.x,
1435                    y: apex.y * w_new + scaled.y,
1436                    z: apex.z * w_new + scaled.z,
1437                    w: w_new,
1438                }
1439            };
1440            let Some(conic) = map_rational_curve(&circle, project) else {
1441                // A parabola or hyperbola: its arcs inside the band.
1442                if cone_plane_open_section_enabled() {
1443                    return cone_plane_open_section(frame, *height, apex, reference_rho, reference_z, k, normal, tolerance, &project);
1444                }
1445                return None;
1446            };
1447            if !section_within_band(&conic, frame, *height, tolerance) {
1448                return Some(Vec::new());
1449            }
1450            Some(vec![conic])
1451        }
1452        AnalyticSurface::Sphere { frame, radius } => {
1453            plane_sphere_section(plane, frame.origin, *radius, tolerance)
1454        }
1455        AnalyticSurface::Torus {
1456            frame,
1457            major_radius,
1458            minor_radius,
1459        } => plane_torus_section(plane, frame, *major_radius, *minor_radius, tolerance),
1460        AnalyticSurface::Plane { .. } => None,
1461        AnalyticSurface::RuledRevolution { .. } => None,
1462        // A REFLECTED sphere or torus (mirror feature, negative-determinant
1463        // transform) recognizes as a general `Revolution` — same point set,
1464        // opposite parameter handedness — and keeps its closed-form sections.
1465        // Any other general revolution has none; the axial-plane and
1466        // tangential-contact paths in imprint own those.
1467        AnalyticSurface::Revolution { .. } => {
1468            if let Some((center, radius)) = quadric.sphere_geometry() {
1469                return plane_sphere_section(plane, center, radius, tolerance);
1470            }
1471            if let Some((frame, major_radius, minor_radius)) = quadric.torus_geometry() {
1472                return plane_torus_section(plane, &frame, major_radius, minor_radius, tolerance);
1473            }
1474            None
1475        }
1476    }
1477}
1478
1479/// Plane × sphere: one circle, or provably empty when the plane misses or
1480/// merely TOUCHES the sphere (a point contact imprints nothing).
1481fn plane_sphere_section(
1482    plane: &PlaneData,
1483    center: Vec3,
1484    radius: f64,
1485    tolerance: f64,
1486) -> Option<Vec<NurbsCurve>> {
1487    let distance = center.sub(plane.origin).dot(plane.normal);
1488    if distance.abs() >= radius - tolerance {
1489        return Some(Vec::new());
1490    }
1491    let circle_center = center.sub(plane.normal.scale(distance));
1492    let circle_radius = (radius * radius - distance * distance).sqrt();
1493    let x_axis = plane.normal.perpendicular().ok()?;
1494    let y_axis = plane.normal.cross(x_axis);
1495    Some(vec![make_arc(
1496        circle_center,
1497        x_axis,
1498        y_axis,
1499        circle_radius,
1500        0.0,
1501        std::f64::consts::TAU,
1502    )
1503    .ok()?])
1504}
1505
1506/// Plane ⟂ torus axis: the two latitude circles at the plane's height (one
1507/// when it grazes the tube's inner side), or provably empty above/below the
1508/// tube.  `frame.origin` must sit at the tube centre's axial position.  An
1509/// oblique plane has no closed form here (`None` → marcher).
1510fn plane_torus_section(
1511    plane: &PlaneData,
1512    frame: &RevolutionFrame,
1513    major_radius: f64,
1514    minor_radius: f64,
1515    tolerance: f64,
1516) -> Option<Vec<NurbsCurve>> {
1517    let alignment = plane.normal.dot(frame.axis);
1518    if alignment.abs() < 1.0 - 1e-12 {
1519        return None;
1520    }
1521    let z = plane.origin.sub(frame.origin).dot(frame.axis);
1522    if z.abs() >= minor_radius - tolerance {
1523        return Some(Vec::new());
1524    }
1525    let offset = (minor_radius * minor_radius - z * z).sqrt();
1526    let mut circles = Vec::new();
1527    for rho in [major_radius - offset, major_radius + offset] {
1528        if rho > tolerance {
1529            circles.push(frame_circle(frame, rho, z)?);
1530        }
1531    }
1532    Some(circles)
1533}
1534
1535/// Reject sections that entirely miss the ruled surface's axial band; the
1536/// imprint trimmer would discard them anyway, but skipping early avoids
1537/// building pcurves for out-of-band curves.
1538///
1539/// Uses the convex-hull property of a same-sign-weight rational curve: every
1540/// curve point's axial coordinate lies within the [min, max] axial span of the
1541/// Cartesian control points. So the section can only miss the band when the
1542/// WHOLE control-point span sits above or below it. The earlier `any(CP in
1543/// band)` test was wrong for near-axis-parallel oblique sections: the affine
1544/// map divides the axial displacement by `alignment`, flinging the rational
1545/// control points far to BOTH sides of the band (they straddle it with none
1546/// landing inside), so a genuine crossing arc was falsely rejected — the
1547/// missing cap∩cylinder imprint behind the curved-primitive open-edge /
1548/// non-integral-genus booleans. An interval-overlap test can never falsely
1549/// reject (hull property); a false accept is harmless (the imprint trimmer
1550/// clips the returned curve to the real face domains regardless).
1551fn section_within_band(
1552    curve: &NurbsCurve,
1553    frame: &RevolutionFrame,
1554    height: f64,
1555    tolerance: f64,
1556) -> bool {
1557    let (band_low, band_high) = if height >= 0.0 {
1558        (0.0, height)
1559    } else {
1560        (height, 0.0)
1561    };
1562    let margin = tolerance.max(1e-9) + 1e-9;
1563    let mut min_z = f64::INFINITY;
1564    let mut max_z = f64::NEG_INFINITY;
1565    for p in &curve.control_points {
1566        let z = Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w)
1567            .sub(frame.origin)
1568            .dot(frame.axis);
1569        min_z = min_z.min(z);
1570        max_z = max_z.max(z);
1571    }
1572    // The control-point axial span overlaps the band.
1573    max_z >= band_low - margin && min_z <= band_high + margin
1574}
1575
1576fn cylinder_parallel_plane_lines(
1577    plane: &PlaneData,
1578    frame: &RevolutionFrame,
1579    radius: f64,
1580    height: f64,
1581    tolerance: f64,
1582) -> Option<Vec<NurbsCurve>> {
1583    // Distance from the axis to the plane, measured in the cross-section.
1584    let axis_to_plane = plane.origin.sub(frame.origin).dot(plane.normal);
1585    if axis_to_plane.abs() >= radius - tolerance {
1586        return Some(Vec::new());
1587    }
1588    // In-plane offset of the chord from the axis foot.
1589    let chord_half = (radius * radius - axis_to_plane * axis_to_plane).sqrt();
1590    let chord_direction = frame.axis.cross(plane.normal).normalized().ok()?;
1591    let foot = frame.origin.add(plane.normal.scale(axis_to_plane));
1592    let mut lines = Vec::new();
1593    for sign in [-1.0, 1.0] {
1594        let base = foot.add(chord_direction.scale(sign * chord_half));
1595        let top = base.add(frame.axis.scale(height));
1596        lines.push(crate::make_line(base, top).ok()?);
1597    }
1598    Some(lines)
1599}
1600
1601fn intersect_sphere_sphere(
1602    center_a: Vec3,
1603    radius_a: f64,
1604    center_b: Vec3,
1605    radius_b: f64,
1606    tolerance: f64,
1607) -> Option<Vec<NurbsCurve>> {
1608    let offset = center_b.sub(center_a);
1609    let distance = offset.length();
1610    if distance <= tolerance {
1611        // Concentric: empty or coincident; the cosurface path owns
1612        // coincident carriers.
1613        return if (radius_a - radius_b).abs() <= tolerance {
1614            None
1615        } else {
1616            Some(Vec::new())
1617        };
1618    }
1619    if distance >= radius_a + radius_b - tolerance
1620        || distance <= (radius_a - radius_b).abs() + tolerance
1621    {
1622        return Some(Vec::new());
1623    }
1624    let normal = offset.scale(1.0 / distance);
1625    let along =
1626        (distance * distance + radius_a * radius_a - radius_b * radius_b) / (2.0 * distance);
1627    let circle_radius_squared = radius_a * radius_a - along * along;
1628    if circle_radius_squared <= tolerance * tolerance {
1629        return Some(Vec::new());
1630    }
1631    let center = center_a.add(normal.scale(along));
1632    let x_axis = normal.perpendicular().ok()?;
1633    let y_axis = normal.cross(x_axis);
1634    Some(vec![make_arc(
1635        center,
1636        x_axis,
1637        y_axis,
1638        circle_radius_squared.sqrt(),
1639        0.0,
1640        std::f64::consts::TAU,
1641    )
1642    .ok()?])
1643}
1644
1645
1646
1647