Skip to main content

brepkit_math/
analytic_intersection.rs

1//! Closed-form and semi-analytic intersections of analytic surfaces with planes.
2//!
3//! Provides specialized intersection algorithms for cylinder, cone, sphere,
4//! and torus surfaces with planes, as well as a general marching approach
5//! for analytic-analytic surface intersections.
6
7use crate::madd::Madd;
8use std::f64::consts::{FRAC_PI_2, TAU};
9
10use crate::MathError;
11use crate::aabb::Aabb3;
12use crate::curves::{Circle3D, Ellipse3D, Hyperbola3D, Line3D, Parabola3D};
13use crate::frame::Frame3;
14use crate::nurbs::curve::NurbsCurve;
15use crate::nurbs::fitting::interpolate;
16use crate::nurbs::intersection::{IntersectionCurve, IntersectionPoint};
17use crate::surfaces::{ConicalSurface, CylindricalSurface, SphericalSurface, ToroidalSurface};
18use crate::tolerance::Tolerance;
19use crate::vec::{Point3, Vec3};
20
21/// Exact curve type resulting from plane-analytic surface intersection.
22#[derive(Debug, Clone)]
23pub enum ExactIntersectionCurve {
24    /// A circle (plane perpendicular to axis of cylinder/cone/sphere).
25    Circle(Circle3D),
26    /// An ellipse (plane oblique to cylinder/cone axis).
27    Ellipse(Ellipse3D),
28    /// Fallback to sampled point chain (torus, degenerate cases).
29    Points(Vec<Point3>),
30}
31
32/// A plane's section of an analytic surface, from [`exact_plane_section`].
33#[derive(Debug, Clone)]
34#[non_exhaustive]
35pub enum PlaneSection {
36    /// A circle.
37    Circle(Circle3D),
38    /// An ellipse.
39    Ellipse(Ellipse3D),
40    /// A straight section: a cylinder's ruling, running both ways from the
41    /// line's origin, or with `ray` a cone's ruling, running from the apex at
42    /// the line's origin along its direction only.
43    Line {
44        /// The ruling's line.
45        line: Line3D,
46        /// Whether the section runs one way only, from the line's origin.
47        ray: bool,
48    },
49    /// The one point where the plane touches the surface.
50    Point(Point3),
51    /// A sampled chain of points along the section.
52    Points(Vec<Point3>),
53    /// A cone's parabola.
54    Parabola(Parabola3D),
55    /// The branch of a cone's hyperbola on the cone's one nappe, which the
56    /// hyperbola's `u_axis` points to from its centre.
57    Hyperbola(Hyperbola3D),
58}
59
60impl From<ExactIntersectionCurve> for PlaneSection {
61    fn from(curve: ExactIntersectionCurve) -> Self {
62        match curve {
63            ExactIntersectionCurve::Circle(circle) => Self::Circle(circle),
64            ExactIntersectionCurve::Ellipse(ellipse) => Self::Ellipse(ellipse),
65            ExactIntersectionCurve::Points(points) => Self::Points(points),
66        }
67    }
68}
69
70/// A plane's exact section of an analytic surface.
71///
72/// It includes the sections [`exact_plane_analytic`] has no curve for: the
73/// rulings a plane along a cylinder's axis or through a cone's apex cuts,
74/// and the point where a plane touches a sphere or meets a cone at its apex
75/// alone. A cone's parabola and hyperbola come back as curves, which
76/// [`exact_plane_analytic`] samples into points, except in a band about the
77/// parabola where neither form keeps its digits.
78///
79/// The plane is `dot(normal, p) = d`, with `normal` of unit length.
80///
81/// # Errors
82///
83/// Returns an error if a section's curve cannot be built.
84pub fn exact_plane_section(
85    surface: AnalyticSurface<'_>,
86    normal: Vec3,
87    d: f64,
88) -> Result<Vec<PlaneSection>, MathError> {
89    match surface {
90        AnalyticSurface::Cylinder(cyl) if normal.dot(cyl.axis()).abs() < 1e-10 => {
91            return plane_cylinder_rulings(cyl, normal, d);
92        }
93        AnalyticSurface::Cone(cone) if plane_holds_apex(cone, normal, d) => {
94            return plane_cone_apex_rulings(cone, normal);
95        }
96        AnalyticSurface::Cone(cone) => {
97            if let Some(open) = plane_cone_open_section(cone, normal, d)? {
98                return Ok(open);
99            }
100        }
101        AnalyticSurface::Sphere(sphere) => {
102            let h = dot_np(normal, sphere.center()) - d;
103            let r = sphere.radius();
104            if (r - h.abs()).abs() <= TOUCH * r {
105                return Ok(vec![PlaneSection::Point(Point3::new(
106                    h.madd(-normal.x(), sphere.center().x()),
107                    h.madd(-normal.y(), sphere.center().y()),
108                    h.madd(-normal.z(), sphere.center().z()),
109                ))]);
110            }
111        }
112        AnalyticSurface::Cylinder(_) | AnalyticSurface::Torus(_) => {}
113    }
114    Ok(exact_plane_analytic(surface, normal, d)?
115        .into_iter()
116        .map(PlaneSection::from)
117        .collect())
118}
119
120/// How far a cone section's `e² − 1` (its eccentricity squared, less one)
121/// may sit from zero for the section to be read as a parabola.
122const PARABOLIC: f64 = 1e-12;
123
124/// Where a cone's hyperbola starts, in `e² − 1`: its centre lies the
125/// plane's offset over the conic coefficient away, and nearer zero its
126/// vertex loses digits.
127const HYPERBOLIC: f64 = 1e-6;
128
129/// A plane's parabola or hyperbola section of a cone, on the cone's one
130/// nappe, worked in the frame of [`exact_plane_cone`]. `None` for a circle
131/// or an ellipse, in the band between [`PARABOLIC`] and [`HYPERBOLIC`], and
132/// for a curve whose points do not hold to the cone (a cone so narrow or so
133/// flat that the formulas lose their digits), all of which go to the
134/// sampled section.
135#[allow(clippy::many_single_char_names)]
136fn plane_cone_open_section(
137    cone: &ConicalSurface,
138    normal: Vec3,
139    d: f64,
140) -> Result<Option<Vec<PlaneSection>>, MathError> {
141    let axis = cone.axis();
142    let c = normal.dot(axis);
143    let p2 = c.madd(-c, 1.0).max(0.0);
144    let p = p2.sqrt();
145    let rise = cone.half_angle().sin();
146    let k = rise * rise;
147    let a_coeff = p2 - k;
148    let eccentric = a_coeff / k;
149    let m = axis - normal * c;
150    let m_len = m.length();
151    if m_len < 1e-12 || eccentric < -PARABOLIC || (eccentric > PARABOLIC && eccentric <= HYPERBOLIC)
152    {
153        return Ok(None);
154    }
155    let e1 = m * (1.0 / m_len);
156    let e2 = normal.cross(e1);
157    let apex = cone.apex();
158    let e = d - dot_np(normal, apex);
159    let origin = apex + normal * e;
160    // A point `s` along `e1` from `origin` lies `e·c + s·p` up the axis from
161    // the apex, which the real nappe keeps non-negative.
162    let real = |s: f64| e.madd(c, s * p) >= 0.0;
163    // On the one nappe a point's height up the axis is `rise` times its
164    // distance from the apex.
165    let holds = |q: Point3| {
166        let w = q - apex;
167        let reach = w.length();
168        reach.is_finite() && (w.dot(axis) - rise * reach).abs() <= 1e-9 * (1.0 + reach)
169    };
170    if eccentric <= PARABOLIC {
171        // k t² = 2ecp s + e²(c² − k): the vertex at t = 0, opening along e1
172        // with the sign of ecp, `1 / 4f = k / 2|ecp|`.
173        let ecp = e * c * p;
174        let vertex_s = -e * (c * c - k) / (2.0 * c * p);
175        let focal = ecp.abs() / (2.0 * k);
176        if !(vertex_s.is_finite() && focal > 0.0 && focal.is_finite()) {
177            return Ok(None);
178        }
179        if !real(vertex_s) {
180            return Ok(Some(Vec::new()));
181        }
182        let parabola = Parabola3D::with_axes(origin + e1 * vertex_s, e1 * ecp.signum(), e2, focal)?;
183        if ![0.0, focal, -focal]
184            .iter()
185            .all(|&t| holds(parabola.evaluate(t)))
186        {
187            return Ok(None);
188        }
189        return Ok(Some(vec![PlaneSection::Parabola(parabola)]));
190    }
191    // A(s − s_c)² − k t² = e²k(1 − k)/A: the branches' vertices lie a real
192    // semi-axis either side of the centre, one on each nappe.
193    let centre_s = -e * c * p / a_coeff;
194    let rhs = e * e * k * (1.0 - k) / a_coeff;
195    let (real_axis, imaginary_axis) = ((rhs / a_coeff).sqrt(), (rhs / k).sqrt());
196    if !(real_axis > 0.0 && imaginary_axis > 0.0 && centre_s.is_finite()) {
197        return Ok(None);
198    }
199    let toward = if real(centre_s + real_axis) { e1 } else { -e1 };
200    let hyperbola = Hyperbola3D::with_axes(
201        origin + e1 * centre_s,
202        real_axis,
203        imaginary_axis,
204        toward,
205        e2,
206    )?;
207    if ![0.0, 1.0, -1.0]
208        .iter()
209        .all(|&t| holds(hyperbola.evaluate(t)))
210    {
211        return Ok(None);
212    }
213    Ok(Some(vec![PlaneSection::Hyperbola(hyperbola)]))
214}
215
216/// Rounding band, relative, within which a plane counts as touching a
217/// surface or passing through a cone's apex.
218const TOUCH: f64 = 4.0 * f64::EPSILON;
219
220/// The rulings a plane along a cylinder's axis cuts from it: two lines, the
221/// one it touches along, or none.
222fn plane_cylinder_rulings(
223    cyl: &CylindricalSurface,
224    normal: Vec3,
225    d: f64,
226) -> Result<Vec<PlaneSection>, MathError> {
227    // n·P(u, 0) = n·O + r·(a cos u + b sin u): the plane holds the ruling at
228    // u where cos(u − φ) = (d − n·O) / (r·√(a² + b²)).
229    let (a, b) = (normal.dot(cyl.x_axis()), normal.dot(cyl.y_axis()));
230    let amp = a.hypot(b);
231    if amp < 1e-12 {
232        return Ok(vec![]);
233    }
234    let ratio = (d - dot_np(normal, cyl.origin())) / (cyl.radius() * amp);
235    if ratio.abs() > 1.0 + TOUCH {
236        return Ok(vec![]);
237    }
238    let phi = b.atan2(a);
239    let spread = ratio.clamp(-1.0, 1.0).acos();
240    let at = if ratio.abs() >= 1.0 - TOUCH {
241        vec![phi + spread]
242    } else {
243        vec![phi + spread, phi - spread]
244    };
245    at.into_iter()
246        .map(|u| {
247            Ok(PlaneSection::Line {
248                line: Line3D::new(cyl.evaluate(u, 0.0), cyl.axis())?,
249                ray: false,
250            })
251        })
252        .collect()
253}
254
255/// Whether a plane passes through a cone's apex, but for rounding.
256fn plane_holds_apex(cone: &ConicalSurface, normal: Vec3, d: f64) -> bool {
257    let apex = cone.apex() - Point3::new(0.0, 0.0, 0.0);
258    (normal.dot(apex) - d).abs() <= TOUCH * (1.0 + apex.length() + d.abs())
259}
260
261/// The rulings a plane through a cone's apex cuts from its nappe, as rays
262/// from the apex: two, the one it touches along, or none, when the plane
263/// meets the cone at the apex alone.
264fn plane_cone_apex_rulings(
265    cone: &ConicalSurface,
266    normal: Vec3,
267) -> Result<Vec<PlaneSection>, MathError> {
268    // g(u) = cos a·(cos u·X + sin u·Y) + sin a·axis, so n·g(u) = 0 reads
269    // A cos u + B sin u = −C.
270    let (sin_a, cos_a) = cone.half_angle().sin_cos();
271    let a = cos_a * normal.dot(cone.x_axis());
272    let b = cos_a * normal.dot(cone.y_axis());
273    let c = sin_a * normal.dot(cone.axis());
274    let amp = a.hypot(b);
275    let apex = cone.apex();
276    if amp < 1e-12 * c.abs().max(1.0) {
277        return Ok(vec![PlaneSection::Point(apex)]);
278    }
279    let ratio = -c / amp;
280    if ratio.abs() > 1.0 + TOUCH {
281        return Ok(vec![PlaneSection::Point(apex)]);
282    }
283    let phi = b.atan2(a);
284    let spread = ratio.clamp(-1.0, 1.0).acos();
285    let at = if ratio.abs() >= 1.0 - TOUCH {
286        vec![phi + spread]
287    } else {
288        vec![phi + spread, phi - spread]
289    };
290    at.into_iter()
291        .map(|u| {
292            Ok(PlaneSection::Line {
293                line: Line3D::new(apex, cone.evaluate(u, 1.0) - apex)?,
294                ray: true,
295            })
296        })
297        .collect()
298}
299
300/// Compute exact intersection curves between a plane and an analytic surface.
301///
302/// Returns exact `Circle3D` or `Ellipse3D` where possible, falling back to
303/// sampled points for complex cases (torus).
304///
305/// A plane along a cylinder's axis or through a cone's apex, whose sections
306/// are straight, and a plane touching a sphere get no curve here;
307/// [`exact_plane_section`] returns those sections.
308///
309/// The plane is defined by `dot(normal, p) = d`.
310///
311/// # Errors
312///
313/// Returns an error if the intersection computation fails.
314pub fn exact_plane_analytic(
315    surface: AnalyticSurface<'_>,
316    plane_normal: Vec3,
317    plane_d: f64,
318) -> Result<Vec<ExactIntersectionCurve>, MathError> {
319    exact_plane_analytic_reaching(surface, plane_normal, plane_d, 0.0)
320}
321
322/// [`exact_plane_analytic`] with a cone's sampled hyperbola or parabola
323/// carried at least `reach` from the apex, so it spans whatever faces the
324/// caller will trim it to.
325///
326/// # Errors
327///
328/// Returns an error if the intersection computation fails.
329pub fn exact_plane_analytic_reaching(
330    surface: AnalyticSurface<'_>,
331    plane_normal: Vec3,
332    plane_d: f64,
333    reach: f64,
334) -> Result<Vec<ExactIntersectionCurve>, MathError> {
335    match surface {
336        AnalyticSurface::Cylinder(cyl) => exact_plane_cylinder(cyl, plane_normal, plane_d),
337        AnalyticSurface::Sphere(sphere) => exact_plane_sphere(sphere, plane_normal, plane_d),
338        AnalyticSurface::Cone(cone) if plane_holds_apex(cone, plane_normal, plane_d) => Ok(vec![]),
339        AnalyticSurface::Cone(cone) => exact_plane_cone(cone, plane_normal, plane_d, reach),
340        AnalyticSurface::Torus(torus) => {
341            if let Some(circles) = exact_plane_torus(torus, plane_normal, plane_d)? {
342                return Ok(circles);
343            }
344            if let Some(loops) = plane_torus_winding_loops(torus, plane_normal, plane_d, 128) {
345                return Ok(loops
346                    .into_iter()
347                    .map(ExactIntersectionCurve::Points)
348                    .collect());
349            }
350            // Other torus sections are degree-4 — fall back to sampling.
351            let chains = sample_plane_torus(torus, plane_normal, plane_d)?;
352            Ok(chains
353                .into_iter()
354                .map(ExactIntersectionCurve::Points)
355                .collect())
356        }
357    }
358}
359
360/// The plane-torus sections that are circles:
361///
362/// - a plane across the axis at height `h` from the centre, `|h| < r`: the
363///   two circles of radius `R ± sqrt(r² − h²)` about the axis;
364/// - a plane through the axis: the two tube cross-sections of radius `r`,
365///   `R` either side of the axis.
366///
367/// A plane across the axis tangent to the tube's top or bottom touches it
368/// along the one circle of radius `R`, ring or spindle.
369///
370/// `Some` of no curves for a plane across the axis that misses the tube;
371/// `None` for any other plane, and for a section across the axis whose inner
372/// circle would reach the axis.
373fn exact_plane_torus(
374    torus: &ToroidalSurface,
375    normal: Vec3,
376    d: f64,
377) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
378    let len = normal.length();
379    let n = normal.normalize()?;
380    let d = d / len;
381    let axis = torus.z_axis();
382    let center = torus.center();
383    let (big, small) = (torus.major_radius(), torus.minor_radius());
384    let height = d - dot_np(n, center);
385    let along = n.dot(axis);
386    if along.abs() > 1.0 - 1e-10 {
387        if height.abs() >= small - 1e-10 * small {
388            if height.abs() > small + 1e-10 * small {
389                return Ok(Some(Vec::new()));
390            }
391            // Tangent to the tube's top or bottom: the plane touches the
392            // torus along the one circle of its own radius. That circle lies
393            // on the torus within the plane's distance from the tube's top,
394            // so it stands for the section while that distance is within the
395            // linear tolerance, whatever the scale. A tilted plane's section
396            // is no circle.
397            if big <= 1e-10 * small
398                || axis.cross(n).length() > 1e-12
399                || (small - height.abs()).abs() > crate::tolerance::Tolerance::default().linear
400            {
401                return Ok(None);
402            }
403            let middle = center + n * height;
404            return Ok(Some(vec![ExactIntersectionCurve::Circle(Circle3D::new(
405                middle, n, big,
406            )?)]));
407        }
408        let reach = small.madd(small, -(height * height)).sqrt();
409        if big - reach <= 1e-10 * big {
410            return Ok(None);
411        }
412        let middle = center + n * height;
413        return Ok(Some(vec![
414            ExactIntersectionCurve::Circle(Circle3D::new(middle, n, big + reach)?),
415            ExactIntersectionCurve::Circle(Circle3D::new(middle, n, big - reach)?),
416        ]));
417    }
418    if along.abs() < 1e-10 && height.abs() < 1e-10 * (big + small) {
419        let out = axis.cross(n).normalize()?;
420        return Ok(Some(vec![
421            ExactIntersectionCurve::Circle(Circle3D::new(center + out * big, n, small)?),
422            ExactIntersectionCurve::Circle(Circle3D::new(center - out * big, n, small)?),
423        ]));
424    }
425    Ok(None)
426}
427
428/// Exact plane-cylinder intersection.
429///
430/// - Plane perpendicular to axis → `Circle3D`
431/// - Plane oblique to axis → `Ellipse3D`
432/// - Plane parallel to axis → `Points` fallback (0 or 2 lines)
433fn exact_plane_cylinder(
434    cyl: &CylindricalSurface,
435    normal: Vec3,
436    d: f64,
437) -> Result<Vec<ExactIntersectionCurve>, MathError> {
438    let axis = cyl.axis();
439    let cos_theta = normal.dot(axis).abs();
440    let r = cyl.radius();
441
442    if cos_theta < 1e-10 {
443        // A plane along the axis cuts straight rulings, which
444        // `exact_plane_section` returns.
445        return Ok(vec![]);
446    }
447
448    // Find where axis intersects the plane: axis_point + t*axis, dot(normal, P) = d
449    // t = (d - dot(normal, origin)) / dot(normal, axis)
450    let n_dot_axis = normal.dot(axis);
451    let n_dot_origin = dot_np(normal, cyl.origin());
452    let t = (d - n_dot_origin) / n_dot_axis;
453    let center_on_axis = Point3::new(
454        cyl.origin().x() + t * axis.x(),
455        cyl.origin().y() + t * axis.y(),
456        cyl.origin().z() + t * axis.z(),
457    );
458
459    if cos_theta > 1.0 - 1e-10 {
460        // Plane perpendicular to axis → Circle
461        let circle = Circle3D::new(center_on_axis, normal, r)?;
462        Ok(vec![ExactIntersectionCurve::Circle(circle)])
463    } else {
464        // Oblique plane → Ellipse
465        // Semi-minor = r (the cylinder radius, unchanged)
466        // Semi-major = r / cos(θ) where θ = angle between plane normal and axis
467        let semi_minor = r;
468        let semi_major = r / cos_theta;
469
470        // The major axis direction lies in the intersection of the plane
471        // with the plane containing the axis and the plane normal.
472        // It's the projection of the axis onto the cutting plane, normalized.
473        let axis_proj = Vec3::new(
474            axis.x() - n_dot_axis * normal.x(),
475            axis.y() - n_dot_axis * normal.y(),
476            axis.z() - n_dot_axis * normal.z(),
477        );
478        let u_axis = axis_proj.normalize()?;
479        let v_axis = normal.cross(u_axis);
480
481        let ellipse = Ellipse3D::with_axes(
482            center_on_axis,
483            normal,
484            semi_major,
485            semi_minor,
486            u_axis,
487            v_axis,
488        )?;
489        Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)])
490    }
491}
492
493/// Exact plane-sphere intersection.
494///
495/// Always produces a `Circle3D` (or empty if no intersection).
496fn exact_plane_sphere(
497    sphere: &SphericalSurface,
498    normal: Vec3,
499    d: f64,
500) -> Result<Vec<ExactIntersectionCurve>, MathError> {
501    let h = dot_np(normal, sphere.center()) - d;
502    let r = sphere.radius();
503
504    // A plane touching the sphere meets it at a point, which
505    // `exact_plane_section` returns.
506    if r - h.abs() <= TOUCH * r {
507        return Ok(vec![]);
508    }
509
510    let circle_r = (r.madd(r, -(h * h))).sqrt();
511    let circle_center = Point3::new(
512        h.madd(-normal.x(), sphere.center().x()),
513        h.madd(-normal.y(), sphere.center().y()),
514        h.madd(-normal.z(), sphere.center().z()),
515    );
516
517    let circle = Circle3D::new(circle_center, normal, circle_r)?;
518    Ok(vec![ExactIntersectionCurve::Circle(circle)])
519}
520
521/// Exact sphere-sphere intersection: the circle on the two spheres' radical
522/// plane, its normal pointing from the first centre to the second. `None`
523/// for one sphere twice (the same surface, no curve).
524///
525/// The circle is built from the smaller sphere, whose radius bounds it, and
526/// from the centres' offset alone, so neither the operands' order nor where
527/// the pair sits in space decides whether a small circle survives.
528///
529/// # Errors
530///
531/// Returns an error if the circle cannot be built.
532pub fn exact_sphere_sphere(
533    s1: &SphericalSurface,
534    s2: &SphericalSurface,
535) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
536    let delta = s2.center() - s1.center();
537    let d = delta.length();
538    let (r1, r2) = (s1.radius(), s2.radius());
539    let scale = r1.max(r2);
540    if d <= 1e-12 * scale {
541        // Concentric spheres of different radii never meet.
542        return Ok(((r1 - r2).abs() > 1e-12 * scale).then(Vec::new));
543    }
544    let normal = delta * (1.0 / d);
545    // From the smaller sphere's centre toward the larger's, the radical plane
546    // lies `along` away.
547    let (centre, toward, r_small, r_big) = if r1 <= r2 {
548        (s1.center(), normal, r1, r2)
549    } else {
550        (s2.center(), -normal, r2, r1)
551    };
552    let along = d.madd(d, r_small.madd(r_small, -(r_big * r_big))) / (2.0 * d);
553    if along.abs() > r_small - 1e-10 * scale.max(1.0) {
554        return Ok(Some(Vec::new()));
555    }
556    let radius = r_small.madd(r_small, -(along * along)).sqrt();
557    let circle = Circle3D::new(centre + toward * along, normal, radius)?;
558    Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
559}
560
561/// Exact plane-cone intersection.
562///
563/// The conic type is set by the cone's half-opening angle from the axis
564/// (`γ = π/2 − half_angle`) versus the plane-axis angle `ψ`:
565/// - Plane perpendicular to axis (`ψ = π/2`) → `Circle3D`
566/// - `ψ > γ` (ellipse) → closed-form `Ellipse3D`
567/// - `ψ ≤ γ` (parabola/hyperbola) → bounded single-branch `Points` (one chain
568///   per branch — a hyperbola's two nappes never share a chain)
569fn exact_plane_cone(
570    cone: &ConicalSurface,
571    normal: Vec3,
572    d: f64,
573    reach: f64,
574) -> Result<Vec<ExactIntersectionCurve>, MathError> {
575    let axis = cone.axis();
576    let cos_theta = normal.dot(axis).abs();
577    let half_angle = cone.half_angle();
578
579    if cos_theta > 1.0 - 1e-10 {
580        // Plane perpendicular to axis → Circle
581        // Find where axis meets the plane
582        let n_dot_axis = normal.dot(axis);
583        let n_dot_apex = dot_np(normal, cone.apex());
584        let t = (d - n_dot_apex) / n_dot_axis;
585
586        // t is the signed distance from apex to plane along the axis.
587        // The real cone is a single nappe; the perpendicular-plane section is a
588        // circle whose radius follows from the axial offset |t|.
589        // |t| ≈ 0 means the plane passes through the apex → degenerate point.
590        if t.abs() < 1e-10 {
591            return Ok(vec![]);
592        }
593
594        let center = Point3::new(
595            cone.apex().x() + t * axis.x(),
596            cone.apex().y() + t * axis.y(),
597            cone.apex().z() + t * axis.z(),
598        );
599        // half_angle is the angle from the radial plane to the surface.
600        // Axial distance t = v * sin(half_angle), so v = t / sin(half_angle).
601        // Radius at v = v * cos(half_angle) = t * cos(half_angle) / sin(half_angle).
602        let circle_r = t.abs() * half_angle.cos() / half_angle.sin();
603        if circle_r < 1e-15 {
604            return Ok(vec![]);
605        }
606
607        let circle = Circle3D::new(center, normal, circle_r)?;
608        return Ok(vec![ExactIntersectionCurve::Circle(circle)]);
609    }
610
611    // Oblique plane. Classify the conic in the plane-aligned frame.
612    //
613    // Decompose the (unit) axis as a = c·n + p·e1, where c = n·a, e1 is the unit
614    // in-plane projection of the axis, and p = |projection| = sqrt(1−c²). Write a
615    // point Q on the plane as Q = apex + e·n + s·e1 + t·e2 (e = d − n·apex,
616    // e2 = n×e1). The cone equation (w·a)² = cos²γ·(w·w) with k = cos²γ =
617    // sin²(half_angle) reduces to (no s·t cross term, since e1/e2 align with the
618    // conic axes):
619    //     (p²−k)·s² + 2ecp·s + e²(c²−k) = k·t²
620    // The s² coefficient A = p²−k = sin²θ − sin²(half_angle) sets the type:
621    // A < 0 → ellipse, A = 0 → parabola, A > 0 → hyperbola.
622    let c = normal.dot(axis);
623    let p2 = (1.0 - c * c).max(0.0);
624    let p = p2.sqrt();
625    let k = half_angle.sin().powi(2);
626    let a_coeff = p2 - k;
627
628    // Build the plane-aligned frame e1 (in-plane axis projection), e2 = n×e1.
629    let m = Vec3::new(
630        axis.x() - c * normal.x(),
631        axis.y() - c * normal.y(),
632        axis.z() - c * normal.z(),
633    );
634    let m_len = m.length();
635    if m_len < 1e-12 {
636        // Axis parallel to normal — handled by the perpendicular branch above;
637        // fall back to sampling for safety.
638        let chains = sample_plane_cone(cone, normal, d, reach)?;
639        return Ok(chains
640            .into_iter()
641            .map(ExactIntersectionCurve::Points)
642            .collect());
643    }
644    let e1 = m * (1.0 / m_len);
645    let e2 = normal.cross(e1);
646    let apex = cone.apex();
647    let e = d - dot_np(normal, apex);
648
649    // Ellipse → closed form. A = p²−k < 0 with a margin to keep the
650    // near-parabolic regime on the robust sampled path.
651    if a_coeff < -1e-9 {
652        let abs_a = -a_coeff; // = k − p² > 0
653        // Real-nappe guard: in the ellipse regime n·g(u) keeps constant sign(c),
654        // so v = e/(n·g) ≥ 0 only when e and c share a sign. When e·c < 0 the
655        // plane is offset to the far side of the apex from the cone's opening —
656        // the section lies entirely on the phantom nappe, so there is no real
657        // curve (RHS below is positive regardless of sign, so it can't catch this).
658        if e * c < 0.0 {
659            return Ok(vec![]);
660        }
661        // |A|(s − s_c)² + k·t² = RHS, with s_c = ecp/|A| and
662        // RHS = e²·k·(1−k)/|A| (always > 0 for a real ellipse).
663        let s_c = e * c * p / abs_a;
664        let rhs = e * e * k * (1.0 - k) / abs_a;
665        if rhs <= 0.0 {
666            return Ok(vec![]);
667        }
668        let semi_s = (rhs / abs_a).sqrt(); // extent along e1
669        let semi_t = (rhs / k).sqrt(); // extent along e2
670        if semi_s < 1e-12 || semi_t < 1e-12 {
671            return Ok(vec![]);
672        }
673        let center = apex + normal * e + e1 * s_c;
674        let (semi_major, semi_minor, u_axis, v_axis) = if semi_s >= semi_t {
675            (semi_s, semi_t, e1, e2)
676        } else {
677            (semi_t, semi_s, e2, e1)
678        };
679        let ellipse = Ellipse3D::with_axes(center, normal, semi_major, semi_minor, u_axis, v_axis)?;
680        return Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)]);
681    }
682
683    // Parabola / hyperbola (and the near-parabolic ellipse margin): the section
684    // is unbounded, so emit bounded, branch-separated sample chains.
685    let chains = sample_plane_cone(cone, normal, d, reach)?;
686    Ok(chains
687        .into_iter()
688        .map(ExactIntersectionCurve::Points)
689        .collect())
690}
691
692/// The exact arc from `from` to `to` of a plane's parabola or hyperbola
693/// section of a cone, both ends on one branch of it, as a rational quadratic
694/// NURBS.
695///
696/// A hyperbola `x = a cosh φ, y = b sinh φ` (in the plane frame of
697/// `exact_plane_cone`) is cut into pieces of at most one unit of `φ`, each
698/// a conic Bézier: its middle point is where the end tangents meet and its
699/// middle weight is the cosh of half the piece's span. A parabola is one
700/// polynomial quadratic. `None` for an elliptic or circular section, a plane
701/// through the apex, or ends off one branch of the section.
702///
703/// # Errors
704///
705/// Returns an error if the plane normal is zero or the curve cannot be built.
706#[allow(clippy::many_single_char_names)]
707pub fn plane_cone_conic_arc(
708    cone: &ConicalSurface,
709    normal: Vec3,
710    d: f64,
711    from: Point3,
712    to: Point3,
713) -> Result<Option<NurbsCurve>, MathError> {
714    let len = normal.length();
715    if len < 1e-15 {
716        return Err(MathError::ZeroVector);
717    }
718    let (normal, d) = (normal * (1.0 / len), d / len);
719    let axis = cone.axis();
720    let c = normal.dot(axis);
721    let p2 = (1.0 - c * c).max(0.0);
722    let p = p2.sqrt();
723    let k = cone.half_angle().sin().powi(2);
724    let a_coeff = p2 - k;
725    let m = Vec3::new(
726        axis.x() - c * normal.x(),
727        axis.y() - c * normal.y(),
728        axis.z() - c * normal.z(),
729    );
730    let m_len = m.length();
731    if m_len < 1e-12 || a_coeff < -1e-9 {
732        return Ok(None);
733    }
734    let e1 = m * (1.0 / m_len);
735    let e2 = normal.cross(e1);
736    let apex = cone.apex();
737    let e = d - dot_np(normal, apex);
738    let origin = apex + normal * e;
739    let plane_st = |q: Point3| {
740        let w = q - origin;
741        (w.dot(e1), w.dot(e2))
742    };
743    let ((s0, t0), (s1, t1)) = (plane_st(from), plane_st(to));
744    let scale = s0.abs().max(t0.abs()).max(s1.abs()).max(t1.abs()).max(1.0);
745    if e.abs() < 1e-9 * scale || (from - to).length() <= 1e-9 * scale {
746        return Ok(None);
747    }
748    let point = |s: f64, t: f64| origin + e1 * s + e2 * t;
749    let on_curve = |q: Point3, r: Point3| (q - r).length() <= 1e-6 * scale;
750    let (control, weights) = if a_coeff.abs() <= 1e-9 {
751        // (p² − k) s² vanishes: 2ecp·s + e²(c² − k) = k·t², s = α t² + β.
752        let lin = 2.0 * e * c * p;
753        if lin.abs() < 1e-12 * scale {
754            return Ok(None);
755        }
756        let (alpha, beta) = (k / lin, -e * e * (c * c - k) / lin);
757        if !on_curve(point(alpha * t0 * t0 + beta, t0), from)
758            || !on_curve(point(alpha * t1 * t1 + beta, t1), to)
759        {
760            return Ok(None);
761        }
762        let mid = point(alpha * t0 * t1 + beta, 0.5 * (t0 + t1));
763        (vec![from, mid, to], vec![1.0; 3])
764    } else {
765        // A (s − s_c)² − k t² = R with R = e² k (1 − k) / A.
766        let s_c = -e * c * p / a_coeff;
767        let r = e * e * k * (1.0 - k) / a_coeff;
768        if r <= 0.0 {
769            return Ok(None);
770        }
771        let (a, b) = ((r / a_coeff).sqrt(), (r / k).sqrt());
772        let (x0, x1) = (s0 - s_c, s1 - s_c);
773        if x0 * x1 <= 0.0 {
774            return Ok(None);
775        }
776        let side = x0.signum();
777        let hyperbola = |phi: f64| point(s_c + side * a * phi.cosh(), b * phi.sinh());
778        let (phi0, phi1) = ((t0 / b).asinh(), (t1 / b).asinh());
779        if !on_curve(hyperbola(phi0), from) || !on_curve(hyperbola(phi1), to) {
780            return Ok(None);
781        }
782        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
783        let pieces = ((phi1 - phi0).abs().ceil() as usize).max(1);
784        let mut control = vec![from];
785        let mut weights = vec![1.0];
786        for i in 0..pieces {
787            #[allow(clippy::cast_precision_loss)]
788            let (fa, fb) = (i as f64 / pieces as f64, (i + 1) as f64 / pieces as f64);
789            let (pa, pb) = (phi0 + (phi1 - phi0) * fa, phi0 + (phi1 - phi0) * fb);
790            let (mid, half) = (0.5 * (pa + pb), 0.5 * (pb - pa));
791            let w = half.cosh();
792            control.push(point(s_c + side * a * mid.cosh() / w, b * mid.sinh() / w));
793            weights.push(w);
794            control.push(if i + 1 == pieces { to } else { hyperbola(pb) });
795            weights.push(1.0);
796        }
797        (control, weights)
798    };
799    let pieces = (control.len() - 1) / 2;
800    let mut knots = vec![0.0; 3];
801    for i in 1..pieces {
802        #[allow(clippy::cast_precision_loss)]
803        knots.extend([i as f64; 2]);
804    }
805    #[allow(clippy::cast_precision_loss)]
806    knots.extend([pieces as f64; 3]);
807    let curve = NurbsCurve::new(2, knots, control, weights)?;
808    // The closed forms drop terms that vanish only on the exact conic (a
809    // barely elliptic section read as a parabola), so the arc must meet the
810    // cone between its ends too: a point at radius ρ and height h off the
811    // apex lies |ρ sin α − |h| cos α| from it.
812    let (sin_a, cos_a) = cone.half_angle().sin_cos();
813    let off_cone = |q: Point3| {
814        let w = q - apex;
815        let h = w.dot(axis);
816        (w - axis * h)
817            .length()
818            .madd(sin_a, -(h.abs() * cos_a))
819            .abs()
820    };
821    for i in 0..pieces {
822        for f in [0.25, 0.5, 0.75] {
823            #[allow(clippy::cast_precision_loss)]
824            if off_cone(curve.evaluate(i as f64 + f)) > 1e-9 * scale {
825                return Ok(None);
826            }
827        }
828    }
829    Ok(Some(curve))
830}
831
832/// Reference to an analytic surface for intersection dispatch.
833#[derive(Clone, Copy)]
834pub enum AnalyticSurface<'a> {
835    /// Cylindrical surface reference.
836    Cylinder(&'a CylindricalSurface),
837    /// Conical surface reference.
838    Cone(&'a ConicalSurface),
839    /// Spherical surface reference.
840    Sphere(&'a SphericalSurface),
841    /// Toroidal surface reference.
842    Torus(&'a ToroidalSurface),
843}
844
845/// Compute `n . p` treating a `Point3` as a position vector.
846fn dot_np(n: Vec3, p: Point3) -> f64 {
847    n.dot(Vec3::new(p.x(), p.y(), p.z()))
848}
849
850/// Intersect a plane with an analytic surface.
851///
852/// The plane is defined by `dot(normal, p) = d`.
853///
854/// # Errors
855///
856/// Returns an error if the intersection computation fails.
857pub fn intersect_plane_analytic(
858    surface: AnalyticSurface<'_>,
859    normal: Vec3,
860    d: f64,
861) -> Result<Vec<IntersectionCurve>, MathError> {
862    match surface {
863        AnalyticSurface::Cylinder(cyl) => intersect_plane_cylinder(cyl, normal, d),
864        AnalyticSurface::Cone(cone) => intersect_plane_cone(cone, normal, d),
865        AnalyticSurface::Sphere(sphere) => intersect_plane_sphere(sphere, normal, d),
866        AnalyticSurface::Torus(torus) => intersect_plane_torus(torus, normal, d),
867    }
868}
869
870/// Sample points on the plane-analytic intersection without NURBS curve fitting.
871///
872/// Returns chains of ordered 3D sample points. Each chain is one connected
873/// component of the intersection curve. This is much faster than
874/// `intersect_plane_analytic` when only sample points are needed (e.g. for
875/// boolean intersection segment generation).
876///
877/// # Errors
878///
879/// Returns an error if the intersection computation fails.
880pub fn sample_plane_analytic(
881    surface: AnalyticSurface<'_>,
882    normal: Vec3,
883    d: f64,
884) -> Result<Vec<Vec<Point3>>, MathError> {
885    match surface {
886        AnalyticSurface::Cylinder(cyl) => sample_plane_cylinder(cyl, normal, d),
887        AnalyticSurface::Cone(cone) => sample_plane_cone(cone, normal, d, 0.0),
888        AnalyticSurface::Sphere(sphere) => sample_plane_sphere(sphere, normal, d),
889        AnalyticSurface::Torus(torus) => sample_plane_torus(torus, normal, d),
890    }
891}
892
893/// Sample the plane-cylinder intersection as ordered 3D points.
894#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
895fn sample_plane_cylinder(
896    cyl: &CylindricalSurface,
897    normal: Vec3,
898    d: f64,
899) -> Result<Vec<Vec<Point3>>, MathError> {
900    let n_samples = 64_usize;
901    let mut points = Vec::with_capacity(n_samples + 1);
902
903    for i in 0..=n_samples {
904        let u = TAU * (i as f64) / (n_samples as f64);
905        let base = cyl.evaluate(u, 0.0);
906        let n_dot_axis = normal.dot(cyl.axis());
907        let n_dot_base = dot_np(normal, base);
908
909        if n_dot_axis.abs() < 1e-12 {
910            if (n_dot_base - d).abs() < 1e-6 {
911                points.push(base);
912            }
913        } else {
914            let v = (d - n_dot_base) / n_dot_axis;
915            if v.abs() <= 100.0 {
916                points.push(cyl.evaluate(u, v));
917            }
918        }
919    }
920
921    if points.len() < 2 {
922        Ok(vec![])
923    } else {
924        Ok(vec![points])
925    }
926}
927
928/// Sample the plane-sphere intersection as ordered 3D points.
929#[allow(clippy::cast_precision_loss)]
930fn sample_plane_sphere(
931    sphere: &SphericalSurface,
932    normal: Vec3,
933    d: f64,
934) -> Result<Vec<Vec<Point3>>, MathError> {
935    let h = dot_np(normal, sphere.center()) - d;
936    let r = sphere.radius();
937
938    if h.abs() > r - 1e-10 {
939        return Ok(vec![]);
940    }
941
942    let circle_r = (r.madd(r, -(h * h))).sqrt();
943    let circle_center = Point3::new(
944        h.madd(-normal.x(), sphere.center().x()),
945        h.madd(-normal.y(), sphere.center().y()),
946        h.madd(-normal.z(), sphere.center().z()),
947    );
948
949    let basis = Frame3::from_normal(circle_center, normal)?;
950    let u_dir = basis.x;
951    let v_dir = basis.y;
952
953    let n_samples = 64_usize;
954    let mut points = Vec::with_capacity(n_samples + 1);
955
956    for i in 0..=n_samples {
957        let theta = TAU * (i as f64) / (n_samples as f64);
958        let (sin_t, cos_t) = theta.sin_cos();
959        points.push(circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t));
960    }
961
962    Ok(vec![points])
963}
964
965/// Sample the plane-cone intersection as ordered 3D points.
966///
967/// The cone is the single real nappe `v >= 0` of `P(u,v) = apex + v·g(u)`.
968/// Along each generator `g(u)` the plane `n·P = d` is linear in `v`, so
969/// `v = (d − n·apex) / (n·g(u))`. We keep only `v >= 0` (the phantom `v < 0`
970/// nappe is geometrically absent) and `v` below a finite bound (near an
971/// asymptote `n·g(u) → 0` so `v → ∞` — those points run off the surface and
972/// must be excluded). The angular samples that survive form one contiguous arc
973/// (ellipse) or two (parabola/hyperbola, one per branch); each contiguous run
974/// is returned as a separate ordered chain so the consumer never stitches two
975/// disjoint branches into one curve.
976#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
977fn sample_plane_cone(
978    cone: &ConicalSurface,
979    normal: Vec3,
980    d: f64,
981    reach: f64,
982) -> Result<Vec<Vec<Point3>>, MathError> {
983    let apex = cone.apex();
984    let n_dot_apex = dot_np(normal, apex);
985    let e = d - n_dot_apex;
986
987    // Per-generator solve: along g(u) the plane is linear in v, v = e / (n·g(u)).
988    // Sample u densely; keep only the real nappe (v >= 0) and skip near-asymptote
989    // generators (n·g(u) ≈ 0 → v → ∞).
990    let n_samples = 512_usize;
991    let mut vs: Vec<Option<f64>> = Vec::with_capacity(n_samples);
992    let mut v_min = f64::INFINITY;
993    for i in 0..n_samples {
994        let u = TAU * (i as f64) / (n_samples as f64);
995        let g = cone.evaluate(u, 1.0) - apex;
996        let n_dot_g = normal.dot(Vec3::new(g.x(), g.y(), g.z()));
997        if n_dot_g.abs() < 1e-12 {
998            vs.push(None);
999            continue;
1000        }
1001        let v = e / n_dot_g;
1002        if v >= -1e-12 {
1003            let v = v.max(0.0);
1004            v_min = v_min.min(v);
1005            vs.push(Some(v));
1006        } else {
1007            vs.push(None);
1008        }
1009    }
1010
1011    if !v_min.is_finite() {
1012        return Ok(Vec::new());
1013    }
1014
1015    // Bound the arc around the conic vertex (closest approach to the apex, at
1016    // v_min). An ellipse is naturally bounded; a parabola/hyperbola is not, so
1017    // cap the cone radius at a generous multiple of the vertex radius. This is
1018    // scale-invariant and centred on where any finite cone face's overlap lies;
1019    // the downstream consumer trims the fitted curve to the actual face AABB, so
1020    // over-coverage is harmless. The floor handles a vertex at the apex (v_min≈0).
1021    // A caller that knows its faces asks for their reach: an open hyperbola
1022    // (a vertex close to the axis) crosses a rim far past eight vertex radii.
1023    let v_max = (8.0 * v_min).max(v_min + 4.0).max(reach);
1024
1025    // Per-sample v within the cap; the raw values stay in `vs` for the
1026    // boundary solve below.
1027    let kept: Vec<Option<f64>> = vs.iter().map(|v| v.filter(|&v| v <= v_max)).collect();
1028
1029    let point_at = |u: f64, v: f64| -> Point3 {
1030        let g = cone.evaluate(u, 1.0) - apex;
1031        apex + g * v
1032    };
1033    #[allow(clippy::cast_precision_loss)]
1034    let u_of = |i: usize| TAU * (i as f64) / (n_samples as f64);
1035    let n_dot_g_at = |u: f64| -> f64 {
1036        let g = cone.evaluate(u, 1.0) - apex;
1037        normal.dot(Vec3::new(g.x(), g.y(), g.z()))
1038    };
1039
1040    if kept.iter().all(Option::is_some) {
1041        // Closed loop (ellipse regime): emit all points and repeat the first.
1042        let mut pts: Vec<Point3> = kept
1043            .iter()
1044            .enumerate()
1045            .filter_map(|(i, v)| v.map(|v| point_at(u_of(i), v)))
1046            .collect();
1047        if let Some(&first) = pts.first() {
1048            pts.push(first);
1049        }
1050        return Ok(vec![pts]);
1051    }
1052
1053    // A hyperbola/parabola tail diverges as 1/(n·g), so between the last kept
1054    // sample and its dropped neighbour v can leap far past `v_max` in one
1055    // uniform-u pitch — and any finite face window inside that leap is lost
1056    // (a taper cone grazed 0.05 by a prism plane lost its entire 0.5-tall
1057    // section to exactly this aliasing). Extend each run end to the exact
1058    // `v_max` boundary: bisect u for `n·g(u) = e/v_max` inside the dropped
1059    // pitch (n·g is monotone there — its extrema sit at the conic vertex,
1060    // far from any asymptote), then fill the tail with uniform-u samples.
1061    let tail = |i_end: usize, forward: bool, kept: &[Option<f64>]| -> Vec<Point3> {
1062        let Some(v_end) = kept[i_end] else {
1063            return Vec::new();
1064        };
1065        let u_end = u_of(i_end);
1066        #[allow(clippy::cast_precision_loss)]
1067        let pitch = TAU / (n_samples as f64);
1068        let u_next = if forward {
1069            u_end + pitch
1070        } else {
1071            u_end - pitch
1072        };
1073        let target = e / v_max;
1074        let h_end = n_dot_g_at(u_end) - target;
1075        let h_next = n_dot_g_at(u_next) - target;
1076        if v_end >= v_max || h_end == 0.0 || h_end.signum() == h_next.signum() {
1077            return Vec::new();
1078        }
1079        let (mut lo, mut hi) = (u_end, u_next);
1080        for _ in 0..60 {
1081            let mid = f64::midpoint(lo, hi);
1082            if (n_dot_g_at(mid) - target).signum() == h_end.signum() {
1083                lo = mid;
1084            } else {
1085                hi = mid;
1086            }
1087        }
1088        let u_star = f64::midpoint(lo, hi);
1089        let tail_n = 8_usize;
1090        (1..=tail_n)
1091            .filter_map(|k| {
1092                #[allow(clippy::cast_precision_loss)]
1093                let u = u_end + (u_star - u_end) * (k as f64) / (tail_n as f64);
1094                let ng = n_dot_g_at(u);
1095                if ng.abs() < 1e-12 {
1096                    return None;
1097                }
1098                let v = e / ng;
1099                (v >= -1e-12 && v <= v_max * (1.0 + 1e-9)).then(|| point_at(u, v.max(0.0)))
1100            })
1101            .collect()
1102    };
1103
1104    // Split into contiguous runs of kept samples, treating the array as
1105    // circular (rotate past a gap) so a branch straddling u=0 stays whole.
1106    let gap = kept.iter().position(Option::is_none).unwrap_or(0);
1107    let mut chains: Vec<Vec<Point3>> = Vec::new();
1108    let mut run: Vec<usize> = Vec::new();
1109    let flush = |run: &mut Vec<usize>, chains: &mut Vec<Vec<Point3>>| {
1110        if run.len() >= 2 {
1111            let first = run[0];
1112            let last = run[run.len() - 1];
1113            let mut pts: Vec<Point3> = tail(first, false, &kept);
1114            pts.reverse();
1115            pts.extend(
1116                run.iter()
1117                    .filter_map(|&i| kept[i].map(|v| point_at(u_of(i), v))),
1118            );
1119            pts.extend(tail(last, true, &kept));
1120            chains.push(pts);
1121        }
1122        run.clear();
1123    };
1124    for k in 0..n_samples {
1125        let idx = (gap + k) % n_samples;
1126        if kept[idx].is_some() {
1127            run.push(idx);
1128        } else {
1129            flush(&mut run, &mut chains);
1130        }
1131    }
1132    flush(&mut run, &mut chains);
1133    Ok(chains.into_iter().filter(|c| c.len() >= 2).collect())
1134}
1135
1136/// Sample the plane-torus intersection as ordered 3D points.
1137///
1138/// Uses the same closed-form loops as `intersect_plane_torus`
1139/// but skips NURBS curve fitting (the callers here only need the points).
1140#[allow(clippy::unnecessary_wraps)] // sibling match-arms and `?` callers need `Result`
1141fn sample_plane_torus(
1142    torus: &ToroidalSurface,
1143    normal: Vec3,
1144    d: f64,
1145) -> Result<Vec<Vec<Point3>>, MathError> {
1146    Ok(plane_torus_loops(torus, normal, d, 128)
1147        .into_iter()
1148        .map(|run| run.into_iter().map(|p| p.point).collect())
1149        .collect())
1150}
1151
1152/// Intersect a plane with a cylindrical surface.
1153///
1154/// For each `u` in `[0, 2pi)`, the cylinder point is linear in `v`,
1155/// so the plane equation `dot(normal, P(u,v)) = d` is linear in `v`
1156/// and can be solved directly.
1157///
1158/// # Errors
1159///
1160/// Returns an error if curve fitting fails.
1161#[allow(clippy::cast_precision_loss)]
1162pub fn intersect_plane_cylinder(
1163    cyl: &CylindricalSurface,
1164    normal: Vec3,
1165    d: f64,
1166) -> Result<Vec<IntersectionCurve>, MathError> {
1167    let n_samples = 64_usize;
1168    let mut points_3d = Vec::new();
1169    let mut ipoints = Vec::new();
1170
1171    for i in 0..=n_samples {
1172        let u = TAU * (i as f64) / (n_samples as f64);
1173        // P(u, v) = origin + r*(cos(u)*x + sin(u)*y) + v*axis
1174        // dot(normal, P) = d  =>  dot(normal, base(u)) + v * dot(normal, axis) = d
1175        let base = cyl.evaluate(u, 0.0);
1176        let n_dot_axis = normal.dot(cyl.axis());
1177        let n_dot_base = dot_np(normal, base);
1178
1179        if n_dot_axis.abs() < 1e-12 {
1180            // Plane parallel to axis -- check if base is on plane.
1181            if (n_dot_base - d).abs() < 1e-6 {
1182                let pt = base;
1183                points_3d.push(pt);
1184                ipoints.push(IntersectionPoint {
1185                    point: pt,
1186                    param1: (u, 0.0),
1187                    param2: (0.0, 0.0),
1188                });
1189            }
1190        } else {
1191            let v = (d - n_dot_base) / n_dot_axis;
1192            // Only keep points within a reasonable v range.
1193            if v.abs() <= 100.0 {
1194                let pt = cyl.evaluate(u, v);
1195                points_3d.push(pt);
1196                ipoints.push(IntersectionPoint {
1197                    point: pt,
1198                    param1: (u, v),
1199                    param2: (0.0, 0.0),
1200                });
1201            }
1202        }
1203    }
1204
1205    build_curves_from_points(&points_3d, ipoints)
1206}
1207
1208/// Intersect a plane with a spherical surface.
1209///
1210/// The intersection of a plane with a sphere is a circle (or empty/point).
1211/// Computes the circle center, radius, and samples points on it.
1212///
1213/// # Errors
1214///
1215/// Returns an error if curve fitting fails.
1216#[allow(clippy::cast_precision_loss)]
1217pub fn intersect_plane_sphere(
1218    sphere: &SphericalSurface,
1219    normal: Vec3,
1220    d: f64,
1221) -> Result<Vec<IntersectionCurve>, MathError> {
1222    let h = dot_np(normal, sphere.center()) - d;
1223    let r = sphere.radius();
1224
1225    // No intersection if plane is too far from center.
1226    if h.abs() > r - 1e-10 {
1227        return Ok(vec![]);
1228    }
1229
1230    let circle_r = (r.madd(r, -(h * h))).sqrt();
1231    let circle_center = Point3::new(
1232        h.madd(-normal.x(), sphere.center().x()),
1233        h.madd(-normal.y(), sphere.center().y()),
1234        h.madd(-normal.z(), sphere.center().z()),
1235    );
1236
1237    // Build a local frame on the plane.
1238    let basis = Frame3::from_normal(circle_center, normal)?;
1239    let u_dir = basis.x;
1240    let v_dir = basis.y;
1241
1242    let n_samples = 64_usize;
1243    let mut points_3d = Vec::new();
1244    let mut ipoints = Vec::new();
1245
1246    for i in 0..=n_samples {
1247        let theta = TAU * (i as f64) / (n_samples as f64);
1248        let (sin_t, cos_t) = theta.sin_cos();
1249        let pt = circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t);
1250        points_3d.push(pt);
1251        ipoints.push(IntersectionPoint {
1252            point: pt,
1253            param1: (theta, 0.0),
1254            param2: (0.0, 0.0),
1255        });
1256    }
1257
1258    build_curves_from_points(&points_3d, ipoints)
1259}
1260
1261/// Intersect a plane with a conical surface.
1262///
1263/// Like a cylinder, the cone is linear along each generatrix, so the plane
1264/// equation is linear in `v` for each fixed `u`.
1265///
1266/// # Errors
1267///
1268/// Returns an error if curve fitting fails.
1269#[allow(clippy::cast_precision_loss)]
1270pub fn intersect_plane_cone(
1271    cone: &ConicalSurface,
1272    normal: Vec3,
1273    d: f64,
1274) -> Result<Vec<IntersectionCurve>, MathError> {
1275    let n_samples = 64_usize;
1276    let mut points_3d = Vec::new();
1277    let mut ipoints = Vec::new();
1278
1279    for i in 0..n_samples {
1280        let u = TAU * (i as f64) / (n_samples as f64);
1281        // P(u, v) = apex + v * dir(u)
1282        // dot(normal, apex) + v * dot(normal, dir(u)) = d
1283        let apex = cone.apex();
1284        let n_dot_apex = dot_np(normal, apex);
1285        // dir(u) = P(u,1) - apex
1286        let p1 = cone.evaluate(u, 1.0);
1287        let dir = p1 - apex;
1288        let n_dot_dir = normal.dot(dir);
1289
1290        if n_dot_dir.abs() < 1e-12 {
1291            continue;
1292        }
1293
1294        let v = (d - n_dot_apex) / n_dot_dir;
1295        // Allow negative v — the cone surface extends in both directions from the apex.
1296        if v.abs() > 1e-10 && v.abs() < 100.0 {
1297            let pt = cone.evaluate(u, v);
1298            points_3d.push(pt);
1299            ipoints.push(IntersectionPoint {
1300                point: pt,
1301                param1: (u, v),
1302                param2: (0.0, 0.0),
1303            });
1304        }
1305    }
1306
1307    build_curves_from_points(&points_3d, ipoints)
1308}
1309
1310/// Intersect a plane with a toroidal surface.
1311///
1312/// The section is a degree-4 curve, but for each `v` the `u` values solve in
1313/// closed form (see `plane_torus_loops`), so it is sampled by a v-scan
1314/// and each loop is fitted to a NURBS curve.
1315///
1316/// # Errors
1317///
1318/// Never returns an error today (curve-fit failures drop the affected loop);
1319/// the `Result` is kept for signature parity with the other plane-analytic
1320/// intersectors.
1321#[allow(clippy::unnecessary_wraps)]
1322pub fn intersect_plane_torus(
1323    torus: &ToroidalSurface,
1324    normal: Vec3,
1325    d: f64,
1326) -> Result<Vec<IntersectionCurve>, MathError> {
1327    // The section satisfies a per-v closed form (see `plane_torus_loops`),
1328    // so scan v and solve u directly instead of a 2D sign-change grid with
1329    // Newton refinement: O(n) rather than O(n²), and every point is exact.
1330    let mut curves = Vec::new();
1331    for ipts in plane_torus_loops(torus, normal, d, 128) {
1332        let pts: Vec<Point3> = ipts.iter().map(|p| p.point).collect();
1333        if let Ok(curve) = interpolate(&pts, 3.min(pts.len() - 1)) {
1334            curves.push(IntersectionCurve {
1335                curve,
1336                points: ipts,
1337            });
1338        }
1339    }
1340
1341    Ok(curves)
1342}
1343
1344/// The fewest and most steps along each branch of a loop a plane cuts from
1345/// a torus between its two turns.
1346const PLANE_TORUS_LOOP_SAMPLES: (f64, f64) = (24.0, 512.0);
1347
1348/// The loops a plane cuts from a torus, each as points on the torus in
1349/// order, closed by repeating its first point.
1350///
1351/// In the torus's own frame let `a = n·X`, `b = n·Y`, `c = n·Z`,
1352/// `s = hypot(a, b)`, `phi = atan2(b, a)`. Substituting the torus
1353/// parameterization into `n·P = d` gives
1354///   `(R + r·cos v)·s·cos(u − phi) + r·c·sin v = d − n·center`,
1355/// so at each tube angle `v` where `|rhs(v)| <= 1`, with
1356/// `rhs(v) = (d − n·center − r·c·sin v) / (s·(R + r·cos v))`, the section's
1357/// two branches are `u = phi ± acos(rhs(v))`. Each run of `v` where the
1358/// section exists is one loop: out along one branch to where the run ends
1359/// and the branches meet, and back along the other. A section present at
1360/// every `v` is two loops winding the tube, one per branch. Every point
1361/// comes from the closed form, so the loops need no chaining.
1362///
1363/// Where the branches touch inside a run (a plane tangent to the tube's
1364/// inner side, at a saddle) the section crosses itself: each branch passes
1365/// through that node, and each loop there starts and ends on it.
1366///
1367/// When `s ≈ 0` the plane is perpendicular to the axis and the section is up
1368/// to two full circles at the `v` values solving `r·c·sin v = d − n·center`,
1369/// sampled by scanning `u`.
1370#[allow(clippy::cast_precision_loss, clippy::too_many_lines)]
1371fn plane_torus_loops(
1372    torus: &ToroidalSurface,
1373    normal: Vec3,
1374    d: f64,
1375    n_v: usize,
1376) -> Vec<Vec<IntersectionPoint>> {
1377    let big_r = torus.major_radius();
1378    let small_r = torus.minor_radius();
1379    let a = normal.dot(torus.x_axis());
1380    let b = normal.dot(torus.y_axis());
1381    let c = normal.dot(torus.z_axis());
1382    let s = a.hypot(b);
1383    let phi = b.atan2(a);
1384    let d_local = d - dot_np(normal, torus.center());
1385    let point = |u: f64, v: f64| IntersectionPoint {
1386        point: torus.evaluate(u, v),
1387        param1: (u, v.rem_euclid(TAU)),
1388        param2: (0.0, 0.0),
1389    };
1390    let closed = |mut run: Vec<IntersectionPoint>| {
1391        run.push(run[0]);
1392        run
1393    };
1394
1395    // Plane perpendicular to the axis: the section is up to two full circles.
1396    if s < 1e-12 {
1397        if c.abs() < 1e-12 {
1398            return Vec::new();
1399        }
1400        let sin_v = d_local / (small_r * c);
1401        if sin_v.abs() > 1.0 + 1e-9 {
1402            return Vec::new();
1403        }
1404        let v0 = sin_v.clamp(-1.0, 1.0).asin();
1405        let v1 = std::f64::consts::PI - v0;
1406        let mut vs = vec![v0];
1407        // Skip the mirror circle when the plane is tangent: at the tube's top
1408        // v0 == v1, and at its bottom they differ by a whole turn.
1409        let apart = (v1 - v0).rem_euclid(TAU);
1410        if apart.min(TAU - apart) > 1e-9 {
1411            vs.push(v1);
1412        }
1413        return vs
1414            .into_iter()
1415            .map(|v| {
1416                closed(
1417                    (0..n_v)
1418                        .map(|i| point(TAU * (i as f64) / (n_v as f64), v))
1419                        .collect(),
1420                )
1421            })
1422            .collect();
1423    }
1424
1425    // R + r·cos v > 0 on a ring torus.
1426    let length = normal.length();
1427    TorusSection {
1428        torus,
1429        phi,
1430        num: [d_local, 0.0, -small_r * c],
1431        den: [s * big_r, s * small_r],
1432        clearance: |p: Point3| (dot_np(normal, p) - d) / length,
1433        slack: 64.0 * f64::EPSILON * (big_r + small_r + d_local.abs() / length),
1434    }
1435    .loops(n_v, PLANE_TORUS_LOOP_SAMPLES)
1436}
1437
1438/// A surface's section of a ring torus that holds, at each tube angle `v`,
1439/// the torus's points with `cos(u − phi) = rhs(v)`: the two branches
1440/// `u = phi ± acos(rhs(v))` wherever `|rhs(v)| <= 1`, as for a plane
1441/// ([`plane_torus_loops`]) or a sphere off the axis ([`sphere_torus_section`]).
1442/// For both, `rhs(v) = (n0 + n1·cos v + n2·sin v) / (d0 + d1·cos v)` with a
1443/// positive denominator, so `rhs` meets `±1` where a sum of `cos v` and
1444/// `sin v` vanishes, at up to four tube angles in closed form.
1445struct TorusSection<'a, F> {
1446    torus: &'a ToroidalSurface,
1447    phi: f64,
1448    /// `n0`, `n1`, `n2`.
1449    num: [f64; 3],
1450    /// `d0`, `d1`.
1451    den: [f64; 2],
1452    /// A point's signed distance from the surface cutting the torus.
1453    clearance: F,
1454    /// The distance rounding can make or hide between the two surfaces.
1455    slack: f64,
1456}
1457
1458impl<F: Fn(Point3) -> f64> TorusSection<'_, F> {
1459    fn rhs(&self, v: f64) -> f64 {
1460        let [n0, n1, n2] = self.num;
1461        let [d0, d1] = self.den;
1462        let (sin, cos) = v.sin_cos();
1463        n2.madd(sin, n1.madd(cos, n0)) / d1.madd(cos, d0)
1464    }
1465
1466    fn point(&self, u: f64, v: f64) -> IntersectionPoint {
1467        IntersectionPoint {
1468            point: self.torus.evaluate(u, v),
1469            param1: (u.rem_euclid(TAU), v.rem_euclid(TAU)),
1470            param2: (0.0, 0.0),
1471        }
1472    }
1473
1474    fn branch(&self, v: f64, sign: f64) -> IntersectionPoint {
1475        self.point(sign.madd(self.rhs(v).clamp(-1.0, 1.0).acos(), self.phi), v)
1476    }
1477
1478    /// Where both branches meet at `v`: `acos` is 0 or π there.
1479    fn node(&self, v: f64) -> IntersectionPoint {
1480        let u = if self.rhs(v) >= 0.0 {
1481            self.phi
1482        } else {
1483            self.phi + std::f64::consts::PI
1484        };
1485        self.point(u, v)
1486    }
1487
1488    /// How far the surface lies from the point where the branches would meet
1489    /// at `v`: zero where the section's run ends, and where it only touches.
1490    fn depth(&self, v: f64) -> f64 {
1491        (self.clearance)(self.node(v).point).abs()
1492    }
1493
1494    /// The tube angles in `[0, 2π)` where `rhs` is `±1`, in order. Each solves
1495    /// `α + β·cos v + γ·sin v = 0`, so `cos(v − atan2(γ, β)) = −α / hypot(β, γ)`;
1496    /// a ratio past 1 by rounding alone is a double root, a touch.
1497    fn crossings(&self) -> Vec<f64> {
1498        let [n0, n1, n2] = self.num;
1499        let [d0, d1] = self.den;
1500        let mut roots = Vec::with_capacity(4);
1501        for c in [1.0_f64, -1.0] {
1502            let (alpha, beta, gamma) = (c.madd(-d0, n0), c.madd(-d1, n1), n2);
1503            let m = beta.hypot(gamma);
1504            let ratio = -alpha / m;
1505            if !ratio.is_finite() || ratio.abs() > 1.0 + 1e-12 {
1506                continue;
1507            }
1508            let theta = gamma.atan2(beta);
1509            let delta = ratio.clamp(-1.0, 1.0).acos();
1510            roots.push((theta - delta).rem_euclid(TAU));
1511            roots.push((theta + delta).rem_euclid(TAU));
1512        }
1513        roots.sort_by(f64::total_cmp);
1514        roots
1515    }
1516
1517    /// Each run of `v` where the section lies, from `lo` to `hi` unwrapped,
1518    /// with the node inside it where its branches touch, and whether it
1519    /// takes the whole turn. Between two crossings `|rhs|` stays on one side
1520    /// of 1; a stretch the surface clears or cuts by no more than `slack` is
1521    /// a touch, a node inside a run and nothing between runs.
1522    fn runs(&self) -> Vec<(f64, f64, Option<f64>, bool)> {
1523        let roots = self.crossings();
1524        let n = roots.len();
1525        if n == 0 {
1526            let whole = self.rhs(0.0).abs() <= 1.0 && self.depth(0.0) > self.slack;
1527            return if whole {
1528                vec![(0.0, TAU, None, true)]
1529            } else {
1530                Vec::new()
1531            };
1532        }
1533        let arcs: Vec<(f64, f64)> = (0..n)
1534            .map(|i| {
1535                (
1536                    roots[i],
1537                    if i + 1 < n {
1538                        roots[i + 1]
1539                    } else {
1540                        roots[0] + TAU
1541                    },
1542                )
1543            })
1544            .collect();
1545        let middle = |i: usize| f64::midpoint(arcs[i].0, arcs[i].1);
1546        let inside: Vec<bool> = (0..n).map(|i| self.rhs(middle(i)).abs() <= 1.0).collect();
1547        let shallow: Vec<bool> = (0..n)
1548            .map(|i| self.depth(middle(i)) <= self.slack)
1549            .collect();
1550        let deep_beside = |i: usize, back: bool| {
1551            (1..n)
1552                .map(|j| if back { (i + n - j) % n } else { (i + j) % n })
1553                .find(|&j| !shallow[j])
1554        };
1555        let kept: Vec<bool> = (0..n)
1556            .map(|i| {
1557                if !shallow[i] {
1558                    return inside[i];
1559                }
1560                matches!(
1561                    (deep_beside(i, true), deep_beside(i, false)),
1562                    (Some(a), Some(b)) if inside[a] && inside[b]
1563                )
1564            })
1565            .collect();
1566        let node_in = |from: usize, len: usize| {
1567            (0..len).find_map(|j| {
1568                let i = (from + j) % n;
1569                let wraps = if from + j >= n { TAU } else { 0.0 };
1570                shallow[i].then(|| middle(i) + wraps)
1571            })
1572        };
1573        let Some(first) = (0..n).find(|&i| kept[i] && !kept[(i + n - 1) % n]) else {
1574            return if kept.iter().all(|&k| k) {
1575                let node = node_in(0, n);
1576                let lo = node.unwrap_or(roots[0]);
1577                vec![(lo, lo + TAU, node, true)]
1578            } else {
1579                Vec::new()
1580            };
1581        };
1582        let mut runs = Vec::new();
1583        let mut j = 0;
1584        while j < n {
1585            let i = (first + j) % n;
1586            if !kept[i] {
1587                j += 1;
1588                continue;
1589            }
1590            let len = (0..n - j).take_while(|&k| kept[(i + k) % n]).count();
1591            let last = i + len - 1;
1592            let hi = arcs[last % n].1 + if last >= n { TAU } else { 0.0 };
1593            runs.push((arcs[i].0, hi, node_in(i, len), false));
1594            j += len;
1595        }
1596        runs
1597    }
1598
1599    /// Each run of the section as one loop, out along one branch to where
1600    /// the run ends and back along the other, closed by repeating its first
1601    /// point; a run taking the whole turn is two loops winding the tube.
1602    /// Where the branches touch inside a run the section crosses itself:
1603    /// each branch passes through that node, and each loop there starts and
1604    /// ends on it.
1605    #[allow(
1606        clippy::cast_precision_loss,
1607        clippy::cast_possible_truncation,
1608        clippy::cast_sign_loss
1609    )]
1610    fn loops(&self, n_v: usize, (fewest, most): (f64, f64)) -> Vec<Vec<IntersectionPoint>> {
1611        let closed = |mut run: Vec<IntersectionPoint>| {
1612            run.push(run[0]);
1613            run
1614        };
1615        let step = TAU / (n_v as f64);
1616        let mut loops = Vec::new();
1617        for (t_lo, t_hi, at_node, whole) in self.runs() {
1618            if whole {
1619                for sign in [1.0, -1.0] {
1620                    loops.push(closed(match at_node {
1621                        Some(v_node) => std::iter::once(self.node(v_node))
1622                            .chain(
1623                                (1..n_v).map(|i| self.branch((i as f64).madd(step, v_node), sign)),
1624                            )
1625                            .collect(),
1626                        None => (0..n_v)
1627                            .map(|i| self.branch((i as f64 + 0.5).madd(step, t_lo), sign))
1628                            .collect(),
1629                    }));
1630                }
1631                continue;
1632            }
1633            // `u` moves like the square root of the distance in `v` to a turn,
1634            // so the loop is sampled at `v = t_lo + (t_hi - t_lo) (1 - cos θ) / 2`
1635            // for even steps of `θ`: `v` then moves like `θ²` at each turn and
1636            // the points fall at near-even steps along the curve, turns
1637            // included. A loop that sweeps far round the axis on a short run of
1638            // `v` (a plane through the centre, tilted a little) takes a step per
1639            // half scan step of `u` its branches sweep.
1640            let len = ((t_hi - t_lo) / step).ceil();
1641            let probes = (len as usize).max(8);
1642            let (u_lo, u_hi) = (0..=probes)
1643                .map(|k| (t_hi - t_lo).madd(k as f64 / probes as f64, t_lo))
1644                .map(|v| self.rhs(v).clamp(-1.0, 1.0).acos())
1645                .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), u| {
1646                    (lo.min(u), hi.max(u))
1647                });
1648            let m = len
1649                .max((n_v as f64) * (u_hi - u_lo) / std::f64::consts::PI)
1650                .max(fewest)
1651                .min(most)
1652                .ceil();
1653            let steps = m as usize;
1654            if let Some(v_node) = at_node {
1655                // Out along one branch from the node to a turn and back along
1656                // the other, once each side of the node.
1657                for (from, to) in [(v_node, t_lo), (v_node, t_hi)] {
1658                    let along = |k: usize| {
1659                        let f = 0.5 * (1.0 - (std::f64::consts::PI * k as f64 / m).cos());
1660                        (to - from).madd(f, from)
1661                    };
1662                    let mut pts = vec![self.node(v_node)];
1663                    pts.extend((1..=steps).map(|k| self.branch(along(k), 1.0)));
1664                    pts.extend((1..steps).rev().map(|k| self.branch(along(k), -1.0)));
1665                    loops.push(closed(pts));
1666                }
1667            } else {
1668                let at = |k: usize| {
1669                    let f = 0.5 * (1.0 - (std::f64::consts::PI * k as f64 / m).cos());
1670                    (t_hi - t_lo).madd(f, t_lo)
1671                };
1672                let mut pts: Vec<IntersectionPoint> =
1673                    (0..=steps).map(|k| self.branch(at(k), 1.0)).collect();
1674                pts.extend((1..steps).rev().map(|k| self.branch(at(k), -1.0)));
1675                loops.push(closed(pts));
1676            }
1677        }
1678        loops
1679    }
1680
1681    /// The section's point halfway in `v` between two of its points, given
1682    /// by their `(u, v)` on the torus, on the branch nearer their middle `u`.
1683    fn between(&self, a: (f64, f64), b: (f64, f64)) -> IntersectionPoint {
1684        let half = |from: f64, to: f64| {
1685            let gap = (to - from + std::f64::consts::PI).rem_euclid(TAU) - std::f64::consts::PI;
1686            0.5_f64.madd(gap, from)
1687        };
1688        let (u, v) = (half(a.0, b.0), half(a.1, b.1));
1689        let off = self.rhs(v).clamp(-1.0, 1.0).acos();
1690        let miss =
1691            |w: f64| ((w - u + std::f64::consts::PI).rem_euclid(TAU) - std::f64::consts::PI).abs();
1692        let sign = if miss(self.phi + off) <= miss(self.phi - off) {
1693            1.0
1694        } else {
1695            -1.0
1696        };
1697        self.branch(v, sign)
1698    }
1699}
1700
1701/// The two sections of a plane that crosses every tube cross-section of a
1702/// torus twice (one parallel to the axis within `R − r` of it, or tilted a
1703/// little from that): both branches `u = phi ± acos(rhs(v))` of
1704/// [`plane_torus_loops`] are then defined for every `v`, so each closes
1705/// into a loop that winds once around the tube. Sampled at `n_v` steps from
1706/// `v = 0`, the outer equator, so every such loop on a torus starts on one
1707/// latitude, as the tube cross-sections of a plane through the axis do.
1708/// `None` when a branch lapses somewhere or the two come close to meeting.
1709#[allow(clippy::cast_precision_loss)]
1710fn plane_torus_winding_loops(
1711    torus: &ToroidalSurface,
1712    normal: Vec3,
1713    d: f64,
1714    n_v: usize,
1715) -> Option<Vec<Vec<Point3>>> {
1716    let big_r = torus.major_radius();
1717    let small_r = torus.minor_radius();
1718    let a = normal.dot(torus.x_axis());
1719    let b = normal.dot(torus.y_axis());
1720    let c = normal.dot(torus.z_axis());
1721    let s = a.hypot(b);
1722    if s < 1e-12 * normal.length() || small_r >= big_r {
1723        return None;
1724    }
1725    let phi = b.atan2(a);
1726    let d_local = d - dot_np(normal, torus.center());
1727    let rhs = |v: f64| (d_local - small_r * c * v.sin()) / (s * small_r.madd(v.cos(), big_r));
1728    let dense = 8 * n_v;
1729    if (0..dense).any(|i| rhs(TAU * i as f64 / dense as f64).abs() > 1.0 - 1e-3) {
1730        return None;
1731    }
1732    let mut loops = [Vec::with_capacity(n_v + 1), Vec::with_capacity(n_v + 1)];
1733    for i in 0..n_v {
1734        let v = TAU * i as f64 / n_v as f64;
1735        let delta = rhs(v).acos();
1736        loops[0].push(torus.evaluate(phi + delta, v));
1737        loops[1].push(torus.evaluate(phi - delta, v));
1738    }
1739    Some(
1740        loops
1741            .into_iter()
1742            .map(|mut run| {
1743                run.push(run[0]);
1744                run
1745            })
1746            .collect(),
1747    )
1748}
1749
1750/// Real intersection parameters `t` of the line `origin + t·dir` with a torus.
1751///
1752/// A line meets a torus in up to four points (degree-4). Substituting the line
1753/// into the torus implicit `(a² + b² + c² + R² − r²)² = 4R²(a² + b²)` — where
1754/// `(a, b, c)` are the line point's coordinates in the torus frame — gives a
1755/// quartic in `t`, solved here for its real roots, each refined by Newton steps
1756/// on the tube it lies nearer (on a spindle torus, the near tube or the one
1757/// swung across the axis). `dir` need not be unit length; `t` is in units of
1758/// `dir`. Returns the roots sorted ascending (0–4 of them).
1759///
1760/// Used by the boolean section trimmer to find where a plane×torus oval exits a
1761/// box face's straight boundary edge — the exact crossing shared by the two
1762/// adjacent faces, which is what makes the notch watertight.
1763#[must_use]
1764pub fn intersect_line_torus(torus: &ToroidalSurface, origin: Point3, dir: Vec3) -> Vec<f64> {
1765    let c = torus.center();
1766    let (xa, ya, za) = (torus.x_axis(), torus.y_axis(), torus.z_axis());
1767    let big_r = torus.major_radius();
1768    let small_r = torus.minor_radius();
1769
1770    // Line point in torus frame: a(t)=a0+a1 t, b(t)=b0+b1 t, c(t)=c0+c1 t.
1771    let o = Vec3::new(origin.x() - c.x(), origin.y() - c.y(), origin.z() - c.z());
1772    let (a0, a1) = (xa.dot(o), xa.dot(dir));
1773    let (b0, b1) = (ya.dot(o), ya.dot(dir));
1774    let (c0, c1) = (za.dot(o), za.dot(dir));
1775
1776    // G(t) = a² + b² + c² + R² − r²  (quadratic: g2 t² + g1 t + g0)
1777    let g2 = a1.madd(a1, b1.madd(b1, c1 * c1));
1778    let g1 = 2.0 * a1.madd(a0, b1.madd(b0, c1 * c0));
1779    let g0 = a0.madd(
1780        a0,
1781        b0.madd(b0, c0.madd(c0, big_r.madd(big_r, -small_r * small_r))),
1782    );
1783
1784    // H(t) = 4R² (a² + b²)  (quadratic: h2 t² + h1 t + h0)
1785    let four_rr = 4.0 * big_r * big_r;
1786    let h2 = four_rr * a1.madd(a1, b1 * b1);
1787    let h1 = four_rr * (2.0 * a1.madd(a0, b1 * b0));
1788    let h0 = four_rr * a0.madd(a0, b0 * b0);
1789
1790    // Quartic G² − H = 0:  e4 t⁴ + e3 t³ + e2 t² + e1 t + e0.
1791    let e4 = g2 * g2;
1792    let e3 = 2.0 * g2 * g1;
1793    let e2 = g1.madd(g1, 2.0 * g2 * g0) - h2;
1794    let e1 = 2.0f64.madd(g1 * g0, -h1);
1795    let e0 = g0.madd(g0, -h0);
1796
1797    let mut roots = real_roots_quartic(e4, e3, e2, e1, e0);
1798    // The quartic also holds a spindle torus's tube swung across the axis
1799    // (`G = -sqrt(H)`), whose roots pair up with the tube's own a few hundredths
1800    // apart when `R` is small: the solver leaves them loose, and polishing one
1801    // against the near tube carries it beside the other root. Each root is
1802    // polished on the tube it lies nearer.
1803    let tube = |t: f64, across: bool| -> f64 {
1804        let p = origin + dir * t;
1805        let q = Vec3::new(p.x() - c.x(), p.y() - c.y(), p.z() - c.z());
1806        let (a, b, cc) = (xa.dot(q), ya.dot(q), za.dot(q));
1807        let centre = if across { -big_r } else { big_r };
1808        (a.hypot(b) - centre).hypot(cc) - small_r
1809    };
1810    for t in &mut roots {
1811        let across = big_r < small_r && tube(*t, true).abs() < tube(*t, false).abs();
1812        for _ in 0..8 {
1813            let eps = 1e-7;
1814            let f = tube(*t, across);
1815            let df = (tube(*t + eps, across) - tube(*t - eps, across)) / (2.0 * eps);
1816            if df.abs() <= 1e-12 {
1817                break;
1818            }
1819            let step = f / df;
1820            *t -= step;
1821            if step.abs() < 1e-14 * (1.0 + t.abs()) {
1822                break;
1823            }
1824        }
1825    }
1826    roots.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
1827    roots.dedup_by(|a, b| (*a - *b).abs() < 1e-9 * (1.0 + b.abs()));
1828    roots
1829}
1830
1831/// Real roots of `c4 x⁴ + c3 x³ + c2 x² + c1 x + c0` via Durand–Kerner, falling
1832/// back to the lower-degree solvers when the leading coefficients vanish.
1833fn real_roots_quartic(c4: f64, c3: f64, c2: f64, c1: f64, c0: f64) -> Vec<f64> {
1834    // Degenerate leading coefficient → lower degree.
1835    if c4.abs() < 1e-14 {
1836        return real_roots_cubic(c3, c2, c1, c0);
1837    }
1838    // Monic: x⁴ + a x³ + b x² + c x + d.
1839    let (a, b, c, d) = (c3 / c4, c2 / c4, c1 / c4, c0 / c4);
1840    let eval = |z: Complex| -> Complex {
1841        // Horner.
1842        let mut acc = Complex::new(1.0, 0.0);
1843        acc = acc * z + Complex::new(a, 0.0);
1844        acc = acc * z + Complex::new(b, 0.0);
1845        acc = acc * z + Complex::new(c, 0.0);
1846        acc * z + Complex::new(d, 0.0)
1847    };
1848    // Durand–Kerner: four roots seeded on a circle, iterated to convergence.
1849    let seed = Complex::new(0.4, 0.9);
1850    let mut r = [
1851        Complex::new(1.0, 0.0),
1852        seed,
1853        seed * seed,
1854        seed * seed * seed,
1855    ];
1856    for _ in 0..100 {
1857        let mut max_step = 0.0_f64;
1858        for i in 0..4 {
1859            let mut denom = Complex::new(1.0, 0.0);
1860            for j in 0..4 {
1861                if i != j {
1862                    denom = denom * (r[i] - r[j]);
1863                }
1864            }
1865            if denom.norm() < 1e-300 {
1866                continue;
1867            }
1868            let step = eval(r[i]) / denom;
1869            r[i] = r[i] - step;
1870            max_step = max_step.max(step.norm());
1871        }
1872        if max_step < 1e-14 {
1873            break;
1874        }
1875    }
1876    // Keep roots with negligible imaginary part AND a small REAL-polynomial
1877    // residual — Durand–Kerner stops after a fixed iteration cap whether or not
1878    // it converged, so a non-converged iterate could otherwise be returned as a
1879    // spurious root. Evaluate the monic quartic at each candidate (real part) and
1880    // keep only |p(x)| below a magnitude-scaled tolerance; de-dup near-equal
1881    // roots (a double root converges to two near-identical iterates).
1882    let p_real = |x: f64| -> f64 { (((x + a) * x + b) * x + c) * x + d };
1883    let mut out: Vec<f64> = Vec::new();
1884    for z in r {
1885        if z.im.abs() >= 1e-7 {
1886            continue;
1887        }
1888        let x = z.re;
1889        // Residual tolerance scales with the polynomial's coefficient magnitude
1890        // and |x|^4 so large-coefficient quartics are not over-rejected.
1891        let scale = 1.0 + a.abs() + b.abs() + c.abs() + d.abs() + x.abs().powi(4);
1892        if p_real(x).abs() > 1e-6 * scale {
1893            continue;
1894        }
1895        if out.iter().any(|&y| (y - x).abs() < 1e-9 * (1.0 + x.abs())) {
1896            continue;
1897        }
1898        out.push(x);
1899    }
1900    out
1901}
1902
1903/// Real roots of `a x³ + b x² + c x + d` (Cardano), with quadratic fallback.
1904fn real_roots_cubic(a: f64, b: f64, c: f64, d: f64) -> Vec<f64> {
1905    if a.abs() < 1e-14 {
1906        return real_roots_quadratic(b, c, d);
1907    }
1908    // Depressed cubic t³ + p t + q via x = t − b/(3a).
1909    let (b, c, d) = (b / a, c / a, d / a);
1910    let p = c - b * b / 3.0;
1911    let q = 2.0 * b * b * b / 27.0 - b * c / 3.0 + d;
1912    let shift = -b / 3.0;
1913    let disc = q * q / 4.0 + p * p * p / 27.0;
1914    if disc > 1e-14 {
1915        let sq = disc.sqrt();
1916        let u = (-q / 2.0 + sq).cbrt();
1917        let v = (-q / 2.0 - sq).cbrt();
1918        vec![u + v + shift]
1919    } else if disc < -1e-14 {
1920        // Three real roots (trigonometric).
1921        let m = 2.0 * (-p / 3.0).sqrt();
1922        let theta = (3.0 * q / (p * m)).clamp(-1.0, 1.0).acos() / 3.0;
1923        (0..3)
1924            .map(|k| {
1925                m.madd(
1926                    (theta - 2.0 * std::f64::consts::PI * f64::from(k) / 3.0).cos(),
1927                    shift,
1928                )
1929            })
1930            .collect()
1931    } else {
1932        // Repeated roots.
1933        let u = (-q / 2.0).cbrt();
1934        vec![2.0 * u + shift, -u + shift]
1935    }
1936}
1937
1938/// Real roots of `a x² + b x + c`, with linear fallback.
1939fn real_roots_quadratic(a: f64, b: f64, c: f64) -> Vec<f64> {
1940    if a.abs() < 1e-14 {
1941        if b.abs() < 1e-14 {
1942            return Vec::new();
1943        }
1944        return vec![-c / b];
1945    }
1946    let disc = b * b - 4.0 * a * c;
1947    if disc < 0.0 {
1948        Vec::new()
1949    } else {
1950        let sq = disc.sqrt();
1951        vec![(-b - sq) / (2.0 * a), (-b + sq) / (2.0 * a)]
1952    }
1953}
1954
1955/// Minimal complex number for the quartic root finder.
1956#[derive(Clone, Copy)]
1957struct Complex {
1958    re: f64,
1959    im: f64,
1960}
1961
1962impl Complex {
1963    const fn new(re: f64, im: f64) -> Self {
1964        Self { re, im }
1965    }
1966    fn norm(self) -> f64 {
1967        self.re.hypot(self.im)
1968    }
1969}
1970
1971impl std::ops::Add for Complex {
1972    type Output = Self;
1973    fn add(self, o: Self) -> Self {
1974        Self::new(self.re + o.re, self.im + o.im)
1975    }
1976}
1977
1978impl std::ops::Sub for Complex {
1979    type Output = Self;
1980    fn sub(self, o: Self) -> Self {
1981        Self::new(self.re - o.re, self.im - o.im)
1982    }
1983}
1984
1985impl std::ops::Mul for Complex {
1986    type Output = Self;
1987    fn mul(self, o: Self) -> Self {
1988        Self::new(
1989            self.re.madd(o.re, -(self.im * o.im)),
1990            self.re.madd(o.im, self.im * o.re),
1991        )
1992    }
1993}
1994
1995impl std::ops::Div for Complex {
1996    type Output = Self;
1997    fn div(self, o: Self) -> Self {
1998        let den = o.re.madd(o.re, o.im * o.im);
1999        Self::new(
2000            self.re.madd(o.re, self.im * o.im) / den,
2001            self.im.madd(o.re, -(self.re * o.im)) / den,
2002        )
2003    }
2004}
2005
2006/// Build intersection curves from a collection of ordered 3D points.
2007///
2008/// If there are enough points, fits a NURBS curve through them.
2009fn build_curves_from_points(
2010    points_3d: &[Point3],
2011    ipoints: Vec<IntersectionPoint>,
2012) -> Result<Vec<IntersectionCurve>, MathError> {
2013    if points_3d.len() < 2 {
2014        return Ok(vec![]);
2015    }
2016
2017    let degree = 3.min(points_3d.len() - 1);
2018    let curve = interpolate(points_3d, degree)?;
2019    Ok(vec![IntersectionCurve {
2020        curve,
2021        points: ipoints,
2022    }])
2023}
2024
2025// -- Analytic-Analytic Intersection -------------------------------------------
2026
2027/// Intersect two analytic surfaces using a general marching approach.
2028///
2029/// Seeds intersection points by sampling both parameter spaces on a grid,
2030/// then marches along the intersection curve using the cross product of
2031/// the two surface normals as the tangent direction.
2032///
2033/// # Errors
2034///
2035/// Returns an error if curve fitting fails.
2036#[allow(
2037    clippy::cast_precision_loss,
2038    clippy::too_many_lines,
2039    clippy::similar_names,
2040    clippy::unnecessary_wraps,
2041    clippy::type_complexity
2042)]
2043pub fn intersect_analytic_analytic(
2044    a: AnalyticSurface<'_>,
2045    b: AnalyticSurface<'_>,
2046    grid_res: usize,
2047) -> Result<Vec<IntersectionCurve>, MathError> {
2048    intersect_analytic_analytic_bounded(a, b, grid_res, None, None)
2049}
2050
2051/// Intersect two analytic surfaces with optional v-range overrides.
2052///
2053/// When `v_range_hint_a` or `v_range_hint_b` is `Some((min, max))`, the
2054/// marching algorithm searches that v-range instead of the hardcoded default.
2055/// This is essential for cylinders and cones whose default v-range is small
2056/// (-1..1 or 0.01..2) but whose actual face may extend much further.
2057///
2058/// # Errors
2059///
2060/// Returns `MathError` if algebraic intersection fails or marching diverges.
2061pub fn intersect_analytic_analytic_bounded(
2062    a: AnalyticSurface<'_>,
2063    b: AnalyticSurface<'_>,
2064    grid_res: usize,
2065    v_range_hint_a: Option<(f64, f64)>,
2066    v_range_hint_b: Option<(f64, f64)>,
2067) -> Result<Vec<IntersectionCurve>, MathError> {
2068    intersect_analytic_analytic_impl(a, b, grid_res, v_range_hint_a, v_range_hint_b, None)
2069}
2070
2071/// [`intersect_analytic_analytic_bounded`] with its general marcher confined
2072/// to `region`.
2073///
2074/// The marcher starts only from seeds that converge into the region (with a
2075/// margin of about two grid cells) and stops where a curve leaves it. Pairs
2076/// solved in closed form are returned whole, as by the unconfined call. Two
2077/// bounded faces meet only inside both their boxes, so their overlap is a
2078/// sound region for a face pair.
2079///
2080/// # Errors
2081///
2082/// Returns `MathError` if algebraic intersection fails or marching diverges.
2083pub fn intersect_analytic_analytic_in_region(
2084    a: AnalyticSurface<'_>,
2085    b: AnalyticSurface<'_>,
2086    grid_res: usize,
2087    v_range_hint_a: Option<(f64, f64)>,
2088    v_range_hint_b: Option<(f64, f64)>,
2089    region: Aabb3,
2090) -> Result<Vec<IntersectionCurve>, MathError> {
2091    intersect_analytic_analytic_impl(a, b, grid_res, v_range_hint_a, v_range_hint_b, Some(region))
2092}
2093
2094fn intersect_analytic_analytic_impl(
2095    a: AnalyticSurface<'_>,
2096    b: AnalyticSurface<'_>,
2097    grid_res: usize,
2098    v_range_hint_a: Option<(f64, f64)>,
2099    v_range_hint_b: Option<(f64, f64)>,
2100    region: Option<Aabb3>,
2101) -> Result<Vec<IntersectionCurve>, MathError> {
2102    // Try algebraic specialization for known surface pairs before falling
2103    // back to the general marching approach.
2104    if let Some(result) = try_algebraic_intersection(&a, &b, v_range_hint_a, v_range_hint_b)? {
2105        return Ok(result);
2106    }
2107
2108    let (surf_a, norm_a, u_range_a, default_v_a) = surface_closures(&a);
2109    let (surf_b, norm_b, u_range_b, default_v_b) = surface_closures(&b);
2110    let v_range_a = v_range_hint_a.unwrap_or(default_v_a);
2111    let v_range_b = v_range_hint_b.unwrap_or(default_v_b);
2112
2113    // Compute characteristic surface dimensions for adaptive parameters.
2114    let diag_a = {
2115        let p00 = surf_a(u_range_a.0, v_range_a.0);
2116        let p11 = surf_a(u_range_a.1, v_range_a.1);
2117        (p00 - p11).length()
2118    };
2119    let diag_b = {
2120        let p00 = surf_b(u_range_b.0, v_range_b.0);
2121        let p11 = surf_b(u_range_b.1, v_range_b.1);
2122        (p00 - p11).length()
2123    };
2124    let char_size = diag_a.min(diag_b).max(0.1);
2125
2126    // Sample surface A on a grid. For each grid point, project it
2127    // analytically onto surface B to find the closest point, then check
2128    // if the distance is below threshold (indicating near-intersection).
2129    #[allow(clippy::type_complexity)]
2130    let mut seeds: Vec<(Point3, (f64, f64), (f64, f64))> = Vec::new();
2131    // Coarse threshold scales with the surface size — the distance from
2132    // a grid point on A to its projection on B can be large even near
2133    // the intersection (e.g., sphere R=2 and cylinder R=1 → gap ≈ 1).
2134    let seed_threshold = diag_a.max(diag_b).max(1.0) * 0.5;
2135    let mut min_dist = f64::INFINITY;
2136
2137    #[allow(clippy::cast_precision_loss)]
2138    for ia in 0..grid_res {
2139        for ja in 0..grid_res {
2140            let ua =
2141                u_range_a.0 + (u_range_a.1 - u_range_a.0) * (ia as f64 + 0.5) / (grid_res as f64);
2142            let va =
2143                v_range_a.0 + (v_range_a.1 - v_range_a.0) * (ja as f64 + 0.5) / (grid_res as f64);
2144
2145            let pa = surf_a(ua, va);
2146
2147            // Analytically project onto surface B.
2148            let (ub, vb) = project_analytic(&b, pa, u_range_b, v_range_b);
2149            let pb = surf_b(ub, vb);
2150            let dist = (pa - pb).length();
2151            min_dist = min_dist.min(dist);
2152
2153            if dist < seed_threshold {
2154                // Use the coarse seed directly. The marching algorithm
2155                // corrects positions at each step via projection, so seeds
2156                // don't need to be on the exact intersection — they just
2157                // need to be close enough for the marcher to converge.
2158                let mid = Point3::new(
2159                    (pa.x() + pb.x()) * 0.5,
2160                    (pa.y() + pb.y()) * 0.5,
2161                    (pa.z() + pb.z()) * 0.5,
2162                );
2163                seeds.push((mid, (ua, va), (ub, vb)));
2164            }
2165        }
2166    }
2167
2168    // Cheap rejection: the grid samples surface A; the closest sample's
2169    // distance to B lower-bounds how near the two bounded patches come. A
2170    // transversal crossing puts a sample within ~one grid cell of it
2171    // (distance on the order of a cell), so if even the nearest sample is
2172    // several cells away the patches cannot cross — skip the expensive
2173    // marching and return empty. Result-preserving: non-crossing pairs
2174    // already march to nothing, just slowly (this is the gridfinity lip's
2175    // ~80 inner-wall × outer-wall pairs that dominate pavefiller time).
2176    let reject_dist = (char_size / grid_res as f64) * 3.0;
2177    if min_dist > reject_dist {
2178        return Ok(vec![]);
2179    }
2180
2181    if seeds.is_empty() {
2182        return Ok(vec![]);
2183    }
2184
2185    // Aggressively deduplicate seeds — we only need 1-2 per intersection
2186    // branch. Scale dedup radius to ~2% of characteristic surface size
2187    // (at least 10× the march step size) to avoid redundant marches.
2188    let march_step = (char_size * 0.02).clamp(0.005, 0.5);
2189    let dedup_radius = march_step * 10.0;
2190    let mut unique_seeds = Vec::new();
2191    for seed in &seeds {
2192        let dominated = unique_seeds
2193            .iter()
2194            .any(|s: &(Point3, (f64, f64), (f64, f64))| (s.0 - seed.0).length() < dedup_radius);
2195        if !dominated {
2196            unique_seeds.push(*seed);
2197        }
2198    }
2199
2200    // A seed is only near the intersection; settle it onto the curve before
2201    // asking whether it lies in the region, so a coarse grid point beside a
2202    // short in-region span still starts its march, and march from there, so
2203    // the march does not begin outside the region and stop at once.
2204    let region = region.map(|r| r.expanded(2.0 * char_size / grid_res as f64));
2205    if let Some(r) = region {
2206        for seed in &mut unique_seeds {
2207            let mut p = seed.0;
2208            for _ in 0..8 {
2209                let (ua, va) = project_analytic(&a, p, u_range_a, v_range_a);
2210                let pa = surf_a(ua, va);
2211                let (ub, vb) = project_analytic(&b, pa, u_range_b, v_range_b);
2212                let pb = surf_b(ub, vb);
2213                p = Point3::new(
2214                    (pa.x() + pb.x()) * 0.5,
2215                    (pa.y() + pb.y()) * 0.5,
2216                    (pa.z() + pb.z()) * 0.5,
2217                );
2218                if (pa - pb).length() < 1e-9 {
2219                    break;
2220                }
2221            }
2222            seed.0 = p;
2223        }
2224        unique_seeds.retain(|seed| r.contains_point(seed.0));
2225    }
2226
2227    // March from each seed.
2228    let mut curves = Vec::new();
2229    let mut used_seeds = vec![false; unique_seeds.len()];
2230
2231    for si in 0..unique_seeds.len() {
2232        if used_seeds[si] {
2233            continue;
2234        }
2235        used_seeds[si] = true;
2236
2237        let march_result = march_analytic_intersection(
2238            &a,
2239            &b,
2240            surf_a.as_ref(),
2241            norm_a.as_ref(),
2242            surf_b.as_ref(),
2243            norm_b.as_ref(),
2244            unique_seeds[si].0,
2245            u_range_a,
2246            v_range_a,
2247            u_range_b,
2248            v_range_b,
2249            march_step,
2250            is_u_periodic(&a),
2251            is_u_periodic(&b),
2252            region,
2253        );
2254
2255        if march_result.len() >= 2 {
2256            for (sj, other) in unique_seeds.iter().enumerate() {
2257                if !used_seeds[sj]
2258                    && march_result
2259                        .iter()
2260                        .any(|p| (*p - other.0).length() < dedup_radius)
2261                {
2262                    used_seeds[sj] = true;
2263                }
2264            }
2265
2266            let ipts: Vec<IntersectionPoint> = march_result
2267                .iter()
2268                .map(|&pt| IntersectionPoint {
2269                    point: pt,
2270                    param1: (0.0, 0.0),
2271                    param2: (0.0, 0.0),
2272                })
2273                .collect();
2274
2275            let degree = 3.min(march_result.len() - 1);
2276            if let Ok(curve) = interpolate(&march_result, degree) {
2277                curves.push(IntersectionCurve {
2278                    curve,
2279                    points: ipts,
2280                });
2281            }
2282        }
2283    }
2284
2285    Ok(curves)
2286}
2287
2288/// Try algebraic (closed-form or semi-algebraic) intersection for known
2289/// surface pairs before falling back to general marching.
2290///
2291/// Returns `Some(curves)` if a specialized method exists, `None` otherwise.
2292///
2293/// Currently handles:
2294/// - **Sphere-sphere**: intersection is a circle (plane through the two centers)
2295/// - **Coaxial cylinders**: same axis → circle(s) or empty
2296/// - **Sphere-cylinder**: reduce to quadratic in one parameter
2297/// - **Cone-cylinder**: parallel axes in the cone's own `v`, other axes
2298///   along the cylinder's rulings
2299/// - **Cone-sphere**: off the cone's axis, along the cone's generators
2300/// - **Torus-cylinder**: along the cylinder's rulings
2301#[allow(clippy::too_many_lines)]
2302fn try_algebraic_intersection(
2303    a: &AnalyticSurface<'_>,
2304    b: &AnalyticSurface<'_>,
2305    v_range_a: Option<(f64, f64)>,
2306    v_range_b: Option<(f64, f64)>,
2307) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
2308    match (a, b) {
2309        (AnalyticSurface::Cone(cone), AnalyticSurface::Cylinder(cyl)) => Ok(
2310            algebraic_parallel_cone_cylinder(cone, cyl, v_range_a, v_range_b)?
2311                .or_else(|| ruling_cone_cylinder(cone, cyl, true)),
2312        ),
2313        (AnalyticSurface::Cylinder(cyl), AnalyticSurface::Cone(cone)) => Ok(
2314            algebraic_parallel_cone_cylinder(cone, cyl, v_range_b, v_range_a)?
2315                .or_else(|| ruling_cone_cylinder(cone, cyl, false)),
2316        ),
2317        (AnalyticSurface::Sphere(s1), AnalyticSurface::Sphere(s2)) => {
2318            algebraic_sphere_sphere(s1, s2).map(Some)
2319        }
2320        (AnalyticSurface::Cylinder(c1), AnalyticSurface::Cylinder(c2)) => {
2321            let axis_dot = c1.axis().dot(c2.axis()).abs();
2322            if axis_dot > 1.0 - 1e-10 {
2323                // Axes are parallel — check if they're the same line.
2324                let delta = c2.origin() - c1.origin();
2325                let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
2326                let along = delta_vec.dot(c1.axis());
2327                let perp = (delta_vec - c1.axis() * along).length();
2328                if perp < 1e-8 {
2329                    // Coaxial: same axis, different radii → no intersection
2330                    // (unless equal radius → degenerate overlap, skip)
2331                    if (c1.radius() - c2.radius()).abs() < 1e-8 {
2332                        return Ok(None); // Overlapping — let marcher handle
2333                    }
2334                    return Ok(Some(vec![])); // Coaxial, different radii
2335                }
2336                if let Some(rulings) = parallel_cylinders(c1, c2, v_range_a, v_range_b)? {
2337                    return Ok(Some(rulings));
2338                }
2339            }
2340            // Non-coaxial: algebraic quadratic in v.
2341            algebraic_cylinder_cylinder(c1, c2)
2342        }
2343        // Sphere-cylinder (both orderings).
2344        (AnalyticSurface::Sphere(s), AnalyticSurface::Cylinder(c)) => {
2345            algebraic_sphere_cylinder(s, c, true)
2346        }
2347        (AnalyticSurface::Cylinder(c), AnalyticSurface::Sphere(s)) => {
2348            algebraic_sphere_cylinder(s, c, false)
2349        }
2350        (AnalyticSurface::Cone(c1), AnalyticSurface::Cone(c2)) => {
2351            if let Some(rulings) = shared_apex_cones(c1, c2, v_range_a, v_range_b)? {
2352                return Ok(Some(rulings));
2353            }
2354            algebraic_cone_cone(c1, c2)
2355        }
2356        (AnalyticSurface::Cone(cone), AnalyticSurface::Sphere(sphere)) => {
2357            Ok(ruling_cone_sphere(cone, sphere, true))
2358        }
2359        (AnalyticSurface::Sphere(sphere), AnalyticSurface::Cone(cone)) => {
2360            Ok(ruling_cone_sphere(cone, sphere, false))
2361        }
2362        (AnalyticSurface::Torus(t), AnalyticSurface::Cylinder(c)) => {
2363            if let Some(exacts) = exact_cylinder_torus(c, t)? {
2364                return exact_circle_curves(exacts, |p| (t.project_point(p), c.project_point(p)))
2365                    .map(Some);
2366            }
2367            Ok(parallel_axis_torus_cylinder(t, c, true)
2368                .or_else(|| ruling_torus_cylinder(t, c, true)))
2369        }
2370        (AnalyticSurface::Cylinder(c), AnalyticSurface::Torus(t)) => {
2371            if let Some(exacts) = exact_cylinder_torus(c, t)? {
2372                return exact_circle_curves(exacts, |p| (c.project_point(p), t.project_point(p)))
2373                    .map(Some);
2374            }
2375            Ok(parallel_axis_torus_cylinder(t, c, false)
2376                .or_else(|| ruling_torus_cylinder(t, c, false)))
2377        }
2378        (AnalyticSurface::Sphere(s), AnalyticSurface::Torus(t)) => {
2379            match exact_sphere_torus(s, t)? {
2380                Some(exacts) => {
2381                    exact_circle_curves(exacts, |p| (s.project_point(p), t.project_point(p)))
2382                        .map(Some)
2383                }
2384                None => Ok(sphere_torus_curves(s, t, true)),
2385            }
2386        }
2387        (AnalyticSurface::Torus(t), AnalyticSurface::Sphere(s)) => {
2388            match exact_sphere_torus(s, t)? {
2389                Some(exacts) => {
2390                    exact_circle_curves(exacts, |p| (t.project_point(p), s.project_point(p)))
2391                        .map(Some)
2392                }
2393                None => Ok(sphere_torus_curves(s, t, false)),
2394            }
2395        }
2396        (AnalyticSurface::Torus(t1), AnalyticSurface::Torus(t2)) => exact_torus_torus(t1, t2)?
2397            .map(|exacts| {
2398                exact_circle_curves(exacts, |p| (t1.project_point(p), t2.project_point(p)))
2399            })
2400            .transpose(),
2401        _ => Ok(None),
2402    }
2403}
2404
2405/// A torus and a cylinder whose axes are parallel but distinct (a drill
2406/// through a ring parallel to its axis), traced along the cylinder's
2407/// rulings. A ruling stays at one distance `ρ` from the torus axis, so it
2408/// meets the tube where `(ρ − R)² + z² = r²`: a quadratic in its axial
2409/// parameter. `None` for any other pair (tilted or coaxial axes) and when
2410/// the sampling misses a window narrower than itself.
2411fn parallel_axis_torus_cylinder(
2412    torus: &ToroidalSurface,
2413    cyl: &CylindricalSurface,
2414    torus_first: bool,
2415) -> Option<Vec<IntersectionCurve>> {
2416    let axis = torus.z_axis();
2417    let along = cyl.axis().dot(axis);
2418    if along.abs() < 1.0 - 1e-10 {
2419        return None;
2420    }
2421    let offset = cyl.origin() - torus.center();
2422    if (offset - axis * offset.dot(axis)).length() < Tolerance::new().linear {
2423        return None;
2424    }
2425    let (major, minor) = (torus.major_radius(), torus.minor_radius());
2426    let roots = |u: f64| {
2427        let q = cyl.evaluate(u, 0.0) - torus.center();
2428        let height = q.dot(axis);
2429        let rho = (q - axis * height).length();
2430        let reach = minor * minor - (rho - major) * (rho - major);
2431        ruling_quadratic(1.0, 2.0 * along.signum() * height, height * height - reach)
2432    };
2433    let samples = ruling_samples(cyl, &roots);
2434    let loops = if samples.iter().all(Option::is_some) {
2435        closed_ruling_loops(cyl, &roots, &samples)
2436    } else {
2437        partial_ruling_loops(cyl, &roots, &samples)
2438    };
2439    if loops.is_empty() {
2440        return None;
2441    }
2442    Some(fit_ruling_loops(&loops, |p| {
2443        in_order(torus.project_point(p), cyl.project_point(p), torus_first)
2444    }))
2445}
2446
2447/// Where two circles in a half-plane through an axis cross, as `(rho, z)`
2448/// pairs (distance from the axis, height along it): each sweeps a circle
2449/// about the axis. Two crossings closer than the linear tolerance are the
2450/// one point where the circles touch, side by side or one inside the
2451/// other. `None` (defer to the marcher) when the circles coincide or a
2452/// crossing lands on or past the axis; `Some` of none when they miss.
2453fn meridian_crossings(
2454    first: (f64, f64, f64),
2455    second: (f64, f64, f64),
2456    scale: f64,
2457) -> Option<Vec<(f64, f64)>> {
2458    let ((x1, z1, r1), (x2, z2, r2)) = (first, second);
2459    let (dx, dz) = (x2 - x1, z2 - z1);
2460    let dist = dx.hypot(dz);
2461    let slack = 1e-9 * scale;
2462    if dist < slack {
2463        return None;
2464    }
2465    let rounding = 8.0 * f64::EPSILON * (x1.abs() + x2.abs() + z1.abs() + z2.abs() + r1 + r2);
2466    if dist > r1 + r2 + rounding || dist < (r1 - r2).abs() - rounding {
2467        return Some(Vec::new());
2468    }
2469    let along = r2.madd(-r2, r1.madd(r1, dist * dist)) / (2.0 * dist);
2470    let across = r1.madd(r1, -(along * along)).max(0.0).sqrt();
2471    let (ux, uz) = (dx / dist, dz / dist);
2472    let sides: &[f64] = if 2.0 * across <= Tolerance::new().linear {
2473        &[0.0]
2474    } else {
2475        &[1.0, -1.0]
2476    };
2477    let mut crossings = Vec::with_capacity(sides.len());
2478    for side in sides {
2479        let rho = x1 + along * ux - side * across * uz;
2480        if rho <= slack {
2481            return None;
2482        }
2483        crossings.push((rho, z1 + along * uz + side * across * ux));
2484    }
2485    Some(crossings)
2486}
2487
2488/// Exact circles as intersection curves, each sampled at 33 points that
2489/// carry both surfaces' parameters, and a lone touching point as a curve
2490/// that stays on it.
2491fn exact_circle_curves(
2492    exacts: Vec<ExactIntersectionCurve>,
2493    params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
2494) -> Result<Vec<IntersectionCurve>, MathError> {
2495    let mut curves = Vec::with_capacity(exacts.len());
2496    for exact in exacts {
2497        match exact {
2498            ExactIntersectionCurve::Circle(circle) => {
2499                let points = (0..=32)
2500                    .map(|i| {
2501                        let point = circle.evaluate(TAU * f64::from(i) / 32.0);
2502                        let (param1, param2) = params(point);
2503                        IntersectionPoint {
2504                            point,
2505                            param1,
2506                            param2,
2507                        }
2508                    })
2509                    .collect();
2510                let r = circle.radius();
2511                let curve = conic_loop(circle.center(), circle.u_axis(), circle.v_axis(), r, r)?;
2512                curves.push(IntersectionCurve { curve, points });
2513            }
2514            // A lone point is where the surfaces touch.
2515            ExactIntersectionCurve::Points(points) if points.len() == 1 => {
2516                let point = points[0];
2517                let (param1, param2) = params(point);
2518                curves.push(IntersectionCurve {
2519                    curve: interpolate(&[point, point], 1)?,
2520                    points: vec![IntersectionPoint {
2521                        point,
2522                        param1,
2523                        param2,
2524                    }],
2525                });
2526            }
2527            ExactIntersectionCurve::Ellipse(_) | ExactIntersectionCurve::Points(_) => {}
2528        }
2529    }
2530    Ok(curves)
2531}
2532
2533/// Circles about an axis through `base`, at the given `(rho, z)` crossings.
2534fn circles_about_axis(
2535    base: Point3,
2536    axis: Vec3,
2537    crossings: &[(f64, f64)],
2538) -> Result<Vec<ExactIntersectionCurve>, MathError> {
2539    crossings
2540        .iter()
2541        .map(|&(rho, z)| {
2542            Circle3D::new(base + axis * z, axis, rho).map(ExactIntersectionCurve::Circle)
2543        })
2544        .collect()
2545}
2546
2547/// Exact intersection of two tori sharing an axis: their tube cross-sections
2548/// in a half-plane through the axis cross in up to two points, and each sweeps
2549/// a circle about the axis.
2550///
2551/// Cross-sections that touch meet at one point, sweeping one circle. `None`
2552/// (defer to the marcher) unless the axes lie on one line, or when the
2553/// cross-sections coincide.
2554///
2555/// # Errors
2556///
2557/// Returns an error if a section circle cannot be built.
2558pub fn exact_torus_torus(
2559    first: &ToroidalSurface,
2560    second: &ToroidalSurface,
2561) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2562    let axis = first.z_axis();
2563    let scale = first.major_radius() + second.major_radius();
2564    let offset = second.center() - first.center();
2565    // A spindle torus's tube also crosses the far side of the axis.
2566    if first.minor_radius() >= first.major_radius()
2567        || second.minor_radius() >= second.major_radius()
2568        || axis.cross(second.z_axis()).length() > 1e-9
2569        || offset.cross(axis).length() > 1e-9 * scale
2570    {
2571        return Ok(None);
2572    }
2573    let Some(crossings) = meridian_crossings(
2574        (first.major_radius(), 0.0, first.minor_radius()),
2575        (
2576            second.major_radius(),
2577            offset.dot(axis),
2578            second.minor_radius(),
2579        ),
2580        scale,
2581    ) else {
2582        return Ok(None);
2583    };
2584    circles_about_axis(first.center(), axis, &crossings).map(Some)
2585}
2586
2587/// Exact intersection of a torus with a cylinder sharing its axis.
2588///
2589/// The wall line and the tube's cross-section in a half-plane through the
2590/// axis cross in up to two points, each sweeping a circle about the axis. A
2591/// wall touching the tube's outer equator, ring or spindle, or a ring torus's
2592/// inner equator meets it along the one circle at the torus's centre.
2593///
2594/// `None` (defer to the marcher) unless the axes lie on one line, or when
2595/// the wall reaches the part of a spindle torus's tube across the axis.
2596///
2597/// # Errors
2598///
2599/// Returns an error if a section circle cannot be built.
2600pub fn exact_cylinder_torus(
2601    cylinder: &CylindricalSurface,
2602    torus: &ToroidalSurface,
2603) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2604    let axis = torus.z_axis();
2605    let scale = torus.major_radius() + cylinder.radius();
2606    let offset = cylinder.origin() - torus.center();
2607    let linear = crate::tolerance::Tolerance::default().linear;
2608    if axis.cross(cylinder.axis()).length() > 1e-9
2609        || offset.cross(axis).length() > 1e-9 * scale
2610        || cylinder.radius() + torus.major_radius() <= torus.minor_radius() + linear
2611    {
2612        return Ok(None);
2613    }
2614    let gap = cylinder.radius() - torus.major_radius();
2615    let small = torus.minor_radius();
2616    // The equator circle lies on the torus within the wall's distance from
2617    // the tube, so it stands for the section while that distance is within
2618    // the linear tolerance, whatever the scale.
2619    if (gap.abs() - small).abs() <= linear {
2620        return circles_about_axis(torus.center(), axis, &[(cylinder.radius(), 0.0)]).map(Some);
2621    }
2622    if gap.abs() > small {
2623        return Ok(Some(Vec::new()));
2624    }
2625    let height = small.madd(small, -(gap * gap)).sqrt();
2626    circles_about_axis(
2627        torus.center(),
2628        axis,
2629        &[(cylinder.radius(), height), (cylinder.radius(), -height)],
2630    )
2631    .map(Some)
2632}
2633
2634/// Exact intersection of a torus with a sphere centred on its axis.
2635///
2636/// The sphere's great circle and the tube's cross-section in a half-plane
2637/// through the axis cross in up to two points, and each sweeps a circle
2638/// about the axis; where they touch (a ball sitting in the ring's hole or
2639/// on its rim) they meet along one circle. A sphere off the axis that
2640/// touches a ring torus at one point gives that point.
2641///
2642/// `None` (defer to the marcher) for a spindle torus, and for a sphere off
2643/// the axis that does not touch the torus at one point.
2644///
2645/// # Errors
2646///
2647/// Returns an error if a section circle cannot be built.
2648pub fn exact_sphere_torus(
2649    sphere: &SphericalSurface,
2650    torus: &ToroidalSurface,
2651) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2652    let axis = torus.z_axis();
2653    let scale = torus.major_radius() + sphere.radius();
2654    let offset = sphere.center() - torus.center();
2655    // A spindle torus's tube also crosses the far side of the axis.
2656    if torus.minor_radius() >= torus.major_radius() {
2657        return Ok(None);
2658    }
2659    if offset.cross(axis).length() > 1e-9 * scale {
2660        // A sphere centred on the core circle with the tube's own radius
2661        // holds the meridian circle through its centre, and the tube round
2662        // it: they meet along that circle alone. The circle strays from the
2663        // tube by the centre's distance from the core circle and the radii's
2664        // difference, which must both be rounding and within tolerance.
2665        let radial = offset - axis * offset.dot(axis);
2666        let slack = 64.0
2667            * f64::EPSILON
2668            * (torus.major_radius() + torus.minor_radius() + sphere.radius() + offset.length());
2669        let stray = (radial.length() - torus.major_radius()).hypot(offset.dot(axis))
2670            + (sphere.radius() - torus.minor_radius()).abs();
2671        if stray <= slack.min(Tolerance::new().linear) {
2672            let along = axis.cross(radial).normalize()?;
2673            return Ok(Some(vec![ExactIntersectionCurve::Circle(Circle3D::new(
2674                sphere.center(),
2675                along,
2676                sphere.radius(),
2677            )?)]));
2678        }
2679        return Ok(
2680            off_axis_touch(sphere, torus).map(|p| vec![ExactIntersectionCurve::Points(vec![p])])
2681        );
2682    }
2683    let Some(crossings) = meridian_crossings(
2684        (0.0, offset.dot(axis), sphere.radius()),
2685        (torus.major_radius(), 0.0, torus.minor_radius()),
2686        scale,
2687    ) else {
2688        return Ok(None);
2689    };
2690    circles_about_axis(torus.center(), axis, &crossings).map(Some)
2691}
2692
2693/// The fewest and most steps along each branch of a loop a sphere cuts from
2694/// a torus: its curve is fitted through them alone, so a small loop takes
2695/// enough to hold the fit to the section.
2696const SPHERE_TORUS_LOOP_SAMPLES: (f64, f64) = (128.0, 1024.0);
2697
2698/// The section a sphere off a ring torus's axis cuts from it. In the
2699/// torus's frame let the sphere's centre sit at `(a, b, h)`, with
2700/// `s = hypot(a, b)` and `phi = atan2(b, a)`. The torus's point at `(u, v)`,
2701/// with `ρ = R + r·cos v`, lies on the sphere of radius `q` when
2702/// `ρ² − 2ρs·cos(u − phi) + s² + (r·sin v − h)² = q²`, so at each `v`
2703/// `cos(u − phi) = (R² + r² + h² + s² − q² + 2Rr·cos v − 2hr·sin v) / (2s·ρ)`.
2704/// `None` for a spindle torus, whose `ρ` reaches zero, or a sphere on the
2705/// axis, whose sections are circles about it.
2706fn sphere_torus_section<'a>(
2707    sphere: &SphericalSurface,
2708    torus: &'a ToroidalSurface,
2709) -> Option<TorusSection<'a, impl Fn(Point3) -> f64>> {
2710    let (big, small, radius) = (torus.major_radius(), torus.minor_radius(), sphere.radius());
2711    let offset = sphere.center() - torus.center();
2712    let (a, b, h) = (
2713        offset.dot(torus.x_axis()),
2714        offset.dot(torus.y_axis()),
2715        offset.dot(torus.z_axis()),
2716    );
2717    let s = a.hypot(b);
2718    if small >= big || s <= 1e-9 * (big + radius) {
2719        return None;
2720    }
2721    let centre = sphere.center();
2722    Some(TorusSection {
2723        torus,
2724        phi: b.atan2(a),
2725        num: [
2726            big.madd(
2727                big,
2728                small.madd(small, h.madd(h, s.madd(s, -radius * radius))),
2729            ),
2730            2.0 * big * small,
2731            -2.0 * h * small,
2732        ],
2733        den: [2.0 * s * big, 2.0 * s * small],
2734        clearance: move |p: Point3| (p - centre).length() - radius,
2735        slack: 64.0 * f64::EPSILON * (big + small + radius + offset.length()),
2736    })
2737}
2738
2739/// How many times a loop's fitted curve may be refined where it strays.
2740const SPHERE_TORUS_FIT_ROUNDS: usize = 6;
2741
2742/// The curves a sphere off a ring torus's axis meets it in, each fitted
2743/// through the closed-form points of [`sphere_torus_section`] and every point
2744/// given its parameters on both surfaces, the sphere's first when
2745/// `sphere_first`. Halfway between each pair of points the curve must lie
2746/// within a quarter of the linear tolerance of both surfaces; where it
2747/// strays the section's own point there joins the fit. `None`, deferring to the marcher, for a
2748/// curve that still strays, or whose points do.
2749fn sphere_torus_curves(
2750    sphere: &SphericalSurface,
2751    torus: &ToroidalSurface,
2752    sphere_first: bool,
2753) -> Option<Vec<IntersectionCurve>> {
2754    let section = sphere_torus_section(sphere, torus)?;
2755    let tol = Tolerance::new().linear;
2756    let (big, small) = (torus.major_radius(), torus.minor_radius());
2757    // The centre's least and greatest distance to the torus: the ball meets
2758    // it whenever its radius lies between them. A section that comes out
2759    // empty for such a ball has lost its loops to rounding, so the marcher
2760    // takes it rather than the pair being called apart.
2761    let offset = sphere.center() - torus.center();
2762    let rise = offset.dot(torus.z_axis());
2763    let reach = (offset - torus.z_axis() * rise).length();
2764    let (nearest, farthest) = (
2765        ((reach - big).hypot(rise) - small).abs(),
2766        (reach + big).hypot(rise) + small,
2767    );
2768    let margin = 8.0 * f64::EPSILON * (big + small + offset.length() + sphere.radius());
2769    let crosses = sphere.radius() > nearest + margin && sphere.radius() < farthest - margin;
2770    let off = |p: Point3| {
2771        let local = p - torus.center();
2772        let (x, y, z) = (
2773            local.dot(torus.x_axis()),
2774            local.dot(torus.y_axis()),
2775            local.dot(torus.z_axis()),
2776        );
2777        let on_torus = (x.hypot(y) - big).hypot(z) - small;
2778        on_torus.abs().max((section.clearance)(p).abs())
2779    };
2780    // `acos` of a ratio near 1 loses digits a small ball on a large torus
2781    // needs, so each point steps onto the sphere across the section, along
2782    // the torus, the shortest way in its own measure.
2783    let centre = sphere.center();
2784    let polish = |q: IntersectionPoint| {
2785        let (mut u, mut v) = q.param1;
2786        let mut best = q;
2787        for _ in 0..4 {
2788            let gap = (section.clearance)(best.point);
2789            let (sin_u, cos_u) = u.sin_cos();
2790            let (sin_v, cos_v) = v.sin_cos();
2791            let rho = small.madd(cos_v, big);
2792            let outward = torus.x_axis() * cos_u + torus.y_axis() * sin_u;
2793            let p_u = (torus.y_axis() * cos_u - torus.x_axis() * sin_u) * rho;
2794            let p_v = outward * (-small * sin_v) + torus.z_axis() * (small * cos_v);
2795            let away = best.point - centre;
2796            let normal = away * (1.0 / away.length());
2797            let (g_u, g_v) = (normal.dot(p_u), normal.dot(p_v));
2798            let (w_u, w_v) = (g_u / (rho * rho), g_v / (small * small));
2799            let reach = g_u.madd(w_u, g_v * w_v);
2800            if reach <= f64::MIN_POSITIVE {
2801                break;
2802            }
2803            let next = section.point(gap.madd(-w_u / reach, u), gap.madd(-w_v / reach, v));
2804            if (section.clearance)(next.point).abs() >= gap.abs() {
2805                break;
2806            }
2807            (u, v) = next.param1;
2808            best = next;
2809        }
2810        best
2811    };
2812    let loops = section.loops(256, SPHERE_TORUS_LOOP_SAMPLES);
2813    if loops.is_empty() && crosses {
2814        return None;
2815    }
2816    let mut curves = Vec::new();
2817    for points in loops {
2818        let mut points: Vec<IntersectionPoint> = points.into_iter().map(polish).collect();
2819        if points.iter().any(|q| off(q.point) > tol) {
2820            return None;
2821        }
2822        // Samples past a turn that `acos` clamped onto the same `u` all step
2823        // to the turn itself.
2824        points.dedup_by(|b, a| (b.point - a.point).length() <= 1e-3 * tol);
2825        let mut rounds = 0;
2826        let curve = loop {
2827            let positions: Vec<Point3> = points.iter().map(|q| q.point).collect();
2828            let curve = interpolate(&positions, 3.min(positions.len() - 1)).ok()?;
2829            let params = crate::nurbs::fitting::chord_length_params(&positions);
2830            let strays: Vec<usize> = (0..positions.len() - 1)
2831                .filter(|&k| {
2832                    off(curve.evaluate(f64::midpoint(params[k], params[k + 1]))) > 0.25 * tol
2833                })
2834                .collect();
2835            if strays.is_empty() {
2836                break curve;
2837            }
2838            if rounds == SPHERE_TORUS_FIT_ROUNDS {
2839                return None;
2840            }
2841            rounds += 1;
2842            for &k in strays.iter().rev() {
2843                let mid = polish(section.between(points[k].param1, points[k + 1].param1));
2844                if off(mid.point) > tol {
2845                    return None;
2846                }
2847                points.insert(k + 1, mid);
2848            }
2849        };
2850        for q in &mut points {
2851            let (on_sphere, on_torus) = (sphere.project_point(q.point), q.param1);
2852            (q.param1, q.param2) = if sphere_first {
2853                (on_sphere, on_torus)
2854            } else {
2855                (on_torus, on_sphere)
2856            };
2857        }
2858        curves.push(IntersectionCurve { curve, points });
2859    }
2860    Some(curves)
2861}
2862
2863/// Where a sphere off a ring torus's axis touches it at one point: from
2864/// outside the tube, from inside it, or holding the whole ring. The touch
2865/// sits over the core circle's point nearest the sphere's centre, at
2866/// `d_near`, or farthest from it, at `d_far`, and the sphere's radius is
2867/// then `d_near − r`, `r − d_near` or `d_far + r`. Each is the centre's
2868/// least or greatest distance to the torus, so the point is all the two
2869/// share. `None` unless the radius matches one to rounding.
2870fn off_axis_touch(sphere: &SphericalSurface, torus: &ToroidalSurface) -> Option<Point3> {
2871    let axis = torus.z_axis();
2872    let (big, small, radius) = (torus.major_radius(), torus.minor_radius(), sphere.radius());
2873    let offset = sphere.center() - torus.center();
2874    let radial = offset - axis * offset.dot(axis);
2875    let out = radial * (1.0 / radial.length());
2876    let near = torus.center() + out * big;
2877    let far = torus.center() - out * big;
2878    let (to_near, to_far) = (sphere.center() - near, sphere.center() - far);
2879    let (d_near, d_far) = (to_near.length(), to_far.length());
2880    let slack = 64.0 * f64::EPSILON * (big + small + radius + offset.length());
2881    // A ball centred on the core circle meets the tube along a whole
2882    // meridian, not at a point.
2883    if d_near > slack
2884        && ((d_near - small - radius).abs() <= slack || (small - d_near - radius).abs() <= slack)
2885    {
2886        return Some(near + to_near * (small / d_near));
2887    }
2888    ((d_far + small - radius).abs() <= slack).then(|| far - to_far * (small / d_far))
2889}
2890
2891/// Exact coaxial cone-cone intersection: returns the shared circle.
2892///
2893/// Two cones that share an axis are concentric circles at every axial
2894/// station, so they meet only where their radii are equal. Each cone's
2895/// radius is linear in the axial coordinate `t` (measured along the shared
2896/// axis from cone 1's apex): `r1 = m1·t` and `r2 = m2·σ·(t − d2)`, where
2897/// `m_i = cot(half_angle_i)`, `σ = sign(axis2·axis1)`, and `d2` is cone 2's
2898/// apex position in that coordinate. Equating gives a single crossing `t*`
2899/// → one circle (the shared rim). The general marcher mishandles this case:
2900/// at the radii-crossing the surfaces are nearly tangent, so a grid-seeded
2901/// march fragments the clean circle into dozens of degenerate micro-curves.
2902///
2903/// Returns `Some(vec![circle])` for a genuine crossing, `Some(vec![])` when
2904/// the cones do not meet (parallel radius lines or a crossing on the wrong
2905/// nappe), and `None` for the identical-cone overlap or a degenerate
2906/// (near-flat) cone — both of which fall through to the general path.
2907/// Parallel-but-offset axes with equal half-angle tangents reduce to a
2908/// radical-plane conic (`offset_parallel_cone_cone`); other offset
2909/// configurations defer to the marcher with `None`.
2910///
2911/// # Errors
2912///
2913/// Returns [`MathError`] if the shared-rim `Circle3D` cannot be constructed
2914/// (e.g. a non-finite center or radius from a malformed cone).
2915pub fn exact_cone_cone(
2916    c1: &ConicalSurface,
2917    c2: &ConicalSurface,
2918) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2919    let axis = c1.axis();
2920    let axis2 = c2.axis();
2921
2922    // Coaxial check: parallel axes and the second apex lies on the first axis.
2923    if axis.dot(axis2).abs() < 1.0 - 1e-10 {
2924        return Ok(None); // Non-coaxial: quartic curve, let the marcher handle.
2925    }
2926    let apex1 = c1.apex();
2927    let apex2 = c2.apex();
2928    let delta = apex2 - apex1;
2929    let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
2930    let along = delta_v.dot(axis);
2931    if (delta_v - axis * along).length() > 1e-8 {
2932        return offset_parallel_cone_cone(c1, c2);
2933    }
2934
2935    let (s1, s2) = (c1.half_angle().sin(), c2.half_angle().sin());
2936    if s1.abs() < 1e-12 || s2.abs() < 1e-12 {
2937        return Ok(None); // Degenerate (near-flat) cone.
2938    }
2939    let m1 = c1.half_angle().cos() / s1;
2940    let m2 = c2.half_angle().cos() / s2;
2941    let sigma = if axis.dot(axis2) >= 0.0 { 1.0 } else { -1.0 };
2942    let d2 = along; // apex2 position along `axis`, measured from apex1.
2943
2944    let denom = m1 - m2 * sigma;
2945    if denom.abs() < 1e-12 {
2946        // Parallel radius lines: identical cones (coincident apex, same opening)
2947        // overlap — defer to the general/same-domain path; otherwise no meeting.
2948        if sigma > 0.0 && d2.abs() < 1e-9 {
2949            return Ok(None);
2950        }
2951        return Ok(Some(vec![]));
2952    }
2953
2954    let t_star = (-m2 * sigma * d2) / denom;
2955    let radius = m1 * t_star;
2956    if radius < 1e-12 {
2957        return Ok(Some(vec![])); // Crossing on the wrong nappe / no real circle.
2958    }
2959
2960    let center = Point3::new(
2961        apex1.x() + axis.x() * t_star,
2962        apex1.y() + axis.y() * t_star,
2963        apex1.z() + axis.z() * t_star,
2964    );
2965    let circle = Circle3D::new(center, axis, radius)?;
2966    Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
2967}
2968
2969/// Parallel-axis (or anti-parallel), offset-apex cones with equal half-angle
2970/// tangents: subtracting the two quadric equations cancels both the radial
2971/// and the axial quadratic terms (their coefficients depend only on
2972/// `tan²(half_angle)`), so every intersection point lies on a plane — the
2973/// degenerate member of the quadric pencil — and plane ∩ cone is an exact
2974/// conic. The gridfinity spacer lip fuse hits this exactly: opposed 45°
2975/// corner cones offset 0.25mm, which the marcher shreds into ~64 closed
2976/// micro-loops per pair (#1570). Unequal angles keep a genuine quadratic
2977/// term, and an unbounded section (hyperbola/parabola) has no closed-form
2978/// win over the marcher — both defer with `None`.
2979fn offset_parallel_cone_cone(
2980    c1: &ConicalSurface,
2981    c2: &ConicalSurface,
2982) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2983    if c1.half_angle().sin().abs() < 1e-12 || c2.half_angle().sin().abs() < 1e-12 {
2984        return Ok(None); // Degenerate (near-flat) cone, as in the coaxial path.
2985    }
2986    let t1 = c1.half_angle().tan();
2987    let t2 = c2.half_angle().tan();
2988    if !t1.is_finite() || !t2.is_finite() {
2989        return Ok(None);
2990    }
2991    if (t1 - t2).abs() > 1e-9 * (1.0 + t1.abs().max(t2.abs())) {
2992        return Ok(None);
2993    }
2994
2995    let w = c1.axis();
2996    let apex1 = c1.apex();
2997    let apex2 = c2.apex();
2998    let delta = apex2 - apex1;
2999    let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
3000    let s = delta_v.dot(w);
3001    let tm = 0.5 * (t1 + t2);
3002    let k = 1.0 + tm * tm;
3003
3004    // In the apex1 frame each cone is |P|² − k(P·w)² = 0 (shifted by δ for
3005    // cone 2; the axis SIGN drops out since only (P·w)² appears). Their
3006    // difference: P·(2δ − 2ksw) = |δ|² − ks².
3007    let n = (delta_v - w * (k * s)) * 2.0;
3008    let n_len = n.length();
3009    if n_len < 1e-12 {
3010        return Ok(None);
3011    }
3012    let n_hat = n * (1.0 / n_len);
3013    let d = (dot_np(n, apex1) + delta_v.dot(delta_v) - k * s * s) / n_len;
3014
3015    // `exact_plane_cone` already rejects sections on cone 1's phantom nappe;
3016    // cone 2's nappe must be checked here. A conic on the shared quadric
3017    // pencil cannot cross between nappes except exactly through apex 2, so
3018    // sampled quarter-points either all pass or all fail; a mixed verdict
3019    // means an apex-touching degeneracy — defer to the marcher.
3020    let axis2 = c2.axis();
3021    let scale = 1.0 + delta_v.length();
3022    let mut out = Vec::new();
3023    for curve in exact_plane_cone(c1, n_hat, d, 0.0)? {
3024        let samples: Vec<Point3> = match &curve {
3025            ExactIntersectionCurve::Circle(c) => (0..4)
3026                .map(|i| crate::traits::ParametricCurve::evaluate(c, TAU * f64::from(i) / 4.0))
3027                .collect(),
3028            ExactIntersectionCurve::Ellipse(e) => (0..4)
3029                .map(|i| crate::traits::ParametricCurve::evaluate(e, TAU * f64::from(i) / 4.0))
3030                .collect(),
3031            ExactIntersectionCurve::Points(_) => return Ok(None),
3032        };
3033        let on_real_nappe = |p: &Point3| {
3034            let rel = *p - apex2;
3035            Vec3::new(rel.x(), rel.y(), rel.z()).dot(axis2) >= -1e-9 * scale
3036        };
3037        let hits = samples.iter().filter(|p| on_real_nappe(p)).count();
3038        match hits {
3039            0 => {}
3040            4 => out.push(curve),
3041            _ => return Ok(None),
3042        }
3043    }
3044    Ok(Some(out))
3045}
3046
3047/// Exact coaxial cone-cylinder intersection: returns the shared circle.
3048///
3049/// A cone and a cylinder sharing an axis are concentric circles at every
3050/// axial station, so they meet only where the cone's radius equals the
3051/// cylinder's. The cone radius is linear in the axial coordinate `t` from its
3052/// apex (`r = m·t`, `m = cot(half_angle)`), the cylinder radius is the
3053/// constant `R`, so `m·t = R` gives a single crossing `t*` → one circle. This
3054/// is the gridfinity lip's top knife edge (inner tapered corner = cone, outer
3055/// corner = cylinder, concentric, radii matching at `Z_PEAK`); the general
3056/// marcher fragments that near-tangent contact into dozens of degenerate
3057/// micro-curves.
3058///
3059/// Returns `Some(vec![circle])` for a genuine crossing, `Some(vec![])` when
3060/// the crossing degenerates to the apex, and `None` (defer to the marcher)
3061/// when the surfaces are not coaxial or the cone is near-flat / near-axial.
3062///
3063/// # Errors
3064///
3065/// Returns [`MathError`] if the shared `Circle3D` cannot be constructed.
3066pub fn exact_cone_cylinder(
3067    cone: &ConicalSurface,
3068    cyl: &CylindricalSurface,
3069) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3070    let axis = cone.axis();
3071    let cyl_axis = cyl.axis();
3072
3073    // Coaxial check: parallel axes and the cone apex on the cylinder's axis.
3074    if axis.dot(cyl_axis).abs() < 1.0 - 1e-10 {
3075        return Ok(None);
3076    }
3077    let apex = cone.apex();
3078    let delta = apex - cyl.origin();
3079    let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
3080    let along = delta_v.dot(cyl_axis);
3081    if (delta_v - cyl_axis * along).length() > 1e-8 {
3082        return Ok(None);
3083    }
3084
3085    let s = cone.half_angle().sin();
3086    if s.abs() < 1e-12 {
3087        return Ok(None); // near-flat cone.
3088    }
3089    let m = cone.half_angle().cos() / s; // dr/dt along the cone axis.
3090    if m.abs() < 1e-12 {
3091        return Ok(None); // near-axial cone: radius ~constant.
3092    }
3093
3094    let t_star = cyl.radius() / m; // where the cone radius m·t equals R.
3095    if t_star.abs() < 1e-12 {
3096        return Ok(Some(vec![])); // crossing at the apex — no real circle.
3097    }
3098    let center = Point3::new(
3099        apex.x() + axis.x() * t_star,
3100        apex.y() + axis.y() * t_star,
3101        apex.z() + axis.z() * t_star,
3102    );
3103    let circle = Circle3D::new(center, axis, cyl.radius())?;
3104    Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
3105}
3106
3107/// The exact rational quadratic NURBS of the full ellipse `centre +
3108/// a·cos(t)·u + b·sin(t)·v` (a circle when `a == b`), starting at
3109/// `centre + a·u`: four quarter arcs, each with its corner weighted by
3110/// cos 45°.
3111fn conic_loop(centre: Point3, u: Vec3, v: Vec3, a: f64, b: f64) -> Result<NurbsCurve, MathError> {
3112    let w = std::f64::consts::FRAC_1_SQRT_2;
3113    let corners: [(f64, f64); 9] = [
3114        (1.0, 0.0),
3115        (1.0, 1.0),
3116        (0.0, 1.0),
3117        (-1.0, 1.0),
3118        (-1.0, 0.0),
3119        (-1.0, -1.0),
3120        (0.0, -1.0),
3121        (1.0, -1.0),
3122        (1.0, 0.0),
3123    ];
3124    let points = corners
3125        .iter()
3126        .map(|&(x, y)| centre + u * (a * x) + v * (b * y))
3127        .collect();
3128    let weights = vec![1.0, w, 1.0, w, 1.0, w, 1.0, w, 1.0];
3129    let knots = vec![
3130        0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0,
3131    ];
3132    NurbsCurve::new(2, knots, points, weights)
3133}
3134
3135/// Two cones sharing an apex meet only along rulings through it. A
3136/// ruling's direction `d` makes each cone's angle with its axis, `d·aᵢ =
3137/// ±sin(half_angleᵢ)` (the half-angle runs from the radial plane), a line
3138/// that crosses the unit sphere twice, touches it where the cones are
3139/// tangent along one ruling, or misses it. Along `apex + t·d` the first
3140/// cone's `v` is `t` and the second's `±t`, so each ruling runs where both
3141/// faces' `v` ranges hold it, as a straight segment cut at the apex. Two
3142/// rulings closer than the linear tolerance across the faces are one.
3143///
3144/// `None` unless both ranges are given, the axes are not parallel (the
3145/// coaxial path's case), and the apexes coincide to rounding.
3146fn shared_apex_cones(
3147    c1: &ConicalSurface,
3148    c2: &ConicalSurface,
3149    v1: Option<(f64, f64)>,
3150    v2: Option<(f64, f64)>,
3151) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3152    let (Some(v1), Some(v2)) = (v1, v2) else {
3153        return Ok(None);
3154    };
3155    let (a1, a2, apex) = (c1.axis(), c2.axis(), c1.apex());
3156    let across = a1.cross(a2);
3157    let sin = across.length();
3158    if sin < 1e-9 {
3159        return Ok(None);
3160    }
3161    let reach = v1.0.abs().max(v1.1.abs()).max(v2.0.abs()).max(v2.1.abs());
3162    let scale = reach.max((apex - Point3::new(0.0, 0.0, 0.0)).length());
3163    if (c2.apex() - apex).length() > 64.0 * f64::EPSILON * scale {
3164        return Ok(None);
3165    }
3166    let normal = across * (1.0 / sin);
3167    let tol = Tolerance::new().linear;
3168    // A ruling's part across the first axis is `(t2 − s1·cos) / sin`, whose
3169    // rounding grows as the axes close up; past a tenth of the tolerance
3170    // over the faces, the pair is left to the marcher.
3171    if f64::EPSILON * reach > 0.1 * tol * sin {
3172        return Ok(None);
3173    }
3174    // The second axis's part across the first, a unit vector.
3175    let toward = normal.cross(a1);
3176    let cos = a1.dot(a2);
3177    let (s1, s2) = (c1.half_angle().sin(), c2.half_angle().sin());
3178    // `evaluate` turns its radial direction round for negative `v`.
3179    let params = |cone: &ConicalSurface, p: Point3| {
3180        let (u, v) = cone.project_point(p);
3181        if v < 0.0 {
3182            ((u + std::f64::consts::PI).rem_euclid(TAU), v)
3183        } else {
3184            (u, v)
3185        }
3186    };
3187    let mut curves = Vec::new();
3188    for nappe in [1.0, -1.0] {
3189        let t2 = nappe * s2;
3190        let side = cos.madd(-s1, t2) / sin;
3191        let foot = a1 * s1 + toward * side;
3192        let lift_sq = s1.madd(-s1, side.madd(-side, 1.0));
3193        let rounding = 4.0 * f64::EPSILON;
3194        let lifts = if lift_sq.abs() <= rounding {
3195            // Within rounding of touching: the rulings that rounding could
3196            // hide part by up to `√(2·rounding)` radians, taken as one while
3197            // that stays within ten tolerances over the faces, and beyond
3198            // it not settled here.
3199            if (2.0 * rounding).sqrt() * reach > 10.0 * tol {
3200                return Ok(None);
3201            }
3202            vec![0.0]
3203        } else if lift_sq < 0.0 {
3204            Vec::new()
3205        } else if 2.0 * lift_sq.sqrt() * reach <= tol {
3206            vec![0.0]
3207        } else {
3208            vec![lift_sq.sqrt(), -lift_sq.sqrt()]
3209        };
3210        let along2 = if nappe > 0.0 { v2 } else { (-v2.1, -v2.0) };
3211        let (lo, hi) = (v1.0.max(along2.0), v1.1.min(along2.1));
3212        if hi - lo <= tol {
3213            continue;
3214        }
3215        for lift in lifts {
3216            let d = (foot + normal * lift).normalize()?;
3217            let pieces = if lo < 0.0 && hi > 0.0 {
3218                vec![(lo, 0.0), (0.0, hi)]
3219            } else {
3220                vec![(lo, hi)]
3221            };
3222            for (from, to) in pieces {
3223                curves.push(ruling_segment(apex + d * from, apex + d * to, |p| {
3224                    (params(c1, p), params(c2, p))
3225                })?);
3226            }
3227        }
3228    }
3229    Ok(Some(curves))
3230}
3231
3232/// Two cylinders of one radius whose axes cross meet in two ellipses, one
3233/// in each plane through the crossing that bisects the axes: a point lies
3234/// as far from both axes where its offsets along them are equal or
3235/// opposite. Both ellipses have their minor axis, of the radius, along the
3236/// axes' common normal, and meet at its two ends. They come back as two
3237/// closed loops, as the first cylinder's rulings pair them: the halves of
3238/// both ellipses on one side of the crossing along its axis, then on the
3239/// other, each exact, rational, and cornered where its halves meet. One
3240/// loop starts at each end of the common normal.
3241///
3242/// `None` unless the radii match and the axes cross to rounding: axes that
3243/// miss by `δ` part the curves at the crossings by about `√(δ·r)`.
3244fn crossing_equal_cylinders(
3245    c1: &CylindricalSurface,
3246    c2: &CylindricalSurface,
3247) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3248    let (d1, d2, r) = (c1.axis(), c2.axis(), c1.radius());
3249    if (c2.radius() - r).abs() > 8.0 * f64::EPSILON * r {
3250        return Ok(None);
3251    }
3252    // An ellipse's semi-major axis is `2r / |d1 ∓ d2|`. Rounding the axes
3253    // turns its major axis by about `ε / |d1 ∓ d2|`, which moves its far
3254    // vertices by `2rε / |d1 ∓ d2|²`; axes nearer parallel than keeps that
3255    // well inside the tolerance are left to the rulings.
3256    let bisectors = [d1 - d2, d1 + d2];
3257    let tol = Tolerance::new().linear;
3258    if bisectors
3259        .iter()
3260        .any(|b| 2.0 * r * f64::EPSILON > 1e-3 * tol * b.dot(*b))
3261    {
3262        return Ok(None);
3263    }
3264    let across = d1.cross(d2);
3265    let sin = across.length();
3266    let normal = across * (1.0 / sin);
3267    let w = c1.origin() - c2.origin();
3268    let cos = d1.dot(d2);
3269    let along = cos.madd(d2.dot(w), -d1.dot(w)) / (sin * sin);
3270    let centre = c1.origin() + d1 * along;
3271    // The miss is read at the crossing's own scale: origins far along
3272    // their axes leave it more rounding than that, and are left to the
3273    // rulings too.
3274    let scale = r.max((centre - Point3::new(0.0, 0.0, 0.0)).length());
3275    if w.dot(normal).abs() > 64.0 * f64::EPSILON * scale {
3276        return Ok(None);
3277    }
3278    // Each ellipse's major axis, turned to lean along the first axis, and
3279    // its semi-major axis.
3280    let majors = bisectors.map(|bisector| {
3281        let length = bisector.length();
3282        let major = (bisector * (1.0 / length)).cross(normal);
3283        let major = if major.dot(d1) < 0.0 { -major } else { major };
3284        (major, 2.0 * r / length)
3285    });
3286    let corner = std::f64::consts::FRAC_1_SQRT_2;
3287    let half = [(1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0)];
3288    let mut curves = Vec::with_capacity(2);
3289    for side in [1.0, -1.0] {
3290        let [(m1, a1), (m2, a2)] = majors;
3291        let out = half
3292            .iter()
3293            .map(|&(x, y)| centre + normal * (side * r * x) + m1 * (side * a1 * y));
3294        let back = half[1..]
3295            .iter()
3296            .map(|&(x, y)| centre - normal * (side * r * x) + m2 * (side * a2 * y));
3297        let curve = NurbsCurve::new(
3298            2,
3299            vec![
3300                0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0,
3301            ],
3302            out.chain(back).collect(),
3303            vec![1.0, corner, 1.0, corner, 1.0, corner, 1.0, corner, 1.0],
3304        )?;
3305        #[allow(clippy::cast_precision_loss)]
3306        let points = (0..=32)
3307            .map(|i| {
3308                let point = curve.evaluate(i as f64 / 32.0);
3309                IntersectionPoint {
3310                    point,
3311                    param1: c1.project_point(point),
3312                    param2: c2.project_point(point),
3313                }
3314            })
3315            .collect();
3316        curves.push(IntersectionCurve { curve, points });
3317    }
3318    Ok(Some(curves))
3319}
3320
3321/// Algebraic cone-cone intersection (NURBS form for the general bounded
3322/// path). Delegates to [`exact_cone_cone`] and returns each exact conic
3323/// (coaxial circle or offset-parallel radical-plane ellipse) as an exact
3324/// rational NURBS `IntersectionCurve` with sample points along it, mirroring
3325/// the sphere-cylinder algebraic path. phase FF prefers the exact circle form
3326/// directly (so the section edge links to the coincident boundary), but a
3327/// caller of `intersect_analytic_analytic_bounded` still gets one clean
3328/// curve instead of the marcher's fragments.
3329fn algebraic_cone_cone(
3330    c1: &ConicalSurface,
3331    c2: &ConicalSurface,
3332) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3333    let Some(exacts) = exact_cone_cone(c1, c2)? else {
3334        return Ok(None);
3335    };
3336    let mut curves = Vec::new();
3337    for exact in exacts {
3338        let n_samples = 33;
3339        let mut points = Vec::with_capacity(n_samples);
3340        #[allow(clippy::cast_precision_loss)]
3341        for i in 0..n_samples {
3342            let theta = TAU * i as f64 / (n_samples - 1) as f64;
3343            let pt = match &exact {
3344                ExactIntersectionCurve::Circle(circle) => {
3345                    crate::traits::ParametricCurve::evaluate(circle, theta)
3346                }
3347                ExactIntersectionCurve::Ellipse(ellipse) => {
3348                    crate::traits::ParametricCurve::evaluate(ellipse, theta)
3349                }
3350                ExactIntersectionCurve::Points(_) => break,
3351            };
3352            points.push(IntersectionPoint {
3353                point: pt,
3354                param1: (0.0, 0.0),
3355                param2: (0.0, 0.0),
3356            });
3357        }
3358        let curve = match &exact {
3359            ExactIntersectionCurve::Circle(c) => {
3360                conic_loop(c.center(), c.u_axis(), c.v_axis(), c.radius(), c.radius())?
3361            }
3362            ExactIntersectionCurve::Ellipse(e) => conic_loop(
3363                e.center(),
3364                e.u_axis(),
3365                e.v_axis(),
3366                e.semi_major(),
3367                e.semi_minor(),
3368            )?,
3369            ExactIntersectionCurve::Points(_) => continue,
3370        };
3371        curves.push(IntersectionCurve { curve, points });
3372    }
3373    Ok(Some(curves))
3374}
3375
3376/// Exact coaxial sphere-cylinder intersection: returns the shared circle(s).
3377///
3378/// A sphere of radius `R` centered at `C` and a cylinder of radius `r` whose
3379/// axis passes through `C` meet in concentric circles of radius `r` at the
3380/// axial stations where `sqrt(R² − z²) = r`, i.e. `z = ±sqrt(R² − r²)`
3381/// measured from `C` along the axis. A proper crossing yields two circles; a
3382/// tangent contact (`r = R`) yields one; a cylinder wider than the sphere, or
3383/// a non-coaxial configuration (quartic curve), yields none/defers.
3384///
3385/// Mirrors [`exact_cone_cylinder`] so phase FF can emit the section as an
3386/// exact `Circle3D` (which the closed-circle split + seam adoption recognise)
3387/// rather than the marcher's NURBS fragments.
3388///
3389/// Returns `Some(vec![..])` (0, 1, or 2 circles) for the coaxial case, and
3390/// `None` (defer to the general marcher) when the axes are not coaxial.
3391///
3392/// # Errors
3393///
3394/// Returns [`MathError`] if a shared `Circle3D` cannot be constructed.
3395pub fn exact_sphere_cylinder(
3396    sphere: &SphericalSurface,
3397    cyl: &CylindricalSurface,
3398) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3399    let sc = sphere.center();
3400    let r_sphere = sphere.radius();
3401    let co = cyl.origin();
3402    let axis = cyl.axis();
3403    let r_cyl = cyl.radius();
3404
3405    // Project sphere center onto the cylinder axis.
3406    let delta = sc - co;
3407    let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
3408    let along = delta_vec.dot(axis);
3409    let perp_vec = delta_vec - axis * along;
3410    let d_perp = perp_vec.length();
3411
3412    // Non-coaxial sphere-cylinder intersections produce quartic curves;
3413    // defer those to the general marcher.
3414    if d_perp > 1e-7 {
3415        return Ok(None);
3416    }
3417
3418    // Coaxial: the sphere center lies on the cylinder axis. No real circle
3419    // when the cylinder is wider than the sphere or they are tangent-internal.
3420    if r_cyl > r_sphere + 1e-10 {
3421        return Ok(Some(vec![]));
3422    }
3423    let z_sq = r_sphere * r_sphere - r_cyl * r_cyl;
3424    if z_sq < 0.0 {
3425        return Ok(Some(vec![]));
3426    }
3427    let z = z_sq.sqrt();
3428
3429    // The sphere center projected onto the axis is the midpoint of the two
3430    // section circles, each offset by ±z along the axis with radius `r_cyl`.
3431    let center_axis_pt = Point3::new(
3432        co.x() + axis.x() * along,
3433        co.y() + axis.y() * along,
3434        co.z() + axis.z() * along,
3435    );
3436
3437    let mut circles = Vec::new();
3438    let offsets: &[f64] = if z < 1e-10 { &[0.0] } else { &[z, -z] };
3439    for &z_offset in offsets {
3440        let center = Point3::new(
3441            center_axis_pt.x() + axis.x() * z_offset,
3442            center_axis_pt.y() + axis.y() * z_offset,
3443            center_axis_pt.z() + axis.z() * z_offset,
3444        );
3445        let circle = Circle3D::new(center, axis, r_cyl)?;
3446        circles.push(ExactIntersectionCurve::Circle(circle));
3447    }
3448    Ok(Some(circles))
3449}
3450
3451/// Exact coaxial cone-sphere intersection: the shared circles.
3452///
3453/// When the cone's axis runs through the sphere's centre `C`, every generator
3454/// `apex + v g` (`g` a unit direction, `v` the distance from the apex) has
3455/// the same `h = g·(apex − C)`, so all of them meet the sphere at the same
3456/// roots of `v² + 2hv + |apex − C|² − R² = 0`. Each root ahead of the apex is
3457/// a circle of radius `v cos a` at `v sin a` along the axis: two for a ball
3458/// the cone passes through, one for a ball that swallows the apex, passes
3459/// through it or touches the wall, none for a ball the cone misses or that
3460/// sits inside it clear of the wall.
3461///
3462/// Returns `Some(vec![..])` for a coaxial pair and `None` (the ruling trace
3463/// or the marcher) otherwise.
3464///
3465/// # Errors
3466///
3467/// Returns [`MathError`] if a shared `Circle3D` cannot be constructed.
3468pub fn exact_cone_sphere(
3469    cone: &ConicalSurface,
3470    sphere: &SphericalSurface,
3471) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3472    let offset = cone.apex() - sphere.center();
3473    let along = offset.dot(cone.axis());
3474    if (offset - cone.axis() * along).length() > 1e-7 {
3475        return Ok(None);
3476    }
3477    let lin_tol = Tolerance::new().linear;
3478    let (sin_a, cos_a) = cone.half_angle().sin_cos();
3479    let (far_sq, radius_sq) = (offset.dot(offset), sphere.radius() * sphere.radius());
3480    let b = 2.0 * sin_a * along;
3481    let (disc, far, near) = ruling_quadratic(1.0, b, far_sq - radius_sq);
3482    // At a tangent ball `b² − 4c` cancels to a few ulps of its terms, which
3483    // can land below zero: that is a touch, not a miss.
3484    let noise = 16.0 * f64::EPSILON * 4.0f64.madd(far_sq + radius_sq, b * b);
3485    if disc < -noise {
3486        return Ok(Some(vec![]));
3487    }
3488    let roots: &[f64] = if far - near < lin_tol {
3489        &[far]
3490    } else {
3491        &[near, far]
3492    };
3493    let mut circles = Vec::new();
3494    for &v in roots {
3495        if v * cos_a > lin_tol {
3496            let centre = cone.apex() + cone.axis() * (v * sin_a);
3497            let circle = Circle3D::new(centre, cone.axis(), v * cos_a)?;
3498            circles.push(ExactIntersectionCurve::Circle(circle));
3499        }
3500    }
3501    Ok(Some(circles))
3502}
3503
3504/// Algebraic sphere-cylinder intersection (NURBS form for the general bounded
3505/// path). A coaxial pair delegates to [`exact_sphere_cylinder`] and returns
3506/// each exact circle as an exact rational NURBS `IntersectionCurve`. phase FF
3507/// prefers the exact circle form directly (so the section edge links to the
3508/// coincident boundary and the closed-circle splitter can carve the spherical
3509/// band), but a caller of `intersect_analytic_analytic_bounded` still gets
3510/// clean curves instead of the marcher's fragments. Any other pair is traced
3511/// along the cylinder's rulings ([`off_axis_sphere_cylinder`]).
3512fn algebraic_sphere_cylinder(
3513    sphere: &SphericalSurface,
3514    cyl: &CylindricalSurface,
3515    sphere_first: bool,
3516) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3517    let Some(exacts) = exact_sphere_cylinder(sphere, cyl)? else {
3518        return Ok(off_axis_sphere_cylinder(sphere, cyl, sphere_first));
3519    };
3520
3521    let mut curves = Vec::new();
3522    for exact in exacts {
3523        let ExactIntersectionCurve::Circle(circle) = exact else {
3524            continue;
3525        };
3526        let n_samples = 33;
3527        let mut points = Vec::with_capacity(n_samples);
3528        #[allow(clippy::cast_precision_loss)]
3529        for i in 0..n_samples {
3530            let theta = TAU * i as f64 / (n_samples - 1) as f64;
3531            let pt = crate::traits::ParametricCurve::evaluate(&circle, theta);
3532            let (param1, param2) = in_order(
3533                sphere.project_point(pt),
3534                cyl.project_point(pt),
3535                sphere_first,
3536            );
3537            points.push(IntersectionPoint {
3538                point: pt,
3539                param1,
3540                param2,
3541            });
3542        }
3543        let r = circle.radius();
3544        let curve = conic_loop(circle.center(), circle.u_axis(), circle.v_axis(), r, r)?;
3545        curves.push(IntersectionCurve { curve, points });
3546    }
3547
3548    Ok(Some(curves))
3549}
3550
3551/// A sphere and a cylinder whose axis misses the sphere's centre (a drill
3552/// entering a ball off its axis), traced along the cylinder's rulings: the
3553/// ruling `c(u) + v·a` meets the sphere where `v² + 2(q·a)·v + |q|² − R² = 0`,
3554/// with `q = c(u) − C`. When every ruling meets the sphere (the cylinder
3555/// passes wholly through it) the roots trace an entry and an exit loop;
3556/// otherwise each window of meeting rulings carries one loop. `Some(empty)`
3557/// when the two cannot meet, `None` when the sampling misses a window
3558/// narrower than itself.
3559fn off_axis_sphere_cylinder(
3560    sphere: &SphericalSurface,
3561    cyl: &CylindricalSurface,
3562    sphere_first: bool,
3563) -> Option<Vec<IntersectionCurve>> {
3564    let (centre, radius) = (sphere.center(), sphere.radius());
3565    let axis = cyl.axis();
3566    let offset = centre - cyl.origin();
3567    let axis_distance = (offset - axis * offset.dot(axis)).length();
3568    let lin_tol = Tolerance::new().linear;
3569    if axis_distance > radius + cyl.radius() + lin_tol
3570        || axis_distance + radius < cyl.radius() - lin_tol
3571    {
3572        return Some(Vec::new());
3573    }
3574    let roots = |u: f64| {
3575        let q = cyl.evaluate(u, 0.0) - centre;
3576        ruling_quadratic(1.0, 2.0 * q.dot(axis), q.dot(q) - radius * radius)
3577    };
3578    let samples = ruling_samples(cyl, &roots);
3579    let loops = if samples.iter().all(Option::is_some) {
3580        closed_ruling_loops(cyl, &roots, &samples)
3581    } else {
3582        partial_ruling_loops(cyl, &roots, &samples)
3583    };
3584    if loops.is_empty() {
3585        return None;
3586    }
3587    Some(fit_ruling_loops(&loops, |p| {
3588        in_order(sphere.project_point(p), cyl.project_point(p), sphere_first)
3589    }))
3590}
3591
3592/// Parameters on the pair's first and second surfaces, from those on `a`
3593/// and `b` and whether `a` came first.
3594const fn in_order(a: (f64, f64), b: (f64, f64), a_first: bool) -> ((f64, f64), (f64, f64)) {
3595    if a_first { (a, b) } else { (b, a) }
3596}
3597
3598/// Two cylinders whose axes are parallel but apart meet along rulings:
3599/// every plane across the axes cuts them in two circles `d` apart, which
3600/// cross in two points, touch in one, or miss, alike in every plane. Each
3601/// crossing sweeps a ruling, cut to the stretch of axis both faces' `v`
3602/// ranges share. Two crossings closer than the linear tolerance are the one
3603/// where the circles touch, side by side or one inside the other. `None`
3604/// (the next solver's case) when neither range is known, since a ruling has
3605/// no ends of its own, or when a ruling's end strays off the second
3606/// cylinder, its axis leaning off the first's by more than the span allows.
3607fn parallel_cylinders(
3608    c1: &CylindricalSurface,
3609    c2: &CylindricalSurface,
3610    v_range_1: Option<(f64, f64)>,
3611    v_range_2: Option<(f64, f64)>,
3612) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3613    let axis = c1.axis();
3614    let delta = c2.origin() - c1.origin();
3615    let along = delta.dot(axis);
3616    let across = delta - axis * along;
3617    let d = across.length();
3618    let (r1, r2) = (c1.radius(), c2.radius());
3619    // The second face's range, measured along the first one's axis.
3620    let flip = c2.axis().dot(axis);
3621    let ranges = [
3622        v_range_1,
3623        v_range_2.map(|(a, b)| (along + a * flip, along + b * flip)),
3624    ];
3625    let (lo, hi) = ranges
3626        .into_iter()
3627        .flatten()
3628        .fold((f64::NEG_INFINITY, f64::INFINITY), |(lo, hi), (a, b)| {
3629            (lo.max(a.min(b)), hi.min(a.max(b)))
3630        });
3631    if !lo.is_finite() || !hi.is_finite() {
3632        return Ok(None);
3633    }
3634    let rounding = 8.0 * f64::EPSILON * (r1 + r2 + d);
3635    if d > r1 + r2 + rounding || d < (r1 - r2).abs() - rounding || hi <= lo {
3636        return Ok(Some(Vec::new()));
3637    }
3638    let toward = across * (1.0 / d);
3639    let side = axis.cross(toward);
3640    let x = r2.madd(-r2, d.madd(d, r1 * r1)) / (2.0 * d);
3641    let y = r1.madd(r1, -(x * x)).max(0.0).sqrt();
3642    let linear = Tolerance::new().linear;
3643    let feet = if 2.0 * y <= linear {
3644        vec![toward * x]
3645    } else {
3646        vec![toward * x + side * y, toward * x - side * y]
3647    };
3648    let on_second = |p: Point3| {
3649        let w = p - c2.origin();
3650        ((w - c2.axis() * w.dot(c2.axis())).length() - r2).abs() <= linear
3651    };
3652    let mut rulings = Vec::with_capacity(feet.len());
3653    for foot in feet {
3654        let base = c1.origin() + foot;
3655        let (from, to) = (base + axis * lo, base + axis * hi);
3656        if !on_second(from) || !on_second(to) {
3657            return Ok(None);
3658        }
3659        rulings.push(ruling_segment(from, to, |p| {
3660            (c1.project_point(p), c2.project_point(p))
3661        })?);
3662    }
3663    Ok(Some(rulings))
3664}
3665
3666/// A straight intersection curve from `from` to `to`, carrying its ends and
3667/// middle as points.
3668fn ruling_segment(
3669    from: Point3,
3670    to: Point3,
3671    params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
3672) -> Result<IntersectionCurve, MathError> {
3673    let curve = NurbsCurve::new(1, vec![0.0, 0.0, 1.0, 1.0], vec![from, to], vec![1.0, 1.0])?;
3674    let points = [from, from + (to - from) * 0.5, to]
3675        .into_iter()
3676        .map(|point| {
3677            let (param1, param2) = params(point);
3678            IntersectionPoint {
3679                point,
3680                param1,
3681                param2,
3682            }
3683        })
3684        .collect();
3685    Ok(IntersectionCurve { curve, points })
3686}
3687
3688/// Algebraic cylinder-cylinder intersection for non-coaxial cylinders.
3689///
3690/// For two cylinders with axes that are NOT parallel, the intersection
3691/// consists of up to two closed space curves. These are found by
3692/// parameterizing one cylinder's angular coordinate `u ∈ [0, 2π]` and
3693/// solving a quadratic in the axial parameter `v` to find where each
3694/// "ring" of cylinder A sits on cylinder B.
3695///
3696/// The quadratic is:
3697///   `v²·(1 - α²) + 2v·(q·a₁ - α·q·a₂) + (|q|² - (q·a₂)² - r₂²) = 0`
3698/// where `α = a₁·a₂`, `q(u)` is the radial point on cylinder 1 minus
3699/// cylinder 2's origin, `a₁`/`a₂` are the cylinder axes, and `r₂` is
3700/// cylinder 2's radius.
3701#[allow(clippy::too_many_lines, clippy::unnecessary_wraps)]
3702fn algebraic_cylinder_cylinder(
3703    c1: &CylindricalSurface,
3704    c2: &CylindricalSurface,
3705) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3706    if let Some(halves) = crossing_equal_cylinders(c1, c2)? {
3707        return Ok(Some(halves));
3708    }
3709    let alpha = c1.axis().dot(c2.axis());
3710    let a_coeff = 1.0 - alpha * alpha;
3711
3712    // Should only be called for non-parallel axes.
3713    if a_coeff.abs() < 1e-12 {
3714        return Ok(None);
3715    }
3716
3717    let r1 = c1.radius();
3718    let r2 = c2.radius();
3719    let o1 = c1.origin();
3720    let o2 = c2.origin();
3721    let a1 = c1.axis();
3722    let a2 = c2.axis();
3723
3724    // Separation check: distance between axes vs sum of radii.
3725    // Closest approach of two skew lines:
3726    let delta = Vec3::new(o1.x() - o2.x(), o1.y() - o2.y(), o1.z() - o2.z());
3727    let cross = a1.cross(a2);
3728    let cross_len = cross.length();
3729    if cross_len > 1e-12 {
3730        let axis_dist = delta.dot(cross).abs() / cross_len;
3731        if axis_dist > r1 + r2 + Tolerance::new().linear {
3732            return Ok(Some(vec![])); // No intersection
3733        }
3734    }
3735
3736    // Solve every ruling of one cylinder against the other. When EVERY
3737    // ruling of the swept cylinder meets the other (the thinner of two
3738    // crossing tubes), the two roots trace the curve's two closed loops.
3739    // Swept the other way only a window of rulings meets, and each root
3740    // traces an open arc of one loop.
3741    let roots = |sweep: &CylindricalSurface, other: &CylindricalSurface| {
3742        let (o, a, radius) = (other.origin(), other.axis(), other.radius());
3743        let alpha = sweep.axis().dot(a);
3744        let quad = 1.0 - alpha * alpha;
3745        let (axis, sweep) = (sweep.axis(), sweep.clone());
3746        move |u: f64| {
3747            let q = sweep.evaluate(u, 0.0) - o;
3748            let (q_a1, q_a2) = (q.dot(axis), q.dot(a));
3749            let b = 2.0 * (q_a1 - alpha * q_a2);
3750            let c = q.dot(q) - q_a2 * q_a2 - radius * radius;
3751            ruling_quadratic(quad, b, c)
3752        }
3753    };
3754    let (roots1, roots2) = (roots(c1, c2), roots(c2, c1));
3755    let samples1 = ruling_samples(c1, &roots1);
3756    let loops = if samples1.iter().all(Option::is_some) {
3757        closed_ruling_loops(c1, &roots1, &samples1)
3758    } else {
3759        let samples2 = ruling_samples(c2, &roots2);
3760        if samples2.iter().all(Option::is_some) {
3761            closed_ruling_loops(c2, &roots2, &samples2)
3762        } else if samples1.iter().any(Option::is_some) {
3763            partial_ruling_loops(c1, &roots1, &samples1)
3764        } else {
3765            partial_ruling_loops(c2, &roots2, &samples2)
3766        }
3767    };
3768    if loops.is_empty() {
3769        return Ok(None);
3770    }
3771    Ok(Some(fit_ruling_loops(&loops, |p| {
3772        (c1.project_point(p), c2.project_point(p))
3773    })))
3774}
3775
3776/// A cone and a cylinder whose axes are not parallel, traced along the
3777/// cylinder's rulings. A ruling `q + t w` meets the cone's double quadric
3778/// `|p - apex|^2 = h^2 / sin^2(half_angle)`, with `h` the offset along the
3779/// cone's axis, where a quadratic in `t` vanishes. `None` (the marcher's
3780/// case) when a ruling meets the far nappe, where no cone face lies, when
3781/// the rulings run along the cone's generators, or when no ruling meets it.
3782fn ruling_cone_cylinder(
3783    cone: &ConicalSurface,
3784    cyl: &CylindricalSurface,
3785    cone_first: bool,
3786) -> Option<Vec<IntersectionCurve>> {
3787    let (sin_t, cos_t) = cone.half_angle().sin_cos();
3788    if sin_t < 1e-12 || cos_t < 1e-12 {
3789        return None;
3790    }
3791    let (apex, d, w) = (cone.apex(), cone.axis(), cyl.axis());
3792    let s = 1.0 / (sin_t * sin_t);
3793    let alpha = w.dot(d);
3794    let quad = 1.0 - s * alpha * alpha;
3795    if quad.abs() < 1e-9 {
3796        return None;
3797    }
3798    let roots = |u: f64| {
3799        let delta = cyl.evaluate(u, 0.0) - apex;
3800        let (dd, dw) = (delta.dot(d), delta.dot(w));
3801        let b = 2.0 * (dw - s * dd * alpha);
3802        let c = delta.dot(delta) - s * dd * dd;
3803        ruling_quadratic(quad, b, c)
3804    };
3805    let lin_tol = Tolerance::new().linear;
3806    let far_nappe = (0..WINDOW_SCAN * RULING_SAMPLES).any(|k| {
3807        #[allow(clippy::cast_precision_loss)]
3808        let u = TAU * (k as f64 + 0.5) / (WINDOW_SCAN * RULING_SAMPLES) as f64;
3809        let (disc, vp, vm) = roots(u);
3810        disc >= -lin_tol
3811            && [vp, vm]
3812                .iter()
3813                .any(|&t| (cyl.evaluate(u, t) - apex).dot(d) < -lin_tol)
3814    });
3815    if far_nappe {
3816        return None;
3817    }
3818    let samples = ruling_samples(cyl, &roots);
3819    // A window of meeting rulings narrower than the sampling would vanish
3820    // (a cone's tip just through the wall) while the others still made
3821    // loops; a finer scan finds every window, and any that the sampling
3822    // covers thinly goes to the marcher.
3823    let scan = WINDOW_SCAN * RULING_SAMPLES;
3824    // Ruling sample `i` lies midway between scan points
3825    // `WINDOW_SCAN i + 7` and `WINDOW_SCAN i + 8`.
3826    #[allow(clippy::cast_precision_loss)]
3827    let meets = |k: usize| roots(TAU * ((k % scan) as f64 + 0.5) / scan as f64).0 >= -lin_tol;
3828    if let Some(start) = (0..scan).find(|&k| !meets(k)) {
3829        let mut k = start;
3830        while k < start + scan {
3831            if !meets(k) {
3832                k += 1;
3833                continue;
3834            }
3835            let first = k;
3836            while k < start + scan && meets(k) {
3837                k += 1;
3838            }
3839            let covered = (first..k)
3840                .filter(|&j| j % WINDOW_SCAN == WINDOW_SCAN / 2 - 1 && meets(j + 1))
3841                .count();
3842            if covered < WINDOW_MIN_SAMPLES {
3843                return None;
3844            }
3845        }
3846    }
3847    let loops = if samples.iter().all(Option::is_some) {
3848        closed_ruling_loops(cyl, &roots, &samples)
3849    } else {
3850        partial_ruling_loops(cyl, &roots, &samples)
3851    };
3852    if loops.is_empty() {
3853        return None;
3854    }
3855    Some(fit_ruling_loops(&loops, |p| {
3856        in_order(cone.project_point(p), cyl.project_point(p), cone_first)
3857    }))
3858}
3859
3860/// A torus and a cylinder whose axes are not parallel, where every ruling
3861/// of the cylinder meets the torus the same nonzero even number of times (a
3862/// rod through the ring's tube): a ruling meets the torus where a quartic in
3863/// its parameter vanishes, and each of its roots, taken in order, sweeps one
3864/// closed loop around the cylinder. `None` (the marcher's case) when the
3865/// count varies between rulings, where the curve turns back between them,
3866/// checked on a scan finer than the sampling so a narrow window of missing
3867/// rulings is not stepped over, and for a spindle torus, whose quartic also
3868/// holds its inner lemon.
3869fn ruling_torus_cylinder(
3870    torus: &ToroidalSurface,
3871    cyl: &CylindricalSurface,
3872    torus_first: bool,
3873) -> Option<Vec<IntersectionCurve>> {
3874    if cyl.axis().dot(torus.z_axis()).abs() > 1.0 - 1e-9
3875        || torus.minor_radius() >= torus.major_radius()
3876    {
3877        return None;
3878    }
3879    let roots = |u: f64| intersect_line_torus(torus, cyl.evaluate(u, 0.0), cyl.axis());
3880    let rows: Vec<Vec<f64>> = (0..RULING_SAMPLES).map(|i| roots(ruling_u(i))).collect();
3881    let count = rows[0].len();
3882    let scan = WINDOW_SCAN * RULING_SAMPLES;
3883    #[allow(clippy::cast_precision_loss)]
3884    if count == 0
3885        || count % 2 == 1
3886        || (0..scan).any(|k| roots(TAU * (k as f64 + 0.5) / scan as f64).len() != count)
3887    {
3888        return None;
3889    }
3890    let loops: Vec<Vec<Point3>> = (0..count)
3891        .map(|j| {
3892            let mut pts: Vec<Point3> = rows
3893                .iter()
3894                .enumerate()
3895                .map(|(i, r)| cyl.evaluate(ruling_u(i), r[j]))
3896                .collect();
3897            pts.push(pts[0]);
3898            pts
3899        })
3900        .collect();
3901    Some(fit_ruling_loops(&loops, |p| {
3902        in_order(torus.project_point(p), cyl.project_point(p), torus_first)
3903    }))
3904}
3905
3906/// A cone and a sphere whose centre is off the cone's axis, where every
3907/// generator of the cone crosses the sphere twice on the cone's nappe (a pin
3908/// through a ball): along a generator `apex + v g` the sphere is a quadratic
3909/// in `v`, and each of its two roots, taken in order, sweeps one closed loop
3910/// around the cone. A ball holding the apex is left once by every generator,
3911/// one loop. `None` when the centre lies on the axis (phase FF takes
3912/// [`exact_cone_sphere`]'s circles there), or the apex on the sphere. A
3913/// sphere only some generators cross goes to [`window_cone_sphere`].
3914fn ruling_cone_sphere(
3915    cone: &ConicalSurface,
3916    sphere: &SphericalSurface,
3917    cone_first: bool,
3918) -> Option<Vec<IntersectionCurve>> {
3919    let (apex, centre, radius) = (cone.apex(), sphere.center(), sphere.radius());
3920    let offset = apex - centre;
3921    let lin_tol = Tolerance::new().linear;
3922    let along = offset.dot(cone.axis());
3923    let across = (offset - cone.axis() * along).length();
3924    if across < lin_tol {
3925        return None;
3926    }
3927    // With the apex inside the ball, `v² + 2hv + K` has roots of opposite
3928    // signs (`K = |offset|² − R² < 0`): every generator leaves the ball once
3929    // ahead of the apex, at `v = √(h² − K) − h`, one loop round the cone.
3930    // Where `h > 0` the root is taken as `−K / (h + √(h² − K))`, free of the
3931    // cancellation.
3932    let k = offset.dot(offset) - radius * radius;
3933    if radius - offset.length() > lin_tol {
3934        let exit = |u: f64| {
3935            let h = (cone.evaluate(u, 1.0) - apex).dot(offset);
3936            let root = h.madd(h, -k).sqrt();
3937            cone.evaluate(u, if h > 0.0 { -k / (h + root) } else { root - h })
3938        };
3939        // A ball that barely holds the apex turns the loop sharply where it
3940        // passes the apex, at the scale of `√−K`: a step whose midpoint
3941        // strays from its chord by a hundredth of the chord (a turn of about
3942        // 0.08 radians) is halved until the turn is resolved.
3943        let mut samples: Vec<(f64, Point3)> = (0..=RULING_SAMPLES)
3944            .map(|i| (ruling_u(i), exit(ruling_u(i))))
3945            .collect();
3946        for _ in 0..10 {
3947            let mut refined = Vec::with_capacity(2 * samples.len());
3948            for pair in samples.windows(2) {
3949                let ((u0, p0), (u1, p1)) = (pair[0], pair[1]);
3950                refined.push(pair[0]);
3951                let um = 0.5 * (u0 + u1);
3952                let pm = exit(um);
3953                let chord = (p1 - p0).length();
3954                if chord > lin_tol && (pm - (p0 + (p1 - p0) * 0.5)).length() > 0.01 * chord {
3955                    refined.push((um, pm));
3956                }
3957            }
3958            refined.extend(samples.last().copied());
3959            if refined.len() == samples.len() {
3960                break;
3961            }
3962            samples = refined;
3963        }
3964        let mut pts: Vec<Point3> = samples.iter().map(|&(_, p)| p).collect();
3965        if let Some(last) = pts.last_mut() {
3966            *last = samples[0].1;
3967        }
3968        return Some(fit_ruling_loops(&[pts], |p| {
3969            in_order(cone.project_point(p), sphere.project_point(p), cone_first)
3970        }));
3971    }
3972    // Both roots along a generator of unit direction `g` (`v` the distance
3973    // from the apex), nearer first, from `h = g·offset`, when it crosses the
3974    // sphere twice ahead of the apex.
3975    let crossing = |h: f64| {
3976        let (disc, vp, vm) = ruling_quadratic(1.0, 2.0 * h, k);
3977        (disc > lin_tol && vm >= lin_tol).then_some((vm, vp))
3978    };
3979    // Around the cone `h` runs between these bounds. Where both roots lie
3980    // ahead of the apex, raising `h` shrinks the discriminant and moves the
3981    // nearer root out, so every generator crosses when the two extreme ones
3982    // do.
3983    let (sin_a, cos_a) = cone.half_angle().sin_cos();
3984    if crossing(sin_a.madd(along, cos_a * across)).is_none()
3985        || crossing(sin_a.madd(along, -cos_a * across)).is_none()
3986    {
3987        return window_cone_sphere(cone, sphere, cone_first);
3988    }
3989    let rows: Vec<(f64, f64)> = (0..RULING_SAMPLES)
3990        .map(|i| crossing((cone.evaluate(ruling_u(i), 1.0) - apex).dot(offset)))
3991        .collect::<Option<_>>()?;
3992    let loops: Vec<Vec<Point3>> = [0, 1]
3993        .iter()
3994        .map(|&j| {
3995            let mut pts: Vec<Point3> = rows
3996                .iter()
3997                .enumerate()
3998                .map(|(i, &(near, far))| {
3999                    cone.evaluate(ruling_u(i), if j == 0 { near } else { far })
4000                })
4001                .collect();
4002            pts.push(pts[0]);
4003            pts
4004        })
4005        .collect();
4006    Some(fit_ruling_loops(&loops, |p| {
4007        in_order(cone.project_point(p), sphere.project_point(p), cone_first)
4008    }))
4009}
4010
4011/// A cone and a sphere off its axis that only some generators cross (a ball
4012/// against the cone's side), with the apex outside the sphere: along the
4013/// generator at `u`, `h(u) = g·(apex − C)` is `c + A cos(u − φ)`, and the
4014/// generator crosses twice ahead of the apex where `h ≤ −√K`, with
4015/// `K = |apex − C|² − R²`. That is one arc of `u`, whose ends are where the
4016/// generator touches the sphere; the section is one loop, the nearer roots
4017/// out along the arc and the farther ones back. Sampled at
4018/// `u = mid − half·cos θ`, the roots' split `±√(h² − K)` changes sign with
4019/// `sin θ` and the loop stays smooth through both touching generators.
4020/// `Some(empty)` when no generator crosses ahead of the apex. `None`, the
4021/// marcher's case, when the apex lies within the sphere, when the centre is
4022/// too near the axis to place the arc, and when every generator reaches the
4023/// sphere (the extremes' test then failed on a touching generator or a root
4024/// at the apex).
4025fn window_cone_sphere(
4026    cone: &ConicalSurface,
4027    sphere: &SphericalSurface,
4028    cone_first: bool,
4029) -> Option<Vec<IntersectionCurve>> {
4030    let offset = cone.apex() - sphere.center();
4031    let lin_tol = Tolerance::new().linear;
4032    if offset.length() - sphere.radius() <= lin_tol {
4033        return None;
4034    }
4035    let k = offset.dot(offset) - sphere.radius() * sphere.radius();
4036    let (sin_a, cos_a) = cone.half_angle().sin_cos();
4037    let (ox, oy) = (offset.dot(cone.x_axis()), offset.dot(cone.y_axis()));
4038    let (c, a) = (sin_a * offset.dot(cone.axis()), cos_a * ox.hypot(oy));
4039    if a < lin_tol {
4040        return None;
4041    }
4042    let reach = (-k.sqrt() - c) / a;
4043    if reach <= -1.0 {
4044        return Some(Vec::new());
4045    }
4046    if reach >= 1.0 {
4047        return None;
4048    }
4049    let (mid, half) = (oy.atan2(ox) + std::f64::consts::PI, reach.acos());
4050    let half = std::f64::consts::PI - half;
4051    let n = RULING_SAMPLES;
4052    let mut pts: Vec<Point3> = (0..n)
4053        .map(|i| {
4054            #[allow(clippy::cast_precision_loss)]
4055            let theta = TAU * i as f64 / n as f64;
4056            let u = half.madd(-theta.cos(), mid);
4057            let h = a.madd((u - mid + std::f64::consts::PI).cos(), c);
4058            let split = h.madd(h, -k).max(0.0).sqrt();
4059            cone.evaluate(u, -h - split.copysign(theta.sin()))
4060        })
4061        .collect();
4062    pts.push(pts[0]);
4063    Some(fit_ruling_loops(&[pts], |p| {
4064        in_order(cone.project_point(p), sphere.project_point(p), cone_first)
4065    }))
4066}
4067
4068/// Scan points per ruling sample when looking for windows of meeting
4069/// rulings, and the fewest samples a window needs to be fit.
4070const WINDOW_SCAN: usize = 16;
4071const WINDOW_MIN_SAMPLES: usize = 8;
4072
4073/// Rulings sampled around a swept cylinder, half a step off u = 0 so the
4074/// branches of a self-touching curve (equal crossing cylinders) do not share
4075/// a sample.
4076const RULING_SAMPLES: usize = 128;
4077
4078#[allow(clippy::cast_precision_loss)]
4079fn ruling_u(i: usize) -> f64 {
4080    TAU * (i as f64 + 0.5) / RULING_SAMPLES as f64
4081}
4082
4083/// The discriminant and roots of `quad·v² + b·v + c = 0`.
4084fn ruling_quadratic(quad: f64, b: f64, c: f64) -> (f64, f64, f64) {
4085    let disc = b * b - 4.0 * quad * c;
4086    let root = disc.max(0.0).sqrt();
4087    (disc, (-b + root) / (2.0 * quad), (-b - root) / (2.0 * quad))
4088}
4089
4090/// The two points where each sampled ruling of `sweep` meets the other
4091/// surface, from `roots(u)` (the discriminant and the two axial parameters),
4092/// or `None` for a ruling that misses it.
4093fn ruling_samples(
4094    sweep: &CylindricalSurface,
4095    roots: &impl Fn(f64) -> (f64, f64, f64),
4096) -> Vec<Option<(Point3, Point3)>> {
4097    let lin_tol = Tolerance::new().linear;
4098    (0..RULING_SAMPLES)
4099        .map(|i| {
4100            let u = ruling_u(i);
4101            let (disc, vp, vm) = roots(u);
4102            (disc >= -lin_tol).then(|| (sweep.evaluate(u, vp), sweep.evaluate(u, vm)))
4103        })
4104        .collect()
4105}
4106
4107/// Every ruling meets the other surface: each root traces a closed loop.
4108/// Where the loops pass closest at one ruling they are sampled from it,
4109/// closer together near it, so the fit follows the narrow neck between
4110/// them; where they touch there, they are the two halves of one curve
4111/// crossing itself, each with a corner at that point, which then falls at
4112/// their shared start and end, where the fit keeps it.
4113fn closed_ruling_loops(
4114    sweep: &CylindricalSurface,
4115    roots: &impl Fn(f64) -> (f64, f64, f64),
4116    samples: &[Option<(Point3, Point3)>],
4117) -> Vec<Vec<Point3>> {
4118    let (mut plus, mut minus): (Vec<Point3>, Vec<Point3>) =
4119        if let Some((neck, touching)) = narrowest_ruling(roots) {
4120            let count = 2 * RULING_SAMPLES;
4121            #[allow(clippy::cast_precision_loss)]
4122            (0..count)
4123                .map(|i| {
4124                    let t = i as f64 / count as f64;
4125                    let u = TAU.madd(t - 0.9 * (TAU * t).sin() / TAU, neck);
4126                    let (_, vp, vm) = roots(u);
4127                    if i == 0 && touching {
4128                        let at = sweep.evaluate(u, 0.5 * (vp + vm));
4129                        (at, at)
4130                    } else {
4131                        (sweep.evaluate(u, vp), sweep.evaluate(u, vm))
4132                    }
4133                })
4134                .unzip()
4135        } else {
4136            samples.iter().flatten().copied().unzip()
4137        };
4138    plus.push(plus[0]);
4139    minus.push(minus[0]);
4140    vec![plus, minus]
4141}
4142
4143/// The ruling where the two roots pass closest, when exactly one ruling
4144/// stands out: a local minimum of their gap, scanned finer than the
4145/// sampling and refined, that either closes to within tolerance (the
4146/// roots touch there; the tolerance scales with the widest gap, the loops'
4147/// own size, so the decision does not move with the model) or narrows
4148/// below a quarter of the widest gap while no other minimum does. Equal
4149/// crossing cylinders touch at two rulings and get `None`.
4150fn narrowest_ruling(roots: &impl Fn(f64) -> (f64, f64, f64)) -> Option<(f64, bool)> {
4151    let scan = WINDOW_SCAN * RULING_SAMPLES;
4152    #[allow(clippy::cast_precision_loss)]
4153    let step = TAU / scan as f64;
4154    let gap = |u: f64| {
4155        let (_, vp, vm) = roots(u);
4156        (vp - vm).abs()
4157    };
4158    #[allow(clippy::cast_precision_loss)]
4159    let gaps: Vec<f64> = (0..scan).map(|k| gap(step * k as f64)).collect();
4160    let widest = gaps.iter().copied().fold(0.0, f64::max);
4161    let tol = Tolerance::new().linear * (1.0 + widest);
4162    let mut necks = Vec::new();
4163    for k in 0..scan {
4164        let (before, here, after) = (gaps[(k + scan - 1) % scan], gaps[k], gaps[(k + 1) % scan]);
4165        if here > before || here >= after || here >= 0.25 * widest {
4166            continue;
4167        }
4168        #[allow(clippy::cast_precision_loss)]
4169        let (mut lo, mut hi) = (step * (k as f64 - 1.0), step * (k as f64 + 1.0));
4170        for _ in 0..100 {
4171            let (a, b) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
4172            if gap(a) < gap(b) {
4173                hi = b;
4174            } else {
4175                lo = a;
4176            }
4177        }
4178        let u = 0.5 * (lo + hi);
4179        necks.push((u, gap(u) <= tol));
4180    }
4181    match necks[..] {
4182        [neck] => Some(neck),
4183        _ => None,
4184    }
4185}
4186
4187/// Only windows of rulings meet the other surface: each cyclic window
4188/// carries one loop, out along one root and back along the other, the two
4189/// joined where the discriminant vanishes. Empty when no sample meets it (a
4190/// window narrower than the sampling).
4191fn partial_ruling_loops(
4192    sweep: &CylindricalSurface,
4193    roots: &impl Fn(f64) -> (f64, f64, f64),
4194    samples: &[Option<(Point3, Point3)>],
4195) -> Vec<Vec<Point3>> {
4196    let branch_point = |inside: usize, outside: usize| -> Point3 {
4197        let (mut lo, mut hi) = (ruling_u(inside), ruling_u(outside));
4198        if (hi - lo).abs() > std::f64::consts::PI {
4199            hi += if hi < lo { TAU } else { -TAU };
4200        }
4201        for _ in 0..60 {
4202            let mid = 0.5 * (lo + hi);
4203            if roots(mid).0 >= 0.0 {
4204                lo = mid;
4205            } else {
4206                hi = mid;
4207            }
4208        }
4209        let (_, vp, vm) = roots(lo);
4210        sweep.evaluate(lo, 0.5 * (vp + vm))
4211    };
4212    let Some(first_gap) = samples.iter().position(Option::is_none) else {
4213        return Vec::new();
4214    };
4215    let mut loops = Vec::new();
4216    let mut k = 0;
4217    while k < RULING_SAMPLES {
4218        let i = (first_gap + k) % RULING_SAMPLES;
4219        if samples[i].is_none() {
4220            k += 1;
4221            continue;
4222        }
4223        let start = i;
4224        let mut run = Vec::new();
4225        while k < RULING_SAMPLES {
4226            let j = (first_gap + k) % RULING_SAMPLES;
4227            let Some(pair) = samples[j] else { break };
4228            run.push(pair);
4229            k += 1;
4230        }
4231        let end = (start + run.len() - 1) % RULING_SAMPLES;
4232        let head = branch_point(start, (start + RULING_SAMPLES - 1) % RULING_SAMPLES);
4233        let tail = branch_point(end, (end + 1) % RULING_SAMPLES);
4234        let mut pts = vec![head];
4235        pts.extend(run.iter().map(|p| p.0));
4236        pts.push(tail);
4237        pts.extend(run.iter().rev().map(|p| p.1));
4238        pts.push(head);
4239        loops.push(pts);
4240    }
4241    loops
4242}
4243
4244/// Cubic interpolants through the swept loops, with `params(p)` giving each
4245/// point's parameters on the two surfaces.
4246fn fit_ruling_loops(
4247    loops: &[Vec<Point3>],
4248    params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
4249) -> Vec<IntersectionCurve> {
4250    let mut curves = Vec::new();
4251    for pts in loops {
4252        if pts.len() < 4 {
4253            continue;
4254        }
4255        let ipts: Vec<IntersectionPoint> = pts
4256            .iter()
4257            .map(|&p| {
4258                let (param1, param2) = params(p);
4259                IntersectionPoint {
4260                    point: p,
4261                    param1,
4262                    param2,
4263                }
4264            })
4265            .collect();
4266        let degree = 3.min(pts.len() - 1);
4267        if let Ok(curve) = interpolate(pts, degree) {
4268            curves.push(IntersectionCurve {
4269                curve,
4270                points: ipts,
4271            });
4272        }
4273    }
4274    curves
4275}
4276
4277/// Algebraic cone-cylinder intersection for PARALLEL (or antiparallel) axes.
4278///
4279/// When the axes are parallel, every plane perpendicular to them cuts the cone
4280/// in a circle of radius `rho = v * cos(half_angle)` about a FIXED centre and
4281/// the cylinder in a circle of radius `R` about a second FIXED centre, so the
4282/// axis separation `d` is constant in `v`. Two coplanar circles meet at
4283/// `u = phi0 +/- acos((d^2 + rho^2 - R^2) / (2*d*rho))`, giving two branches
4284/// parameterised exactly by the cone's own `v`. The branches exist only where
4285/// `rho` lies in `[|d - R|, d + R]`, which bounds the curve naturally.
4286///
4287/// This replaces the general grid-seeded marcher for the configuration, which
4288/// mis-handles it badly: seeds are accepted anywhere within half the surface
4289/// diagonal of the partner, the march-result dedup only consumes seeds the
4290/// traced polyline passes near, and the survivors are dozens of overlapping
4291/// partial traces of the same curve. Those fragments carry no usable in-face
4292/// span, so a cone corner-round crossed by a boss cylinder never splits (a
4293/// counterbore/countersink meeting a pad — the gridfinity lightweight base).
4294///
4295/// Returns `None` (defer to the caller's other paths) when the axes are not
4296/// parallel, or when they are coaxial — a coaxial pair degenerates to shared
4297/// circles, which [`exact_cone_cylinder`] emits exactly and phase FF calls
4298/// directly. Note that `intersect_analytic_analytic_bounded` does NOT consult
4299/// `exact_cone_cylinder`, so a coaxial pair reaching this path through that
4300/// caller falls through to the marcher; only the FF path gets the exact circles.
4301// Result-wrapped to match the other `try_algebraic_intersection` arms' shape.
4302#[allow(clippy::unnecessary_wraps)]
4303fn algebraic_parallel_cone_cylinder(
4304    cone: &ConicalSurface,
4305    cyl: &CylindricalSurface,
4306    v_range_cone: Option<(f64, f64)>,
4307    v_range_cyl: Option<(f64, f64)>,
4308) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
4309    let axis = cone.axis();
4310    if axis.dot(cyl.axis()).abs() < 1.0 - 1e-10 {
4311        return Ok(None); // Skew or oblique: `ruling_cone_cylinder` traces it.
4312    }
4313
4314    let apex = cone.apex();
4315    let delta = cyl.origin() - apex;
4316    let along = delta.dot(axis);
4317    let perp = delta - axis * along;
4318    let d = perp.length();
4319    if d < 1e-9 {
4320        return Ok(None); // Coaxial — `exact_cone_cylinder` owns this.
4321    }
4322
4323    let (e1, e2) = (cone.x_axis(), cone.y_axis());
4324    let phi0 = perp.dot(e2).atan2(perp.dot(e1));
4325
4326    let (sin_t, cos_t) = cone.half_angle().sin_cos();
4327    if cos_t < 1e-12 || sin_t < 1e-12 {
4328        return Ok(None);
4329    }
4330    let r = cyl.radius();
4331
4332    // Branch existence: |d - R| <= rho <= d + R, with rho = v * cos(half_angle).
4333    let mut v_min = (d - r).abs() / cos_t;
4334    let mut v_max = (d + r) / cos_t;
4335    if v_max <= v_min {
4336        return Ok(Some(vec![]));
4337    }
4338
4339    // Narrow the sampled span to the faces' own extents so the fixed sample
4340    // budget resolves the in-face part of the curve rather than spreading over
4341    // a loop that mostly lies off both patches. A face's crossing can be a
4342    // fraction of a degree of the cone's sweep (the corner-round case above),
4343    // and an unnarrowed sampling puts fewer than one sample across it.
4344    let mut lo = v_min;
4345    let mut hi = v_max;
4346    // Clip EXACTLY to the hints, not to a padded window: an endpoint that lands
4347    // exactly on the face's own v-limit lies ON that boundary rim, so the
4348    // downstream pave machinery anchors it to the rim edge instead of leaving
4349    // the section dangling just past the face.
4350    if let Some((a, b)) = v_range_cone {
4351        let (a, b) = if a <= b { (a, b) } else { (b, a) };
4352        lo = lo.max(a);
4353        hi = hi.min(b);
4354    }
4355    if let Some((a, b)) = v_range_cyl {
4356        // The cylinder's v is a signed distance along its axis from its origin;
4357        // convert both ends to the cone's v via the shared axial direction.
4358        let flip = cyl.axis().dot(axis);
4359        let to_cone_v = |cv: f64| (along + cv * flip) / sin_t;
4360        let (a, b) = (to_cone_v(a), to_cone_v(b));
4361        let (a, b) = if a <= b { (a, b) } else { (b, a) };
4362        lo = lo.max(a);
4363        hi = hi.min(b);
4364    }
4365    let (turn_lo, turn_hi) = (v_min, v_max);
4366    v_min = lo.max(v_min);
4367    v_max = hi.min(v_max);
4368    if v_max - v_min <= 1e-12 {
4369        return Ok(Some(vec![]));
4370    }
4371    // A cylinder beside the axis, with both turning points inside both faces,
4372    // meets the cone in a whole loop: traced along the cylinder's rulings,
4373    // each of which meets the nappe once, it comes back as one closed curve,
4374    // which the band split of the cylinder it winds needs. Around the axis
4375    // the loop winds the cone too and stays in two branches, and so does a
4376    // wall passing so near the axis that the loop's bend there, about
4377    // `(d - r) / sqrt(d r)` of a turn wide, spans fewer than a few rulings.
4378    let slack = Tolerance::new().linear;
4379    #[allow(clippy::cast_precision_loss)]
4380    let resolved = d - r > 3.0 * (d * r).sqrt() * TAU / RULING_SAMPLES as f64;
4381    if v_min <= turn_lo + slack && v_max >= turn_hi - slack && resolved {
4382        let mut pts: Vec<Point3> = (0..RULING_SAMPLES)
4383            .map(|i| {
4384                let (sin_u, cos_u) = ruling_u(i).sin_cos();
4385                let foot = cyl.origin() + (cyl.x_axis() * cos_u + cyl.y_axis() * sin_u) * r;
4386                let off = foot - apex;
4387                let across = off - axis * off.dot(axis);
4388                apex + across + axis * (across.length() * sin_t / cos_t)
4389            })
4390            .collect();
4391        pts.push(pts[0]);
4392        return Ok(Some(fit_ruling_loops(&[pts], |p| {
4393            (cone.project_point(p), cyl.project_point(p))
4394        })));
4395    }
4396
4397    let n_samples = 128;
4398    let mut plus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
4399    let mut minus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
4400    #[allow(clippy::cast_precision_loss)]
4401    for i in 0..=n_samples {
4402        let v = v_min + (v_max - v_min) * (i as f64) / (n_samples as f64);
4403        let rho = v * cos_t;
4404        if rho < 1e-12 {
4405            // The apex. `cos_alpha` has rho in its denominator, so it is only
4406            // meaningful in the limit: it tends to 0 (alpha -> pi/2) when the
4407            // cylinder passes exactly through the apex (d == R), and diverges
4408            // otherwise — where the clamp would manufacture a spurious alpha of
4409            // 0 or pi. So keep the apex only in the d == R case, where it is a
4410            // genuine point of the intersection and the shared endpoint at
4411            // which the two branches meet.
4412            if (d - r).abs() < 1e-12 {
4413                let apex = cone.evaluate(phi0, v);
4414                plus.push(apex);
4415                minus.push(apex);
4416            }
4417            continue;
4418        }
4419        let cos_alpha = ((d * d + rho * rho - r * r) / (2.0 * d * rho)).clamp(-1.0, 1.0);
4420        let alpha = cos_alpha.acos();
4421        plus.push(cone.evaluate(phi0 + alpha, v));
4422        minus.push(cone.evaluate(phi0 - alpha, v));
4423    }
4424
4425    let mut curves = Vec::new();
4426    for pts in [&plus, &minus] {
4427        // Fewer than four samples in range means this branch does not cross the
4428        // bounded region at all (the other branch may still).
4429        if pts.len() < 4 {
4430            continue;
4431        }
4432        let ipts: Vec<IntersectionPoint> = pts
4433            .iter()
4434            .map(|&p| IntersectionPoint {
4435                point: p,
4436                param1: cone.project_point(p),
4437                param2: cyl.project_point(p),
4438            })
4439            .collect();
4440        let degree = 3.min(pts.len() - 1);
4441        match interpolate(pts, degree) {
4442            Ok(curve) => curves.push(IntersectionCurve {
4443                curve,
4444                points: ipts,
4445            }),
4446            // Emitting only the branch that happened to fit would starve the
4447            // section chain of exactly the piece this path exists to supply —
4448            // the same silent half-answer the marcher's fragments produced.
4449            // Defer the whole pair to the caller's other paths instead.
4450            Err(_) => return Ok(None),
4451        }
4452    }
4453
4454    Ok(Some(curves))
4455}
4456
4457/// Algebraic sphere-sphere intersection.
4458///
4459/// Two spheres intersect in a circle lying in the radical plane.
4460/// The radical plane is perpendicular to the line connecting the centers,
4461/// at a distance d1 from center1 where:
4462///   d1 = (D² + R1² - R2²) / (2D)
4463/// and D is the distance between centers.
4464fn algebraic_sphere_sphere(
4465    s1: &SphericalSurface,
4466    s2: &SphericalSurface,
4467) -> Result<Vec<IntersectionCurve>, MathError> {
4468    let c1 = s1.center();
4469    let c2 = s2.center();
4470    let r1 = s1.radius();
4471    let r2 = s2.radius();
4472
4473    let delta = c2 - c1;
4474    let d_sq = delta.x() * delta.x() + delta.y() * delta.y() + delta.z() * delta.z();
4475    let d = d_sq.sqrt();
4476
4477    if d < 1e-12 {
4478        // Concentric spheres: no intersection (unless same radius → degenerate).
4479        return Ok(vec![]);
4480    }
4481
4482    // Check separation conditions.
4483    if d > r1 + r2 + 1e-10 {
4484        return Ok(vec![]); // Too far apart
4485    }
4486    if d + r2.min(r1) + 1e-10 < r1.max(r2) {
4487        return Ok(vec![]); // One inside the other
4488    }
4489
4490    // Distance from c1 to the radical plane along the center line.
4491    let d1 = (d_sq + r1 * r1 - r2 * r2) / (2.0 * d);
4492
4493    // Radius of the intersection circle.
4494    let r_circle_sq = r1 * r1 - d1 * d1;
4495    if r_circle_sq < 0.0 {
4496        // Tangent or no intersection (numerical noise).
4497        if r_circle_sq > -1e-10 {
4498            // Tangent: single point.
4499            let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
4500            let tangent_pt = Point3::new(
4501                c1.x() + axis.x() * d1,
4502                c1.y() + axis.y() * d1,
4503                c1.z() + axis.z() * d1,
4504            );
4505            let ipt = IntersectionPoint {
4506                point: tangent_pt,
4507                param1: (0.0, 0.0),
4508                param2: (0.0, 0.0),
4509            };
4510            // Single-point "curve" — not very useful but correct.
4511            return Ok(vec![IntersectionCurve {
4512                curve: interpolate(&[tangent_pt, tangent_pt], 1)?,
4513                points: vec![ipt],
4514            }]);
4515        }
4516        return Ok(vec![]);
4517    }
4518
4519    let r_circle = r_circle_sq.sqrt();
4520    let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
4521    let center = Point3::new(
4522        c1.x() + axis.x() * d1,
4523        c1.y() + axis.y() * d1,
4524        c1.z() + axis.z() * d1,
4525    );
4526
4527    // Build a reference frame for the circle.
4528    let basis = Frame3::from_normal(center, axis)?;
4529    let u_dir = basis.x;
4530    let v_dir = basis.y;
4531
4532    // Sample points along the circle for the IntersectionCurve.
4533    let n_samples = 33; // Odd for symmetry
4534    let mut points = Vec::with_capacity(n_samples);
4535    #[allow(clippy::cast_precision_loss)]
4536    for i in 0..n_samples {
4537        let theta = TAU * i as f64 / (n_samples - 1) as f64;
4538        let (sin_t, cos_t) = theta.sin_cos();
4539        let pt = Point3::new(
4540            center.x() + (u_dir.x() * cos_t + v_dir.x() * sin_t) * r_circle,
4541            center.y() + (u_dir.y() * cos_t + v_dir.y() * sin_t) * r_circle,
4542            center.z() + (u_dir.z() * cos_t + v_dir.z() * sin_t) * r_circle,
4543        );
4544        points.push(IntersectionPoint {
4545            point: pt,
4546            param1: (0.0, 0.0),
4547            param2: (0.0, 0.0),
4548        });
4549    }
4550
4551    let curve = conic_loop(center, u_dir, v_dir, r_circle, r_circle)?;
4552
4553    Ok(vec![IntersectionCurve { curve, points }])
4554}
4555
4556/// Newton correction: project a point back onto the intersection curve
4557/// of two analytic surfaces. Solves the 3×3 system:
4558///   δ · na = -da  (eliminate distance to surface A)
4559///   δ · nb = -db  (eliminate distance to surface B)
4560///   δ · t  = 0    (minimal correction, perpendicular to tangent)
4561#[allow(clippy::too_many_arguments)]
4562fn correct_to_intersection(
4563    a: &AnalyticSurface<'_>,
4564    b: &AnalyticSurface<'_>,
4565    surf_a: &dyn Fn(f64, f64) -> Point3,
4566    norm_a: &dyn Fn(f64, f64) -> Vec3,
4567    surf_b: &dyn Fn(f64, f64) -> Point3,
4568    norm_b: &dyn Fn(f64, f64) -> Vec3,
4569    point: Point3,
4570    u_range_a: (f64, f64),
4571    v_range_a: (f64, f64),
4572    u_range_b: (f64, f64),
4573    v_range_b: (f64, f64),
4574    max_iters: usize,
4575) -> Point3 {
4576    let mut p = point;
4577    for _ in 0..max_iters {
4578        let (ua, va) = project_analytic(a, p, u_range_a, v_range_a);
4579        let (ub, vb) = project_analytic(b, p, u_range_b, v_range_b);
4580        let pa = surf_a(ua, va);
4581        let pb = surf_b(ub, vb);
4582        let na = norm_a(ua, va);
4583        let nb = norm_b(ub, vb);
4584        let pv = Vec3::new(p.x(), p.y(), p.z());
4585
4586        let da = (pv - Vec3::new(pa.x(), pa.y(), pa.z())).dot(na);
4587        let db = (pv - Vec3::new(pb.x(), pb.y(), pb.z())).dot(nb);
4588
4589        if da.abs() < 1e-7 && db.abs() < 1e-7 {
4590            break;
4591        }
4592
4593        let t = na.cross(nb);
4594        let t_len = t.length();
4595        if t_len < 1e-10 {
4596            // Surfaces are tangent — fall back to midpoint.
4597            return Point3::new(
4598                (pa.x() + pb.x()) * 0.5,
4599                (pa.y() + pb.y()) * 0.5,
4600                (pa.z() + pb.z()) * 0.5,
4601            );
4602        }
4603        let t_hat = t * (1.0 / t_len);
4604
4605        // Solve [na; nb; t_hat] · δ = [-da, -db, 0] via Cramer's rule.
4606        let det = na.x() * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
4607            - na.y() * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
4608            + na.z() * (nb.x() * t_hat.y() - nb.y() * t_hat.x());
4609        if det.abs() < 1e-15 {
4610            return Point3::new(
4611                (pa.x() + pb.x()) * 0.5,
4612                (pa.y() + pb.y()) * 0.5,
4613                (pa.z() + pb.z()) * 0.5,
4614            );
4615        }
4616        let inv = 1.0 / det;
4617        // Cramer's rule: replace each column of A with rhs = (-da, -db, 0).
4618        let dx = inv
4619            * (-da * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
4620                + db * (na.y() * t_hat.z() - na.z() * t_hat.y()));
4621        let dy = inv
4622            * (da * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
4623                - db * (na.x() * t_hat.z() - na.z() * t_hat.x()));
4624        let dz = inv
4625            * (-da * (nb.x() * t_hat.y() - nb.y() * t_hat.x())
4626                + db * (na.x() * t_hat.y() - na.y() * t_hat.x()));
4627        let candidate = Point3::new(p.x() + dx, p.y() + dy, p.z() + dz);
4628
4629        // Divergence guard: if the correction moves farther from both
4630        // surfaces, abandon Newton and return the best point so far.
4631        let (uc, vc) = project_analytic(a, candidate, u_range_a, v_range_a);
4632        let (ud, vd) = project_analytic(b, candidate, u_range_b, v_range_b);
4633        let pc_a = surf_a(uc, vc);
4634        let pc_b = surf_b(ud, vd);
4635        let cv = Vec3::new(candidate.x(), candidate.y(), candidate.z());
4636        let da_new = (cv - Vec3::new(pc_a.x(), pc_a.y(), pc_a.z()))
4637            .dot(norm_a(uc, vc))
4638            .abs();
4639        let db_new = (cv - Vec3::new(pc_b.x(), pc_b.y(), pc_b.z()))
4640            .dot(norm_b(ud, vd))
4641            .abs();
4642        if da_new > da.abs() && db_new > db.abs() {
4643            return p;
4644        }
4645
4646        p = candidate;
4647    }
4648    p
4649}
4650
4651/// March along the intersection of two surfaces from a seed point.
4652///
4653/// Uses the cross product of surface normals as the tangent direction
4654/// and projects back onto both surfaces using analytical projection
4655/// (for cylinders/spheres) or grid search (fallback).
4656#[allow(clippy::too_many_arguments)]
4657fn march_analytic_intersection(
4658    a: &AnalyticSurface<'_>,
4659    b: &AnalyticSurface<'_>,
4660    surf_a: &dyn Fn(f64, f64) -> Point3,
4661    norm_a: &dyn Fn(f64, f64) -> Vec3,
4662    surf_b: &dyn Fn(f64, f64) -> Point3,
4663    norm_b: &dyn Fn(f64, f64) -> Vec3,
4664    seed: Point3,
4665    u_range_a: (f64, f64),
4666    v_range_a: (f64, f64),
4667    u_range_b: (f64, f64),
4668    v_range_b: (f64, f64),
4669    initial_step: f64,
4670    u_periodic_a: bool,
4671    u_periodic_b: bool,
4672    region: Option<Aabb3>,
4673) -> Vec<Point3> {
4674    let max_steps = 500;
4675    let h_min = 1e-6;
4676    let h_max = initial_step * 4.0;
4677    // Fixed closure threshold: the adaptive step `h` varies with curvature
4678    // and can shrink below the actual miss distance at the seed re-approach.
4679    // Use `initial_step * 5` to robustly detect closure on the first pass.
4680    let closure_dist = initial_step * 5.0;
4681    // Angular thresholds for curvature-adaptive stepping.
4682    let max_angle = 10.0_f64.to_radians();
4683    let min_angle = 2.0_f64.to_radians();
4684
4685    // March forward from seed, collecting points.
4686    let mut forward = Vec::new();
4687    // March backward from seed, collecting points (reversed at end).
4688    let mut backward = Vec::new();
4689
4690    for (direction, points) in [(1.0_f64, &mut forward), (-1.0_f64, &mut backward)] {
4691        let mut current = seed;
4692        let mut h = initial_step;
4693        let mut prev_tangent: Option<Vec3> = None;
4694
4695        for _ in 0..max_steps {
4696            let (ua, va) = project_analytic(a, current, u_range_a, v_range_a);
4697            let (ub, vb) = project_analytic(b, current, u_range_b, v_range_b);
4698
4699            let na = norm_a(ua, va);
4700            let nb = norm_b(ub, vb);
4701
4702            let tangent = na.cross(nb);
4703            let t_len = tangent.length();
4704            if t_len < 1e-10 {
4705                break;
4706            }
4707            let t_dir = tangent * (direction / t_len);
4708
4709            // Curvature-adaptive step: check angular deviation from previous tangent.
4710            if let Some(prev_t) = prev_tangent {
4711                let cos_angle = prev_t.dot(t_dir).clamp(-1.0, 1.0);
4712                let angle = cos_angle.acos();
4713                if angle > max_angle && h > h_min {
4714                    h = (h * 0.5).max(h_min);
4715                } else if angle < min_angle {
4716                    h = (h * 2.0).min(h_max);
4717                }
4718            }
4719            prev_tangent = Some(t_dir);
4720
4721            let next = Point3::new(
4722                h.madd(t_dir.x(), current.x()),
4723                h.madd(t_dir.y(), current.y()),
4724                h.madd(t_dir.z(), current.z()),
4725            );
4726
4727            let (ua2, va2) = project_analytic(a, next, u_range_a, v_range_a);
4728            let (ub2, vb2) = project_analytic(b, next, u_range_b, v_range_b);
4729
4730            let pa = surf_a(ua2, va2);
4731            let pb = surf_b(ub2, vb2);
4732            let mid = Point3::new(
4733                (pa.x() + pb.x()) * 0.5,
4734                (pa.y() + pb.y()) * 0.5,
4735                (pa.z() + pb.z()) * 0.5,
4736            );
4737            let out_a = (!u_periodic_a && (ua2 <= u_range_a.0 || ua2 >= u_range_a.1))
4738                || va2 <= v_range_a.0
4739                || va2 >= v_range_a.1;
4740            let out_b = (!u_periodic_b && (ub2 <= u_range_b.0 || ub2 >= u_range_b.1))
4741                || vb2 <= v_range_b.0
4742                || vb2 >= v_range_b.1;
4743
4744            if out_a || out_b {
4745                break;
4746            }
4747            if region.is_some_and(|r| !r.contains_point(mid)) {
4748                points.push(mid);
4749                break;
4750            }
4751
4752            // Check for loop closure — if we've collected enough points and
4753            // the current point is close to the seed, the curve is closed.
4754            // Require ≥10 steps to avoid premature closure near the seed.
4755            let dist_to_seed = (mid - seed).length();
4756            if points.len() > 10 && dist_to_seed < closure_dist {
4757                points.push(seed);
4758                break;
4759            }
4760
4761            points.push(mid);
4762            current = mid;
4763        }
4764    }
4765
4766    // Assemble result: backward (reversed) + seed + forward
4767    backward.reverse();
4768    let mut result = backward;
4769    result.push(seed);
4770    result.append(&mut forward);
4771
4772    // Refine all points onto the intersection curve via Newton correction.
4773    for pt in &mut result {
4774        *pt = correct_to_intersection(
4775            a, b, surf_a, norm_a, surf_b, norm_b, *pt, u_range_a, v_range_a, u_range_b, v_range_b,
4776            5,
4777        );
4778    }
4779
4780    result
4781}
4782
4783/// Project a 3D point onto an analytic surface using the surface's
4784/// analytical projection method. Falls back to grid search for surface
4785/// types without analytical projection.
4786fn project_analytic(
4787    surface: &AnalyticSurface<'_>,
4788    point: Point3,
4789    u_range: (f64, f64),
4790    v_range: (f64, f64),
4791) -> (f64, f64) {
4792    match surface {
4793        AnalyticSurface::Cylinder(cyl) => {
4794            let (u, v) = cyl.project_point(point);
4795            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
4796        }
4797        AnalyticSurface::Sphere(sphere) => {
4798            let (u, v) = sphere.project_point(point);
4799            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
4800        }
4801        AnalyticSurface::Cone(cone) => {
4802            let (u, v) = cone.project_point(point);
4803            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
4804        }
4805        AnalyticSurface::Torus(torus) => {
4806            let (u, v) = torus.project_point(point);
4807            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
4808        }
4809    }
4810}
4811
4812/// Returns `true` if the surface's u-parameter is periodic (wraps around 2π).
4813/// All current `AnalyticSurface` variants have periodic u — this is trivially
4814/// true today but exists as a guard for future non-periodic analytic types.
4815fn is_u_periodic(surface: &AnalyticSurface<'_>) -> bool {
4816    matches!(
4817        surface,
4818        AnalyticSurface::Cylinder(_)
4819            | AnalyticSurface::Cone(_)
4820            | AnalyticSurface::Sphere(_)
4821            | AnalyticSurface::Torus(_)
4822    )
4823}
4824
4825/// Extract closures and parameter ranges for an analytic surface.
4826#[allow(clippy::type_complexity)]
4827fn surface_closures<'a>(
4828    surface: &'a AnalyticSurface<'a>,
4829) -> (
4830    Box<dyn Fn(f64, f64) -> Point3 + 'a>,
4831    Box<dyn Fn(f64, f64) -> Vec3 + 'a>,
4832    (f64, f64),
4833    (f64, f64),
4834) {
4835    match surface {
4836        AnalyticSurface::Cylinder(cyl) => (
4837            Box::new(|u, v| cyl.evaluate(u, v)),
4838            Box::new(|u, v| cyl.normal(u, v)),
4839            (0.0, TAU),
4840            (-1.0, 1.0),
4841        ),
4842        AnalyticSurface::Cone(cone) => (
4843            Box::new(|u, v| cone.evaluate(u, v)),
4844            Box::new(|u, v| cone.normal(u, v)),
4845            (0.0, TAU),
4846            (0.01, 2.0),
4847        ),
4848        AnalyticSurface::Sphere(sphere) => (
4849            Box::new(|u, v| sphere.evaluate(u, v)),
4850            Box::new(|u, v| sphere.normal(u, v)),
4851            (0.0, TAU),
4852            (-FRAC_PI_2, FRAC_PI_2),
4853        ),
4854        AnalyticSurface::Torus(torus) => (
4855            Box::new(|u, v| torus.evaluate(u, v)),
4856            Box::new(|u, v| torus.normal(u, v)),
4857            (0.0, TAU),
4858            (0.0, TAU),
4859        ),
4860    }
4861}
4862
4863#[cfg(test)]
4864#[allow(clippy::unwrap_used, clippy::expect_used)]
4865mod tests {
4866    use super::*;
4867    use crate::tolerance::Tolerance;
4868
4869    /// Arcs of a cone's hyperbola (a plane parallel to the axis) and parabola
4870    /// (a plane parallel to a ruling) between two of their sampled points
4871    /// stay on both the plane and the cone everywhere, not just at samples.
4872    #[test]
4873    fn plane_cone_conic_arcs_lie_on_both_surfaces() {
4874        let half_angle = 1.1_f64;
4875        let cone = ConicalSurface::new(
4876            Point3::new(0.0, 0.0, 0.0),
4877            Vec3::new(0.0, 0.0, 1.0),
4878            half_angle,
4879        )
4880        .unwrap();
4881        let ruling = Vec3::new(half_angle.sin(), 0.0, half_angle.cos());
4882        for (normal, d) in [(Vec3::new(1.0, 0.0, 0.0), 0.5), (ruling, 1.0)] {
4883            let chains =
4884                exact_plane_analytic_reaching(AnalyticSurface::Cone(&cone), normal, d, 10.0)
4885                    .unwrap();
4886            let chain = chains
4887                .iter()
4888                .find_map(|c| match c {
4889                    ExactIntersectionCurve::Points(chain) => Some(chain),
4890                    _ => None,
4891                })
4892                .expect("a parabola or hyperbola section is sampled");
4893            let (from, to) = (chain[2], chain[chain.len() - 3]);
4894            let arc = plane_cone_conic_arc(&cone, normal, d, from, to)
4895                .unwrap()
4896                .expect("an exact arc");
4897            let (t0, t1) = arc.domain();
4898            assert!((arc.evaluate(t0) - from).length() < 1e-12);
4899            assert!((arc.evaluate(t1) - to).length() < 1e-12);
4900            for i in 0..=200 {
4901                let q = arc.evaluate(t0 + (t1 - t0) * f64::from(i) / 200.0);
4902                let w = q - Point3::new(0.0, 0.0, 0.0);
4903                let off_plane = (normal.dot(w) - d).abs();
4904                let off_cone = (w.z() - w.length() * half_angle.sin()).abs();
4905                assert!(off_plane < 1e-9, "off the plane by {off_plane}");
4906                assert!(off_cone < 1e-9, "off the cone by {off_cone}");
4907            }
4908        }
4909    }
4910
4911    /// A plane a few 1e-10 short of parallel to a ruling cuts a vast ellipse
4912    /// that the parabola's closed form only approximates: the arc is either
4913    /// declined or on the cone, and an arc with coincident ends is declined.
4914    #[test]
4915    fn plane_cone_conic_arc_declines_a_near_parabolic_ellipse() {
4916        let half_angle = 1.1_f64;
4917        let cone = ConicalSurface::new(
4918            Point3::new(0.0, 0.0, 0.0),
4919            Vec3::new(0.0, 0.0, 1.0),
4920            half_angle,
4921        )
4922        .unwrap();
4923        for shortfall in [1e-10, 3e-10, 8e-10] {
4924            let tilt = half_angle - shortfall / (2.0 * half_angle).sin();
4925            let normal = Vec3::new(tilt.sin(), 0.0, tilt.cos());
4926            let chains =
4927                exact_plane_analytic_reaching(AnalyticSurface::Cone(&cone), normal, 1.0, 10.0)
4928                    .unwrap();
4929            let Some(chain) = chains.iter().find_map(|c| match c {
4930                ExactIntersectionCurve::Points(chain) => Some(chain),
4931                _ => None,
4932            }) else {
4933                continue;
4934            };
4935            let (from, to) = (chain[2], chain[chain.len() - 3]);
4936            assert!(
4937                plane_cone_conic_arc(&cone, normal, 1.0, from, from)
4938                    .unwrap()
4939                    .is_none(),
4940                "coincident ends"
4941            );
4942            let Some(arc) = plane_cone_conic_arc(&cone, normal, 1.0, from, to).unwrap() else {
4943                continue;
4944            };
4945            let (t0, t1) = arc.domain();
4946            for i in 0..=200 {
4947                let w = arc.evaluate(t0 + (t1 - t0) * f64::from(i) / 200.0)
4948                    - Point3::new(0.0, 0.0, 0.0);
4949                let off_cone = (w.z() - w.length() * half_angle.sin()).abs();
4950                assert!(off_cone < 1e-8, "{shortfall}: off the cone by {off_cone}");
4951            }
4952        }
4953    }
4954
4955    #[test]
4956    fn plane_cylinder_perpendicular() {
4957        let cyl =
4958            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
4959                .unwrap();
4960
4961        // Horizontal plane at z=3 -- produces a circle at height 3.
4962        let curves = intersect_plane_cylinder(&cyl, Vec3::new(0.0, 0.0, 1.0), 3.0).unwrap();
4963        assert!(!curves.is_empty(), "should find intersection curve");
4964        assert!(
4965            curves[0].points.len() > 10,
4966            "should have many sample points"
4967        );
4968
4969        let tol = Tolerance::loose();
4970        for pt in &curves[0].points {
4971            assert!(
4972                tol.approx_eq(pt.point.z(), 3.0),
4973                "z should be ~3.0, got {}",
4974                pt.point.z()
4975            );
4976            let r = pt.point.x().hypot(pt.point.y());
4977            assert!(tol.approx_eq(r, 2.0), "radius should be ~2.0, got {r}");
4978        }
4979    }
4980
4981    #[test]
4982    fn plane_sphere_equator() {
4983        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 3.0).unwrap();
4984
4985        let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
4986        assert!(!curves.is_empty());
4987
4988        let tol = Tolerance::loose();
4989        for pt in &curves[0].points {
4990            assert!(
4991                tol.approx_eq(pt.point.z(), 0.0),
4992                "z should be ~0, got {}",
4993                pt.point.z()
4994            );
4995            let r = pt.point.x().hypot(pt.point.y());
4996            assert!(tol.approx_eq(r, 3.0), "radius should be ~3.0, got {r}");
4997        }
4998    }
4999
5000    #[test]
5001    fn plane_sphere_no_intersection() {
5002        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
5003
5004        let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 5.0).unwrap();
5005        assert!(curves.is_empty());
5006    }
5007
5008    #[test]
5009    fn plane_cone_cross_section() {
5010        let cone = ConicalSurface::new(
5011            Point3::new(0.0, 0.0, 0.0),
5012            Vec3::new(0.0, 0.0, 1.0),
5013            std::f64::consts::FRAC_PI_4,
5014        )
5015        .unwrap();
5016
5017        let curves = intersect_plane_cone(&cone, Vec3::new(0.0, 0.0, 1.0), 1.0).unwrap();
5018        assert!(!curves.is_empty(), "should find intersection with cone");
5019    }
5020
5021    /// The 1u gridfinity spacer lip fuse corner (#1570): the body's lip
5022    /// recess cone (45 deg, opening downward) meets the tool's lip cone
5023    /// (45 deg, opening upward) with axes offset 0.25mm in x and y. Equal
5024    /// half-angle tangents put the whole intersection on the radical plane,
5025    /// so the section is one exact ellipse; the marcher shredded this into
5026    /// ~64 closed micro-loops per pair.
5027    #[test]
5028    fn offset_parallel_equal_angle_cones_give_one_exact_ellipse() {
5029        let c1 = ConicalSurface::new(
5030            Point3::new(
5031                -16.999_999_999_999_975,
5032                -16.999_999_999_999_975,
5033                5.849_999_999_999_951,
5034            ),
5035            Vec3::new(0.0, 0.0, -1.0),
5036            0.785_398_163_397_433_5,
5037        )
5038        .unwrap();
5039        let c2 = ConicalSurface::new(
5040            Point3::new(
5041                -16.750_000_000_000_036,
5042                -16.750_000_000_000_018,
5043                0.749_999_999_999_881,
5044            ),
5045            Vec3::new(0.0, 0.0, 1.0),
5046            0.785_398_163_397_467_6,
5047        )
5048        .unwrap();
5049
5050        let curves = exact_cone_cone(&c1, &c2)
5051            .unwrap()
5052            .expect("offset parallel equal-angle cones must take the radical-plane path");
5053        assert_eq!(curves.len(), 1, "expected exactly one section conic");
5054        assert!(
5055            matches!(curves[0], ExactIntersectionCurve::Ellipse(_)),
5056            "expected an ellipse section, got {:?}",
5057            curves[0]
5058        );
5059        let ExactIntersectionCurve::Ellipse(ellipse) = &curves[0] else {
5060            return;
5061        };
5062
5063        // Every sample must lie on BOTH cones: distance to the axis equals
5064        // tan(half_angle) times the axial distance from the apex, on the
5065        // real nappe of each.
5066        for i in 0..16 {
5067            let p = crate::traits::ParametricCurve::evaluate(ellipse, TAU * f64::from(i) / 16.0);
5068            for (cone, label) in [(&c1, "c1"), (&c2, "c2")] {
5069                let rel = p - cone.apex();
5070                let rel_v = Vec3::new(rel.x(), rel.y(), rel.z());
5071                let axial = rel_v.dot(cone.axis());
5072                let radial = (rel_v - cone.axis() * axial).length();
5073                assert!(
5074                    axial > 0.0,
5075                    "{label}: sample on phantom nappe (axial {axial})"
5076                );
5077                let expect = cone.half_angle().tan() * axial;
5078                assert!(
5079                    (radial - expect).abs() < 1e-9,
5080                    "{label}: sample off surface by {}",
5081                    (radial - expect).abs()
5082                );
5083            }
5084        }
5085    }
5086
5087    /// Opposed cones whose real nappes occupy disjoint half-spaces share a
5088    /// radical-plane conic only on the phantom nappe — the exact path must
5089    /// report a definitive empty intersection, not defer to the marcher.
5090    #[test]
5091    fn offset_parallel_cones_opening_apart_have_no_real_intersection() {
5092        let c1 = ConicalSurface::new(
5093            Point3::new(0.0, 0.0, 5.0),
5094            Vec3::new(0.0, 0.0, -1.0),
5095            std::f64::consts::FRAC_PI_4,
5096        )
5097        .unwrap();
5098        let c2 = ConicalSurface::new(
5099            Point3::new(0.25, 0.25, 20.0),
5100            Vec3::new(0.0, 0.0, 1.0),
5101            std::f64::consts::FRAC_PI_4,
5102        )
5103        .unwrap();
5104        let curves = exact_cone_cone(&c1, &c2)
5105            .unwrap()
5106            .expect("radical-plane path");
5107        assert!(curves.is_empty(), "disjoint nappes must yield no curves");
5108    }
5109
5110    /// Unequal half-angles keep a quadratic term in the pencil — no plane
5111    /// reduction exists, so the exact path must defer to the marcher.
5112    #[test]
5113    fn offset_parallel_cones_with_unequal_angles_defer() {
5114        let c1 = ConicalSurface::new(
5115            Point3::new(0.0, 0.0, 5.0),
5116            Vec3::new(0.0, 0.0, -1.0),
5117            std::f64::consts::FRAC_PI_4,
5118        )
5119        .unwrap();
5120        let c2 = ConicalSurface::new(Point3::new(0.25, 0.25, 0.5), Vec3::new(0.0, 0.0, 1.0), 0.6)
5121            .unwrap();
5122        assert!(exact_cone_cone(&c1, &c2).unwrap().is_none());
5123    }
5124
5125    /// A 45 degree cone and a radius 0.1 tube tilted 40 degrees that pierces
5126    /// both nappes, so the ruling path declines and the general marcher runs:
5127    /// the tube's axis meets the near nappe at (0.1, -1.368, 1.370).
5128    fn cone_and_tilted_tube() -> (ConicalSurface, CylindricalSurface) {
5129        let cone = ConicalSurface::new(
5130            Point3::new(0.0, 0.0, 0.0),
5131            Vec3::new(0.0, 0.0, 1.0),
5132            std::f64::consts::FRAC_PI_4,
5133        )
5134        .unwrap();
5135        let (s, c) = 40.0_f64.to_radians().sin_cos();
5136        let tube =
5137            CylindricalSurface::new(Point3::new(0.1, 0.0, 3.0), Vec3::new(0.0, s, c), 0.1).unwrap();
5138        (cone, tube)
5139    }
5140
5141    #[test]
5142    fn marcher_keeps_to_its_region() {
5143        let (cone, tube) = cone_and_tilted_tube();
5144        let run = |region: Option<Aabb3>| {
5145            let (a, b) = (
5146                AnalyticSurface::Cone(&cone),
5147                AnalyticSurface::Cylinder(&tube),
5148            );
5149            let (va, vb) = (Some((0.5, 4.0)), Some((-5.0, 5.0)));
5150            match region {
5151                Some(r) => intersect_analytic_analytic_in_region(a, b, 32, va, vb, r),
5152                None => intersect_analytic_analytic_bounded(a, b, 32, va, vb),
5153            }
5154            .unwrap()
5155        };
5156        assert!(!run(None).is_empty());
5157        let near = Aabb3 {
5158            min: Point3::new(-0.5, -2.0, 0.8),
5159            max: Point3::new(0.7, -0.7, 2.0),
5160        };
5161        let curves = run(Some(near));
5162        assert!(!curves.is_empty(), "the loop through the region is kept");
5163        // The region's margin (two grid cells) and one marching step past it.
5164        let reach = near.expanded(0.6);
5165        for curve in &curves {
5166            assert!(curve.points.iter().all(|p| reach.contains_point(p.point)));
5167        }
5168        let away = Aabb3 {
5169            min: Point3::new(5.0, 5.0, 5.0),
5170            max: Point3::new(6.0, 6.0, 6.0),
5171        };
5172        assert!(run(Some(away)).is_empty(), "nothing is marched outside it");
5173    }
5174
5175    #[test]
5176    fn coaxial_cones_cross_at_single_circle() {
5177        // Two coaxial truncated cones (outer base r10->top r8, inner r9->r8
5178        // over height 10) cross where their radii match: z=10, r=8. The
5179        // intersection must be ONE clean circle, not the dozens of degenerate
5180        // micro-curves the general marcher produces at near-tangency.
5181        let outer = ConicalSurface::new(
5182            Point3::new(0.0, 0.0, 50.0),
5183            Vec3::new(0.0, 0.0, -1.0),
5184            5.0_f64.atan(),
5185        )
5186        .unwrap();
5187        let inner = ConicalSurface::new(
5188            Point3::new(0.0, 0.0, 90.0),
5189            Vec3::new(0.0, 0.0, -1.0),
5190            10.0_f64.atan(),
5191        )
5192        .unwrap();
5193
5194        let curves = intersect_analytic_analytic_bounded(
5195            AnalyticSurface::Cone(&outer),
5196            AnalyticSurface::Cone(&inner),
5197            32,
5198            None,
5199            None,
5200        )
5201        .unwrap();
5202
5203        assert_eq!(
5204            curves.len(),
5205            1,
5206            "coaxial cones crossing at one circle must yield exactly one curve, got {}",
5207            curves.len()
5208        );
5209        for p in &curves[0].points {
5210            let r = p.point.x().hypot(p.point.y());
5211            assert!(
5212                (p.point.z() - 10.0).abs() < 1e-6 && (r - 8.0).abs() < 1e-6,
5213                "intersection point off the expected z=10,r=8 circle: {:?}",
5214                p.point
5215            );
5216        }
5217    }
5218
5219    #[test]
5220    fn plane_torus_cross_section() {
5221        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 5.0, 1.0).unwrap();
5222
5223        let curves = intersect_plane_torus(&torus, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
5224        assert!(
5225            !curves.is_empty(),
5226            "should find intersection curves with torus"
5227        );
5228    }
5229
5230    /// A plane resting on a torus's tube touches it along one circle of the
5231    /// torus's own radius, ring or spindle, at the tube's top or bottom.
5232    #[test]
5233    fn plane_tangent_to_a_tube_touches_it_along_one_circle() {
5234        for (major, minor) in [(5.0, 1.0), (0.1, 2.45)] {
5235            let torus = ToroidalSurface::new(Point3::new(1.0, 2.0, 3.0), major, minor).unwrap();
5236            for z in [3.0 - minor, 3.0 + minor] {
5237                let exact = exact_plane_analytic(
5238                    AnalyticSurface::Torus(&torus),
5239                    Vec3::new(0.0, 0.0, 1.0),
5240                    z,
5241                )
5242                .unwrap();
5243                assert_eq!(exact.len(), 1, "R={major} r={minor} z={z}");
5244                let circle = match &exact[0] {
5245                    ExactIntersectionCurve::Circle(c) => Some(c),
5246                    _ => None,
5247                };
5248                let c = circle.expect("a circle");
5249                assert!((c.radius() - major).abs() < 1e-12);
5250                assert!((c.center() - Point3::new(1.0, 2.0, z)).length() < 1e-12);
5251
5252                let sampled = intersect_plane_torus(&torus, Vec3::new(0.0, 0.0, 1.0), z).unwrap();
5253                assert_eq!(sampled.len(), 1, "R={major} r={minor} z={z}");
5254            }
5255            // A tilted plane cuts no single circle of radius R.
5256            let single = |normal: Vec3, d: f64| {
5257                matches!(
5258                    exact_plane_analytic(AnalyticSurface::Torus(&torus), normal, d)
5259                        .unwrap()
5260                        .as_slice(),
5261                    [ExactIntersectionCurve::Circle(_)]
5262                )
5263            };
5264            assert!(!single(Vec3::new(1e-6, 0.0, 1.0), 3.0 + minor));
5265        }
5266    }
5267
5268    /// Tangency is read from the plane's distance to the tube's top, so it
5269    /// survives rounding on a large torus, and a plane further inside than
5270    /// the linear tolerance still cuts its two circles.
5271    #[test]
5272    fn plane_tangent_to_a_large_tube_is_read_through_rounding() {
5273        let torus = ToroidalSurface::new(Point3::new(0.3, -0.7, 3.0), 200.0, 100.1).unwrap();
5274        let level = Vec3::new(0.0, 0.0, 1.0);
5275        let curves =
5276            |d: f64| exact_plane_analytic(AnalyticSurface::Torus(&torus), level, d).unwrap();
5277        assert!(matches!(
5278            curves(3.0 + 100.1).as_slice(),
5279            [ExactIntersectionCurve::Circle(_)]
5280        ));
5281        let inside = curves(3.0 + 100.1 - 4e-7);
5282        assert!(!matches!(
5283            inside.as_slice(),
5284            [ExactIntersectionCurve::Circle(_)]
5285        ));
5286    }
5287
5288    /// Signed distance of a point to a z-axis torus centred at the origin:
5289    /// `sqrt((sqrt(x^2+y^2) - R)^2 + z^2) - r`.
5290    fn torus_implicit(p: Point3, major: f64, minor: f64) -> f64 {
5291        let rho = p.x().hypot(p.y());
5292        ((rho - major).hypot(p.z())) - minor
5293    }
5294
5295    /// The gridfinity lightweight base's failing corner, reduced: a cavity
5296    /// corner-round cone (apex below the floor, 45 deg, axis +z) crossed by a
5297    /// parallel-axis boss cylinder. The general marcher returned ~49 overlapping
5298    /// partial traces of one curve here; the algebraic path must return exactly
5299    /// the two branches, each ON both surfaces and inside the cone's v-hint.
5300    #[test]
5301    fn oblique_cone_cylinder_traces_curves_on_both() {
5302        use crate::traits::ParametricCurve;
5303        // A pointed cone opening down from (0, 0, 3), radius half the depth,
5304        // and a rod along y through (x0, ., 1): one loop through the wall
5305        // when the rod pokes out, two when every ruling meets the cone.
5306        let cone = ConicalSurface::new(
5307            Point3::new(0.0, 0.0, 3.0),
5308            Vec3::new(0.0, 0.0, -1.0),
5309            2.0_f64.atan(),
5310        )
5311        .unwrap();
5312        for (x0, loops) in [(0.5, 1), (0.0, 2)] {
5313            let cyl =
5314                CylindricalSurface::new(Point3::new(x0, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
5315                    .unwrap();
5316            for cone_first in [true, false] {
5317                let (a, b) = if cone_first {
5318                    (
5319                        AnalyticSurface::Cone(&cone),
5320                        AnalyticSurface::Cylinder(&cyl),
5321                    )
5322                } else {
5323                    (
5324                        AnalyticSurface::Cylinder(&cyl),
5325                        AnalyticSurface::Cone(&cone),
5326                    )
5327                };
5328                let curves = intersect_analytic_analytic(a, b, 32).unwrap();
5329                assert_eq!(curves.len(), loops, "x0 {x0}: loops");
5330                for c in &curves {
5331                    let (t0, t1) = c.curve.domain();
5332                    for k in 0..=64 {
5333                        let t = (t1 - t0).madd(f64::from(k) / 64.0, t0);
5334                        let p = ParametricCurve::evaluate(&c.curve, t);
5335                        // A cubic through the ruling samples, bent most at the
5336                        // loop's branch points.
5337                        let rod = (p.x() - x0).hypot(p.z() - 1.0);
5338                        assert!(
5339                            (rod - 0.6).abs() < 1e-4,
5340                            "x0 {x0}: off the rod by {}",
5341                            rod - 0.6
5342                        );
5343                        let cone_r = p.x().hypot(p.y());
5344                        assert!(
5345                            (cone_r - 0.5 * (3.0 - p.z())).abs() < 1e-4,
5346                            "x0 {x0}: off the cone at {p:?}"
5347                        );
5348                    }
5349                }
5350            }
5351        }
5352    }
5353
5354    #[test]
5355    fn a_rod_through_a_rings_tube_traces_four_loops() {
5356        use crate::traits::ParametricCurve;
5357        let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
5358        // Along y through (0.5, ., 0.3): every ruling enters and leaves the
5359        // tube on either side of the hole, four roots, four loops.
5360        let rod =
5361            CylindricalSurface::new(Point3::new(0.5, 0.0, 0.3), Vec3::new(0.0, 1.0, 0.0), 0.6)
5362                .unwrap();
5363        let curves = ruling_torus_cylinder(&ring, &rod, true).unwrap();
5364        assert_eq!(curves.len(), 4);
5365        for c in &curves {
5366            let (t0, t1) = c.curve.domain();
5367            for k in 0..=64 {
5368                let p =
5369                    ParametricCurve::evaluate(&c.curve, (t1 - t0).madd(f64::from(k) / 64.0, t0));
5370                let on_rod = (p.x() - 0.5).hypot(p.z() - 0.3) - 0.6;
5371                let on_ring = (p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5;
5372                assert!(
5373                    on_rod.abs() < 1e-4 && on_ring.abs() < 1e-4,
5374                    "off by {on_rod}, {on_ring}"
5375                );
5376            }
5377        }
5378        // Higher, the rod's top rulings pass over the tube: the count varies.
5379        let high =
5380            CylindricalSurface::new(Point3::new(0.5, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
5381                .unwrap();
5382        assert!(ruling_torus_cylinder(&ring, &high, true).is_none());
5383        // Its top clears the tube only between two sampled rulings.
5384        let grazing =
5385            CylindricalSurface::new(Point3::new(0.5, 0.0, 0.9001), Vec3::new(0.0, 1.0, 0.0), 0.6)
5386                .unwrap();
5387        assert!(ruling_torus_cylinder(&ring, &grazing, true).is_none());
5388        // A spindle torus's quartic also holds its inner lemon.
5389        let spindle = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0, 2.0).unwrap();
5390        let thin =
5391            CylindricalSurface::new(Point3::new(0.3, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), 0.2)
5392                .unwrap();
5393        assert!(ruling_torus_cylinder(&spindle, &thin, true).is_none());
5394    }
5395
5396    #[test]
5397    fn a_pin_through_a_ball_traces_two_loops() {
5398        use crate::traits::ParametricCurve;
5399        let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 3.0).unwrap();
5400        // A pin tapering from radius 1.2 at (1, 0.5, -5) to 0.4 at 10 up:
5401        // radial 0.08 per unit of height.
5402        let half = 0.08_f64.atan();
5403        let apex = Point3::new(1.0, 0.5, -5.0 + 1.2 / 0.08);
5404        let pin = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, -1.0), FRAC_PI_2 - half).unwrap();
5405        for cone_first in [true, false] {
5406            let (a, b) = if cone_first {
5407                (AnalyticSurface::Cone(&pin), AnalyticSurface::Sphere(&ball))
5408            } else {
5409                (AnalyticSurface::Sphere(&ball), AnalyticSurface::Cone(&pin))
5410            };
5411            let curves = intersect_analytic_analytic(a, b, 32).unwrap();
5412            assert_eq!(curves.len(), 2, "entry and exit loops");
5413            for c in &curves {
5414                let (t0, t1) = c.curve.domain();
5415                for k in 0..=64 {
5416                    let p = ParametricCurve::evaluate(
5417                        &c.curve,
5418                        (t1 - t0).madd(f64::from(k) / 64.0, t0),
5419                    );
5420                    let on_ball = (p - Point3::new(0.0, 0.0, 0.0)).length() - 3.0;
5421                    let axial = apex.z() - p.z();
5422                    let on_pin = (p.x() - 1.0).hypot(p.y() - 0.5) - axial * half.tan();
5423                    assert!(
5424                        on_ball.abs() < 1e-4 && on_pin.abs() < 1e-4,
5425                        "off by {on_ball}, {on_pin}"
5426                    );
5427                }
5428            }
5429        }
5430        // On the ball's axis the loops are circles, which defer. A pin whose
5431        // apex is inside the ball leaves it once along every generator, and
5432        // one only partly through the ball meets it over the generators that
5433        // reach it: one loop each. One that opens away meets it not at all.
5434        let coaxial =
5435            ConicalSurface::new(Point3::new(0.0, 0.0, 10.0), Vec3::new(0.0, 0.0, -1.0), 1.4)
5436                .unwrap();
5437        assert!(ruling_cone_sphere(&coaxial, &ball, true).is_none());
5438        let aside = ConicalSurface::new(
5439            Point3::new(2.8, 0.0, 10.0),
5440            Vec3::new(0.0, 0.0, -1.0),
5441            FRAC_PI_2 - half,
5442        )
5443        .unwrap();
5444        assert_eq!(ruling_cone_sphere(&aside, &ball, true).unwrap().len(), 1);
5445        let holding = ConicalSurface::new(
5446            Point3::new(1.0, 0.5, 1.0),
5447            Vec3::new(0.0, 0.0, -1.0),
5448            FRAC_PI_2 - half,
5449        )
5450        .unwrap();
5451        assert_eq!(ruling_cone_sphere(&holding, &ball, true).unwrap().len(), 1);
5452        let away = ConicalSurface::new(
5453            Point3::new(1.0, 0.5, 10.0),
5454            Vec3::new(0.0, 0.0, 1.0),
5455            FRAC_PI_2 - half,
5456        )
5457        .unwrap();
5458        assert!(ruling_cone_sphere(&away, &ball, true).unwrap().is_empty());
5459        // Grazing: the generators that miss span about 0.002 radians,
5460        // narrower than a 2048-angle scan's step, and the near and far
5461        // roots join into one loop across them.
5462        let step = TAU / 2048.0;
5463        let grazed =
5464            SphericalSurface::new(Point3::new(step.cos(), step.sin(), 10.0), 9.255_250_971_8)
5465                .unwrap();
5466        let wide =
5467            ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5).unwrap();
5468        assert_eq!(ruling_cone_sphere(&wide, &grazed, true).unwrap().len(), 1);
5469    }
5470
5471    #[test]
5472    fn a_ball_beside_a_cone_meets_it_in_one_loop() {
5473        use crate::traits::ParametricCurve;
5474        // Apex 3 up, opening downward, the radius half the depth below it.
5475        let cone = ConicalSurface::new(
5476            Point3::new(0.0, 0.0, 3.0),
5477            Vec3::new(0.0, 0.0, -1.0),
5478            2.0_f64.atan(),
5479        )
5480        .unwrap();
5481        for (centre, radius) in [
5482            (Point3::new(1.0, 0.8, 1.2), 1.1),
5483            (Point3::new(1.5, 0.0, 0.0), 0.8),
5484        ] {
5485            let ball = SphericalSurface::new(centre, radius).unwrap();
5486            let curves = ruling_cone_sphere(&cone, &ball, true).unwrap();
5487            assert_eq!(curves.len(), 1, "one loop for the ball at {centre:?}");
5488            let (t0, t1) = curves[0].curve.domain();
5489            for k in 0..=64 {
5490                let p = ParametricCurve::evaluate(
5491                    &curves[0].curve,
5492                    (t1 - t0).madd(f64::from(k) / 64.0, t0),
5493                );
5494                let on_ball = (p - centre).length() - radius;
5495                let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
5496                assert!(
5497                    on_ball.abs() < 1e-5 && on_cone.abs() < 1e-5,
5498                    "ball at {centre:?}: off by {on_ball}, {on_cone}"
5499                );
5500            }
5501        }
5502        // A ball the nappe's generators miss, and one on the apex.
5503        let clear = SphericalSurface::new(Point3::new(4.0, 0.0, 0.0), 0.5).unwrap();
5504        assert!(ruling_cone_sphere(&cone, &clear, true).unwrap().is_empty());
5505        let on_apex = SphericalSurface::new(Point3::new(0.6, 0.0, 3.8), 1.0).unwrap();
5506        assert!(ruling_cone_sphere(&cone, &on_apex, true).is_none());
5507    }
5508
5509    #[test]
5510    fn a_ball_holding_a_cones_apex_meets_it_in_one_loop() {
5511        use crate::traits::ParametricCurve;
5512        let cone = ConicalSurface::new(
5513            Point3::new(0.0, 0.0, 3.0),
5514            Vec3::new(0.0, 0.0, -1.0),
5515            2.0_f64.atan(),
5516        )
5517        .unwrap();
5518        // Off the axis, and barely holding the apex: the generators pointing
5519        // away from the centre leave it just past the apex.
5520        for (centre, radius) in [
5521            (Point3::new(0.5, 0.0, 2.5), 2.0),
5522            (Point3::new(-0.4, 0.3, 2.0), 1.5),
5523            (Point3::new(0.0, 0.8, 3.0), 0.8001),
5524            (Point3::new(0.0, 0.8, 3.0), 0.800_001),
5525        ] {
5526            let ball = SphericalSurface::new(centre, radius).unwrap();
5527            let curves = ruling_cone_sphere(&cone, &ball, true).unwrap();
5528            assert_eq!(curves.len(), 1, "one loop for the ball at {centre:?}");
5529            let (t0, t1) = curves[0].curve.domain();
5530            for k in 0..=4096 {
5531                let p = ParametricCurve::evaluate(
5532                    &curves[0].curve,
5533                    (t1 - t0).madd(f64::from(k) / 4096.0, t0),
5534                );
5535                let on_ball = (p - centre).length() - radius;
5536                let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
5537                assert!(
5538                    on_ball.abs() < 1e-5 && on_cone.abs() < 1e-5 && p.z() < 3.0,
5539                    "ball at {centre:?}: off by {on_ball}, {on_cone} at {p:?}"
5540                );
5541            }
5542        }
5543    }
5544
5545    #[test]
5546    fn oblique_cone_cylinder_defers_where_rulings_cannot_trace_it() {
5547        let t = 2.0_f64.atan();
5548        let cone =
5549            ConicalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(0.0, 0.0, -1.0), t).unwrap();
5550        // A rod through the apex meets the far nappe.
5551        let through_apex =
5552            CylindricalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
5553                .unwrap();
5554        assert!(ruling_cone_cylinder(&cone, &through_apex, true).is_none());
5555        // A rod along a generator meets each ruling once.
5556        let generator = Vec3::new(t.cos(), 0.0, -t.sin());
5557        let along = CylindricalSurface::new(Point3::new(0.0, 0.3, 0.0), generator, 0.2).unwrap();
5558        assert!(ruling_cone_cylinder(&cone, &along, true).is_none());
5559        // A pin's tip just through a tube's wall: the tube's rulings that
5560        // meet it span a window narrower than the sampling.
5561        let pin =
5562            ConicalSurface::new(Point3::new(20.5, 0.0, 0.0), Vec3::new(-1.0, 0.0, 0.0), t).unwrap();
5563        let tube =
5564            CylindricalSurface::new(Point3::new(0.0, 0.0, -10.0), Vec3::new(0.0, 0.0, 1.0), 20.0)
5565                .unwrap();
5566        assert!(ruling_cone_cylinder(&pin, &tube, true).is_none());
5567    }
5568
5569    #[test]
5570    fn parallel_cone_cylinder_gives_two_exact_branches() {
5571        use crate::traits::ParametricCurve;
5572        let cone = ConicalSurface::new(
5573            Point3::new(-5.45, -36.55, -4.85),
5574            Vec3::new(0.0, 0.0, 1.0),
5575            std::f64::consts::FRAC_PI_4,
5576        )
5577        .unwrap();
5578        let cyl = CylindricalSurface::new(
5579            Point3::new(-8.0, -34.0, -5.0),
5580            Vec3::new(0.0, 0.0, 1.0),
5581            4.45,
5582        )
5583        .unwrap();
5584        // The cone face spans z in [-3.8, -3.0]; v = (z - apex_z) / sin(45 deg).
5585        let v_hint = (1.484_924_240_492_058, 2.616_295_090_390_43);
5586        let curves = intersect_analytic_analytic_bounded(
5587            AnalyticSurface::Cone(&cone),
5588            AnalyticSurface::Cylinder(&cyl),
5589            32,
5590            Some(v_hint),
5591            Some((0.0, 2.5)),
5592        )
5593        .unwrap();
5594
5595        assert_eq!(curves.len(), 2, "expected exactly the two branches");
5596        for c in &curves {
5597            let (t0, t1) = c.curve.domain();
5598            for k in 0..=32 {
5599                let t = (t1 - t0).madd(f64::from(k) / 32.0, t0);
5600                let p = ParametricCurve::evaluate(&c.curve, t);
5601                // On the cylinder: radial distance from its axis is the radius.
5602                let radial = ((p.x() + 8.0).powi(2) + (p.y() + 34.0).powi(2)).sqrt();
5603                assert!((radial - 4.45).abs() < 1e-6, "off cylinder: {radial}");
5604                // On the cone: radial distance from its axis is z - apex_z.
5605                let cone_r = ((p.x() + 5.45).powi(2) + (p.y() + 36.55).powi(2)).sqrt();
5606                assert!((cone_r - (p.z() + 4.85)).abs() < 1e-6, "off cone at {p:?}");
5607                // Inside the cone face's own v-window (the hint is respected).
5608                assert!(p.z() >= -3.8 - 1e-9 && p.z() <= -3.0 + 1e-9, "z={}", p.z());
5609            }
5610        }
5611    }
5612
5613    #[test]
5614    fn parallel_rod_through_a_cones_wall_closes_one_loop() {
5615        use crate::traits::ParametricCurve;
5616        // Apex 3 up, opening downward, the radius half the depth below it.
5617        let cone = ConicalSurface::new(
5618            Point3::new(0.0, 0.0, 3.0),
5619            Vec3::new(0.0, 0.0, -1.0),
5620            2.0_f64.atan(),
5621        )
5622        .unwrap();
5623        // Beside the axis: each ruling meets the nappe once.
5624        for (x, y) in [(0.0, 1.3), (1.2, 0.5)] {
5625            let rod =
5626                CylindricalSurface::new(Point3::new(x, y, -10.0), Vec3::new(0.0, 0.0, 1.0), 0.6)
5627                    .unwrap();
5628            let curves = algebraic_parallel_cone_cylinder(&cone, &rod, None, None)
5629                .unwrap()
5630                .unwrap();
5631            assert_eq!(curves.len(), 1, "one closed loop at ({x}, {y})");
5632            let (t0, t1) = curves[0].curve.domain();
5633            let (first, last) = (
5634                ParametricCurve::evaluate(&curves[0].curve, t0),
5635                ParametricCurve::evaluate(&curves[0].curve, t1),
5636            );
5637            assert!((first - last).length() < 1e-9, "open at ({x}, {y})");
5638            for k in 0..=64 {
5639                let p = ParametricCurve::evaluate(
5640                    &curves[0].curve,
5641                    (t1 - t0).madd(f64::from(k) / 64.0, t0),
5642                );
5643                let on_rod = (p.x() - x).hypot(p.y() - y) - 0.6;
5644                let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
5645                assert!(
5646                    on_rod.abs() < 1e-5 && on_cone.abs() < 1e-5,
5647                    "({x}, {y}): off by {on_rod}, {on_cone}"
5648                );
5649            }
5650        }
5651        // Around the axis, and beside it by less than the bend the rulings
5652        // resolve: two branches.
5653        for (x, y) in [(0.3, 0.2), (0.65, 0.0)] {
5654            let rod =
5655                CylindricalSurface::new(Point3::new(x, y, -10.0), Vec3::new(0.0, 0.0, 1.0), 0.6)
5656                    .unwrap();
5657            let curves = algebraic_parallel_cone_cylinder(&cone, &rod, None, None)
5658                .unwrap()
5659                .unwrap();
5660            assert_eq!(curves.len(), 2, "two branches at ({x}, {y})");
5661        }
5662    }
5663
5664    /// A coaxial pair has no radical line; the algebraic path must defer rather
5665    /// than divide by a zero axis separation.
5666    #[test]
5667    fn coaxial_cone_cylinder_defers_to_other_paths() {
5668        let cone = ConicalSurface::new(
5669            Point3::new(0.0, 0.0, 0.0),
5670            Vec3::new(0.0, 0.0, 1.0),
5671            std::f64::consts::FRAC_PI_4,
5672        )
5673        .unwrap();
5674        let cyl =
5675            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
5676                .unwrap();
5677        assert!(
5678            algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
5679                .unwrap()
5680                .is_none()
5681        );
5682    }
5683
5684    #[test]
5685    fn oblique_cone_cylinder_defers_to_other_paths() {
5686        let cone = ConicalSurface::new(
5687            Point3::new(0.0, 0.0, 0.0),
5688            Vec3::new(0.0, 0.0, 1.0),
5689            std::f64::consts::FRAC_PI_4,
5690        )
5691        .unwrap();
5692        let cyl =
5693            CylindricalSurface::new(Point3::new(3.0, 0.0, 1.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
5694                .unwrap();
5695        assert!(
5696            algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
5697                .unwrap()
5698                .is_none()
5699        );
5700    }
5701
5702    #[test]
5703    fn plane_torus_lobe_closes_and_stays_on_surface() {
5704        use crate::traits::ParametricCurve;
5705        let (major, minor) = (10.0, 3.0);
5706        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5707
5708        // The census cutting planes (y=-4, x=6) each cut the +x and -x tube lobes
5709        // in a CLOSED oval. The greedy marcher stops one grid step short of
5710        // closing; the wrap-close must make every fitted lobe close exactly.
5711        for (n, d) in [
5712            (Vec3::new(0.0, -1.0, 0.0), 4.0),  // y = -4
5713            (Vec3::new(-1.0, 0.0, 0.0), -6.0), // x = 6
5714            (Vec3::new(0.0, 0.0, 1.0), 0.0),   // z = 0 -> two concentric circles
5715        ] {
5716            let curves = intersect_plane_torus(&torus, n, d).unwrap();
5717            assert!(!curves.is_empty(), "plane n={n:?} d={d} found no curves");
5718            for c in &curves {
5719                let p0 = ParametricCurve::evaluate(&c.curve, 0.0);
5720                let p1 = ParametricCurve::evaluate(&c.curve, 1.0);
5721                assert!(
5722                    (p0 - p1).length() < 1e-7,
5723                    "lobe not closed: gap={} (n={n:?} d={d})",
5724                    (p0 - p1).length()
5725                );
5726                // Every fitted sample stays on the torus (shape-preserving).
5727                for k in 0..=64 {
5728                    let t = f64::from(k) / 64.0;
5729                    let p = ParametricCurve::evaluate(&c.curve, t);
5730                    assert!(
5731                        torus_implicit(p, major, minor).abs() < 1e-2,
5732                        "off-surface point {p:?} implicit={}",
5733                        torus_implicit(p, major, minor)
5734                    );
5735                }
5736            }
5737        }
5738    }
5739
5740    /// A plane tangent to the inner equator (x = major - minor = 7) cuts a
5741    /// figure-eight that crosses itself on that equator. It comes out as its
5742    /// two lobes, each a loop that starts and ends on the node, one either
5743    /// side of the plane y = 0, never as one loop sealed across the node.
5744    #[test]
5745    fn plane_torus_inner_tangent_figure_eight_is_two_loops_through_its_node() {
5746        let (major, minor) = (10.0, 3.0);
5747        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5748        let curves =
5749            intersect_plane_torus(&torus, Vec3::new(-1.0, 0.0, 0.0), -(major - minor)).unwrap();
5750        assert_eq!(curves.len(), 2, "one loop per lobe");
5751        let node = Point3::new(major - minor, 0.0, 0.0);
5752        let mut sides = Vec::new();
5753        for c in &curves {
5754            let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
5755            assert!((first - node).length() < 1e-6, "starts at {first:?}");
5756            assert_eq!(first, last, "closes on the node");
5757            for p in c.points.iter().map(|p| p.point) {
5758                assert!((p.x() - node.x()).abs() < 1e-9, "off the plane at {p:?}");
5759                assert!(
5760                    torus_implicit(p, major, minor).abs() < 1e-6,
5761                    "off the torus at {p:?}"
5762                );
5763            }
5764            let y: f64 = c.points.iter().map(|p| p.point.y()).sum();
5765            sides.push(y > 0.0);
5766            assert!(
5767                c.points.iter().all(|p| p.point.y() * y >= -1e-9),
5768                "a lobe crosses y = 0"
5769            );
5770        }
5771        assert_ne!(sides[0], sides[1], "the lobes lie either side of y = 0");
5772    }
5773
5774    /// A wall just off the inner tangent has no node. Just past it the
5775    /// section has a gap 0.028 wide in tube angle about the inner equator,
5776    /// between two samples inside it, and is one loop turning either side of
5777    /// the gap; just short of it the section winds the tube twice. Every
5778    /// point lies on the wall.
5779    #[test]
5780    fn a_wall_just_off_the_inner_tangent_cuts_no_node() {
5781        let (major, minor) = (3.0, 1.0);
5782        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5783        for (x, loops) in [(2.0001, 1), (1.9999, 2)] {
5784            let curves = intersect_plane_torus(&torus, Vec3::new(1.0, 0.0, 0.0), x).unwrap();
5785            assert_eq!(curves.len(), loops, "x = {x}");
5786            for c in &curves {
5787                let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
5788                assert_eq!(first, last, "x = {x}: the loop closes");
5789                for p in c.points.iter().map(|p| p.point) {
5790                    assert!((p.x() - x).abs() < 1e-9, "x = {x}: off the wall at {p:?}");
5791                    assert!(
5792                        torus_implicit(p, major, minor).abs() < 1e-6,
5793                        "x = {x}: off the torus at {p:?}"
5794                    );
5795                }
5796            }
5797        }
5798        // The loop past the tangent turns either side of the gap, 0.028 apart.
5799        let curves = intersect_plane_torus(&torus, Vec3::new(1.0, 0.0, 0.0), 2.0001).unwrap();
5800        let low = curves[0]
5801            .points
5802            .iter()
5803            .map(|p| p.point)
5804            .filter(|p| p.y().abs() < 1e-6)
5805            .map(Point3::z)
5806            .collect::<Vec<_>>();
5807        let gap = (2.0001_f64 - 2.0)
5808            .madd(2.0, -(2.0001_f64 - 2.0).powi(2))
5809            .sqrt();
5810        assert!(
5811            low.iter().any(|z| (z - gap).abs() < 1e-6)
5812                && low.iter().any(|z| (z + gap).abs() < 1e-6),
5813            "turns at {low:?}, not at z = ±{gap}"
5814        );
5815    }
5816
5817    /// A plane tangent to the tube's inner side off its equator, at a saddle,
5818    /// cuts a figure-eight that crosses itself where it touches. Its lobes
5819    /// come out as two loops, each starting and ending on that node.
5820    #[test]
5821    fn a_tilted_plane_tangent_inside_the_tube_cuts_two_loops_through_its_node() {
5822        let (major, minor) = (3.0, 1.0);
5823        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5824        for v0 in [1.7_f64, 2.0, 2.5, 4.0] {
5825            let normal = Vec3::new(v0.cos(), 0.0, v0.sin());
5826            let node = torus.evaluate(0.0, v0);
5827            let d = normal.dot(Vec3::new(node.x(), node.y(), node.z()));
5828            let curves = intersect_plane_torus(&torus, normal, d).unwrap();
5829            assert_eq!(curves.len(), 2, "v0 {v0}: one loop per lobe");
5830            for c in &curves {
5831                let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
5832                assert!(
5833                    (first - node).length() < 1e-6,
5834                    "v0 {v0}: starts at {first:?}, not {node:?}"
5835                );
5836                assert_eq!(first, last, "v0 {v0}: closes on the node");
5837                for p in c.points.iter().map(|p| p.point) {
5838                    let off = normal.dot(Vec3::new(p.x(), p.y(), p.z())) - d;
5839                    assert!(off.abs() < 1e-9, "v0 {v0}: off the plane at {p:?}");
5840                    assert!(
5841                        torus_implicit(p, major, minor).abs() < 1e-6,
5842                        "v0 {v0}: off the torus at {p:?}"
5843                    );
5844                }
5845            }
5846        }
5847    }
5848
5849    /// A wall parallel to the axis cuts one loop from the ring past the
5850    /// inner equator (its two turns where the branches meet), and two loops
5851    /// winding the tube inside it; each closes, at any scale, however near
5852    /// the wall runs to an equator.
5853    #[test]
5854    fn plane_torus_wall_sections_close_into_their_loops() {
5855        for (major, minor) in [(4.0, 1.5), (100.0, 30.0), (0.05, 0.01)] {
5856            let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5857            for k in 1..200 {
5858                let (d, want) = match k.cmp(&100) {
5859                    // Within the inner equator: two loops winding the tube.
5860                    std::cmp::Ordering::Less => ((major - minor) * f64::from(k) / 100.0, 2),
5861                    // Past it, short of the outer equator: one loop.
5862                    std::cmp::Ordering::Greater => (
5863                        2.0f64.madd(minor * f64::from(k - 100) / 100.0, major - minor),
5864                        1,
5865                    ),
5866                    std::cmp::Ordering::Equal => continue,
5867                };
5868                let loops = plane_torus_loops(&torus, Vec3::new(1.0, 0.0, 0.0), d, 128);
5869                let closed = loops
5870                    .iter()
5871                    .filter(|l| (l[0].point - l[l.len() - 1].point).length() < 1e-12)
5872                    .count();
5873                assert_eq!(
5874                    (loops.len(), closed),
5875                    (want, want),
5876                    "R {major} r {minor}, wall at {d}"
5877                );
5878            }
5879        }
5880    }
5881
5882    /// A plane through the centre tilted a little from the equator cuts two
5883    /// loops that each run all the way round the axis on a short run of `v`;
5884    /// their fitted curves stay on the torus.
5885    #[test]
5886    fn plane_torus_sections_round_the_axis_stay_on_the_torus() {
5887        let (major, minor) = (4.0, 1.5);
5888        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5889        for tilt in [0.03_f64, 0.08, 0.2] {
5890            let normal = Vec3::new(tilt.sin(), 0.0, tilt.cos());
5891            let curves = intersect_plane_torus(&torus, normal, 0.0).unwrap();
5892            assert_eq!(curves.len(), 2, "tilt {tilt}");
5893            for c in &curves {
5894                let (t0, t1) = c.curve.domain();
5895                let off = (0..=400)
5896                    .map(|k| {
5897                        let p = c.curve.evaluate((t1 - t0).madd(f64::from(k) / 400.0, t0));
5898                        (p.x().hypot(p.y()) - major).hypot(p.z()) - minor
5899                    })
5900                    .fold(0.0_f64, |m, e| m.max(e.abs()));
5901                assert!(
5902                    off < 1e-6,
5903                    "tilt {tilt}: fitted section {off} off the torus"
5904                );
5905            }
5906        }
5907    }
5908
5909    #[test]
5910    fn line_torus_box_edge_crossing_is_exact() {
5911        // The census box edge x=6, y=-4 (z varying) crosses the torus (R=10,r=3)
5912        // at z = ±sqrt(r² − (rho−R)²), rho = hypot(6,4) ≈ 7.2111 → z ≈ ±1.1055.
5913        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
5914        let ts = intersect_line_torus(
5915            &torus,
5916            Point3::new(6.0, -4.0, -5.0),
5917            Vec3::new(0.0, 0.0, 1.0),
5918        );
5919        // Vertical line through (6,-4) meets the tube twice.
5920        assert_eq!(ts.len(), 2, "expected 2 crossings, got {ts:?}");
5921        let zs: Vec<f64> = ts.iter().map(|t| -5.0 + t).collect();
5922        let rho = 6.0_f64.hypot(4.0);
5923        let z_exp = (9.0 - (rho - 10.0).powi(2)).sqrt();
5924        assert!(
5925            (zs[0] - (-z_exp)).abs() < 1e-9,
5926            "z0={} exp={}",
5927            zs[0],
5928            -z_exp
5929        );
5930        assert!((zs[1] - z_exp).abs() < 1e-9, "z1={} exp={}", zs[1], z_exp);
5931        // Each crossing lies on the torus.
5932        for &t in &ts {
5933            let p = Point3::new(6.0, -4.0, -5.0 + t);
5934            let rho = p.x().hypot(p.y());
5935            let impl_v = (rho - 10.0).hypot(p.z()) - 3.0;
5936            assert!(impl_v.abs() < 1e-9, "off-torus impl={impl_v}");
5937        }
5938    }
5939
5940    /// A ray out of a pocket corner's spindle torus (major 0.1, minor 2.45)
5941    /// meets the tube swung across the axis at t 0.124 and its own tube at
5942    /// 0.398: each root lies on one of the two tubes, not polished off the
5943    /// first onto a point beside the second.
5944    #[test]
5945    fn line_spindle_torus_roots_lie_on_their_tubes() {
5946        let torus = ToroidalSurface::new(Point3::new(41.0, 17.0, 4.7), 0.1, 2.45).unwrap();
5947        let origin = Point3::new(42.36, 18.31, 3.4);
5948        let dir = Vec3::new(
5949            0.573_576_436_351_046,
5950            0.740_535_693_464_567_5,
5951            0.350_889_803_483_932_2,
5952        );
5953        let ts = intersect_line_torus(&torus, origin, dir);
5954        let tube = |t: f64, across: f64| {
5955            let q = origin + dir * t;
5956            ((q.x() - 41.0).hypot(q.y() - 17.0) - across * 0.1).hypot(q.z() - 4.7) - 2.45
5957        };
5958        for &t in &ts {
5959            assert!(
5960                tube(t, 1.0).abs().min(tube(t, -1.0).abs()) < 1e-9,
5961                "root {t} off both tubes in {ts:?}"
5962            );
5963        }
5964        for want in [0.124, 0.398] {
5965            assert!(
5966                ts.iter().any(|&t| (t - want).abs() < 1e-3),
5967                "no root near {want} in {ts:?}"
5968            );
5969        }
5970    }
5971
5972    #[test]
5973    fn line_torus_miss_and_tangent() {
5974        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
5975        // A vertical line at rho beyond the outer rim (x=20) misses entirely.
5976        let miss = intersect_line_torus(
5977            &torus,
5978            Point3::new(20.0, 0.0, 0.0),
5979            Vec3::new(0.0, 0.0, 1.0),
5980        );
5981        assert!(miss.is_empty(), "expected no crossings, got {miss:?}");
5982        // The z-axis (rho=0) passes through the hole — no intersection.
5983        let axis =
5984            intersect_line_torus(&torus, Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0));
5985        assert!(axis.is_empty(), "z-axis should miss the tube, got {axis:?}");
5986    }
5987
5988    #[test]
5989    fn dispatch_via_analytic_surface() {
5990        let cyl =
5991            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
5992                .unwrap();
5993        let curves = intersect_plane_analytic(
5994            AnalyticSurface::Cylinder(&cyl),
5995            Vec3::new(0.0, 0.0, 1.0),
5996            0.0,
5997        )
5998        .unwrap();
5999        assert!(!curves.is_empty());
6000    }
6001
6002    #[test]
6003    fn perpendicular_cylinders_intersect() {
6004        let cyl_z =
6005            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
6006                .unwrap();
6007        let cyl_x =
6008            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
6009                .unwrap();
6010
6011        let curves = intersect_analytic_analytic(
6012            AnalyticSurface::Cylinder(&cyl_z),
6013            AnalyticSurface::Cylinder(&cyl_x),
6014            16,
6015        )
6016        .unwrap();
6017
6018        assert!(
6019            !curves.is_empty(),
6020            "perpendicular cylinders should intersect"
6021        );
6022
6023        for c in &curves {
6024            assert!(
6025                c.points.len() >= 2,
6026                "intersection curve should have >= 2 points, got {}",
6027                c.points.len()
6028            );
6029        }
6030    }
6031
6032    /// Neither cylinder's rulings all meet the other: the curve is one loop
6033    /// joined at its two branch points.
6034    #[test]
6035    fn partially_overlapping_cylinders_meet_in_one_closed_loop() {
6036        let cyl_z =
6037            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
6038                .unwrap();
6039        let cyl_x =
6040            CylindricalSurface::new(Point3::new(0.0, 1.2, 0.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
6041                .unwrap();
6042        let curves = algebraic_cylinder_cylinder(&cyl_z, &cyl_x)
6043            .unwrap()
6044            .unwrap();
6045        assert_eq!(curves.len(), 1);
6046        let curve = &curves[0].curve;
6047        let (t0, t1) = curve.domain();
6048        assert!((curve.evaluate(t0) - curve.evaluate(t1)).length() < 1e-9);
6049        let off = |p: Point3| {
6050            let on_z = (p.x().hypot(p.y()) - 1.0).abs();
6051            let on_x = ((p.y() - 1.2).hypot(p.z()) - 1.0).abs();
6052            on_z.max(on_x)
6053        };
6054        let worst = (0..=400)
6055            .map(|k| off(curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0)))
6056            .fold(0.0, f64::max);
6057        assert!(worst < 2e-4, "curve leaves the cylinders by {worst}");
6058    }
6059
6060    /// Near tangency the thick cylinder's window of rulings (0.02 either side
6061    /// of a quarter turn) falls between its samples; the thin one's sweep
6062    /// finds the loop.
6063    #[test]
6064    fn near_tangent_cylinders_find_their_loop_on_the_thinner_sweep() {
6065        let cyl_z =
6066            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
6067                .unwrap();
6068        let cyl_x =
6069            CylindricalSurface::new(Point3::new(0.0, 1.1998, 0.0), Vec3::new(1.0, 0.0, 0.0), 0.2)
6070                .unwrap();
6071        let curves = algebraic_cylinder_cylinder(&cyl_z, &cyl_x)
6072            .unwrap()
6073            .expect("the thin cylinder's sweep finds the loop");
6074        assert_eq!(curves.len(), 1);
6075    }
6076
6077    /// Cylinders of radius 1.5 whose axes cross at 60° meet in two ellipses
6078    /// crossing at the ends of the axes' common normal: two exact loops,
6079    /// one from each end, each the halves of both ellipses on one side of
6080    /// the crossing along the first axis, on both cylinders to rounding.
6081    #[test]
6082    fn equal_cylinders_with_crossing_axes_meet_in_two_cornered_loops() {
6083        let crossing = Point3::new(1.0, 2.0, 3.0);
6084        let (s, c) = 60.0_f64.to_radians().sin_cos();
6085        let (d1, d2) = (Vec3::new(0.0, 0.0, 1.0), Vec3::new(s, 0.0, c));
6086        let c1 = CylindricalSurface::new(crossing - d1 * 2.0, d1, 1.5).unwrap();
6087        let c2 = CylindricalSurface::new(crossing + d2 * 0.7, d2, 1.5).unwrap();
6088        let curves = algebraic_cylinder_cylinder(&c1, &c2).unwrap().unwrap();
6089        assert_eq!(curves.len(), 2);
6090        let off = |p: Point3, cyl: &CylindricalSurface| {
6091            let q = p - cyl.origin();
6092            ((q - cyl.axis() * q.dot(cyl.axis())).length() - 1.5).abs()
6093        };
6094        let ends = [
6095            crossing + Vec3::new(0.0, 1.5, 0.0),
6096            crossing - Vec3::new(0.0, 1.5, 0.0),
6097        ];
6098        let mut vertices: Vec<Point3> = Vec::new();
6099        for (ic, (end, side)) in curves.iter().zip([(ends[0], 1.0), (ends[1], -1.0)]) {
6100            let (t0, t1) = ic.curve.domain();
6101            for k in 0..=400 {
6102                let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
6103                assert!(off(p, &c1).max(off(p, &c2)) < 1e-13);
6104                assert!(side * (p - crossing).dot(d1) > -1e-13);
6105            }
6106            assert!((ic.curve.evaluate(t0) - end).length() < 1e-14);
6107            assert!((ic.curve.evaluate(t1) - end).length() < 1e-14);
6108            let other = ends[usize::from(side > 0.0)];
6109            assert!((ic.curve.evaluate(0.5) - other).length() < 1e-14);
6110            for t in [0.25, 0.75] {
6111                let vertex = ic.curve.evaluate(t);
6112                assert!(vertices.iter().all(|&v| (v - vertex).length() > 1.0));
6113                vertices.push(vertex);
6114            }
6115        }
6116    }
6117
6118    /// Axes that miss each other by 1e-9, or radii that differ by as much,
6119    /// part the curves where the ellipses would cross; neither is taken for
6120    /// a pair of ellipses, nor a miss of 1e-6 read between origins 1e8
6121    /// apart along an axis.
6122    #[test]
6123    fn nearly_crossing_equal_cylinders_are_not_ellipses() {
6124        let z = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
6125            .unwrap();
6126        let x = |(x0, y): (f64, f64), r: f64| {
6127            CylindricalSurface::new(Point3::new(x0, y, 0.0), Vec3::new(1.0, 0.0, 0.0), r).unwrap()
6128        };
6129        let taken = |c: &CylindricalSurface| crossing_equal_cylinders(&z, c).unwrap().is_some();
6130        assert!(taken(&x((-2.0, 0.0), 1.0)));
6131        assert!(!taken(&x((-2.0, 1e-9), 1.0)));
6132        assert!(!taken(&x((-2.0, 0.0), 1.0 + 1e-9)));
6133        assert!(!taken(&x((-1e8, 1e-6), 1.0)));
6134    }
6135
6136    /// Axes 1e-8 and 1.5e-5 apart in angle cross in ellipses whose far
6137    /// vertices rounding alone would move past the tolerance; they are
6138    /// left to the rulings.
6139    #[test]
6140    fn nearly_parallel_equal_cylinders_are_not_ellipses() {
6141        let z = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 10.0)
6142            .unwrap();
6143        for slope in [1e-8, 1.5e-5] {
6144            let tilted = CylindricalSurface::new(
6145                Point3::new(0.0, 0.0, 0.0),
6146                Vec3::new(slope, 0.0, 1.0),
6147                10.0,
6148            )
6149            .unwrap();
6150            assert!(crossing_equal_cylinders(&z, &tilted).unwrap().is_none());
6151        }
6152    }
6153
6154    #[test]
6155    fn sphere_cylinder_intersect() {
6156        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
6157        let cyl =
6158            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
6159                .unwrap();
6160
6161        let curves = intersect_analytic_analytic(
6162            AnalyticSurface::Sphere(&sphere),
6163            AnalyticSurface::Cylinder(&cyl),
6164            16,
6165        )
6166        .unwrap();
6167
6168        // A sphere of radius 2 and a cylinder of radius 1, both centered
6169        // at the origin, should intersect (the cylinder passes through
6170        // the sphere).
6171        assert!(!curves.is_empty(), "sphere and cylinder should intersect");
6172    }
6173
6174    #[test]
6175    fn exact_sphere_cylinder_coaxial_two_circles() {
6176        // Sphere r=6 at origin, coaxial cylinder r=3 along z: two latitude
6177        // circles at z = ±sqrt(36-9) = ±sqrt(27), each of radius 3.
6178        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
6179        let cyl =
6180            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
6181                .unwrap();
6182        let circles = exact_sphere_cylinder(&sphere, &cyl)
6183            .unwrap()
6184            .expect("coaxial case returns Some");
6185        assert_eq!(circles.len(), 2, "through-bore meets the sphere twice");
6186        let mut zs: Vec<f64> = circles
6187            .iter()
6188            .filter_map(|c| match c {
6189                ExactIntersectionCurve::Circle(circle) => {
6190                    assert!(
6191                        (circle.radius() - 3.0).abs() < 1e-9,
6192                        "rim radius == cyl radius"
6193                    );
6194                    Some(circle.center().z())
6195                }
6196                _ => None,
6197            })
6198            .collect();
6199        assert_eq!(zs.len(), 2, "both sections must be exact circles");
6200        zs.sort_by(f64::total_cmp);
6201        let z = 27.0_f64.sqrt();
6202        assert!((zs[0] + z).abs() < 1e-9 && (zs[1] - z).abs() < 1e-9);
6203    }
6204
6205    #[test]
6206    fn exact_sphere_cylinder_non_coaxial_defers() {
6207        // Cylinder axis offset from the sphere center → quartic curve, deferred.
6208        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
6209        let cyl =
6210            CylindricalSurface::new(Point3::new(2.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
6211                .unwrap();
6212        assert!(
6213            exact_sphere_cylinder(&sphere, &cyl).unwrap().is_none(),
6214            "non-coaxial sphere/cylinder defers to the marcher"
6215        );
6216    }
6217
6218    #[test]
6219    fn a_ball_on_a_cones_axis_meets_it_in_circles() {
6220        // Apex 3 up, opening downward, the radius half the depth below it.
6221        let cone = ConicalSurface::new(
6222            Point3::new(0.0, 0.0, 3.0),
6223            Vec3::new(0.0, 0.0, -1.0),
6224            2.0_f64.atan(),
6225        )
6226        .unwrap();
6227        for (height, radius, count) in [
6228            (0.0, 2.0, 2), // through the cone's middle
6229            (2.5, 1.3, 1), // swallowing the apex
6230            (2.5, 0.5, 1), // through the apex: the apex root is no circle
6231            (0.0, 1.0, 0), // inside, clear of the wall
6232            (5.0, 1.0, 0), // on the other nappe's side
6233        ] {
6234            let centre = Point3::new(0.0, 0.0, height);
6235            let ball = SphericalSurface::new(centre, radius).unwrap();
6236            let curves = exact_cone_sphere(&cone, &ball).unwrap().unwrap();
6237            let circles = circles_of(&curves);
6238            assert_eq!(circles.len(), count, "ball at {height}, radius {radius}");
6239            for circle in circles {
6240                for k in 0..16 {
6241                    let p = circle.evaluate(TAU * f64::from(k) / 16.0);
6242                    let on_ball = (p - centre).length() - radius;
6243                    let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
6244                    assert!(
6245                        on_ball.abs() < 1e-9 && on_cone.abs() < 1e-9,
6246                        "ball at {height}: off by {on_ball}, {on_cone}"
6247                    );
6248                }
6249            }
6250        }
6251        let aside = SphericalSurface::new(Point3::new(0.5, 0.0, 0.0), 2.0).unwrap();
6252        assert!(exact_cone_sphere(&cone, &aside).unwrap().is_none());
6253        // A ball touching a wide cone a million units out, where the
6254        // discriminant cancels to a few ulps below zero.
6255        let wide =
6256            ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.3).unwrap();
6257        let far = SphericalSurface::new(Point3::new(0.0, 0.0, 1e6), 1e6 * 0.3_f64.cos()).unwrap();
6258        let curves = exact_cone_sphere(&wide, &far).unwrap().unwrap();
6259        let circles = circles_of(&curves);
6260        assert_eq!(circles.len(), 1, "the touch");
6261        let touch = 1e6 * 0.3_f64.sin() * 0.3_f64.cos();
6262        assert!(
6263            (circles[0].radius() - touch).abs() < 1e-3,
6264            "{}",
6265            circles[0].radius()
6266        );
6267    }
6268
6269    /// The circles among exact section curves.
6270    fn circles_of(curves: &[ExactIntersectionCurve]) -> Vec<&Circle3D> {
6271        curves
6272            .iter()
6273            .filter_map(|c| match c {
6274                ExactIntersectionCurve::Circle(circle) => Some(circle),
6275                _ => None,
6276            })
6277            .collect()
6278    }
6279
6280    /// Worst distance of a circle's points from a torus and from a second
6281    /// surface given by its own distance function.
6282    fn worst_off(
6283        circles: &[&Circle3D],
6284        torus: &ToroidalSurface,
6285        other: impl Fn(Point3) -> f64,
6286    ) -> f64 {
6287        let mut worst = 0.0_f64;
6288        for circle in circles {
6289            for k in 0..16 {
6290                let p = circle.evaluate(TAU * f64::from(k) / 16.0);
6291                let q = p - torus.center();
6292                let along = q.dot(torus.z_axis());
6293                let rho = (q - torus.z_axis() * along).length();
6294                let off = ((rho - torus.major_radius()).hypot(along) - torus.minor_radius()).abs();
6295                worst = worst.max(off).max(other(p).abs());
6296            }
6297        }
6298        worst
6299    }
6300
6301    #[test]
6302    fn exact_sphere_torus_meets_a_ball_on_the_axis_in_circles() {
6303        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
6304        for height in [0.0, 1.0] {
6305            let centre = Point3::new(0.0, 0.0, height);
6306            let sphere = SphericalSurface::new(centre, 3.0).unwrap();
6307            let curves = exact_sphere_torus(&sphere, &torus).unwrap().unwrap();
6308            let circles = circles_of(&curves);
6309            assert_eq!((curves.len(), circles.len()), (2, 2), "height {height}");
6310            let worst = worst_off(&circles, &torus, |p| (p - centre).length() - 3.0);
6311            assert!(worst < 1e-9, "height {height}: {worst}");
6312        }
6313    }
6314
6315    /// Balls off a ring torus's axis, one poking out of the tube's top, one
6316    /// wider than the tube on its core circle, one anywhere, and one just past
6317    /// the tube's outside, in a loop narrower than the scan's step, meet the
6318    /// torus in curves whose points lie on both surfaces, given either way
6319    /// round, where the marcher found nothing with the torus first.
6320    #[test]
6321    fn a_ball_off_a_torus_axis_meets_it_in_its_closed_form_loops() {
6322        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
6323        let on_torus = |p: Point3| (p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5;
6324        for (centre, radius, loops) in [
6325            (Point3::new(4.0, 0.0, 1.0), 1.0, 1),
6326            (Point3::new(4.0, 0.0, 0.0), 2.0, 2),
6327            (Point3::new(2.0, 1.0, 0.5), 1.2, 1),
6328            (Point3::new(6.4999, 0.0, 0.0), 1.0, 1),
6329        ] {
6330            let ball = SphericalSurface::new(centre, radius).unwrap();
6331            let on_ball = |p: Point3| (p - centre).length() - radius;
6332            for ball_first in [true, false] {
6333                let (a, b) = if ball_first {
6334                    (
6335                        AnalyticSurface::Sphere(&ball),
6336                        AnalyticSurface::Torus(&torus),
6337                    )
6338                } else {
6339                    (
6340                        AnalyticSurface::Torus(&torus),
6341                        AnalyticSurface::Sphere(&ball),
6342                    )
6343                };
6344                let curves = intersect_analytic_analytic(a, b, 32).unwrap();
6345                let case = format!("ball {radius} at {centre:?}, ball first {ball_first}");
6346                assert_eq!(curves.len(), loops, "{case}");
6347                for ic in &curves {
6348                    for q in &ic.points {
6349                        let off = on_ball(q.point).abs().max(on_torus(q.point).abs());
6350                        assert!(off < 1e-9, "{case}: a point lies {off:.2e} off");
6351                        let (on_ball_at, on_torus_at) = if ball_first {
6352                            (q.param1, q.param2)
6353                        } else {
6354                            (q.param2, q.param1)
6355                        };
6356                        let (pb, pt) = (
6357                            ball.evaluate(on_ball_at.0, on_ball_at.1),
6358                            torus.evaluate(on_torus_at.0, on_torus_at.1),
6359                        );
6360                        assert!(
6361                            (pb - q.point).length() < 1e-9 && (pt - q.point).length() < 1e-9,
6362                            "{case}: a point's parameters miss it"
6363                        );
6364                    }
6365                    let (t0, t1) = ic.curve.domain();
6366                    for k in 0..=400 {
6367                        let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
6368                        let off = on_ball(p).abs().max(on_torus(p).abs());
6369                        assert!(off < 1e-7, "{case}: the curve strays {off:.2e}");
6370                    }
6371                }
6372            }
6373        }
6374    }
6375
6376    /// Balls whose loops a fixed scan of the tube misses or blurs: one far
6377    /// smaller than its torus, one near the axis whose two loops share a
6378    /// scan step, one a hair larger than the tube it sits in, whose two
6379    /// loops lie close together all the way round, and one whose winding
6380    /// loops swing round the axis within a few scan steps. Each loop is met
6381    /// either way round, and its curve holds to both surfaces.
6382    #[test]
6383    fn balls_meet_tori_in_loops_a_scan_would_miss() {
6384        for (big, small, centre, radius, loops) in [
6385            (4000.0, 1500.0, Point3::new(5500.0, 0.0, 0.0), 0.001, 1),
6386            (4.0, 1.5, Point3::new(1e-6, 0.0, 0.0), 2.500_002, 2),
6387            (1000.0, 1.0, Point3::new(1000.0, 0.0, 0.0), 1.000_000_5, 2),
6388            (4.0, 1.5, Point3::new(1.500_001, 0.0, 0.0), 4.0, 2),
6389        ] {
6390            let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), big, small).unwrap();
6391            let ball = SphericalSurface::new(centre, radius).unwrap();
6392            let on_torus = |p: Point3| (p.x().hypot(p.y()) - big).hypot(p.z()) - small;
6393            let on_ball = |p: Point3| (p - centre).length() - radius;
6394            for ball_first in [true, false] {
6395                let (a, b) = if ball_first {
6396                    (
6397                        AnalyticSurface::Sphere(&ball),
6398                        AnalyticSurface::Torus(&torus),
6399                    )
6400                } else {
6401                    (
6402                        AnalyticSurface::Torus(&torus),
6403                        AnalyticSurface::Sphere(&ball),
6404                    )
6405                };
6406                let curves = intersect_analytic_analytic(a, b, 32).unwrap();
6407                let case = format!("ball {radius} at {centre:?} on torus ({big}, {small})");
6408                assert_eq!(curves.len(), loops, "{case}");
6409                for ic in &curves {
6410                    for q in &ic.points {
6411                        let off = on_ball(q.point).abs().max(on_torus(q.point).abs());
6412                        assert!(off < 1e-9, "{case}: a point lies {off:.2e} off");
6413                    }
6414                    let (t0, t1) = ic.curve.domain();
6415                    for k in 0..=2000 {
6416                        let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 2000.0);
6417                        let off = on_ball(p).abs().max(on_torus(p).abs());
6418                        assert!(off < 1e-7, "{case}: the curve strays {off:.2e}");
6419                    }
6420                }
6421            }
6422        }
6423    }
6424
6425    /// Sections a closed form can lose to scale or rounding: a plane whose
6426    /// equation is scaled by 1e14 keeps the loop of the plane it describes; a
6427    /// ball 1e-5 across poking out of a large torus, and a ball a micron wider
6428    /// than the tube of a ring 1e8 across, defer to the marcher instead of
6429    /// reading as apart, and the last is not taken for the meridian circle.
6430    #[test]
6431    fn scaled_and_ill_conditioned_sections_are_kept_or_deferred() {
6432        let origin = Point3::new(0.0, 0.0, 0.0);
6433        let torus = ToroidalSurface::new(origin, 4.0, 1.5).unwrap();
6434        let unit = plane_torus_loops(&torus, Vec3::new(1.0, 0.0, 0.0), 4.0, 128).len();
6435        let scaled = plane_torus_loops(&torus, Vec3::new(1e14, 0.0, 0.0), 4e14, 128).len();
6436        assert_eq!((unit, scaled), (1, 1));
6437
6438        let large = ToroidalSurface::new(origin, 4000.0, 1500.0).unwrap();
6439        let speck = SphericalSurface::new(Point3::new(5_500.000_001, 0.0, 0.0), 1e-5).unwrap();
6440        assert!(sphere_torus_curves(&speck, &large, true).is_none());
6441
6442        let ring = ToroidalSurface::new(origin, 1e8, 1.0).unwrap();
6443        let ball = SphericalSurface::new(Point3::new(1e8, 0.0, 0.0), 1.000_001).unwrap();
6444        assert!(exact_sphere_torus(&ball, &ring).unwrap().is_none());
6445        assert!(sphere_torus_curves(&ball, &ring, true).is_none());
6446    }
6447
6448    /// A ball centred on a ring torus's core circle with the tube's own
6449    /// radius meets it along the meridian circle through its centre: one
6450    /// circle, given either way round.
6451    #[test]
6452    fn a_ball_filling_a_torus_tube_meets_it_in_one_meridian_circle() {
6453        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
6454        let centre = Point3::new(4.0, 0.0, 0.0);
6455        let ball = SphericalSurface::new(centre, 1.5).unwrap();
6456        for (a, b) in [
6457            (
6458                AnalyticSurface::Sphere(&ball),
6459                AnalyticSurface::Torus(&torus),
6460            ),
6461            (
6462                AnalyticSurface::Torus(&torus),
6463                AnalyticSurface::Sphere(&ball),
6464            ),
6465        ] {
6466            let curves = intersect_analytic_analytic(a, b, 32).unwrap();
6467            assert_eq!(curves.len(), 1);
6468            let (t0, t1) = curves[0].curve.domain();
6469            for k in 0..=100 {
6470                let p = curves[0]
6471                    .curve
6472                    .evaluate(t0 + (t1 - t0) * f64::from(k) / 100.0);
6473                let off = ((p - centre).length() - 1.5).abs().max(p.y().abs());
6474                assert!(off < 1e-9, "the circle strays {off:.2e}");
6475            }
6476        }
6477    }
6478
6479    #[test]
6480    fn exact_sphere_torus_misses_touches_and_defers() {
6481        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
6482        let ball = |x: f64, r: f64| SphericalSurface::new(Point3::new(x, 0.0, 0.0), r).unwrap();
6483        assert!(
6484            exact_sphere_torus(&ball(0.0, 1.0), &torus)
6485                .unwrap()
6486                .unwrap()
6487                .is_empty(),
6488            "a small ball in the hole misses"
6489        );
6490        let touching = exact_sphere_torus(&ball(0.0, 2.5), &torus)
6491            .unwrap()
6492            .unwrap();
6493        let circles = circles_of(&touching);
6494        assert_eq!(
6495            circles.len(),
6496            1,
6497            "a ball in the hole touches the inner equator"
6498        );
6499        assert!((circles[0].radius() - 2.5).abs() < 1e-12);
6500        assert!(circles[0].center().z().abs() < 1e-12);
6501        assert!(
6502            exact_sphere_torus(&ball(1.0, 3.0), &torus)
6503                .unwrap()
6504                .is_none(),
6505            "a ball off the axis defers"
6506        );
6507        let spindle = ToroidalSurface::with_axis_and_ref_dir(
6508            Point3::new(0.0, 0.0, 0.0),
6509            1.0,
6510            2.0,
6511            Vec3::new(0.0, 0.0, 1.0),
6512            Vec3::new(1.0, 0.0, 0.0),
6513        )
6514        .unwrap();
6515        assert!(
6516            exact_sphere_torus(&ball(0.0, 2.5), &spindle)
6517                .unwrap()
6518                .is_none()
6519        );
6520    }
6521
6522    #[test]
6523    fn exact_cylinder_torus_meets_a_coaxial_rod_in_circles() {
6524        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
6525        let z = Vec3::new(0.0, 0.0, 1.0);
6526        let rod = |r: f64| CylindricalSurface::new(Point3::new(0.0, 0.0, -5.0), z, r).unwrap();
6527        let curves = exact_cylinder_torus(&rod(4.2), &torus).unwrap().unwrap();
6528        let circles = circles_of(&curves);
6529        assert_eq!((curves.len(), circles.len()), (2, 2));
6530        let worst = worst_off(&circles, &torus, |p| p.x().hypot(p.y()) - 4.2);
6531        assert!(worst < 1e-9, "{worst}");
6532        assert!(
6533            exact_cylinder_torus(&rod(2.0), &torus)
6534                .unwrap()
6535                .unwrap()
6536                .is_empty(),
6537            "a rod clear in the hole misses"
6538        );
6539        for (wall, label) in [(5.5, "outer"), (2.5, "inner")] {
6540            let curves = exact_cylinder_torus(&rod(wall), &torus).unwrap().unwrap();
6541            let circles = circles_of(&curves);
6542            assert_eq!(circles.len(), 1, "a wall touching the {label} equator");
6543            assert!(circles[0].center().z().abs() < 1e-12, "{label}");
6544            let worst = worst_off(&circles, &torus, |p| p.x().hypot(p.y()) - wall);
6545            assert!(worst < 1e-9, "{label}: {worst}");
6546        }
6547        assert!(
6548            exact_cylinder_torus(&rod(5.5 + 1e-6), &torus)
6549                .unwrap()
6550                .unwrap()
6551                .is_empty(),
6552            "a wall clear of the tube by more than the tolerance misses it"
6553        );
6554        assert_eq!(
6555            exact_cylinder_torus(&rod(5.5 - 1e-6), &torus)
6556                .unwrap()
6557                .unwrap()
6558                .len(),
6559            2,
6560            "a wall into the tube by more than the tolerance crosses it twice"
6561        );
6562        // Within the linear tolerance of the tube the wall reads as touching
6563        // it: the two crossings lie under 1e-3 apart on a band the wall
6564        // never leaves by more than that tolerance.
6565        for wall in [5.5 - 5e-8, 5.5 + 5e-8] {
6566            let curves = exact_cylinder_torus(&rod(wall), &torus).unwrap().unwrap();
6567            assert_eq!(circles_of(&curves).len(), 1, "a wall at {wall}");
6568        }
6569        let tilted =
6570            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.1, 1.0), 4.2)
6571                .unwrap();
6572        let offset = CylindricalSurface::new(Point3::new(0.5, 0.0, 0.0), z, 4.2).unwrap();
6573        assert!(exact_cylinder_torus(&tilted, &torus).unwrap().is_none());
6574        assert!(exact_cylinder_torus(&offset, &torus).unwrap().is_none());
6575        let spindle = ToroidalSurface::with_axis_and_ref_dir(
6576            Point3::new(0.0, 0.0, 0.0),
6577            1.0,
6578            2.0,
6579            z,
6580            Vec3::new(1.0, 0.0, 0.0),
6581        )
6582        .unwrap();
6583        assert!(
6584            exact_cylinder_torus(&rod(0.5), &spindle).unwrap().is_none(),
6585            "a spindle torus's inner lemon also meets the rod"
6586        );
6587        // The rounded air wall of a fillet whose radius nearly fills its
6588        // corner: the spindle's outer equator rests on the wall.
6589        let spindle = ToroidalSurface::with_axis_and_ref_dir(
6590            Point3::new(0.0, 0.0, 4.7),
6591            0.1,
6592            2.45,
6593            z,
6594            Vec3::new(1.0, 0.0, 0.0),
6595        )
6596        .unwrap();
6597        let curves = exact_cylinder_torus(&rod(2.55), &spindle).unwrap().unwrap();
6598        let circles = circles_of(&curves);
6599        assert_eq!(circles.len(), 1);
6600        assert!((circles[0].center().z() - 4.7).abs() < 1e-12);
6601        let worst = worst_off(&circles, &spindle, |p| p.x().hypot(p.y()) - 2.55);
6602        assert!(worst < 1e-9, "{worst}");
6603        let curves = exact_cylinder_torus(&rod(2.4), &spindle).unwrap().unwrap();
6604        let circles = circles_of(&curves);
6605        assert_eq!(circles.len(), 2, "a wall into the spindle's outer tube");
6606        let worst = worst_off(&circles, &spindle, |p| p.x().hypot(p.y()) - 2.4);
6607        assert!(worst < 1e-9, "{worst}");
6608    }
6609
6610    /// Loops of an off-axis sphere-cylinder pair: `(count, worst distance
6611    /// from either surface)`.
6612    fn off_axis_loops(cylinder_origin: Point3, cylinder_radius: f64) -> (usize, f64) {
6613        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
6614        let cyl =
6615            CylindricalSurface::new(cylinder_origin, Vec3::new(0.0, 0.0, 1.0), cylinder_radius)
6616                .unwrap();
6617        let curves = algebraic_sphere_cylinder(&sphere, &cyl, true)
6618            .unwrap()
6619            .unwrap();
6620        let mut worst: f64 = 0.0;
6621        for c in &curves {
6622            for ip in &c.points {
6623                let on_sphere = sphere.evaluate(ip.param1.0, ip.param1.1);
6624                let on_cylinder = cyl.evaluate(ip.param2.0, ip.param2.1);
6625                worst = worst
6626                    .max((on_sphere - ip.point).length())
6627                    .max((on_cylinder - ip.point).length());
6628            }
6629            let (t0, t1) = c.curve.domain();
6630            assert!((c.curve.evaluate(t0) - c.curve.evaluate(t1)).length() < 1e-9);
6631            for k in 0..=400 {
6632                let p = c.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
6633                let on_sphere = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 2.0).abs();
6634                let on_cylinder = ((p.x() - cylinder_origin.x())
6635                    .hypot(p.y() - cylinder_origin.y())
6636                    - cylinder_radius)
6637                    .abs();
6638                worst = worst.max(on_sphere).max(on_cylinder);
6639            }
6640        }
6641        (curves.len(), worst)
6642    }
6643
6644    /// A drill off the ball's axis passes through it: an entry and an exit
6645    /// loop.
6646    #[test]
6647    fn off_axis_drill_through_a_sphere_meets_it_in_two_loops() {
6648        let (count, worst) = off_axis_loops(Point3::new(0.5, 0.0, 0.0), 0.2);
6649        assert_eq!(count, 2);
6650        assert!(worst < 1e-5, "loops leave the surfaces by {worst}");
6651    }
6652
6653    /// A cylinder over the ball's side: one loop joined at its branch points.
6654    #[test]
6655    fn cylinder_over_a_spheres_side_meets_it_in_one_loop() {
6656        let (count, worst) = off_axis_loops(Point3::new(1.8, 0.0, 0.0), 0.5);
6657        assert_eq!(count, 1);
6658        assert!(worst < 5e-4, "loop leaves the surfaces by {worst}");
6659    }
6660
6661    #[test]
6662    fn disjoint_cylinders_no_intersection() {
6663        let cyl_a =
6664            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
6665                .unwrap();
6666        let cyl_b =
6667            CylindricalSurface::new(Point3::new(5.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
6668                .unwrap();
6669
6670        let curves = intersect_analytic_analytic(
6671            AnalyticSurface::Cylinder(&cyl_a),
6672            AnalyticSurface::Cylinder(&cyl_b),
6673            16,
6674        )
6675        .unwrap();
6676
6677        assert!(curves.is_empty(), "disjoint cylinders should not intersect");
6678    }
6679
6680    // ── Oblique plane × cone conic (ellipse / parabola / hyperbola) ──────
6681
6682    /// Collect 3D points from a returned exact curve, sampling analytic forms.
6683    fn collect_points(curve: &ExactIntersectionCurve) -> Vec<Point3> {
6684        use crate::traits::ParametricCurve;
6685        match curve {
6686            ExactIntersectionCurve::Circle(c) => (0..=64)
6687                .map(|i| ParametricCurve::evaluate(c, TAU * f64::from(i) / 64.0))
6688                .collect(),
6689            ExactIntersectionCurve::Ellipse(e) => (0..=64)
6690                .map(|i| ParametricCurve::evaluate(e, TAU * f64::from(i) / 64.0))
6691                .collect(),
6692            ExactIntersectionCurve::Points(pts) => pts.clone(),
6693        }
6694    }
6695
6696    /// Assert every returned point lies on the plane and the cone surface, on
6697    /// the real (`v >= 0`) nappe, and within a sane axial bound.
6698    fn assert_on_plane_and_cone(
6699        curves: &[ExactIntersectionCurve],
6700        cone: &ConicalSurface,
6701        n: Vec3,
6702        d: f64,
6703        z_bound: (f64, f64),
6704    ) {
6705        assert!(!curves.is_empty(), "expected at least one section curve");
6706        let mut total = 0;
6707        for curve in curves {
6708            for p in collect_points(curve) {
6709                total += 1;
6710                let plane_err = (n.x() * p.x() + n.y() * p.y() + n.z() * p.z() - d).abs();
6711                assert!(
6712                    plane_err < 1e-9,
6713                    "point off plane by {plane_err:.2e}: {p:?}"
6714                );
6715                let (u, v) = cone.project_point(p);
6716                let q = cone.evaluate(u, v);
6717                let cone_err =
6718                    ((p.x() - q.x()).powi(2) + (p.y() - q.y()).powi(2) + (p.z() - q.z()).powi(2))
6719                        .sqrt();
6720                assert!(cone_err < 1e-7, "point off cone by {cone_err:.2e}: {p:?}");
6721                assert!(v >= -1e-9, "point on phantom nappe (v={v:.4}): {p:?}");
6722                assert!(
6723                    p.z() >= z_bound.0 - 1e-6 && p.z() <= z_bound.1 + 1e-6,
6724                    "point z={:.4} outside sane bound {z_bound:?}: {p:?}",
6725                    p.z()
6726                );
6727            }
6728        }
6729        assert!(total >= 8, "too few section points ({total})");
6730    }
6731
6732    #[test]
6733    fn oblique_plane_cone_ellipse_is_exact_and_on_both() {
6734        // 45°-half-angle cone (axis +z). A plane tilted only ~16.7° off horizontal
6735        // has plane-axis angle ≈ 73° > 45° (the cone's half-opening from axis) →
6736        // ellipse. Must come back as an exact Ellipse, fully on both surfaces.
6737        let cone = ConicalSurface::new(
6738            Point3::new(0.0, 0.0, 0.0),
6739            Vec3::new(0.0, 0.0, 1.0),
6740            std::f64::consts::FRAC_PI_4,
6741        )
6742        .unwrap();
6743        let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
6744        // Plane through (0,0,5): d = n·(0,0,5).
6745        let d = n.z() * 5.0;
6746        let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
6747        assert!(
6748            curves
6749                .iter()
6750                .any(|c| matches!(c, ExactIntersectionCurve::Ellipse(_))),
6751            "oblique steep plane × cone must yield an exact Ellipse"
6752        );
6753        // The ellipse straddles z=5; with the 0.3 tilt the z-extent stays modest.
6754        assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 12.0));
6755    }
6756
6757    #[test]
6758    fn oblique_plane_cone_wrong_nappe_is_empty() {
6759        // Same ellipse-regime plane as above, but offset to the FAR side of the
6760        // apex (z=-5). The +z cone's real (v≥0) nappe is not met — only the
6761        // phantom v<0 nappe — so the result must be EMPTY, not a phantom ellipse.
6762        let cone = ConicalSurface::new(
6763            Point3::new(0.0, 0.0, 0.0),
6764            Vec3::new(0.0, 0.0, 1.0),
6765            std::f64::consts::FRAC_PI_4,
6766        )
6767        .unwrap();
6768        let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
6769        let d = n.z() * -5.0;
6770        let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
6771        assert!(
6772            curves.is_empty(),
6773            "plane on the phantom-nappe side must yield no real curve, got {}",
6774            curves.len()
6775        );
6776    }
6777
6778    #[test]
6779    fn oblique_plane_cone_parabola_on_both_single_branch() {
6780        // Plane normal at exactly 45° to the axis (= the cone half-opening) → the
6781        // plane is parallel to a generator → parabola. One unbounded branch.
6782        let cone = ConicalSurface::new(
6783            Point3::new(0.0, 0.0, 0.0),
6784            Vec3::new(0.0, 0.0, 1.0),
6785            std::f64::consts::FRAC_PI_4,
6786        )
6787        .unwrap();
6788        let n = Vec3::new(1.0, 0.0, 1.0).normalize().unwrap();
6789        let d = n.x() * 3.0 + n.z() * 3.0; // through (3,0,3)
6790        let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
6791        assert_eq!(
6792            curves.len(),
6793            1,
6794            "a parabola is a single branch, got {}",
6795            curves.len()
6796        );
6797        // Bounded by r_max = 32·|e|; |e| here is O(few), so allow a wide z window.
6798        assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 400.0));
6799    }
6800
6801    #[test]
6802    fn oblique_plane_cone_hyperbola_real_nappe_only() {
6803        // Faithful scooplabel lip-foot geometry: a 45° cone with axis −z and
6804        // apex at (−59,−59,15.85) (a bin corner), cut by the upper ramp tread
6805        // plane n=(0,0.99518,0.09802), d=−58.36056. The plane is nearly parallel
6806        // to the axis (cos≈0.098) → plane-axis angle ≈ 5.6° < 45° → hyperbola.
6807        // The downward real nappe is hit by exactly one branch; the phantom
6808        // upward nappe (and the asymptote runaway) must NOT appear, and the arc
6809        // must stay near the apex (the plane is ~1.2 mm from it).
6810        let cone = ConicalSurface::new(
6811            Point3::new(-59.0, -59.0, 15.85),
6812            Vec3::new(0.0, 0.0, -1.0),
6813            std::f64::consts::FRAC_PI_4,
6814        )
6815        .unwrap();
6816        let n = Vec3::new(0.0, 0.995_18, 0.098_02).normalize().unwrap();
6817        let d = -58.360_56;
6818        let cos_theta = n.dot(cone.axis()).abs();
6819        assert!(cos_theta < 0.2, "expected a shallow (hyperbola) plane");
6820        let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
6821        // Real downward nappe only: never above the apex (z=15.85). The vertex is
6822        // ~1.2 mm from the apex, so the bounded arc stays within a few mm of it.
6823        assert_on_plane_and_cone(&curves, &cone, n, d, (5.0, 15.85));
6824        // Every returned curve is sampled Points (no false Circle/Ellipse).
6825        for c in &curves {
6826            assert!(
6827                matches!(c, ExactIntersectionCurve::Points(_)),
6828                "hyperbola must be sampled Points, not a closed conic"
6829            );
6830        }
6831    }
6832
6833    /// Two spheres meet in one circle on both of them; spheres apart, one
6834    /// inside the other, or concentric of different radii meet in nothing,
6835    /// and one sphere twice has no curve.
6836    #[test]
6837    fn sphere_sphere_meets_in_a_circle_on_both() {
6838        let ball = |x: f64, y: f64, z: f64, r: f64| {
6839            SphericalSurface::new(Point3::new(x, y, z), r).unwrap()
6840        };
6841        let (a, b) = (ball(0.0, 0.0, 0.0, 2.0), ball(1.6, 0.3, 0.2, 1.5));
6842        let curves = exact_sphere_sphere(&a, &b).unwrap().unwrap();
6843        assert_eq!(curves.len(), 1);
6844        let circle = match &curves[0] {
6845            ExactIntersectionCurve::Circle(circle) => circle,
6846            other => unreachable!("expected a circle, got {other:?}"),
6847        };
6848        for k in 0..16 {
6849            let p = circle.evaluate(std::f64::consts::TAU * f64::from(k) / 16.0);
6850            assert!(((p - a.center()).length() - 2.0).abs() < 1e-12);
6851            assert!(((p - b.center()).length() - 1.5).abs() < 1e-12);
6852        }
6853        assert!(
6854            exact_sphere_sphere(&a, &ball(4.0, 0.0, 0.0, 1.5))
6855                .unwrap()
6856                .unwrap()
6857                .is_empty()
6858        );
6859        assert!(
6860            exact_sphere_sphere(&a, &ball(0.2, 0.0, 0.0, 1.0))
6861                .unwrap()
6862                .unwrap()
6863                .is_empty()
6864        );
6865        assert!(
6866            exact_sphere_sphere(&a, &ball(0.0, 0.0, 0.0, 1.0))
6867                .unwrap()
6868                .unwrap()
6869                .is_empty()
6870        );
6871        assert!(
6872            exact_sphere_sphere(&a, &ball(0.0, 0.0, 0.0, 2.0))
6873                .unwrap()
6874                .is_none()
6875        );
6876
6877        // A tiny sphere nearly bisected by a large one, in either order, and a
6878        // pair far from the origin: each meets in its small circle.
6879        let radius = |p: &SphericalSurface, q: &SphericalSurface| -> f64 {
6880            match exact_sphere_sphere(p, q).unwrap().unwrap().as_slice() {
6881                [ExactIntersectionCurve::Circle(c)] => c.radius(),
6882                other => unreachable!("expected one circle, got {other:?}"),
6883            }
6884        };
6885        let tiny = ball(2.0, 0.0, 0.0, 1e-5);
6886        assert!((radius(&a, &tiny) - 1e-5).abs() < 1e-9);
6887        assert!((radius(&tiny, &a) - 1e-5).abs() < 1e-9);
6888        let near = radius(&ball(0.0, 0.0, 0.0, 2.0), &ball(3.5, 0.0, 0.0, 1.500_001));
6889        let far = radius(
6890            &ball(1e10, 0.0, 0.0, 2.0),
6891            &ball(1e10 + 3.5, 0.0, 0.0, 1.500_001),
6892        );
6893        assert!(near > 1e-3);
6894        assert!((far - near).abs() < 1e-9 * near.max(1.0));
6895    }
6896
6897    /// Each line among `sections`, and whether it is a ray; any other
6898    /// section fails the test.
6899    #[allow(clippy::panic)]
6900    fn lines_of(sections: &[PlaneSection]) -> Vec<(Line3D, bool)> {
6901        sections
6902            .iter()
6903            .map(|s| match s {
6904                PlaneSection::Line { line, ray } => (line.clone(), *ray),
6905                other => panic!("expected a line, got {other:?}"),
6906            })
6907            .collect()
6908    }
6909
6910    /// A plane along a cylinder's axis cuts its rulings: two through the
6911    /// axis, two 2e-6 apart where it sinks a hair into the cylinder, the one
6912    /// it touches along, and none past it. `exact_plane_analytic` gives no
6913    /// curve for any of them.
6914    #[test]
6915    fn a_plane_along_a_cylinder_cuts_its_rulings() {
6916        let cyl =
6917            CylindricalSurface::new(Point3::new(0.0, 0.0, -2.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
6918                .unwrap();
6919        let y = Vec3::new(0.0, 1.0, 0.0);
6920        let surface = AnalyticSurface::Cylinder(&cyl);
6921        let on_both = |p: Point3, d: f64| {
6922            assert!((p.y() - d).abs() < 1e-12, "{p:?} off the plane y = {d}");
6923            assert!(
6924                (p.x().hypot(p.y()) - 1.0).abs() < 1e-12,
6925                "{p:?} off the cylinder"
6926            );
6927        };
6928        for (d, count) in [(0.0, 2), (1e-6_f64.cos(), 2), (1.0, 1), (1.5, 0)] {
6929            assert!(exact_plane_analytic(surface, y, d).unwrap().is_empty());
6930            let lines = lines_of(&exact_plane_section(surface, y, d).unwrap());
6931            assert_eq!(lines.len(), count, "plane y = {d}");
6932            let mut xs = Vec::new();
6933            for (line, ray) in lines {
6934                assert!(!ray);
6935                assert!(line.direction().cross(cyl.axis()).length() < 1e-12);
6936                for t in [-3.0, 0.0, 3.0] {
6937                    on_both(line.evaluate(t), d);
6938                }
6939                xs.push(line.evaluate(0.0).x());
6940            }
6941            if count == 2 {
6942                let apart = (xs[0] - xs[1]).abs();
6943                let want = 2.0 * (1.0 - d * d).sqrt();
6944                assert!(
6945                    (apart - want).abs() < 1e-9 * want.max(1e-6),
6946                    "{apart} apart"
6947                );
6948            }
6949        }
6950    }
6951
6952    /// A plane through a cone's apex cuts rays from it: two for a plane
6953    /// through the axis, one for a plane touching the cone along a ruling,
6954    /// and the apex alone for a plane missing the nappe. A plane 5e-8 off the
6955    /// apex still cuts its conic.
6956    #[test]
6957    #[allow(clippy::panic)]
6958    fn a_plane_through_a_cone_apex_cuts_its_rulings() {
6959        use std::f64::consts::FRAC_PI_4;
6960
6961        let cone = ConicalSurface::new(
6962            Point3::new(1.0, 2.0, 3.0),
6963            Vec3::new(0.0, 0.0, 1.0),
6964            FRAC_PI_4,
6965        )
6966        .unwrap();
6967        let surface = AnalyticSurface::Cone(&cone);
6968        let apex = cone.apex();
6969        let through = |n: Vec3| {
6970            let n = n.normalize().unwrap();
6971            let d = n.dot(apex - Point3::new(0.0, 0.0, 0.0));
6972            assert!(exact_plane_analytic(surface, n, d).unwrap().is_empty());
6973            (n, d, exact_plane_section(surface, n, d).unwrap())
6974        };
6975        for (n, count) in [
6976            (Vec3::new(1.0, 0.0, 0.0), 2),
6977            (Vec3::new(1.0, 0.0, -1.0), 1),
6978        ] {
6979            let (n, d, sections) = through(n);
6980            let rays = lines_of(&sections);
6981            assert_eq!(rays.len(), count, "plane normal {n:?}");
6982            for (line, ray) in rays {
6983                assert!(ray);
6984                assert!((line.evaluate(0.0) - apex).length() < 1e-12);
6985                let p = line.evaluate(2.0);
6986                assert!((n.dot(p - Point3::new(0.0, 0.0, 0.0)) - d).abs() < 1e-12);
6987                let rel = p - apex;
6988                assert!(rel.z() > 0.0, "{p:?} on the phantom nappe");
6989                assert!(
6990                    (rel.x().hypot(rel.y()) - rel.z()).abs() < 1e-12,
6991                    "{p:?} off the cone"
6992                );
6993            }
6994        }
6995        for n in [Vec3::new(0.1, 0.0, 1.0), Vec3::new(0.0, 0.0, 1.0)] {
6996            let (_, _, sections) = through(n);
6997            assert!(
6998                matches!(sections[..], [PlaneSection::Point(p)] if (p - apex).length() < 1e-12),
6999                "{sections:?}"
7000            );
7001        }
7002
7003        let upright = ConicalSurface::new(
7004            Point3::new(0.0, 0.0, 0.0),
7005            Vec3::new(0.0, 0.0, 1.0),
7006            FRAC_PI_4,
7007        )
7008        .unwrap();
7009        let n = Vec3::new((0.5 - 1e-8_f64).sqrt(), 0.0, (0.5 + 1e-8_f64).sqrt());
7010        let sections = exact_plane_section(AnalyticSurface::Cone(&upright), n, 5e-8).unwrap();
7011        let [PlaneSection::Ellipse(ellipse)] = &sections[..] else {
7012            panic!("{sections:?}");
7013        };
7014        assert!(
7015            ellipse.semi_major() > 1.0,
7016            "semi-major {}",
7017            ellipse.semi_major()
7018        );
7019    }
7020
7021    /// A plane touching a sphere meets it at the point of contact, and one a
7022    /// hair inside cuts the small circle there, however small.
7023    #[test]
7024    #[allow(clippy::panic)]
7025    fn a_plane_touching_a_sphere_meets_it_at_a_point() {
7026        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 1.0), 1.0).unwrap();
7027        let surface = AnalyticSurface::Sphere(&sphere);
7028        let z = Vec3::new(0.0, 0.0, 1.0);
7029        assert!(exact_plane_analytic(surface, z, 0.0).unwrap().is_empty());
7030        let sections = exact_plane_section(surface, z, 0.0).unwrap();
7031        assert!(
7032            matches!(sections[..], [PlaneSection::Point(p)] if p.z().abs() < 1e-15 && p.x() == 0.0),
7033            "{sections:?}"
7034        );
7035        assert!(exact_plane_section(surface, z, -1e-9).unwrap().is_empty());
7036        for height in [5e-15, 1e-12, 1e-8] {
7037            let sections = exact_plane_section(surface, z, height).unwrap();
7038            let [PlaneSection::Circle(circle)] = &sections[..] else {
7039                panic!("{sections:?}");
7040            };
7041            let want = (height * (2.0 - height)).sqrt();
7042            assert!(
7043                (circle.radius() - want).abs() < 1e-3 * want,
7044                "circle at z = {height}: radius {}, want {want}",
7045                circle.radius()
7046            );
7047            assert!((circle.center().z() - height).abs() < 1e-15);
7048        }
7049    }
7050
7051    /// The farthest any of `curves` strays from `off`, sampled densely.
7052    fn farthest(curves: &[IntersectionCurve], off: impl Fn(Point3) -> f64) -> f64 {
7053        let mut far = 0.0_f64;
7054        for ic in curves {
7055            let (t0, t1) = ic.curve.domain();
7056            for i in 0..=2000 {
7057                let t = t0 + (t1 - t0) * f64::from(i) / 2000.0;
7058                far = far.max(off(ic.curve.evaluate(t)));
7059            }
7060        }
7061        far
7062    }
7063
7064    /// A ball sitting in a bore of its own radius touches it along its
7065    /// equator, which comes back as the exact circle.
7066    #[test]
7067    fn a_ball_in_its_bore_meets_it_on_an_exact_circle() {
7068        let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
7069        let bore =
7070            CylindricalSurface::new(Point3::new(0.0, 0.0, -2.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7071                .unwrap();
7072        let curves = intersect_analytic_analytic_bounded(
7073            AnalyticSurface::Sphere(&ball),
7074            AnalyticSurface::Cylinder(&bore),
7075            64,
7076            None,
7077            Some((0.0, 4.0)),
7078        )
7079        .unwrap();
7080        assert_eq!(curves.len(), 1);
7081        let far = farthest(&curves, |p| {
7082            let on_ball = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 1.0).abs();
7083            on_ball
7084                .max((p.x().hypot(p.y()) - 1.0).abs())
7085                .max(p.z().abs())
7086        });
7087        assert!(far < 1e-14, "circle strays {far:.2e}");
7088    }
7089
7090    /// Two unit balls a unit apart meet in a circle of radius √3/2, which
7091    /// comes back exact.
7092    #[test]
7093    fn overlapping_balls_meet_on_an_exact_circle() {
7094        let a = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
7095        let b = SphericalSurface::new(Point3::new(1.0, 0.0, 0.0), 1.0).unwrap();
7096        let curves = intersect_analytic_analytic_bounded(
7097            AnalyticSurface::Sphere(&a),
7098            AnalyticSurface::Sphere(&b),
7099            64,
7100            None,
7101            None,
7102        )
7103        .unwrap();
7104        assert_eq!(curves.len(), 1);
7105        let far = farthest(&curves, |p| {
7106            let on_a = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 1.0).abs();
7107            on_a.max(((p - Point3::new(1.0, 0.0, 0.0)).length() - 1.0).abs())
7108        });
7109        assert!(far < 1e-14, "circle strays {far:.2e}");
7110    }
7111
7112    /// A loop with semi-axes 3 and 1.5 in a tilted frame lies on its ellipse
7113    /// all the way round and starts at the end of its major axis.
7114    #[test]
7115    fn a_conic_loop_is_its_ellipse() {
7116        let centre = Point3::new(1.0, -2.0, 0.5);
7117        let frame = Frame3::from_normal(centre, Vec3::new(0.3, -0.4, 1.0)).unwrap();
7118        let curve = conic_loop(centre, frame.x, frame.y, 3.0, 1.5).unwrap();
7119        let (t0, t1) = curve.domain();
7120        assert!((curve.evaluate(t0) - (centre + frame.x * 3.0)).length() < 1e-15);
7121        for i in 0..=2000 {
7122            let p = curve.evaluate(t0 + (t1 - t0) * f64::from(i) / 2000.0) - centre;
7123            let (x, y) = (p.dot(frame.x) / 3.0, p.dot(frame.y) / 1.5);
7124            assert!(
7125                (x.hypot(y) - 1.0).abs() < 1e-14,
7126                "off its ellipse by {}",
7127                x.hypot(y) - 1.0
7128            );
7129            assert!(p.dot(frame.z).abs() < 1e-14);
7130        }
7131    }
7132
7133    /// A ball sitting in a ring's hole, and a ring resting on a wider one,
7134    /// meet them along the one circle where they touch, and the bounded
7135    /// call returns it exactly.
7136    #[test]
7137    fn touching_coaxial_rings_meet_along_one_circle() {
7138        let z = Vec3::new(0.0, 0.0, 1.0);
7139        let x = Vec3::new(1.0, 0.0, 0.0);
7140        let ring =
7141            ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 0.0), 3.0, 1.0, z, x)
7142                .unwrap();
7143        let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
7144        let curves = intersect_analytic_analytic_bounded(
7145            AnalyticSurface::Sphere(&ball),
7146            AnalyticSurface::Torus(&ring),
7147            64,
7148            None,
7149            None,
7150        )
7151        .unwrap();
7152        assert_eq!(curves.len(), 1);
7153        let far = farthest(&curves, |p| {
7154            let q = p - Point3::new(0.0, 0.0, 0.0);
7155            let rho = q.x().hypot(q.y());
7156            let on_ring = ((rho - 3.0).hypot(q.z()) - 1.0).abs();
7157            on_ring.max((q.length() - 2.0).abs())
7158        });
7159        assert!(far < 1e-14, "circle strays {far:.2e}");
7160
7161        // Tubes of radius 1 and 0.5 on rings of radius 3 and 3.9, the second
7162        // raised 1.2: their centres lie 1.5 apart, so they touch a third of
7163        // the way along, at height 0.8 on a circle of radius 3.6.
7164        let wider =
7165            ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 1.2), 3.9, 0.5, z, x)
7166                .unwrap();
7167        let touching = exact_torus_torus(&ring, &wider).unwrap().unwrap();
7168        let circles = circles_of(&touching);
7169        assert_eq!(circles.len(), 1);
7170        assert!(
7171            (circles[0].radius() - 3.6).abs() < 1e-12,
7172            "{}",
7173            circles[0].radius()
7174        );
7175        assert!((circles[0].center().z() - 0.8).abs() < 1e-12);
7176    }
7177
7178    /// Unit tubes on rings of radius 1e6 and 1e6 + 1.999 overlap by 0.001
7179    /// and cross in two circles 0.063 apart; on rings 2.001 apart they miss.
7180    /// Neither is read as a touch, at a scale where a millionth of it is
7181    /// two thousandths.
7182    #[test]
7183    fn huge_coaxial_rings_cross_or_miss_rather_than_touch() {
7184        let z = Vec3::new(0.0, 0.0, 1.0);
7185        let x = Vec3::new(1.0, 0.0, 0.0);
7186        let ring = |big: f64| {
7187            ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 0.0), big, 1.0, z, x)
7188                .unwrap()
7189        };
7190        let crossing = exact_torus_torus(&ring(1e6), &ring(1_000_001.999))
7191            .unwrap()
7192            .unwrap();
7193        let circles = circles_of(&crossing);
7194        assert_eq!(circles.len(), 2);
7195        for circle in circles {
7196            let height = (1.0 - 0.9995_f64 * 0.9995).sqrt();
7197            assert!(
7198                (circle.center().z().abs() - height).abs() < 1e-9,
7199                "{}",
7200                circle.center().z()
7201            );
7202        }
7203        let apart = exact_torus_torus(&ring(1e6), &ring(1_000_002.001))
7204            .unwrap()
7205            .unwrap();
7206        assert!(apart.is_empty());
7207    }
7208
7209    /// A plane parallel to a cone's axis cuts the branch of a hyperbola on
7210    /// the cone's one nappe; planes parallel to a generator cut a parabola
7211    /// on one side of the apex and miss the cone on the other.
7212    #[test]
7213    fn a_plane_cuts_a_cones_open_conics() {
7214        let up = Vec3::new(0.0, 0.0, 1.0);
7215        let on_cone = |p: Point3, slope: f64| (p.z() - slope * p.x().hypot(p.y())).abs();
7216        let steep =
7217            ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, 60_f64.to_radians()).unwrap();
7218        let slope = 60_f64.to_radians().tan();
7219        let along =
7220            exact_plane_section(AnalyticSurface::Cone(&steep), Vec3::new(1.0, 0.0, 0.0), 1.0)
7221                .unwrap();
7222        let [PlaneSection::Hyperbola(h)] = along.as_slice() else {
7223            unreachable!("{along:?}")
7224        };
7225        for i in -20..=20 {
7226            let p = h.evaluate(f64::from(i) / 5.0);
7227            assert!((p.x() - 1.0).abs() < 1e-12 && p.z() > 0.0, "{p:?}");
7228            assert!(on_cone(p, slope) < 1e-12 * p.z().max(1.0), "{p:?}");
7229        }
7230        let even =
7231            ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, 45_f64.to_radians()).unwrap();
7232        let tilt = Vec3::new(-1.0, 0.0, 1.0) * std::f64::consts::FRAC_1_SQRT_2;
7233        let above = exact_plane_section(AnalyticSurface::Cone(&even), tilt, 1.0).unwrap();
7234        let [PlaneSection::Parabola(parabola)] = above.as_slice() else {
7235            unreachable!("{above:?}")
7236        };
7237        for i in -20..=20 {
7238            let p = parabola.evaluate(f64::from(i) / 2.0);
7239            assert!(
7240                (tilt.dot(p - Point3::new(0.0, 0.0, 0.0)) - 1.0).abs() < 1e-12,
7241                "{p:?}"
7242            );
7243            assert!(
7244                p.z() > 0.0 && on_cone(p, 1.0) < 1e-12 * p.z().max(1.0),
7245                "{p:?}"
7246            );
7247        }
7248        let below = exact_plane_section(AnalyticSurface::Cone(&even), tilt, -1.0).unwrap();
7249        assert!(below.is_empty(), "{below:?}");
7250    }
7251
7252    /// A cone so flat it rises 1e-7 from its radial plane, cut by a plane
7253    /// tilted 7e-7 off it, and a cone so narrow it opens 5e-7 off its axis,
7254    /// cut by a plane parallel to the axis, give sections that lie on the
7255    /// cone: a hyperbola for the flat one, read from its eccentricity, and
7256    /// sampled points where the formulas lose their digits.
7257    #[test]
7258    fn extreme_cones_give_sections_on_the_cone() {
7259        let up = Vec3::new(0.0, 0.0, 1.0);
7260        let apex = Point3::new(0.0, 0.0, 0.0);
7261        let holds = |cone: &ConicalSurface, q: Point3| {
7262            let w = q - apex;
7263            (w.dot(up) - cone.half_angle().sin() * w.length()).abs() <= 1e-6 * (1.0 + w.length())
7264        };
7265        let flat = ConicalSurface::new(apex, up, 1e-7).unwrap();
7266        let tilt = Vec3::new(5e-13_f64.sqrt(), 0.0, (1.0 - 5e-13_f64).sqrt());
7267        let needle = ConicalSurface::new(apex, up, FRAC_PI_2 - 5e-7).unwrap();
7268        for (cone, normal, d) in [(&flat, tilt, 1.0), (&needle, Vec3::new(1.0, 0.0, 0.0), 1.0)] {
7269            let sections = exact_plane_section(AnalyticSurface::Cone(cone), normal, d).unwrap();
7270            assert!(!sections.is_empty());
7271            for section in &sections {
7272                let points: Vec<Point3> = match section {
7273                    PlaneSection::Hyperbola(h) => {
7274                        (-4..=4).map(|i| h.evaluate(f64::from(i) / 4.0)).collect()
7275                    }
7276                    PlaneSection::Parabola(q) => {
7277                        (-4..=4).map(|i| q.evaluate(f64::from(i))).collect()
7278                    }
7279                    PlaneSection::Points(points) => points.clone(),
7280                    other => unreachable!("{other:?}"),
7281                };
7282                for q in points {
7283                    assert!(holds(cone, q), "{q:?} off the cone");
7284                }
7285            }
7286        }
7287        let flat_section = exact_plane_section(AnalyticSurface::Cone(&flat), tilt, 1.0).unwrap();
7288        assert!(matches!(
7289            flat_section.as_slice(),
7290            [PlaneSection::Hyperbola(_)]
7291        ));
7292    }
7293
7294    /// The rulings two parallel cylinders meet along, from the bounded call
7295    /// with each face's `v` range: each ruling's ends, sorted by height.
7296    fn parallel_rulings(
7297        (c1, r1, v1): (Point3, f64, (f64, f64)),
7298        (c2, r2, axis2, v2): (Point3, f64, Vec3, (f64, f64)),
7299    ) -> Vec<(Point3, Point3)> {
7300        rulings_within((c1, r1, v1), (c2, r2, axis2, v2), 1e-12)
7301    }
7302
7303    /// [`parallel_rulings`] with each curve held to `tolerance` of both
7304    /// cylinders.
7305    fn rulings_within(
7306        (c1, r1, v1): (Point3, f64, (f64, f64)),
7307        (c2, r2, axis2, v2): (Point3, f64, Vec3, (f64, f64)),
7308        tolerance: f64,
7309    ) -> Vec<(Point3, Point3)> {
7310        let a = CylindricalSurface::new(c1, Vec3::new(0.0, 0.0, 1.0), r1).unwrap();
7311        let b = CylindricalSurface::new(c2, axis2, r2).unwrap();
7312        let curves = intersect_analytic_analytic_bounded(
7313            AnalyticSurface::Cylinder(&a),
7314            AnalyticSurface::Cylinder(&b),
7315            32,
7316            Some(v1),
7317            Some(v2),
7318        )
7319        .unwrap();
7320        curves
7321            .iter()
7322            .map(|ic| {
7323                let (t0, t1) = ic.curve.domain();
7324                let (p, q) = (ic.curve.evaluate(t0), ic.curve.evaluate(t1));
7325                for i in 0..=100 {
7326                    let x = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(i) / 100.0);
7327                    let on_a = ((x - c1) - Vec3::new(0.0, 0.0, (x - c1).z())).length() - r1;
7328                    let w = x - c2;
7329                    let on_b = (w - axis2 * w.dot(axis2)).length() - r2;
7330                    assert!(
7331                        on_a.abs() < tolerance && on_b.abs() < tolerance,
7332                        "{x:?} off a cylinder by {on_a:.1e}, {on_b:.1e}"
7333                    );
7334                }
7335                if p.z() <= q.z() { (p, q) } else { (q, p) }
7336            })
7337            .collect()
7338    }
7339
7340    /// Rods of radius 1 with axes 1.2 apart overlap along two rulings, at
7341    /// x 0.6 and y ±0.8, over the height both faces share; the second rod's
7342    /// axis runs down, so its range counts down from its origin.
7343    #[test]
7344    fn overlapping_parallel_rods_meet_along_two_rulings() {
7345        let mut rulings = parallel_rulings(
7346            (Point3::new(0.0, 0.0, 0.0), 1.0, (0.0, 4.0)),
7347            (
7348                Point3::new(1.2, 0.0, 3.0),
7349                1.0,
7350                Vec3::new(0.0, 0.0, -1.0),
7351                (0.0, 2.0),
7352            ),
7353        );
7354        rulings.sort_by(|a, b| a.0.y().total_cmp(&b.0.y()));
7355        assert_eq!(rulings.len(), 2);
7356        for ((lo, hi), y) in rulings.into_iter().zip([-0.8, 0.8]) {
7357            assert!((lo - Point3::new(0.6, y, 1.0)).length() < 1e-12, "{lo:?}");
7358            assert!((hi - Point3::new(0.6, y, 3.0)).length() < 1e-12, "{hi:?}");
7359        }
7360    }
7361
7362    /// Rods touching side by side, or one inside another against its wall,
7363    /// meet along the one ruling where they touch; rods apart do not meet.
7364    #[test]
7365    fn touching_parallel_rods_meet_along_one_ruling() {
7366        let up = Vec3::new(0.0, 0.0, 1.0);
7367        let beside = parallel_rulings(
7368            (Point3::new(0.0, 0.0, 0.0), 1.0, (-2.0, 2.0)),
7369            (Point3::new(2.0, 0.0, -2.0), 1.0, up, (0.0, 4.0)),
7370        );
7371        assert_eq!(beside.len(), 1);
7372        assert!((beside[0].0 - Point3::new(1.0, 0.0, -2.0)).length() < 1e-12);
7373        assert!((beside[0].1 - Point3::new(1.0, 0.0, 2.0)).length() < 1e-12);
7374        let inside = parallel_rulings(
7375            (Point3::new(0.0, 0.0, 0.0), 2.0, (0.0, 1.0)),
7376            (Point3::new(-1.0, 0.0, 0.0), 1.0, up, (0.0, 1.0)),
7377        );
7378        assert_eq!(inside.len(), 1);
7379        assert!((inside[0].0 - Point3::new(-2.0, 0.0, 0.0)).length() < 1e-12);
7380        let apart = parallel_rulings(
7381            (Point3::new(0.0, 0.0, 0.0), 1.0, (0.0, 1.0)),
7382            (Point3::new(2.5, 0.0, 0.0), 1.0, up, (0.0, 1.0)),
7383        );
7384        assert!(apart.is_empty());
7385    }
7386
7387    /// Rods whose axes lean 1e-5 apart drift 1e-3 over a span of 100, so
7388    /// the rulings defer to the next solver there; over a span of 0.001
7389    /// they drift 1e-8 and keep their two rulings.
7390    #[test]
7391    fn rods_leaning_apart_keep_rulings_only_over_a_short_span() {
7392        let up = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7393            .unwrap();
7394        let lean = Vec3::new(1e-5_f64.sin(), 0.0, 1e-5_f64.cos());
7395        let leaning = CylindricalSurface::new(Point3::new(1.2, 0.0, 0.0), lean, 1.0).unwrap();
7396        let span = |h: f64| parallel_cylinders(&up, &leaning, Some((0.0, h)), Some((0.0, h)));
7397        assert!(span(100.0).unwrap().is_none());
7398        assert_eq!(span(0.001).unwrap().map(|r| r.len()), Some(2));
7399    }
7400
7401    /// Huge rods a short stretch long still meet along both rulings, and
7402    /// rods of radius 100 whose axes lie 3e-7 short of touching meet along
7403    /// two rulings 0.011 apart, not the one where they would touch.
7404    #[test]
7405    fn parallel_rods_keep_short_and_close_rulings() {
7406        let up = Vec3::new(0.0, 0.0, 1.0);
7407        let huge = rulings_within(
7408            (Point3::new(0.0, 0.0, 0.0), 1e6, (0.0, 0.001)),
7409            (Point3::new(1.2e6, 0.0, 0.0), 1e6, up, (0.0, 0.001)),
7410            1e-9,
7411        );
7412        assert_eq!(huge.len(), 2);
7413        assert!(
7414            huge.iter()
7415                .all(|(lo, hi)| ((*hi - *lo).length() - 0.001).abs() < 1e-12)
7416        );
7417        let mut close = rulings_within(
7418            (Point3::new(0.0, 0.0, 0.0), 100.0, (0.0, 1.0)),
7419            (Point3::new(199.999_999_7, 0.0, 0.0), 100.0, up, (0.0, 1.0)),
7420            1e-9,
7421        );
7422        assert_eq!(close.len(), 2);
7423        close.sort_by(|a, b| a.0.y().total_cmp(&b.0.y()));
7424        let apart = close[1].0.y() - close[0].0.y();
7425        assert!((apart - 0.010_954).abs() < 1e-5, "{apart}");
7426    }
7427
7428    /// How far `p` lies off `cone` (either nappe), and its `v` there.
7429    fn off_cone(cone: &ConicalSurface, p: Point3) -> (f64, f64) {
7430        let q = p - cone.apex();
7431        let (along, s) = (q.dot(cone.axis()), cone.half_angle().sin());
7432        ((along.abs() - s * q.length()).abs(), along / s)
7433    }
7434
7435    /// Cones sharing an apex, their axes 40° apart and each opening 20°
7436    /// from its axis, touch along the one ruling between the axes, which
7437    /// runs where both faces hold it.
7438    #[test]
7439    fn cones_sharing_an_apex_touch_along_one_ruling() {
7440        let apex = Point3::new(1.0, 2.0, 3.0);
7441        let a = 20.0_f64.to_radians();
7442        let half = std::f64::consts::FRAC_PI_2 - a;
7443        let c1 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, a.sin()), half).unwrap();
7444        let c2 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, -a.sin()), half).unwrap();
7445        let curves = intersect_analytic_analytic_bounded(
7446            AnalyticSurface::Cone(&c1),
7447            AnalyticSurface::Cone(&c2),
7448            64,
7449            Some((0.2, 3.0)),
7450            Some((0.5, 4.0)),
7451        )
7452        .unwrap();
7453        assert_eq!(curves.len(), 1);
7454        let curve = &curves[0].curve;
7455        let (t0, t1) = curve.domain();
7456        let x = Vec3::new(1.0, 0.0, 0.0);
7457        assert!((curve.evaluate(t0) - (apex + x * 0.5)).length() < 1e-12);
7458        assert!((curve.evaluate(t1) - (apex + x * 3.0)).length() < 1e-12);
7459    }
7460
7461    /// Cones sharing an apex, their axes 20° apart and each opening 30°,
7462    /// cross along two rulings; faces reaching past the apex hold each on
7463    /// both sides of it, in two segments that end there.
7464    #[test]
7465    fn cones_sharing_an_apex_cross_along_two_rulings() {
7466        let apex = Point3::new(-1.0, 0.5, 2.0);
7467        let b = 20.0_f64.to_radians();
7468        let half = 60.0_f64.to_radians();
7469        let c1 = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, 1.0), half).unwrap();
7470        let c2 = ConicalSurface::new(apex, Vec3::new(b.sin(), 0.0, b.cos()), half).unwrap();
7471        for (range, pieces) in [((0.5, 2.0), 2), ((-2.0, 2.0), 4)] {
7472            let curves = intersect_analytic_analytic_bounded(
7473                AnalyticSurface::Cone(&c1),
7474                AnalyticSurface::Cone(&c2),
7475                64,
7476                Some(range),
7477                Some(range),
7478            )
7479            .unwrap();
7480            assert_eq!(curves.len(), pieces, "{range:?}");
7481            for ic in &curves {
7482                let (t0, t1) = ic.curve.domain();
7483                for k in 0..=20 {
7484                    let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 20.0);
7485                    for cone in [&c1, &c2] {
7486                        let (off, v) = off_cone(cone, p);
7487                        assert!(off < 1e-12, "{range:?}: off a cone by {off:.2e}");
7488                        assert!(v > range.0 - 1e-12 && v < range.1 + 1e-12);
7489                    }
7490                }
7491                if pieces == 4 {
7492                    let ends = [ic.curve.evaluate(t0), ic.curve.evaluate(t1)];
7493                    assert!(ends.iter().any(|&e| (e - apex).length() < 1e-12));
7494                }
7495                for point in &ic.points {
7496                    let (on1, on2) = (point.param1, point.param2);
7497                    assert!((c1.evaluate(on1.0, on1.1) - point.point).length() < 1e-9);
7498                    assert!((c2.evaluate(on2.0, on2.1) - point.point).length() < 1e-9);
7499                }
7500            }
7501        }
7502    }
7503
7504    /// Axes 1e-8 apart in angle leave a ruling's part across them to
7505    /// rounding, and cones touching within rounding along a ruling leave
7506    /// how far apart their rulings may be 1e6 out to it: neither is solved
7507    /// here.
7508    #[test]
7509    fn cones_sharing_an_apex_defer_what_rounding_cannot_settle() {
7510        let apex = Point3::new(0.0, 0.0, 0.0);
7511        let half = 60.0_f64.to_radians();
7512        let c1 = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, 1.0), half).unwrap();
7513        let c2 = ConicalSurface::new(apex, Vec3::new(1e-8_f64.sin(), 0.0, 1e-8_f64.cos()), half)
7514            .unwrap();
7515        let near = Some((0.5, 2.0));
7516        assert!(shared_apex_cones(&c1, &c2, near, near).unwrap().is_none());
7517        let a = 20.0_f64.to_radians();
7518        let half = std::f64::consts::FRAC_PI_2 - a;
7519        let c1 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, a.sin()), half).unwrap();
7520        let c2 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, -a.sin()), half).unwrap();
7521        let far = Some((0.5, 1e6));
7522        assert!(shared_apex_cones(&c1, &c2, far, far).unwrap().is_none());
7523    }
7524
7525    /// Perpendicular cones opening 1e-15 short of touching cross along two
7526    /// rulings, which part by about 0.09 a million out: two segments.
7527    #[test]
7528    fn cones_sharing_an_apex_just_short_of_touching_cross_in_two_rulings() {
7529        let apex = Point3::new(0.0, 0.0, 0.0);
7530        let half = std::f64::consts::FRAC_PI_4 - 1e-15;
7531        let c1 = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, 1.0), half).unwrap();
7532        let c2 = ConicalSurface::new(apex, Vec3::new(1.0, 0.0, 0.0), half).unwrap();
7533        let range = Some((0.5, 1e6));
7534        let curves = shared_apex_cones(&c1, &c2, range, range).unwrap().unwrap();
7535        assert_eq!(curves.len(), 2);
7536        let ends: Vec<Point3> = curves
7537            .iter()
7538            .map(|ic| ic.curve.evaluate(ic.curve.domain().1))
7539            .collect();
7540        assert!((ends[0] - ends[1]).length() > 0.05);
7541    }
7542
7543    /// A ball off a ring's axis touches it at one point from outside the
7544    /// tube, from inside it, or holding the whole ring, and that point is
7545    /// all they share. A ball reaching 1e-6 further cuts the tube in a small
7546    /// loop, which is left to the section's closed form, and one centred on
7547    /// the core circle with the tube's radius meets it along the meridian
7548    /// circle through its centre.
7549    #[test]
7550    fn a_ball_off_a_rings_axis_touches_it_at_one_point() {
7551        let o = Point3::new(1.0, 2.0, 3.0);
7552        let ring = ToroidalSurface::new(o, 3.0, 1.0).unwrap();
7553        let (s, c) = 30.0_f64.to_radians().sin_cos();
7554        let (out, up) = (Vec3::new(c, s, 0.0), Vec3::new(0.0, 0.0, 1.0));
7555        let on_ring = |p: Point3| {
7556            let q = p - o;
7557            ((q.x().hypot(q.y()) - 3.0).hypot(q.z()) - 1.0).abs()
7558        };
7559        let balls = [
7560            (o + out * 5.0, 1.0),
7561            (o + out * 3.2 + up * 0.1, 1.0 - 0.05_f64.sqrt()),
7562            (o + out + up * 0.5, 1.0 + 16.25_f64.sqrt()),
7563        ];
7564        let mut touches = Vec::new();
7565        for (centre, radius) in balls {
7566            let ball = SphericalSurface::new(centre, radius).unwrap();
7567            let exacts = exact_sphere_torus(&ball, &ring).unwrap().unwrap();
7568            let p = match exacts.as_slice() {
7569                [ExactIntersectionCurve::Points(points)] => points[0],
7570                _ => unreachable!("one touching point"),
7571            };
7572            assert!(on_ring(p) < 1e-12 && ((p - centre).length() - radius).abs() < 1e-12);
7573            let curves = intersect_analytic_analytic(
7574                AnalyticSurface::Sphere(&ball),
7575                AnalyticSurface::Torus(&ring),
7576                16,
7577            )
7578            .unwrap();
7579            assert_eq!(curves.len(), 1);
7580            let (t0, t1) = curves[0].curve.domain();
7581            assert!((curves[0].curve.evaluate(t0) - p).length() < 1e-15);
7582            assert!((curves[0].curve.evaluate(t1) - p).length() < 1e-15);
7583            touches.push(p);
7584        }
7585        assert!((touches[0] - (o + out * 4.0)).length() < 1e-12);
7586        let past = SphericalSurface::new(o + out * 5.0, 1.0 + 1e-6).unwrap();
7587        assert!(exact_sphere_torus(&past, &ring).unwrap().is_none());
7588        let on_core = SphericalSurface::new(o + out * 3.0, 1.0).unwrap();
7589        let meridian = exact_sphere_torus(&on_core, &ring).unwrap().unwrap();
7590        let [ExactIntersectionCurve::Circle(circle)] = meridian.as_slice() else {
7591            unreachable!("one meridian circle");
7592        };
7593        assert!((circle.center() - (o + out * 3.0)).length() < 1e-12);
7594        assert!((circle.radius() - 1.0).abs() < 1e-12);
7595    }
7596}