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 std::f64::consts::{FRAC_PI_2, TAU};
8
9use crate::MathError;
10use crate::curves::{Circle3D, Ellipse3D};
11use crate::frame::Frame3;
12use crate::nurbs::fitting::interpolate;
13use crate::nurbs::intersection::{IntersectionCurve, IntersectionPoint};
14use crate::surfaces::{ConicalSurface, CylindricalSurface, SphericalSurface, ToroidalSurface};
15use crate::tolerance::Tolerance;
16use crate::vec::{Point3, Vec3};
17
18/// Exact curve type resulting from plane-analytic surface intersection.
19#[derive(Debug, Clone)]
20pub enum ExactIntersectionCurve {
21    /// A circle (plane perpendicular to axis of cylinder/cone/sphere).
22    Circle(Circle3D),
23    /// An ellipse (plane oblique to cylinder/cone axis).
24    Ellipse(Ellipse3D),
25    /// Fallback to sampled point chain (torus, degenerate cases).
26    Points(Vec<Point3>),
27}
28
29/// Compute exact intersection curves between a plane and an analytic surface.
30///
31/// Returns exact `Circle3D` or `Ellipse3D` where possible, falling back to
32/// sampled points for complex cases (torus).
33///
34/// The plane is defined by `dot(normal, p) = d`.
35///
36/// # Errors
37///
38/// Returns an error if the intersection computation fails.
39pub fn exact_plane_analytic(
40    surface: AnalyticSurface<'_>,
41    plane_normal: Vec3,
42    plane_d: f64,
43) -> Result<Vec<ExactIntersectionCurve>, MathError> {
44    match surface {
45        AnalyticSurface::Cylinder(cyl) => exact_plane_cylinder(cyl, plane_normal, plane_d),
46        AnalyticSurface::Sphere(sphere) => exact_plane_sphere(sphere, plane_normal, plane_d),
47        AnalyticSurface::Cone(cone) => exact_plane_cone(cone, plane_normal, plane_d),
48        AnalyticSurface::Torus(torus) => {
49            // Torus intersections are degree-4 — fall back to sampling.
50            let chains = sample_plane_torus(torus, plane_normal, plane_d)?;
51            Ok(chains
52                .into_iter()
53                .map(ExactIntersectionCurve::Points)
54                .collect())
55        }
56    }
57}
58
59/// Exact plane-cylinder intersection.
60///
61/// - Plane perpendicular to axis → `Circle3D`
62/// - Plane oblique to axis → `Ellipse3D`
63/// - Plane parallel to axis → `Points` fallback (0 or 2 lines)
64fn exact_plane_cylinder(
65    cyl: &CylindricalSurface,
66    normal: Vec3,
67    d: f64,
68) -> Result<Vec<ExactIntersectionCurve>, MathError> {
69    let axis = cyl.axis();
70    let cos_theta = normal.dot(axis).abs();
71    let r = cyl.radius();
72
73    if cos_theta < 1e-10 {
74        // Plane parallel to cylinder axis → 0 or 2 line segments.
75        // Fall back to sampled points.
76        let chains = sample_plane_cylinder(cyl, normal, d)?;
77        return Ok(chains
78            .into_iter()
79            .map(ExactIntersectionCurve::Points)
80            .collect());
81    }
82
83    // Find where axis intersects the plane: axis_point + t*axis, dot(normal, P) = d
84    // t = (d - dot(normal, origin)) / dot(normal, axis)
85    let n_dot_axis = normal.dot(axis);
86    let n_dot_origin = dot_np(normal, cyl.origin());
87    let t = (d - n_dot_origin) / n_dot_axis;
88    let center_on_axis = Point3::new(
89        cyl.origin().x() + t * axis.x(),
90        cyl.origin().y() + t * axis.y(),
91        cyl.origin().z() + t * axis.z(),
92    );
93
94    if cos_theta > 1.0 - 1e-10 {
95        // Plane perpendicular to axis → Circle
96        let circle = Circle3D::new(center_on_axis, normal, r)?;
97        Ok(vec![ExactIntersectionCurve::Circle(circle)])
98    } else {
99        // Oblique plane → Ellipse
100        // Semi-minor = r (the cylinder radius, unchanged)
101        // Semi-major = r / cos(θ) where θ = angle between plane normal and axis
102        let semi_minor = r;
103        let semi_major = r / cos_theta;
104
105        // The major axis direction lies in the intersection of the plane
106        // with the plane containing the axis and the plane normal.
107        // It's the projection of the axis onto the cutting plane, normalized.
108        let axis_proj = Vec3::new(
109            axis.x() - n_dot_axis * normal.x(),
110            axis.y() - n_dot_axis * normal.y(),
111            axis.z() - n_dot_axis * normal.z(),
112        );
113        let u_axis = axis_proj.normalize()?;
114        let v_axis = normal.cross(u_axis);
115
116        let ellipse = Ellipse3D::with_axes(
117            center_on_axis,
118            normal,
119            semi_major,
120            semi_minor,
121            u_axis,
122            v_axis,
123        )?;
124        Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)])
125    }
126}
127
128/// Exact plane-sphere intersection.
129///
130/// Always produces a `Circle3D` (or empty if no intersection).
131fn exact_plane_sphere(
132    sphere: &SphericalSurface,
133    normal: Vec3,
134    d: f64,
135) -> Result<Vec<ExactIntersectionCurve>, MathError> {
136    let h = dot_np(normal, sphere.center()) - d;
137    let r = sphere.radius();
138
139    if h.abs() > r - 1e-10 {
140        return Ok(vec![]);
141    }
142
143    let circle_r = (r.mul_add(r, -(h * h))).sqrt();
144    let circle_center = Point3::new(
145        h.mul_add(-normal.x(), sphere.center().x()),
146        h.mul_add(-normal.y(), sphere.center().y()),
147        h.mul_add(-normal.z(), sphere.center().z()),
148    );
149
150    let circle = Circle3D::new(circle_center, normal, circle_r)?;
151    Ok(vec![ExactIntersectionCurve::Circle(circle)])
152}
153
154/// Exact plane-cone intersection.
155///
156/// The conic type is set by the cone's half-opening angle from the axis
157/// (`γ = π/2 − half_angle`) versus the plane-axis angle `ψ`:
158/// - Plane perpendicular to axis (`ψ = π/2`) → `Circle3D`
159/// - `ψ > γ` (ellipse) → closed-form `Ellipse3D`
160/// - `ψ ≤ γ` (parabola/hyperbola) → bounded single-branch `Points` (one chain
161///   per branch — a hyperbola's two nappes never share a chain)
162fn exact_plane_cone(
163    cone: &ConicalSurface,
164    normal: Vec3,
165    d: f64,
166) -> Result<Vec<ExactIntersectionCurve>, MathError> {
167    let axis = cone.axis();
168    let cos_theta = normal.dot(axis).abs();
169    let half_angle = cone.half_angle();
170
171    if cos_theta > 1.0 - 1e-10 {
172        // Plane perpendicular to axis → Circle
173        // Find where axis meets the plane
174        let n_dot_axis = normal.dot(axis);
175        let n_dot_apex = dot_np(normal, cone.apex());
176        let t = (d - n_dot_apex) / n_dot_axis;
177
178        // t is the signed distance from apex to plane along the axis.
179        // The real cone is a single nappe; the perpendicular-plane section is a
180        // circle whose radius follows from the axial offset |t|.
181        // |t| ≈ 0 means the plane passes through the apex → degenerate point.
182        if t.abs() < 1e-10 {
183            return Ok(vec![]);
184        }
185
186        let center = Point3::new(
187            cone.apex().x() + t * axis.x(),
188            cone.apex().y() + t * axis.y(),
189            cone.apex().z() + t * axis.z(),
190        );
191        // half_angle is the angle from the radial plane to the surface.
192        // Axial distance t = v * sin(half_angle), so v = t / sin(half_angle).
193        // Radius at v = v * cos(half_angle) = t * cos(half_angle) / sin(half_angle).
194        let circle_r = t.abs() * half_angle.cos() / half_angle.sin();
195        if circle_r < 1e-15 {
196            return Ok(vec![]);
197        }
198
199        let circle = Circle3D::new(center, normal, circle_r)?;
200        return Ok(vec![ExactIntersectionCurve::Circle(circle)]);
201    }
202
203    // Oblique plane. Classify the conic in the plane-aligned frame.
204    //
205    // Decompose the (unit) axis as a = c·n + p·e1, where c = n·a, e1 is the unit
206    // in-plane projection of the axis, and p = |projection| = sqrt(1−c²). Write a
207    // point Q on the plane as Q = apex + e·n + s·e1 + t·e2 (e = d − n·apex,
208    // e2 = n×e1). The cone equation (w·a)² = cos²γ·(w·w) with k = cos²γ =
209    // sin²(half_angle) reduces to (no s·t cross term, since e1/e2 align with the
210    // conic axes):
211    //     (p²−k)·s² + 2ecp·s + e²(c²−k) = k·t²
212    // The s² coefficient A = p²−k = sin²θ − sin²(half_angle) sets the type:
213    // A < 0 → ellipse, A = 0 → parabola, A > 0 → hyperbola.
214    let c = normal.dot(axis);
215    let p2 = (1.0 - c * c).max(0.0);
216    let p = p2.sqrt();
217    let k = half_angle.sin().powi(2);
218    let a_coeff = p2 - k;
219
220    // Build the plane-aligned frame e1 (in-plane axis projection), e2 = n×e1.
221    let m = Vec3::new(
222        axis.x() - c * normal.x(),
223        axis.y() - c * normal.y(),
224        axis.z() - c * normal.z(),
225    );
226    let m_len = m.length();
227    if m_len < 1e-12 {
228        // Axis parallel to normal — handled by the perpendicular branch above;
229        // fall back to sampling for safety.
230        let chains = sample_plane_cone(cone, normal, d)?;
231        return Ok(chains
232            .into_iter()
233            .map(ExactIntersectionCurve::Points)
234            .collect());
235    }
236    let e1 = m * (1.0 / m_len);
237    let e2 = normal.cross(e1);
238    let apex = cone.apex();
239    let e = d - dot_np(normal, apex);
240
241    // Ellipse → closed form. A = p²−k < 0 with a margin to keep the
242    // near-parabolic regime on the robust sampled path.
243    if a_coeff < -1e-9 {
244        let abs_a = -a_coeff; // = k − p² > 0
245        // Real-nappe guard: in the ellipse regime n·g(u) keeps constant sign(c),
246        // so v = e/(n·g) ≥ 0 only when e and c share a sign. When e·c < 0 the
247        // plane is offset to the far side of the apex from the cone's opening —
248        // the section lies entirely on the phantom nappe, so there is no real
249        // curve (RHS below is positive regardless of sign, so it can't catch this).
250        if e * c < 0.0 {
251            return Ok(vec![]);
252        }
253        // |A|(s − s_c)² + k·t² = RHS, with s_c = ecp/|A| and
254        // RHS = e²·k·(1−k)/|A| (always > 0 for a real ellipse).
255        let s_c = e * c * p / abs_a;
256        let rhs = e * e * k * (1.0 - k) / abs_a;
257        if rhs <= 0.0 {
258            return Ok(vec![]);
259        }
260        let semi_s = (rhs / abs_a).sqrt(); // extent along e1
261        let semi_t = (rhs / k).sqrt(); // extent along e2
262        if semi_s < 1e-12 || semi_t < 1e-12 {
263            return Ok(vec![]);
264        }
265        let center = apex + normal * e + e1 * s_c;
266        let (semi_major, semi_minor, u_axis, v_axis) = if semi_s >= semi_t {
267            (semi_s, semi_t, e1, e2)
268        } else {
269            (semi_t, semi_s, e2, e1)
270        };
271        let ellipse = Ellipse3D::with_axes(center, normal, semi_major, semi_minor, u_axis, v_axis)?;
272        return Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)]);
273    }
274
275    // Parabola / hyperbola (and the near-parabolic ellipse margin): the section
276    // is unbounded, so emit bounded, branch-separated sample chains.
277    let chains = sample_plane_cone(cone, normal, d)?;
278    Ok(chains
279        .into_iter()
280        .map(ExactIntersectionCurve::Points)
281        .collect())
282}
283
284/// Reference to an analytic surface for intersection dispatch.
285#[derive(Clone, Copy)]
286pub enum AnalyticSurface<'a> {
287    /// Cylindrical surface reference.
288    Cylinder(&'a CylindricalSurface),
289    /// Conical surface reference.
290    Cone(&'a ConicalSurface),
291    /// Spherical surface reference.
292    Sphere(&'a SphericalSurface),
293    /// Toroidal surface reference.
294    Torus(&'a ToroidalSurface),
295}
296
297/// Compute `n . p` treating a `Point3` as a position vector.
298fn dot_np(n: Vec3, p: Point3) -> f64 {
299    n.dot(Vec3::new(p.x(), p.y(), p.z()))
300}
301
302/// Intersect a plane with an analytic surface.
303///
304/// The plane is defined by `dot(normal, p) = d`.
305///
306/// # Errors
307///
308/// Returns an error if the intersection computation fails.
309pub fn intersect_plane_analytic(
310    surface: AnalyticSurface<'_>,
311    normal: Vec3,
312    d: f64,
313) -> Result<Vec<IntersectionCurve>, MathError> {
314    match surface {
315        AnalyticSurface::Cylinder(cyl) => intersect_plane_cylinder(cyl, normal, d),
316        AnalyticSurface::Cone(cone) => intersect_plane_cone(cone, normal, d),
317        AnalyticSurface::Sphere(sphere) => intersect_plane_sphere(sphere, normal, d),
318        AnalyticSurface::Torus(torus) => intersect_plane_torus(torus, normal, d),
319    }
320}
321
322/// Sample points on the plane-analytic intersection without NURBS curve fitting.
323///
324/// Returns chains of ordered 3D sample points. Each chain is one connected
325/// component of the intersection curve. This is much faster than
326/// `intersect_plane_analytic` when only sample points are needed (e.g. for
327/// boolean intersection segment generation).
328///
329/// # Errors
330///
331/// Returns an error if the intersection computation fails.
332pub fn sample_plane_analytic(
333    surface: AnalyticSurface<'_>,
334    normal: Vec3,
335    d: f64,
336) -> Result<Vec<Vec<Point3>>, MathError> {
337    match surface {
338        AnalyticSurface::Cylinder(cyl) => sample_plane_cylinder(cyl, normal, d),
339        AnalyticSurface::Cone(cone) => sample_plane_cone(cone, normal, d),
340        AnalyticSurface::Sphere(sphere) => sample_plane_sphere(sphere, normal, d),
341        AnalyticSurface::Torus(torus) => sample_plane_torus(torus, normal, d),
342    }
343}
344
345/// Sample the plane-cylinder intersection as ordered 3D points.
346#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
347fn sample_plane_cylinder(
348    cyl: &CylindricalSurface,
349    normal: Vec3,
350    d: f64,
351) -> Result<Vec<Vec<Point3>>, MathError> {
352    let n_samples = 64_usize;
353    let mut points = Vec::with_capacity(n_samples + 1);
354
355    for i in 0..=n_samples {
356        let u = TAU * (i as f64) / (n_samples as f64);
357        let base = cyl.evaluate(u, 0.0);
358        let n_dot_axis = normal.dot(cyl.axis());
359        let n_dot_base = dot_np(normal, base);
360
361        if n_dot_axis.abs() < 1e-12 {
362            if (n_dot_base - d).abs() < 1e-6 {
363                points.push(base);
364            }
365        } else {
366            let v = (d - n_dot_base) / n_dot_axis;
367            if v.abs() <= 100.0 {
368                points.push(cyl.evaluate(u, v));
369            }
370        }
371    }
372
373    if points.len() < 2 {
374        Ok(vec![])
375    } else {
376        Ok(vec![points])
377    }
378}
379
380/// Sample the plane-sphere intersection as ordered 3D points.
381#[allow(clippy::cast_precision_loss)]
382fn sample_plane_sphere(
383    sphere: &SphericalSurface,
384    normal: Vec3,
385    d: f64,
386) -> Result<Vec<Vec<Point3>>, MathError> {
387    let h = dot_np(normal, sphere.center()) - d;
388    let r = sphere.radius();
389
390    if h.abs() > r - 1e-10 {
391        return Ok(vec![]);
392    }
393
394    let circle_r = (r.mul_add(r, -(h * h))).sqrt();
395    let circle_center = Point3::new(
396        h.mul_add(-normal.x(), sphere.center().x()),
397        h.mul_add(-normal.y(), sphere.center().y()),
398        h.mul_add(-normal.z(), sphere.center().z()),
399    );
400
401    let basis = Frame3::from_normal(circle_center, normal)?;
402    let u_dir = basis.x;
403    let v_dir = basis.y;
404
405    let n_samples = 64_usize;
406    let mut points = Vec::with_capacity(n_samples + 1);
407
408    for i in 0..=n_samples {
409        let theta = TAU * (i as f64) / (n_samples as f64);
410        let (sin_t, cos_t) = theta.sin_cos();
411        points.push(circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t));
412    }
413
414    Ok(vec![points])
415}
416
417/// Sample the plane-cone intersection as ordered 3D points.
418///
419/// The cone is the single real nappe `v >= 0` of `P(u,v) = apex + v·g(u)`.
420/// Along each generator `g(u)` the plane `n·P = d` is linear in `v`, so
421/// `v = (d − n·apex) / (n·g(u))`. We keep only `v >= 0` (the phantom `v < 0`
422/// nappe is geometrically absent) and `v` below a finite bound (near an
423/// asymptote `n·g(u) → 0` so `v → ∞` — those points run off the surface and
424/// must be excluded). The angular samples that survive form one contiguous arc
425/// (ellipse) or two (parabola/hyperbola, one per branch); each contiguous run
426/// is returned as a separate ordered chain so the consumer never stitches two
427/// disjoint branches into one curve.
428#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
429fn sample_plane_cone(
430    cone: &ConicalSurface,
431    normal: Vec3,
432    d: f64,
433) -> Result<Vec<Vec<Point3>>, MathError> {
434    let apex = cone.apex();
435    let n_dot_apex = dot_np(normal, apex);
436    let e = d - n_dot_apex;
437
438    // Per-generator solve: along g(u) the plane is linear in v, v = e / (n·g(u)).
439    // Sample u densely; keep only the real nappe (v >= 0) and skip near-asymptote
440    // generators (n·g(u) ≈ 0 → v → ∞).
441    let n_samples = 512_usize;
442    let mut vs: Vec<Option<f64>> = Vec::with_capacity(n_samples);
443    let mut v_min = f64::INFINITY;
444    for i in 0..n_samples {
445        let u = TAU * (i as f64) / (n_samples as f64);
446        let g = cone.evaluate(u, 1.0) - apex;
447        let n_dot_g = normal.dot(Vec3::new(g.x(), g.y(), g.z()));
448        if n_dot_g.abs() < 1e-12 {
449            vs.push(None);
450            continue;
451        }
452        let v = e / n_dot_g;
453        if v >= -1e-12 {
454            let v = v.max(0.0);
455            v_min = v_min.min(v);
456            vs.push(Some(v));
457        } else {
458            vs.push(None);
459        }
460    }
461
462    if !v_min.is_finite() {
463        return Ok(Vec::new());
464    }
465
466    // Bound the arc around the conic vertex (closest approach to the apex, at
467    // v_min). An ellipse is naturally bounded; a parabola/hyperbola is not, so
468    // cap the cone radius at a generous multiple of the vertex radius. This is
469    // scale-invariant and centred on where any finite cone face's overlap lies;
470    // the downstream consumer trims the fitted curve to the actual face AABB, so
471    // over-coverage is harmless. The floor handles a vertex at the apex (v_min≈0).
472    let v_max = (8.0 * v_min).max(v_min + 4.0);
473
474    // Per-sample v within the cap; the raw values stay in `vs` for the
475    // boundary solve below.
476    let kept: Vec<Option<f64>> = vs.iter().map(|v| v.filter(|&v| v <= v_max)).collect();
477
478    let point_at = |u: f64, v: f64| -> Point3 {
479        let g = cone.evaluate(u, 1.0) - apex;
480        apex + g * v
481    };
482    #[allow(clippy::cast_precision_loss)]
483    let u_of = |i: usize| TAU * (i as f64) / (n_samples as f64);
484    let n_dot_g_at = |u: f64| -> f64 {
485        let g = cone.evaluate(u, 1.0) - apex;
486        normal.dot(Vec3::new(g.x(), g.y(), g.z()))
487    };
488
489    if kept.iter().all(Option::is_some) {
490        // Closed loop (ellipse regime): emit all points and repeat the first.
491        let mut pts: Vec<Point3> = kept
492            .iter()
493            .enumerate()
494            .filter_map(|(i, v)| v.map(|v| point_at(u_of(i), v)))
495            .collect();
496        if let Some(&first) = pts.first() {
497            pts.push(first);
498        }
499        return Ok(vec![pts]);
500    }
501
502    // A hyperbola/parabola tail diverges as 1/(n·g), so between the last kept
503    // sample and its dropped neighbour v can leap far past `v_max` in one
504    // uniform-u pitch — and any finite face window inside that leap is lost
505    // (a taper cone grazed 0.05 by a prism plane lost its entire 0.5-tall
506    // section to exactly this aliasing). Extend each run end to the exact
507    // `v_max` boundary: bisect u for `n·g(u) = e/v_max` inside the dropped
508    // pitch (n·g is monotone there — its extrema sit at the conic vertex,
509    // far from any asymptote), then fill the tail with uniform-u samples.
510    let tail = |i_end: usize, forward: bool, kept: &[Option<f64>]| -> Vec<Point3> {
511        let Some(v_end) = kept[i_end] else {
512            return Vec::new();
513        };
514        let u_end = u_of(i_end);
515        #[allow(clippy::cast_precision_loss)]
516        let pitch = TAU / (n_samples as f64);
517        let u_next = if forward {
518            u_end + pitch
519        } else {
520            u_end - pitch
521        };
522        let target = e / v_max;
523        let h_end = n_dot_g_at(u_end) - target;
524        let h_next = n_dot_g_at(u_next) - target;
525        if v_end >= v_max || h_end == 0.0 || h_end.signum() == h_next.signum() {
526            return Vec::new();
527        }
528        let (mut lo, mut hi) = (u_end, u_next);
529        for _ in 0..60 {
530            let mid = f64::midpoint(lo, hi);
531            if (n_dot_g_at(mid) - target).signum() == h_end.signum() {
532                lo = mid;
533            } else {
534                hi = mid;
535            }
536        }
537        let u_star = f64::midpoint(lo, hi);
538        let tail_n = 8_usize;
539        (1..=tail_n)
540            .filter_map(|k| {
541                #[allow(clippy::cast_precision_loss)]
542                let u = u_end + (u_star - u_end) * (k as f64) / (tail_n as f64);
543                let ng = n_dot_g_at(u);
544                if ng.abs() < 1e-12 {
545                    return None;
546                }
547                let v = e / ng;
548                (v >= -1e-12 && v <= v_max * (1.0 + 1e-9)).then(|| point_at(u, v.max(0.0)))
549            })
550            .collect()
551    };
552
553    // Split into contiguous runs of kept samples, treating the array as
554    // circular (rotate past a gap) so a branch straddling u=0 stays whole.
555    let gap = kept.iter().position(Option::is_none).unwrap_or(0);
556    let mut chains: Vec<Vec<Point3>> = Vec::new();
557    let mut run: Vec<usize> = Vec::new();
558    let flush = |run: &mut Vec<usize>, chains: &mut Vec<Vec<Point3>>| {
559        if run.len() >= 2 {
560            let first = run[0];
561            let last = run[run.len() - 1];
562            let mut pts: Vec<Point3> = tail(first, false, &kept);
563            pts.reverse();
564            pts.extend(
565                run.iter()
566                    .filter_map(|&i| kept[i].map(|v| point_at(u_of(i), v))),
567            );
568            pts.extend(tail(last, true, &kept));
569            chains.push(pts);
570        }
571        run.clear();
572    };
573    for k in 0..n_samples {
574        let idx = (gap + k) % n_samples;
575        if kept[idx].is_some() {
576            run.push(idx);
577        } else {
578            flush(&mut run, &mut chains);
579        }
580    }
581    flush(&mut run, &mut chains);
582    Ok(chains.into_iter().filter(|c| c.len() >= 2).collect())
583}
584
585/// Sample the plane-torus intersection as ordered 3D points.
586///
587/// Uses the same Newton-refined sampling grid as `intersect_plane_torus`
588/// but skips NURBS curve fitting.
589#[allow(clippy::cast_precision_loss)]
590fn sample_plane_torus(
591    torus: &ToroidalSurface,
592    normal: Vec3,
593    d: f64,
594) -> Result<Vec<Vec<Point3>>, MathError> {
595    let curves = intersect_plane_torus(torus, normal, d)?;
596    Ok(curves
597        .into_iter()
598        .map(|c| c.points.into_iter().map(|p| p.point).collect())
599        .collect())
600}
601
602/// Intersect a plane with a cylindrical surface.
603///
604/// For each `u` in `[0, 2pi)`, the cylinder point is linear in `v`,
605/// so the plane equation `dot(normal, P(u,v)) = d` is linear in `v`
606/// and can be solved directly.
607///
608/// # Errors
609///
610/// Returns an error if curve fitting fails.
611#[allow(clippy::cast_precision_loss)]
612pub fn intersect_plane_cylinder(
613    cyl: &CylindricalSurface,
614    normal: Vec3,
615    d: f64,
616) -> Result<Vec<IntersectionCurve>, MathError> {
617    let n_samples = 64_usize;
618    let mut points_3d = Vec::new();
619    let mut ipoints = Vec::new();
620
621    for i in 0..=n_samples {
622        let u = TAU * (i as f64) / (n_samples as f64);
623        // P(u, v) = origin + r*(cos(u)*x + sin(u)*y) + v*axis
624        // dot(normal, P) = d  =>  dot(normal, base(u)) + v * dot(normal, axis) = d
625        let base = cyl.evaluate(u, 0.0);
626        let n_dot_axis = normal.dot(cyl.axis());
627        let n_dot_base = dot_np(normal, base);
628
629        if n_dot_axis.abs() < 1e-12 {
630            // Plane parallel to axis -- check if base is on plane.
631            if (n_dot_base - d).abs() < 1e-6 {
632                let pt = base;
633                points_3d.push(pt);
634                ipoints.push(IntersectionPoint {
635                    point: pt,
636                    param1: (u, 0.0),
637                    param2: (0.0, 0.0),
638                });
639            }
640        } else {
641            let v = (d - n_dot_base) / n_dot_axis;
642            // Only keep points within a reasonable v range.
643            if v.abs() <= 100.0 {
644                let pt = cyl.evaluate(u, v);
645                points_3d.push(pt);
646                ipoints.push(IntersectionPoint {
647                    point: pt,
648                    param1: (u, v),
649                    param2: (0.0, 0.0),
650                });
651            }
652        }
653    }
654
655    build_curves_from_points(&points_3d, ipoints)
656}
657
658/// Intersect a plane with a spherical surface.
659///
660/// The intersection of a plane with a sphere is a circle (or empty/point).
661/// Computes the circle center, radius, and samples points on it.
662///
663/// # Errors
664///
665/// Returns an error if curve fitting fails.
666#[allow(clippy::cast_precision_loss)]
667pub fn intersect_plane_sphere(
668    sphere: &SphericalSurface,
669    normal: Vec3,
670    d: f64,
671) -> Result<Vec<IntersectionCurve>, MathError> {
672    let h = dot_np(normal, sphere.center()) - d;
673    let r = sphere.radius();
674
675    // No intersection if plane is too far from center.
676    if h.abs() > r - 1e-10 {
677        return Ok(vec![]);
678    }
679
680    let circle_r = (r.mul_add(r, -(h * h))).sqrt();
681    let circle_center = Point3::new(
682        h.mul_add(-normal.x(), sphere.center().x()),
683        h.mul_add(-normal.y(), sphere.center().y()),
684        h.mul_add(-normal.z(), sphere.center().z()),
685    );
686
687    // Build a local frame on the plane.
688    let basis = Frame3::from_normal(circle_center, normal)?;
689    let u_dir = basis.x;
690    let v_dir = basis.y;
691
692    let n_samples = 64_usize;
693    let mut points_3d = Vec::new();
694    let mut ipoints = Vec::new();
695
696    for i in 0..=n_samples {
697        let theta = TAU * (i as f64) / (n_samples as f64);
698        let (sin_t, cos_t) = theta.sin_cos();
699        let pt = circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t);
700        points_3d.push(pt);
701        ipoints.push(IntersectionPoint {
702            point: pt,
703            param1: (theta, 0.0),
704            param2: (0.0, 0.0),
705        });
706    }
707
708    build_curves_from_points(&points_3d, ipoints)
709}
710
711/// Intersect a plane with a conical surface.
712///
713/// Like a cylinder, the cone is linear along each generatrix, so the plane
714/// equation is linear in `v` for each fixed `u`.
715///
716/// # Errors
717///
718/// Returns an error if curve fitting fails.
719#[allow(clippy::cast_precision_loss)]
720pub fn intersect_plane_cone(
721    cone: &ConicalSurface,
722    normal: Vec3,
723    d: f64,
724) -> Result<Vec<IntersectionCurve>, MathError> {
725    let n_samples = 64_usize;
726    let mut points_3d = Vec::new();
727    let mut ipoints = Vec::new();
728
729    for i in 0..n_samples {
730        let u = TAU * (i as f64) / (n_samples as f64);
731        // P(u, v) = apex + v * dir(u)
732        // dot(normal, apex) + v * dot(normal, dir(u)) = d
733        let apex = cone.apex();
734        let n_dot_apex = dot_np(normal, apex);
735        // dir(u) = P(u,1) - apex
736        let p1 = cone.evaluate(u, 1.0);
737        let dir = p1 - apex;
738        let n_dot_dir = normal.dot(dir);
739
740        if n_dot_dir.abs() < 1e-12 {
741            continue;
742        }
743
744        let v = (d - n_dot_apex) / n_dot_dir;
745        // Allow negative v — the cone surface extends in both directions from the apex.
746        if v.abs() > 1e-10 && v.abs() < 100.0 {
747            let pt = cone.evaluate(u, v);
748            points_3d.push(pt);
749            ipoints.push(IntersectionPoint {
750                point: pt,
751                param1: (u, v),
752                param2: (0.0, 0.0),
753            });
754        }
755    }
756
757    build_curves_from_points(&points_3d, ipoints)
758}
759
760/// Intersect a plane with a toroidal surface.
761///
762/// The torus-plane intersection is a degree-4 curve with no simple closed form.
763/// Uses grid sampling with sign-change detection and Newton refinement.
764///
765/// # Errors
766///
767/// Returns an error if curve fitting fails.
768#[allow(
769    clippy::cast_precision_loss,
770    clippy::too_many_lines,
771    clippy::unnecessary_wraps
772)]
773pub fn intersect_plane_torus(
774    torus: &ToroidalSurface,
775    normal: Vec3,
776    d: f64,
777) -> Result<Vec<IntersectionCurve>, MathError> {
778    let n_grid = 128_usize;
779
780    // Signed distance to plane for a torus point.
781    let sdf = |u: f64, v: f64| -> f64 { dot_np(normal, torus.evaluate(u, v)) - d };
782
783    // Collect zero-crossing points by scanning edges of a (u,v) grid.
784    let mut crossing_pts: Vec<(f64, f64, Point3)> = Vec::new();
785
786    let du = TAU / (n_grid as f64);
787    let dv = TAU / (n_grid as f64);
788
789    // Offset grid by half a cell to avoid landing exactly on zero crossings
790    // (e.g. sin(0) = 0.0 exactly in IEEE 754, which defeats sign-change detection).
791    let u_off = du * 0.5;
792    let v_off = dv * 0.5;
793
794    for iu in 0..n_grid {
795        for iv in 0..n_grid {
796            let u0 = (iu as f64).mul_add(du, u_off);
797            let v0 = (iv as f64).mul_add(dv, v_off);
798            let u1 = u0 + du;
799            let v1 = v0 + dv;
800
801            let f00 = sdf(u0, v0);
802            let f10 = sdf(u1, v0);
803            let f01 = sdf(u0, v1);
804
805            // Check horizontal edge (u0,v0)-(u1,v0).
806            if f00 * f10 < 0.0 {
807                let t = f00 / (f00 - f10);
808                let u = t.mul_add(u1 - u0, u0);
809                let (u_r, v_r) = newton_refine_torus(torus, normal, d, u, v0);
810                crossing_pts.push((u_r, v_r, torus.evaluate(u_r, v_r)));
811            }
812
813            // Check vertical edge (u0,v0)-(u0,v1).
814            if f00 * f01 < 0.0 {
815                let t = f00 / (f00 - f01);
816                let v = t.mul_add(v1 - v0, v0);
817                let (u_r, v_r) = newton_refine_torus(torus, normal, d, u0, v);
818                crossing_pts.push((u_r, v_r, torus.evaluate(u_r, v_r)));
819            }
820        }
821    }
822
823    if crossing_pts.is_empty() {
824        return Ok(vec![]);
825    }
826
827    // Group nearby points into connected curves via greedy chaining.
828    let mut used = vec![false; crossing_pts.len()];
829    let mut curves = Vec::new();
830
831    for start in 0..crossing_pts.len() {
832        if used[start] {
833            continue;
834        }
835        used[start] = true;
836        let mut chain = vec![start];
837
838        loop {
839            let last = chain[chain.len() - 1];
840            let last_pt = crossing_pts[last].2;
841            let mut best_idx = None;
842            let mut best_dist = 1.0_f64;
843
844            for (j, &is_used) in used.iter().enumerate() {
845                if is_used {
846                    continue;
847                }
848                let dist = (crossing_pts[j].2 - last_pt).length();
849                if dist < best_dist {
850                    best_dist = dist;
851                    best_idx = Some(j);
852                }
853            }
854
855            if let Some(j) = best_idx {
856                used[j] = true;
857                chain.push(j);
858            } else {
859                break;
860            }
861        }
862
863        if chain.len() >= 4 {
864            let mut pts: Vec<Point3> = chain.iter().map(|&i| crossing_pts[i].2).collect();
865            let mut ipts: Vec<IntersectionPoint> = chain
866                .iter()
867                .map(|&i| IntersectionPoint {
868                    point: crossing_pts[i].2,
869                    param1: (crossing_pts[i].0, crossing_pts[i].1),
870                    param2: (0.0, 0.0),
871                })
872                .collect();
873
874            // Plane × full torus is always a set of CLOSED loops, but the greedy
875            // nearest-neighbour chaining stops one step short of closing: the
876            // first point is already `used`, so the walk never re-adds it and the
877            // last point sits ~one grid step from the start. Detect that wrap (the
878            // end-to-start gap is comparable to the chain's own point spacing) and
879            // append the exact start point, so the fitted NURBS closes
880            // (`evaluate(0) == evaluate(1)`) and downstream consumers see a closed
881            // section curve instead of a near-closed open one. A fragmented chain
882            // (greedy walk broke a loop at a near-tangency) ends FAR from its
883            // start (gap ≫ spacing) and is left open — it must not be force-closed
884            // into a wrong loop.
885            let closing_gap = (pts[pts.len() - 1] - pts[0]).length();
886            let median_spacing = {
887                let mut spac: Vec<f64> = pts.windows(2).map(|w| (w[1] - w[0]).length()).collect();
888                spac.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
889                spac.get(spac.len() / 2).copied().unwrap_or(0.0)
890            };
891            // Wrap when the closing gap is within ~2 point-spacings (measured
892            // ratio ≈ 1.0 for the census ovals) and not already coincident.
893            let wrapped =
894                closing_gap > 1e-9 && median_spacing > 1e-12 && closing_gap <= 2.0 * median_spacing;
895            if wrapped {
896                pts.push(pts[0]);
897                ipts.push(ipts[0]);
898            }
899
900            if let Ok(curve) = interpolate(&pts, 3.min(pts.len() - 1)) {
901                curves.push(IntersectionCurve {
902                    curve,
903                    points: ipts,
904                });
905            }
906        }
907    }
908
909    Ok(curves)
910}
911
912/// Newton-refine a torus parameter to lie on the cutting plane.
913fn newton_refine_torus(
914    torus: &ToroidalSurface,
915    normal: Vec3,
916    d: f64,
917    mut u: f64,
918    mut v: f64,
919) -> (f64, f64) {
920    let eps = 1e-6;
921    for _ in 0..10 {
922        let f = dot_np(normal, torus.evaluate(u, v)) - d;
923        if f.abs() < 1e-12 {
924            break;
925        }
926        // Numerical gradient via central differences.
927        let fu = (dot_np(normal, torus.evaluate(u + eps, v))
928            - dot_np(normal, torus.evaluate(u - eps, v)))
929            / (2.0 * eps);
930        let fv = (dot_np(normal, torus.evaluate(u, v + eps))
931            - dot_np(normal, torus.evaluate(u, v - eps)))
932            / (2.0 * eps);
933
934        let grad_sq = fu.mul_add(fu, fv * fv);
935        if grad_sq < 1e-20 {
936            break;
937        }
938        let step = f / grad_sq;
939        u -= step * fu;
940        v -= step * fv;
941    }
942    (u, v)
943}
944
945/// Real intersection parameters `t` of the line `origin + t·dir` with a torus.
946///
947/// A line meets a torus in up to four points (degree-4). Substituting the line
948/// into the torus implicit `(a² + b² + c² + R² − r²)² = 4R²(a² + b²)` — where
949/// `(a, b, c)` are the line point's coordinates in the torus frame — gives a
950/// quartic in `t`, solved here for its real roots (each refined by one Newton
951/// step against the implicit). `dir` need not be unit length; `t` is in units of
952/// `dir`. Returns the roots sorted ascending (0–4 of them).
953///
954/// Used by the boolean section trimmer to find where a plane×torus oval exits a
955/// box face's straight boundary edge — the exact crossing shared by the two
956/// adjacent faces, which is what makes the notch watertight.
957#[must_use]
958pub fn intersect_line_torus(torus: &ToroidalSurface, origin: Point3, dir: Vec3) -> Vec<f64> {
959    let c = torus.center();
960    let (xa, ya, za) = (torus.x_axis(), torus.y_axis(), torus.z_axis());
961    let big_r = torus.major_radius();
962    let small_r = torus.minor_radius();
963
964    // Line point in torus frame: a(t)=a0+a1 t, b(t)=b0+b1 t, c(t)=c0+c1 t.
965    let o = Vec3::new(origin.x() - c.x(), origin.y() - c.y(), origin.z() - c.z());
966    let (a0, a1) = (xa.dot(o), xa.dot(dir));
967    let (b0, b1) = (ya.dot(o), ya.dot(dir));
968    let (c0, c1) = (za.dot(o), za.dot(dir));
969
970    // G(t) = a² + b² + c² + R² − r²  (quadratic: g2 t² + g1 t + g0)
971    let g2 = a1.mul_add(a1, b1.mul_add(b1, c1 * c1));
972    let g1 = 2.0 * a1.mul_add(a0, b1.mul_add(b0, c1 * c0));
973    let g0 = a0.mul_add(
974        a0,
975        b0.mul_add(b0, c0.mul_add(c0, big_r.mul_add(big_r, -small_r * small_r))),
976    );
977
978    // H(t) = 4R² (a² + b²)  (quadratic: h2 t² + h1 t + h0)
979    let four_rr = 4.0 * big_r * big_r;
980    let h2 = four_rr * a1.mul_add(a1, b1 * b1);
981    let h1 = four_rr * (2.0 * a1.mul_add(a0, b1 * b0));
982    let h0 = four_rr * a0.mul_add(a0, b0 * b0);
983
984    // Quartic G² − H = 0:  e4 t⁴ + e3 t³ + e2 t² + e1 t + e0.
985    let e4 = g2 * g2;
986    let e3 = 2.0 * g2 * g1;
987    let e2 = g1.mul_add(g1, 2.0 * g2 * g0) - h2;
988    let e1 = 2.0f64.mul_add(g1 * g0, -h1);
989    let e0 = g0.mul_add(g0, -h0);
990
991    let mut roots = real_roots_quartic(e4, e3, e2, e1, e0);
992    // One Newton polish against the torus implicit for full precision.
993    let impl_f = |t: f64| -> f64 {
994        let p = origin + dir * t;
995        let q = Vec3::new(p.x() - c.x(), p.y() - c.y(), p.z() - c.z());
996        let (a, b, cc) = (xa.dot(q), ya.dot(q), za.dot(q));
997        (a.hypot(b) - big_r).hypot(cc) - small_r
998    };
999    for t in &mut roots {
1000        let eps = 1e-7;
1001        let f = impl_f(*t);
1002        let df = (impl_f(*t + eps) - impl_f(*t - eps)) / (2.0 * eps);
1003        if df.abs() > 1e-12 {
1004            *t -= f / df;
1005        }
1006    }
1007    roots.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
1008    roots
1009}
1010
1011/// Real roots of `c4 x⁴ + c3 x³ + c2 x² + c1 x + c0` via Durand–Kerner, falling
1012/// back to the lower-degree solvers when the leading coefficients vanish.
1013fn real_roots_quartic(c4: f64, c3: f64, c2: f64, c1: f64, c0: f64) -> Vec<f64> {
1014    // Degenerate leading coefficient → lower degree.
1015    if c4.abs() < 1e-14 {
1016        return real_roots_cubic(c3, c2, c1, c0);
1017    }
1018    // Monic: x⁴ + a x³ + b x² + c x + d.
1019    let (a, b, c, d) = (c3 / c4, c2 / c4, c1 / c4, c0 / c4);
1020    let eval = |z: Complex| -> Complex {
1021        // Horner.
1022        let mut acc = Complex::new(1.0, 0.0);
1023        acc = acc * z + Complex::new(a, 0.0);
1024        acc = acc * z + Complex::new(b, 0.0);
1025        acc = acc * z + Complex::new(c, 0.0);
1026        acc * z + Complex::new(d, 0.0)
1027    };
1028    // Durand–Kerner: four roots seeded on a circle, iterated to convergence.
1029    let seed = Complex::new(0.4, 0.9);
1030    let mut r = [
1031        Complex::new(1.0, 0.0),
1032        seed,
1033        seed * seed,
1034        seed * seed * seed,
1035    ];
1036    for _ in 0..100 {
1037        let mut max_step = 0.0_f64;
1038        for i in 0..4 {
1039            let mut denom = Complex::new(1.0, 0.0);
1040            for j in 0..4 {
1041                if i != j {
1042                    denom = denom * (r[i] - r[j]);
1043                }
1044            }
1045            if denom.norm() < 1e-300 {
1046                continue;
1047            }
1048            let step = eval(r[i]) / denom;
1049            r[i] = r[i] - step;
1050            max_step = max_step.max(step.norm());
1051        }
1052        if max_step < 1e-14 {
1053            break;
1054        }
1055    }
1056    // Keep roots with negligible imaginary part AND a small REAL-polynomial
1057    // residual — Durand–Kerner stops after a fixed iteration cap whether or not
1058    // it converged, so a non-converged iterate could otherwise be returned as a
1059    // spurious root. Evaluate the monic quartic at each candidate (real part) and
1060    // keep only |p(x)| below a magnitude-scaled tolerance; de-dup near-equal
1061    // roots (a double root converges to two near-identical iterates).
1062    let p_real = |x: f64| -> f64 { (((x + a) * x + b) * x + c) * x + d };
1063    let mut out: Vec<f64> = Vec::new();
1064    for z in r {
1065        if z.im.abs() >= 1e-7 {
1066            continue;
1067        }
1068        let x = z.re;
1069        // Residual tolerance scales with the polynomial's coefficient magnitude
1070        // and |x|^4 so large-coefficient quartics are not over-rejected.
1071        let scale = 1.0 + a.abs() + b.abs() + c.abs() + d.abs() + x.abs().powi(4);
1072        if p_real(x).abs() > 1e-6 * scale {
1073            continue;
1074        }
1075        if out.iter().any(|&y| (y - x).abs() < 1e-9 * (1.0 + x.abs())) {
1076            continue;
1077        }
1078        out.push(x);
1079    }
1080    out
1081}
1082
1083/// Real roots of `a x³ + b x² + c x + d` (Cardano), with quadratic fallback.
1084fn real_roots_cubic(a: f64, b: f64, c: f64, d: f64) -> Vec<f64> {
1085    if a.abs() < 1e-14 {
1086        return real_roots_quadratic(b, c, d);
1087    }
1088    // Depressed cubic t³ + p t + q via x = t − b/(3a).
1089    let (b, c, d) = (b / a, c / a, d / a);
1090    let p = c - b * b / 3.0;
1091    let q = 2.0 * b * b * b / 27.0 - b * c / 3.0 + d;
1092    let shift = -b / 3.0;
1093    let disc = q * q / 4.0 + p * p * p / 27.0;
1094    if disc > 1e-14 {
1095        let sq = disc.sqrt();
1096        let u = (-q / 2.0 + sq).cbrt();
1097        let v = (-q / 2.0 - sq).cbrt();
1098        vec![u + v + shift]
1099    } else if disc < -1e-14 {
1100        // Three real roots (trigonometric).
1101        let m = 2.0 * (-p / 3.0).sqrt();
1102        let theta = (3.0 * q / (p * m)).clamp(-1.0, 1.0).acos() / 3.0;
1103        (0..3)
1104            .map(|k| {
1105                m.mul_add(
1106                    (theta - 2.0 * std::f64::consts::PI * f64::from(k) / 3.0).cos(),
1107                    shift,
1108                )
1109            })
1110            .collect()
1111    } else {
1112        // Repeated roots.
1113        let u = (-q / 2.0).cbrt();
1114        vec![2.0 * u + shift, -u + shift]
1115    }
1116}
1117
1118/// Real roots of `a x² + b x + c`, with linear fallback.
1119fn real_roots_quadratic(a: f64, b: f64, c: f64) -> Vec<f64> {
1120    if a.abs() < 1e-14 {
1121        if b.abs() < 1e-14 {
1122            return Vec::new();
1123        }
1124        return vec![-c / b];
1125    }
1126    let disc = b * b - 4.0 * a * c;
1127    if disc < 0.0 {
1128        Vec::new()
1129    } else {
1130        let sq = disc.sqrt();
1131        vec![(-b - sq) / (2.0 * a), (-b + sq) / (2.0 * a)]
1132    }
1133}
1134
1135/// Minimal complex number for the quartic root finder.
1136#[derive(Clone, Copy)]
1137struct Complex {
1138    re: f64,
1139    im: f64,
1140}
1141
1142impl Complex {
1143    const fn new(re: f64, im: f64) -> Self {
1144        Self { re, im }
1145    }
1146    fn norm(self) -> f64 {
1147        self.re.hypot(self.im)
1148    }
1149}
1150
1151impl std::ops::Add for Complex {
1152    type Output = Self;
1153    fn add(self, o: Self) -> Self {
1154        Self::new(self.re + o.re, self.im + o.im)
1155    }
1156}
1157
1158impl std::ops::Sub for Complex {
1159    type Output = Self;
1160    fn sub(self, o: Self) -> Self {
1161        Self::new(self.re - o.re, self.im - o.im)
1162    }
1163}
1164
1165impl std::ops::Mul for Complex {
1166    type Output = Self;
1167    fn mul(self, o: Self) -> Self {
1168        Self::new(
1169            self.re.mul_add(o.re, -(self.im * o.im)),
1170            self.re.mul_add(o.im, self.im * o.re),
1171        )
1172    }
1173}
1174
1175impl std::ops::Div for Complex {
1176    type Output = Self;
1177    fn div(self, o: Self) -> Self {
1178        let den = o.re.mul_add(o.re, o.im * o.im);
1179        Self::new(
1180            self.re.mul_add(o.re, self.im * o.im) / den,
1181            self.im.mul_add(o.re, -(self.re * o.im)) / den,
1182        )
1183    }
1184}
1185
1186/// Build intersection curves from a collection of ordered 3D points.
1187///
1188/// If there are enough points, fits a NURBS curve through them.
1189fn build_curves_from_points(
1190    points_3d: &[Point3],
1191    ipoints: Vec<IntersectionPoint>,
1192) -> Result<Vec<IntersectionCurve>, MathError> {
1193    if points_3d.len() < 2 {
1194        return Ok(vec![]);
1195    }
1196
1197    let degree = 3.min(points_3d.len() - 1);
1198    let curve = interpolate(points_3d, degree)?;
1199    Ok(vec![IntersectionCurve {
1200        curve,
1201        points: ipoints,
1202    }])
1203}
1204
1205// -- Analytic-Analytic Intersection -------------------------------------------
1206
1207/// Intersect two analytic surfaces using a general marching approach.
1208///
1209/// Seeds intersection points by sampling both parameter spaces on a grid,
1210/// then marches along the intersection curve using the cross product of
1211/// the two surface normals as the tangent direction.
1212///
1213/// # Errors
1214///
1215/// Returns an error if curve fitting fails.
1216#[allow(
1217    clippy::cast_precision_loss,
1218    clippy::too_many_lines,
1219    clippy::similar_names,
1220    clippy::unnecessary_wraps,
1221    clippy::type_complexity
1222)]
1223pub fn intersect_analytic_analytic(
1224    a: AnalyticSurface<'_>,
1225    b: AnalyticSurface<'_>,
1226    grid_res: usize,
1227) -> Result<Vec<IntersectionCurve>, MathError> {
1228    intersect_analytic_analytic_bounded(a, b, grid_res, None, None)
1229}
1230
1231/// Intersect two analytic surfaces with optional v-range overrides.
1232///
1233/// When `v_range_hint_a` or `v_range_hint_b` is `Some((min, max))`, the
1234/// marching algorithm searches that v-range instead of the hardcoded default.
1235/// This is essential for cylinders and cones whose default v-range is small
1236/// (-1..1 or 0.01..2) but whose actual face may extend much further.
1237///
1238/// # Errors
1239///
1240/// Returns `MathError` if algebraic intersection fails or marching diverges.
1241pub fn intersect_analytic_analytic_bounded(
1242    a: AnalyticSurface<'_>,
1243    b: AnalyticSurface<'_>,
1244    grid_res: usize,
1245    v_range_hint_a: Option<(f64, f64)>,
1246    v_range_hint_b: Option<(f64, f64)>,
1247) -> Result<Vec<IntersectionCurve>, MathError> {
1248    // Try algebraic specialization for known surface pairs before falling
1249    // back to the general marching approach.
1250    if let Some(result) = try_algebraic_intersection(&a, &b, v_range_hint_a, v_range_hint_b)? {
1251        return Ok(result);
1252    }
1253
1254    let (surf_a, norm_a, u_range_a, default_v_a) = surface_closures(&a);
1255    let (surf_b, norm_b, u_range_b, default_v_b) = surface_closures(&b);
1256    let v_range_a = v_range_hint_a.unwrap_or(default_v_a);
1257    let v_range_b = v_range_hint_b.unwrap_or(default_v_b);
1258
1259    // Compute characteristic surface dimensions for adaptive parameters.
1260    let diag_a = {
1261        let p00 = surf_a(u_range_a.0, v_range_a.0);
1262        let p11 = surf_a(u_range_a.1, v_range_a.1);
1263        (p00 - p11).length()
1264    };
1265    let diag_b = {
1266        let p00 = surf_b(u_range_b.0, v_range_b.0);
1267        let p11 = surf_b(u_range_b.1, v_range_b.1);
1268        (p00 - p11).length()
1269    };
1270    let char_size = diag_a.min(diag_b).max(0.1);
1271
1272    // Sample surface A on a grid. For each grid point, project it
1273    // analytically onto surface B to find the closest point, then check
1274    // if the distance is below threshold (indicating near-intersection).
1275    #[allow(clippy::type_complexity)]
1276    let mut seeds: Vec<(Point3, (f64, f64), (f64, f64))> = Vec::new();
1277    // Coarse threshold scales with the surface size — the distance from
1278    // a grid point on A to its projection on B can be large even near
1279    // the intersection (e.g., sphere R=2 and cylinder R=1 → gap ≈ 1).
1280    let seed_threshold = diag_a.max(diag_b).max(1.0) * 0.5;
1281    let mut min_dist = f64::INFINITY;
1282
1283    #[allow(clippy::cast_precision_loss)]
1284    for ia in 0..grid_res {
1285        for ja in 0..grid_res {
1286            let ua =
1287                u_range_a.0 + (u_range_a.1 - u_range_a.0) * (ia as f64 + 0.5) / (grid_res as f64);
1288            let va =
1289                v_range_a.0 + (v_range_a.1 - v_range_a.0) * (ja as f64 + 0.5) / (grid_res as f64);
1290
1291            let pa = surf_a(ua, va);
1292
1293            // Analytically project onto surface B.
1294            let (ub, vb) = project_analytic(&b, pa, u_range_b, v_range_b);
1295            let pb = surf_b(ub, vb);
1296            let dist = (pa - pb).length();
1297            min_dist = min_dist.min(dist);
1298
1299            if dist < seed_threshold {
1300                // Use the coarse seed directly. The marching algorithm
1301                // corrects positions at each step via projection, so seeds
1302                // don't need to be on the exact intersection — they just
1303                // need to be close enough for the marcher to converge.
1304                let mid = Point3::new(
1305                    (pa.x() + pb.x()) * 0.5,
1306                    (pa.y() + pb.y()) * 0.5,
1307                    (pa.z() + pb.z()) * 0.5,
1308                );
1309                seeds.push((mid, (ua, va), (ub, vb)));
1310            }
1311        }
1312    }
1313
1314    // Cheap rejection: the grid samples surface A; the closest sample's
1315    // distance to B lower-bounds how near the two bounded patches come. A
1316    // transversal crossing puts a sample within ~one grid cell of it
1317    // (distance on the order of a cell), so if even the nearest sample is
1318    // several cells away the patches cannot cross — skip the expensive
1319    // marching and return empty. Result-preserving: non-crossing pairs
1320    // already march to nothing, just slowly (this is the gridfinity lip's
1321    // ~80 inner-wall × outer-wall pairs that dominate pavefiller time).
1322    let reject_dist = (char_size / grid_res as f64) * 3.0;
1323    if min_dist > reject_dist {
1324        return Ok(vec![]);
1325    }
1326
1327    if seeds.is_empty() {
1328        return Ok(vec![]);
1329    }
1330
1331    // Aggressively deduplicate seeds — we only need 1-2 per intersection
1332    // branch. Scale dedup radius to ~2% of characteristic surface size
1333    // (at least 10× the march step size) to avoid redundant marches.
1334    let march_step = (char_size * 0.02).clamp(0.005, 0.5);
1335    let dedup_radius = march_step * 10.0;
1336    let mut unique_seeds = Vec::new();
1337    for seed in &seeds {
1338        let dominated = unique_seeds
1339            .iter()
1340            .any(|s: &(Point3, (f64, f64), (f64, f64))| (s.0 - seed.0).length() < dedup_radius);
1341        if !dominated {
1342            unique_seeds.push(*seed);
1343        }
1344    }
1345
1346    // March from each seed.
1347    let mut curves = Vec::new();
1348    let mut used_seeds = vec![false; unique_seeds.len()];
1349
1350    for si in 0..unique_seeds.len() {
1351        if used_seeds[si] {
1352            continue;
1353        }
1354        used_seeds[si] = true;
1355
1356        let march_result = march_analytic_intersection(
1357            &a,
1358            &b,
1359            surf_a.as_ref(),
1360            norm_a.as_ref(),
1361            surf_b.as_ref(),
1362            norm_b.as_ref(),
1363            unique_seeds[si].0,
1364            u_range_a,
1365            v_range_a,
1366            u_range_b,
1367            v_range_b,
1368            march_step,
1369            is_u_periodic(&a),
1370            is_u_periodic(&b),
1371        );
1372
1373        if march_result.len() >= 2 {
1374            for (sj, other) in unique_seeds.iter().enumerate() {
1375                if !used_seeds[sj]
1376                    && march_result
1377                        .iter()
1378                        .any(|p| (*p - other.0).length() < dedup_radius)
1379                {
1380                    used_seeds[sj] = true;
1381                }
1382            }
1383
1384            let ipts: Vec<IntersectionPoint> = march_result
1385                .iter()
1386                .map(|&pt| IntersectionPoint {
1387                    point: pt,
1388                    param1: (0.0, 0.0),
1389                    param2: (0.0, 0.0),
1390                })
1391                .collect();
1392
1393            let degree = 3.min(march_result.len() - 1);
1394            if let Ok(curve) = interpolate(&march_result, degree) {
1395                curves.push(IntersectionCurve {
1396                    curve,
1397                    points: ipts,
1398                });
1399            }
1400        }
1401    }
1402
1403    Ok(curves)
1404}
1405
1406/// Try algebraic (closed-form or semi-algebraic) intersection for known
1407/// surface pairs before falling back to general marching.
1408///
1409/// Returns `Some(curves)` if a specialized method exists, `None` otherwise.
1410///
1411/// Currently handles:
1412/// - **Sphere-sphere**: intersection is a circle (plane through the two centers)
1413/// - **Coaxial cylinders**: same axis → circle(s) or empty
1414/// - **Sphere-cylinder**: reduce to quadratic in one parameter
1415#[allow(clippy::too_many_lines)]
1416fn try_algebraic_intersection(
1417    a: &AnalyticSurface<'_>,
1418    b: &AnalyticSurface<'_>,
1419    v_range_a: Option<(f64, f64)>,
1420    v_range_b: Option<(f64, f64)>,
1421) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
1422    match (a, b) {
1423        (AnalyticSurface::Cone(cone), AnalyticSurface::Cylinder(cyl)) => {
1424            algebraic_parallel_cone_cylinder(cone, cyl, v_range_a, v_range_b)
1425        }
1426        (AnalyticSurface::Cylinder(cyl), AnalyticSurface::Cone(cone)) => {
1427            algebraic_parallel_cone_cylinder(cone, cyl, v_range_b, v_range_a)
1428        }
1429        (AnalyticSurface::Sphere(s1), AnalyticSurface::Sphere(s2)) => {
1430            algebraic_sphere_sphere(s1, s2).map(Some)
1431        }
1432        (AnalyticSurface::Cylinder(c1), AnalyticSurface::Cylinder(c2)) => {
1433            let axis_dot = c1.axis().dot(c2.axis()).abs();
1434            if axis_dot > 1.0 - 1e-10 {
1435                // Axes are parallel — check if they're the same line.
1436                let delta = c2.origin() - c1.origin();
1437                let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
1438                let along = delta_vec.dot(c1.axis());
1439                let perp = (delta_vec - c1.axis() * along).length();
1440                if perp < 1e-8 {
1441                    // Coaxial: same axis, different radii → no intersection
1442                    // (unless equal radius → degenerate overlap, skip)
1443                    if (c1.radius() - c2.radius()).abs() < 1e-8 {
1444                        return Ok(None); // Overlapping — let marcher handle
1445                    }
1446                    return Ok(Some(vec![])); // Coaxial, different radii
1447                }
1448            }
1449            // Non-coaxial: algebraic quadratic in v.
1450            algebraic_cylinder_cylinder(c1, c2)
1451        }
1452        // Sphere-cylinder (both orderings).
1453        (AnalyticSurface::Sphere(s), AnalyticSurface::Cylinder(c))
1454        | (AnalyticSurface::Cylinder(c), AnalyticSurface::Sphere(s)) => {
1455            algebraic_sphere_cylinder(s, c)
1456        }
1457        (AnalyticSurface::Cone(c1), AnalyticSurface::Cone(c2)) => algebraic_cone_cone(c1, c2),
1458        _ => Ok(None),
1459    }
1460}
1461
1462/// Exact coaxial cone-cone intersection: returns the shared circle.
1463///
1464/// Two cones that share an axis are concentric circles at every axial
1465/// station, so they meet only where their radii are equal. Each cone's
1466/// radius is linear in the axial coordinate `t` (measured along the shared
1467/// axis from cone 1's apex): `r1 = m1·t` and `r2 = m2·σ·(t − d2)`, where
1468/// `m_i = cot(half_angle_i)`, `σ = sign(axis2·axis1)`, and `d2` is cone 2's
1469/// apex position in that coordinate. Equating gives a single crossing `t*`
1470/// → one circle (the shared rim). The general marcher mishandles this case:
1471/// at the radii-crossing the surfaces are nearly tangent, so a grid-seeded
1472/// march fragments the clean circle into dozens of degenerate micro-curves.
1473///
1474/// Returns `Some(vec![circle])` for a genuine crossing, `Some(vec![])` when
1475/// the cones do not meet (parallel radius lines or a crossing on the wrong
1476/// nappe), and `None` for the identical-cone overlap or a degenerate
1477/// (near-flat) cone — both of which fall through to the general path.
1478/// Parallel-but-offset axes with equal half-angle tangents reduce to a
1479/// radical-plane conic (`offset_parallel_cone_cone`); other offset
1480/// configurations defer to the marcher with `None`.
1481///
1482/// # Errors
1483///
1484/// Returns [`MathError`] if the shared-rim `Circle3D` cannot be constructed
1485/// (e.g. a non-finite center or radius from a malformed cone).
1486pub fn exact_cone_cone(
1487    c1: &ConicalSurface,
1488    c2: &ConicalSurface,
1489) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
1490    let axis = c1.axis();
1491    let axis2 = c2.axis();
1492
1493    // Coaxial check: parallel axes and the second apex lies on the first axis.
1494    if axis.dot(axis2).abs() < 1.0 - 1e-10 {
1495        return Ok(None); // Non-coaxial: quartic curve, let the marcher handle.
1496    }
1497    let apex1 = c1.apex();
1498    let apex2 = c2.apex();
1499    let delta = apex2 - apex1;
1500    let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
1501    let along = delta_v.dot(axis);
1502    if (delta_v - axis * along).length() > 1e-8 {
1503        return offset_parallel_cone_cone(c1, c2);
1504    }
1505
1506    let (s1, s2) = (c1.half_angle().sin(), c2.half_angle().sin());
1507    if s1.abs() < 1e-12 || s2.abs() < 1e-12 {
1508        return Ok(None); // Degenerate (near-flat) cone.
1509    }
1510    let m1 = c1.half_angle().cos() / s1;
1511    let m2 = c2.half_angle().cos() / s2;
1512    let sigma = if axis.dot(axis2) >= 0.0 { 1.0 } else { -1.0 };
1513    let d2 = along; // apex2 position along `axis`, measured from apex1.
1514
1515    let denom = m1 - m2 * sigma;
1516    if denom.abs() < 1e-12 {
1517        // Parallel radius lines: identical cones (coincident apex, same opening)
1518        // overlap — defer to the general/same-domain path; otherwise no meeting.
1519        if sigma > 0.0 && d2.abs() < 1e-9 {
1520            return Ok(None);
1521        }
1522        return Ok(Some(vec![]));
1523    }
1524
1525    let t_star = (-m2 * sigma * d2) / denom;
1526    let radius = m1 * t_star;
1527    if radius < 1e-12 {
1528        return Ok(Some(vec![])); // Crossing on the wrong nappe / no real circle.
1529    }
1530
1531    let center = Point3::new(
1532        apex1.x() + axis.x() * t_star,
1533        apex1.y() + axis.y() * t_star,
1534        apex1.z() + axis.z() * t_star,
1535    );
1536    let circle = Circle3D::new(center, axis, radius)?;
1537    Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
1538}
1539
1540/// Parallel-axis (or anti-parallel), offset-apex cones with equal half-angle
1541/// tangents: subtracting the two quadric equations cancels both the radial
1542/// and the axial quadratic terms (their coefficients depend only on
1543/// `tan²(half_angle)`), so every intersection point lies on a plane — the
1544/// degenerate member of the quadric pencil — and plane ∩ cone is an exact
1545/// conic. The gridfinity spacer lip fuse hits this exactly: opposed 45°
1546/// corner cones offset 0.25mm, which the marcher shreds into ~64 closed
1547/// micro-loops per pair (#1570). Unequal angles keep a genuine quadratic
1548/// term, and an unbounded section (hyperbola/parabola) has no closed-form
1549/// win over the marcher — both defer with `None`.
1550fn offset_parallel_cone_cone(
1551    c1: &ConicalSurface,
1552    c2: &ConicalSurface,
1553) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
1554    if c1.half_angle().sin().abs() < 1e-12 || c2.half_angle().sin().abs() < 1e-12 {
1555        return Ok(None); // Degenerate (near-flat) cone, as in the coaxial path.
1556    }
1557    let t1 = c1.half_angle().tan();
1558    let t2 = c2.half_angle().tan();
1559    if !t1.is_finite() || !t2.is_finite() {
1560        return Ok(None);
1561    }
1562    if (t1 - t2).abs() > 1e-9 * (1.0 + t1.abs().max(t2.abs())) {
1563        return Ok(None);
1564    }
1565
1566    let w = c1.axis();
1567    let apex1 = c1.apex();
1568    let apex2 = c2.apex();
1569    let delta = apex2 - apex1;
1570    let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
1571    let s = delta_v.dot(w);
1572    let tm = 0.5 * (t1 + t2);
1573    let k = 1.0 + tm * tm;
1574
1575    // In the apex1 frame each cone is |P|² − k(P·w)² = 0 (shifted by δ for
1576    // cone 2; the axis SIGN drops out since only (P·w)² appears). Their
1577    // difference: P·(2δ − 2ksw) = |δ|² − ks².
1578    let n = (delta_v - w * (k * s)) * 2.0;
1579    let n_len = n.length();
1580    if n_len < 1e-12 {
1581        return Ok(None);
1582    }
1583    let n_hat = n * (1.0 / n_len);
1584    let d = (dot_np(n, apex1) + delta_v.dot(delta_v) - k * s * s) / n_len;
1585
1586    // `exact_plane_cone` already rejects sections on cone 1's phantom nappe;
1587    // cone 2's nappe must be checked here. A conic on the shared quadric
1588    // pencil cannot cross between nappes except exactly through apex 2, so
1589    // sampled quarter-points either all pass or all fail; a mixed verdict
1590    // means an apex-touching degeneracy — defer to the marcher.
1591    let axis2 = c2.axis();
1592    let scale = 1.0 + delta_v.length();
1593    let mut out = Vec::new();
1594    for curve in exact_plane_cone(c1, n_hat, d)? {
1595        let samples: Vec<Point3> = match &curve {
1596            ExactIntersectionCurve::Circle(c) => (0..4)
1597                .map(|i| crate::traits::ParametricCurve::evaluate(c, TAU * f64::from(i) / 4.0))
1598                .collect(),
1599            ExactIntersectionCurve::Ellipse(e) => (0..4)
1600                .map(|i| crate::traits::ParametricCurve::evaluate(e, TAU * f64::from(i) / 4.0))
1601                .collect(),
1602            ExactIntersectionCurve::Points(_) => return Ok(None),
1603        };
1604        let on_real_nappe = |p: &Point3| {
1605            let rel = *p - apex2;
1606            Vec3::new(rel.x(), rel.y(), rel.z()).dot(axis2) >= -1e-9 * scale
1607        };
1608        let hits = samples.iter().filter(|p| on_real_nappe(p)).count();
1609        match hits {
1610            0 => {}
1611            4 => out.push(curve),
1612            _ => return Ok(None),
1613        }
1614    }
1615    Ok(Some(out))
1616}
1617
1618/// Exact coaxial cone-cylinder intersection: returns the shared circle.
1619///
1620/// A cone and a cylinder sharing an axis are concentric circles at every
1621/// axial station, so they meet only where the cone's radius equals the
1622/// cylinder's. The cone radius is linear in the axial coordinate `t` from its
1623/// apex (`r = m·t`, `m = cot(half_angle)`), the cylinder radius is the
1624/// constant `R`, so `m·t = R` gives a single crossing `t*` → one circle. This
1625/// is the gridfinity lip's top knife edge (inner tapered corner = cone, outer
1626/// corner = cylinder, concentric, radii matching at `Z_PEAK`); the general
1627/// marcher fragments that near-tangent contact into dozens of degenerate
1628/// micro-curves.
1629///
1630/// Returns `Some(vec![circle])` for a genuine crossing, `Some(vec![])` when
1631/// the crossing degenerates to the apex, and `None` (defer to the marcher)
1632/// when the surfaces are not coaxial or the cone is near-flat / near-axial.
1633///
1634/// # Errors
1635///
1636/// Returns [`MathError`] if the shared `Circle3D` cannot be constructed.
1637pub fn exact_cone_cylinder(
1638    cone: &ConicalSurface,
1639    cyl: &CylindricalSurface,
1640) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
1641    let axis = cone.axis();
1642    let cyl_axis = cyl.axis();
1643
1644    // Coaxial check: parallel axes and the cone apex on the cylinder's axis.
1645    if axis.dot(cyl_axis).abs() < 1.0 - 1e-10 {
1646        return Ok(None);
1647    }
1648    let apex = cone.apex();
1649    let delta = apex - cyl.origin();
1650    let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
1651    let along = delta_v.dot(cyl_axis);
1652    if (delta_v - cyl_axis * along).length() > 1e-8 {
1653        return Ok(None);
1654    }
1655
1656    let s = cone.half_angle().sin();
1657    if s.abs() < 1e-12 {
1658        return Ok(None); // near-flat cone.
1659    }
1660    let m = cone.half_angle().cos() / s; // dr/dt along the cone axis.
1661    if m.abs() < 1e-12 {
1662        return Ok(None); // near-axial cone: radius ~constant.
1663    }
1664
1665    let t_star = cyl.radius() / m; // where the cone radius m·t equals R.
1666    if t_star.abs() < 1e-12 {
1667        return Ok(Some(vec![])); // crossing at the apex — no real circle.
1668    }
1669    let center = Point3::new(
1670        apex.x() + axis.x() * t_star,
1671        apex.y() + axis.y() * t_star,
1672        apex.z() + axis.z() * t_star,
1673    );
1674    let circle = Circle3D::new(center, axis, cyl.radius())?;
1675    Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
1676}
1677
1678/// Algebraic cone-cone intersection (NURBS form for the general bounded
1679/// path). Delegates to [`exact_cone_cone`] and samples each exact conic
1680/// (coaxial circle or offset-parallel radical-plane ellipse) into an
1681/// interpolated NURBS `IntersectionCurve`, mirroring the
1682/// sphere-cylinder algebraic path. phase FF prefers the exact circle form
1683/// directly (so the section edge links to the coincident boundary), but a
1684/// caller of `intersect_analytic_analytic_bounded` still gets one clean
1685/// curve instead of the marcher's fragments.
1686fn algebraic_cone_cone(
1687    c1: &ConicalSurface,
1688    c2: &ConicalSurface,
1689) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
1690    let Some(exacts) = exact_cone_cone(c1, c2)? else {
1691        return Ok(None);
1692    };
1693    let mut curves = Vec::new();
1694    for exact in exacts {
1695        let n_samples = 33;
1696        let mut positions = Vec::with_capacity(n_samples);
1697        let mut points = Vec::with_capacity(n_samples);
1698        #[allow(clippy::cast_precision_loss)]
1699        for i in 0..n_samples {
1700            let theta = TAU * i as f64 / (n_samples - 1) as f64;
1701            let pt = match &exact {
1702                ExactIntersectionCurve::Circle(circle) => {
1703                    crate::traits::ParametricCurve::evaluate(circle, theta)
1704                }
1705                ExactIntersectionCurve::Ellipse(ellipse) => {
1706                    crate::traits::ParametricCurve::evaluate(ellipse, theta)
1707                }
1708                ExactIntersectionCurve::Points(_) => break,
1709            };
1710            positions.push(pt);
1711            points.push(IntersectionPoint {
1712                point: pt,
1713                param1: (0.0, 0.0),
1714                param2: (0.0, 0.0),
1715            });
1716        }
1717        if positions.is_empty() {
1718            continue;
1719        }
1720        let degree = 3.min(positions.len() - 1);
1721        let curve = interpolate(&positions, degree)?;
1722        curves.push(IntersectionCurve { curve, points });
1723    }
1724    Ok(Some(curves))
1725}
1726
1727/// Exact coaxial sphere-cylinder intersection: returns the shared circle(s).
1728///
1729/// A sphere of radius `R` centered at `C` and a cylinder of radius `r` whose
1730/// axis passes through `C` meet in concentric circles of radius `r` at the
1731/// axial stations where `sqrt(R² − z²) = r`, i.e. `z = ±sqrt(R² − r²)`
1732/// measured from `C` along the axis. A proper crossing yields two circles; a
1733/// tangent contact (`r = R`) yields one; a cylinder wider than the sphere, or
1734/// a non-coaxial configuration (quartic curve), yields none/defers.
1735///
1736/// Mirrors [`exact_cone_cylinder`] so phase FF can emit the section as an
1737/// exact `Circle3D` (which the closed-circle split + seam adoption recognise)
1738/// rather than the marcher's NURBS fragments.
1739///
1740/// Returns `Some(vec![..])` (0, 1, or 2 circles) for the coaxial case, and
1741/// `None` (defer to the general marcher) when the axes are not coaxial.
1742///
1743/// # Errors
1744///
1745/// Returns [`MathError`] if a shared `Circle3D` cannot be constructed.
1746pub fn exact_sphere_cylinder(
1747    sphere: &SphericalSurface,
1748    cyl: &CylindricalSurface,
1749) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
1750    let sc = sphere.center();
1751    let r_sphere = sphere.radius();
1752    let co = cyl.origin();
1753    let axis = cyl.axis();
1754    let r_cyl = cyl.radius();
1755
1756    // Project sphere center onto the cylinder axis.
1757    let delta = sc - co;
1758    let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
1759    let along = delta_vec.dot(axis);
1760    let perp_vec = delta_vec - axis * along;
1761    let d_perp = perp_vec.length();
1762
1763    // Non-coaxial sphere-cylinder intersections produce quartic curves;
1764    // defer those to the general marcher.
1765    if d_perp > 1e-7 {
1766        return Ok(None);
1767    }
1768
1769    // Coaxial: the sphere center lies on the cylinder axis. No real circle
1770    // when the cylinder is wider than the sphere or they are tangent-internal.
1771    if r_cyl > r_sphere + 1e-10 {
1772        return Ok(Some(vec![]));
1773    }
1774    let z_sq = r_sphere * r_sphere - r_cyl * r_cyl;
1775    if z_sq < 0.0 {
1776        return Ok(Some(vec![]));
1777    }
1778    let z = z_sq.sqrt();
1779
1780    // The sphere center projected onto the axis is the midpoint of the two
1781    // section circles, each offset by ±z along the axis with radius `r_cyl`.
1782    let center_axis_pt = Point3::new(
1783        co.x() + axis.x() * along,
1784        co.y() + axis.y() * along,
1785        co.z() + axis.z() * along,
1786    );
1787
1788    let mut circles = Vec::new();
1789    let offsets: &[f64] = if z < 1e-10 { &[0.0] } else { &[z, -z] };
1790    for &z_offset in offsets {
1791        let center = Point3::new(
1792            center_axis_pt.x() + axis.x() * z_offset,
1793            center_axis_pt.y() + axis.y() * z_offset,
1794            center_axis_pt.z() + axis.z() * z_offset,
1795        );
1796        let circle = Circle3D::new(center, axis, r_cyl)?;
1797        circles.push(ExactIntersectionCurve::Circle(circle));
1798    }
1799    Ok(Some(circles))
1800}
1801
1802/// Algebraic sphere-cylinder intersection (NURBS form for the general bounded
1803/// path). Delegates to [`exact_sphere_cylinder`] and samples each exact circle
1804/// into an interpolated NURBS `IntersectionCurve`. phase FF prefers the exact
1805/// circle form directly (so the section edge links to the coincident boundary
1806/// and the closed-circle splitter can carve the spherical band), but a caller
1807/// of `intersect_analytic_analytic_bounded` still gets clean curves instead of
1808/// the marcher's fragments.
1809fn algebraic_sphere_cylinder(
1810    sphere: &SphericalSurface,
1811    cyl: &CylindricalSurface,
1812) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
1813    let Some(exacts) = exact_sphere_cylinder(sphere, cyl)? else {
1814        return Ok(None);
1815    };
1816
1817    let mut curves = Vec::new();
1818    for exact in exacts {
1819        let ExactIntersectionCurve::Circle(circle) = exact else {
1820            continue;
1821        };
1822        let n_samples = 33;
1823        let mut points = Vec::with_capacity(n_samples);
1824        let mut positions = Vec::with_capacity(n_samples);
1825        #[allow(clippy::cast_precision_loss)]
1826        for i in 0..n_samples {
1827            let theta = TAU * i as f64 / (n_samples - 1) as f64;
1828            let pt = crate::traits::ParametricCurve::evaluate(&circle, theta);
1829            positions.push(pt);
1830            points.push(IntersectionPoint {
1831                point: pt,
1832                param1: (0.0, 0.0),
1833                param2: (0.0, 0.0),
1834            });
1835        }
1836        let degree = 3.min(positions.len() - 1);
1837        let curve = interpolate(&positions, degree)?;
1838        curves.push(IntersectionCurve { curve, points });
1839    }
1840
1841    Ok(Some(curves))
1842}
1843
1844/// Algebraic cylinder-cylinder intersection for non-coaxial cylinders.
1845///
1846/// For two cylinders with axes that are NOT parallel, the intersection
1847/// consists of up to two closed space curves. These are found by
1848/// parameterizing one cylinder's angular coordinate `u ∈ [0, 2π]` and
1849/// solving a quadratic in the axial parameter `v` to find where each
1850/// "ring" of cylinder A sits on cylinder B.
1851///
1852/// The quadratic is:
1853///   `v²·(1 - α²) + 2v·(q·a₁ - α·q·a₂) + (|q|² - (q·a₂)² - r₂²) = 0`
1854/// where `α = a₁·a₂`, `q(u)` is the radial point on cylinder 1 minus
1855/// cylinder 2's origin, `a₁`/`a₂` are the cylinder axes, and `r₂` is
1856/// cylinder 2's radius.
1857#[allow(clippy::too_many_lines, clippy::unnecessary_wraps)]
1858fn algebraic_cylinder_cylinder(
1859    c1: &CylindricalSurface,
1860    c2: &CylindricalSurface,
1861) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
1862    let alpha = c1.axis().dot(c2.axis());
1863    let a_coeff = 1.0 - alpha * alpha;
1864
1865    // Should only be called for non-parallel axes.
1866    if a_coeff.abs() < 1e-12 {
1867        return Ok(None);
1868    }
1869
1870    let r1 = c1.radius();
1871    let r2 = c2.radius();
1872    let o1 = c1.origin();
1873    let o2 = c2.origin();
1874    let a1 = c1.axis();
1875    let a2 = c2.axis();
1876    let x1 = c1.x_axis();
1877    let y1 = c1.y_axis();
1878
1879    // Separation check: distance between axes vs sum of radii.
1880    // Closest approach of two skew lines:
1881    let delta = Vec3::new(o1.x() - o2.x(), o1.y() - o2.y(), o1.z() - o2.z());
1882    let cross = a1.cross(a2);
1883    let cross_len = cross.length();
1884    if cross_len > 1e-12 {
1885        let axis_dist = delta.dot(cross).abs() / cross_len;
1886        if axis_dist > r1 + r2 + Tolerance::new().linear {
1887            return Ok(Some(vec![])); // No intersection
1888        }
1889    }
1890
1891    // Sample u from 0 to 2π on cylinder 1. Offset by half a step to avoid
1892    // landing exactly on crossing points where disc=0 and both curves coincide.
1893    // This ensures the two algebraic branches have distinct sample endpoints,
1894    // so the face splitter's wire builder doesn't face 4-way junction ambiguity.
1895    let n_samples = 128;
1896    let mut curve_plus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
1897    let mut curve_minus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
1898    let u_offset = TAU / (n_samples as f64 * 2.0); // half a step
1899
1900    // Sample n_samples DISTINCT points (no duplicate at closure).
1901    // After the loop, explicitly close each curve by copying the first point.
1902    #[allow(clippy::cast_precision_loss)]
1903    for i in 0..n_samples {
1904        let u = u_offset + TAU * i as f64 / n_samples as f64;
1905        let (sin_u, cos_u) = u.sin_cos();
1906
1907        // Radial point on c1 at angle u, height v=0:
1908        // q = c1.origin + r1*(cos(u)*x1 + sin(u)*y1) - c2.origin
1909        let qx = o1.x() + r1 * (cos_u * x1.x() + sin_u * y1.x()) - o2.x();
1910        let qy = o1.y() + r1 * (cos_u * x1.y() + sin_u * y1.y()) - o2.y();
1911        let qz = o1.z() + r1 * (cos_u * x1.z() + sin_u * y1.z()) - o2.z();
1912
1913        let q_dot_a1 = qx * a1.x() + qy * a1.y() + qz * a1.z();
1914        let q_dot_a2 = qx * a2.x() + qy * a2.y() + qz * a2.z();
1915        let q_sq = qx * qx + qy * qy + qz * qz;
1916
1917        let b_coeff = 2.0 * (q_dot_a1 - alpha * q_dot_a2);
1918        let c_coeff = q_sq - q_dot_a2 * q_dot_a2 - r2 * r2;
1919
1920        let disc = b_coeff * b_coeff - 4.0 * a_coeff * c_coeff;
1921        // Clamp tiny negative discriminant (floating-point noise near tangent
1922        // crossing points where disc → 0) to avoid gaps in the sample set.
1923        if disc < -Tolerance::new().linear {
1924            continue;
1925        }
1926
1927        let sqrt_disc = disc.max(0.0).sqrt();
1928        let v_plus = (-b_coeff + sqrt_disc) / (2.0 * a_coeff);
1929        let v_minus = (-b_coeff - sqrt_disc) / (2.0 * a_coeff);
1930
1931        curve_plus.push(c1.evaluate(u, v_plus));
1932        curve_minus.push(c1.evaluate(u, v_minus));
1933    }
1934
1935    // Explicitly close each curve by copying the first point (exact match
1936    // avoids near-zero chord length in NURBS interpolation).
1937    if !curve_plus.is_empty() {
1938        curve_plus.push(curve_plus[0]);
1939    }
1940    if !curve_minus.is_empty() {
1941        curve_minus.push(curve_minus[0]);
1942    }
1943
1944    let mut curves = Vec::new();
1945
1946    for pts in [&curve_plus, &curve_minus] {
1947        if pts.len() < 4 {
1948            continue;
1949        }
1950
1951        let ipts: Vec<IntersectionPoint> = pts
1952            .iter()
1953            .map(|&p| {
1954                let (u1, v1) = c1.project_point(p);
1955                let (u2, v2) = c2.project_point(p);
1956                IntersectionPoint {
1957                    point: p,
1958                    param1: (u1, v1),
1959                    param2: (u2, v2),
1960                }
1961            })
1962            .collect();
1963
1964        let degree = 3.min(pts.len() - 1);
1965        if let Ok(curve) = interpolate(pts, degree) {
1966            curves.push(IntersectionCurve {
1967                curve,
1968                points: ipts,
1969            });
1970        }
1971    }
1972
1973    Ok(Some(curves))
1974}
1975
1976/// Algebraic cone-cylinder intersection for PARALLEL (or antiparallel) axes.
1977///
1978/// When the axes are parallel, every plane perpendicular to them cuts the cone
1979/// in a circle of radius `rho = v * cos(half_angle)` about a FIXED centre and
1980/// the cylinder in a circle of radius `R` about a second FIXED centre, so the
1981/// axis separation `d` is constant in `v`. Two coplanar circles meet at
1982/// `u = phi0 +/- acos((d^2 + rho^2 - R^2) / (2*d*rho))`, giving two branches
1983/// parameterised exactly by the cone's own `v`. The branches exist only where
1984/// `rho` lies in `[|d - R|, d + R]`, which bounds the curve naturally.
1985///
1986/// This replaces the general grid-seeded marcher for the configuration, which
1987/// mis-handles it badly: seeds are accepted anywhere within half the surface
1988/// diagonal of the partner, the march-result dedup only consumes seeds the
1989/// traced polyline passes near, and the survivors are dozens of overlapping
1990/// partial traces of the same curve. Those fragments carry no usable in-face
1991/// span, so a cone corner-round crossed by a boss cylinder never splits (a
1992/// counterbore/countersink meeting a pad — the gridfinity lightweight base).
1993///
1994/// Returns `None` (defer to the caller's other paths) when the axes are not
1995/// parallel, or when they are coaxial — a coaxial pair degenerates to shared
1996/// circles, which [`exact_cone_cylinder`] emits exactly and phase FF calls
1997/// directly. Note that `intersect_analytic_analytic_bounded` does NOT consult
1998/// `exact_cone_cylinder`, so a coaxial pair reaching this path through that
1999/// caller falls through to the marcher; only the FF path gets the exact circles.
2000// Result-wrapped to match the other `try_algebraic_intersection` arms' shape.
2001#[allow(clippy::unnecessary_wraps)]
2002fn algebraic_parallel_cone_cylinder(
2003    cone: &ConicalSurface,
2004    cyl: &CylindricalSurface,
2005    v_range_cone: Option<(f64, f64)>,
2006    v_range_cyl: Option<(f64, f64)>,
2007) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
2008    let axis = cone.axis();
2009    if axis.dot(cyl.axis()).abs() < 1.0 - 1e-10 {
2010        return Ok(None); // Skew/oblique — general marcher.
2011    }
2012
2013    let apex = cone.apex();
2014    let delta = cyl.origin() - apex;
2015    let along = delta.dot(axis);
2016    let perp = delta - axis * along;
2017    let d = perp.length();
2018    if d < 1e-9 {
2019        return Ok(None); // Coaxial — `exact_cone_cylinder` owns this.
2020    }
2021
2022    let (e1, e2) = (cone.x_axis(), cone.y_axis());
2023    let phi0 = perp.dot(e2).atan2(perp.dot(e1));
2024
2025    let (sin_t, cos_t) = cone.half_angle().sin_cos();
2026    if cos_t < 1e-12 || sin_t < 1e-12 {
2027        return Ok(None);
2028    }
2029    let r = cyl.radius();
2030
2031    // Branch existence: |d - R| <= rho <= d + R, with rho = v * cos(half_angle).
2032    let mut v_min = (d - r).abs() / cos_t;
2033    let mut v_max = (d + r) / cos_t;
2034    if v_max <= v_min {
2035        return Ok(Some(vec![]));
2036    }
2037
2038    // Narrow the sampled span to the faces' own extents so the fixed sample
2039    // budget resolves the in-face part of the curve rather than spreading over
2040    // a loop that mostly lies off both patches. A face's crossing can be a
2041    // fraction of a degree of the cone's sweep (the corner-round case above),
2042    // and an unnarrowed sampling puts fewer than one sample across it.
2043    let mut lo = v_min;
2044    let mut hi = v_max;
2045    // Clip EXACTLY to the hints, not to a padded window: an endpoint that lands
2046    // exactly on the face's own v-limit lies ON that boundary rim, so the
2047    // downstream pave machinery anchors it to the rim edge instead of leaving
2048    // the section dangling just past the face.
2049    if let Some((a, b)) = v_range_cone {
2050        let (a, b) = if a <= b { (a, b) } else { (b, a) };
2051        lo = lo.max(a);
2052        hi = hi.min(b);
2053    }
2054    if let Some((a, b)) = v_range_cyl {
2055        // The cylinder's v is a signed distance along its axis from its origin;
2056        // convert both ends to the cone's v via the shared axial direction.
2057        let flip = cyl.axis().dot(axis);
2058        let to_cone_v = |cv: f64| (along + cv * flip) / sin_t;
2059        let (a, b) = (to_cone_v(a), to_cone_v(b));
2060        let (a, b) = if a <= b { (a, b) } else { (b, a) };
2061        lo = lo.max(a);
2062        hi = hi.min(b);
2063    }
2064    v_min = lo.max(v_min);
2065    v_max = hi.min(v_max);
2066    if v_max - v_min <= 1e-12 {
2067        return Ok(Some(vec![]));
2068    }
2069
2070    let n_samples = 128;
2071    let mut plus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
2072    let mut minus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
2073    #[allow(clippy::cast_precision_loss)]
2074    for i in 0..=n_samples {
2075        let v = v_min + (v_max - v_min) * (i as f64) / (n_samples as f64);
2076        let rho = v * cos_t;
2077        if rho < 1e-12 {
2078            // The apex. `cos_alpha` has rho in its denominator, so it is only
2079            // meaningful in the limit: it tends to 0 (alpha -> pi/2) when the
2080            // cylinder passes exactly through the apex (d == R), and diverges
2081            // otherwise — where the clamp would manufacture a spurious alpha of
2082            // 0 or pi. So keep the apex only in the d == R case, where it is a
2083            // genuine point of the intersection and the shared endpoint at
2084            // which the two branches meet.
2085            if (d - r).abs() < 1e-12 {
2086                let apex = cone.evaluate(phi0, v);
2087                plus.push(apex);
2088                minus.push(apex);
2089            }
2090            continue;
2091        }
2092        let cos_alpha = ((d * d + rho * rho - r * r) / (2.0 * d * rho)).clamp(-1.0, 1.0);
2093        let alpha = cos_alpha.acos();
2094        plus.push(cone.evaluate(phi0 + alpha, v));
2095        minus.push(cone.evaluate(phi0 - alpha, v));
2096    }
2097
2098    let mut curves = Vec::new();
2099    for pts in [&plus, &minus] {
2100        // Fewer than four samples in range means this branch does not cross the
2101        // bounded region at all (the other branch may still).
2102        if pts.len() < 4 {
2103            continue;
2104        }
2105        let ipts: Vec<IntersectionPoint> = pts
2106            .iter()
2107            .map(|&p| IntersectionPoint {
2108                point: p,
2109                param1: cone.project_point(p),
2110                param2: cyl.project_point(p),
2111            })
2112            .collect();
2113        let degree = 3.min(pts.len() - 1);
2114        match interpolate(pts, degree) {
2115            Ok(curve) => curves.push(IntersectionCurve {
2116                curve,
2117                points: ipts,
2118            }),
2119            // Emitting only the branch that happened to fit would starve the
2120            // section chain of exactly the piece this path exists to supply —
2121            // the same silent half-answer the marcher's fragments produced.
2122            // Defer the whole pair to the caller's other paths instead.
2123            Err(_) => return Ok(None),
2124        }
2125    }
2126
2127    Ok(Some(curves))
2128}
2129
2130/// Algebraic sphere-sphere intersection.
2131///
2132/// Two spheres intersect in a circle lying in the radical plane.
2133/// The radical plane is perpendicular to the line connecting the centers,
2134/// at a distance d1 from center1 where:
2135///   d1 = (D² + R1² - R2²) / (2D)
2136/// and D is the distance between centers.
2137fn algebraic_sphere_sphere(
2138    s1: &SphericalSurface,
2139    s2: &SphericalSurface,
2140) -> Result<Vec<IntersectionCurve>, MathError> {
2141    let c1 = s1.center();
2142    let c2 = s2.center();
2143    let r1 = s1.radius();
2144    let r2 = s2.radius();
2145
2146    let delta = c2 - c1;
2147    let d_sq = delta.x() * delta.x() + delta.y() * delta.y() + delta.z() * delta.z();
2148    let d = d_sq.sqrt();
2149
2150    if d < 1e-12 {
2151        // Concentric spheres: no intersection (unless same radius → degenerate).
2152        return Ok(vec![]);
2153    }
2154
2155    // Check separation conditions.
2156    if d > r1 + r2 + 1e-10 {
2157        return Ok(vec![]); // Too far apart
2158    }
2159    if d + r2.min(r1) + 1e-10 < r1.max(r2) {
2160        return Ok(vec![]); // One inside the other
2161    }
2162
2163    // Distance from c1 to the radical plane along the center line.
2164    let d1 = (d_sq + r1 * r1 - r2 * r2) / (2.0 * d);
2165
2166    // Radius of the intersection circle.
2167    let r_circle_sq = r1 * r1 - d1 * d1;
2168    if r_circle_sq < 0.0 {
2169        // Tangent or no intersection (numerical noise).
2170        if r_circle_sq > -1e-10 {
2171            // Tangent: single point.
2172            let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
2173            let tangent_pt = Point3::new(
2174                c1.x() + axis.x() * d1,
2175                c1.y() + axis.y() * d1,
2176                c1.z() + axis.z() * d1,
2177            );
2178            let ipt = IntersectionPoint {
2179                point: tangent_pt,
2180                param1: (0.0, 0.0),
2181                param2: (0.0, 0.0),
2182            };
2183            // Single-point "curve" — not very useful but correct.
2184            return Ok(vec![IntersectionCurve {
2185                curve: interpolate(&[tangent_pt, tangent_pt], 1)?,
2186                points: vec![ipt],
2187            }]);
2188        }
2189        return Ok(vec![]);
2190    }
2191
2192    let r_circle = r_circle_sq.sqrt();
2193    let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
2194    let center = Point3::new(
2195        c1.x() + axis.x() * d1,
2196        c1.y() + axis.y() * d1,
2197        c1.z() + axis.z() * d1,
2198    );
2199
2200    // Build a reference frame for the circle.
2201    let basis = Frame3::from_normal(center, axis)?;
2202    let u_dir = basis.x;
2203    let v_dir = basis.y;
2204
2205    // Sample the circle for the IntersectionCurve representation.
2206    let n_samples = 33; // Odd for symmetry
2207    let mut points = Vec::with_capacity(n_samples);
2208    let mut positions = Vec::with_capacity(n_samples);
2209    #[allow(clippy::cast_precision_loss)]
2210    for i in 0..n_samples {
2211        let theta = TAU * i as f64 / (n_samples - 1) as f64;
2212        let (sin_t, cos_t) = theta.sin_cos();
2213        let pt = Point3::new(
2214            center.x() + (u_dir.x() * cos_t + v_dir.x() * sin_t) * r_circle,
2215            center.y() + (u_dir.y() * cos_t + v_dir.y() * sin_t) * r_circle,
2216            center.z() + (u_dir.z() * cos_t + v_dir.z() * sin_t) * r_circle,
2217        );
2218        positions.push(pt);
2219        points.push(IntersectionPoint {
2220            point: pt,
2221            param1: (0.0, 0.0),
2222            param2: (0.0, 0.0),
2223        });
2224    }
2225
2226    let degree = 3.min(positions.len() - 1);
2227    let curve = interpolate(&positions, degree)?;
2228
2229    Ok(vec![IntersectionCurve { curve, points }])
2230}
2231
2232/// Newton correction: project a point back onto the intersection curve
2233/// of two analytic surfaces. Solves the 3×3 system:
2234///   δ · na = -da  (eliminate distance to surface A)
2235///   δ · nb = -db  (eliminate distance to surface B)
2236///   δ · t  = 0    (minimal correction, perpendicular to tangent)
2237#[allow(clippy::too_many_arguments)]
2238fn correct_to_intersection(
2239    a: &AnalyticSurface<'_>,
2240    b: &AnalyticSurface<'_>,
2241    surf_a: &dyn Fn(f64, f64) -> Point3,
2242    norm_a: &dyn Fn(f64, f64) -> Vec3,
2243    surf_b: &dyn Fn(f64, f64) -> Point3,
2244    norm_b: &dyn Fn(f64, f64) -> Vec3,
2245    point: Point3,
2246    u_range_a: (f64, f64),
2247    v_range_a: (f64, f64),
2248    u_range_b: (f64, f64),
2249    v_range_b: (f64, f64),
2250    max_iters: usize,
2251) -> Point3 {
2252    let mut p = point;
2253    for _ in 0..max_iters {
2254        let (ua, va) = project_analytic(a, p, u_range_a, v_range_a);
2255        let (ub, vb) = project_analytic(b, p, u_range_b, v_range_b);
2256        let pa = surf_a(ua, va);
2257        let pb = surf_b(ub, vb);
2258        let na = norm_a(ua, va);
2259        let nb = norm_b(ub, vb);
2260        let pv = Vec3::new(p.x(), p.y(), p.z());
2261
2262        let da = (pv - Vec3::new(pa.x(), pa.y(), pa.z())).dot(na);
2263        let db = (pv - Vec3::new(pb.x(), pb.y(), pb.z())).dot(nb);
2264
2265        if da.abs() < 1e-7 && db.abs() < 1e-7 {
2266            break;
2267        }
2268
2269        let t = na.cross(nb);
2270        let t_len = t.length();
2271        if t_len < 1e-10 {
2272            // Surfaces are tangent — fall back to midpoint.
2273            return Point3::new(
2274                (pa.x() + pb.x()) * 0.5,
2275                (pa.y() + pb.y()) * 0.5,
2276                (pa.z() + pb.z()) * 0.5,
2277            );
2278        }
2279        let t_hat = t * (1.0 / t_len);
2280
2281        // Solve [na; nb; t_hat] · δ = [-da, -db, 0] via Cramer's rule.
2282        let det = na.x() * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
2283            - na.y() * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
2284            + na.z() * (nb.x() * t_hat.y() - nb.y() * t_hat.x());
2285        if det.abs() < 1e-15 {
2286            return Point3::new(
2287                (pa.x() + pb.x()) * 0.5,
2288                (pa.y() + pb.y()) * 0.5,
2289                (pa.z() + pb.z()) * 0.5,
2290            );
2291        }
2292        let inv = 1.0 / det;
2293        // Cramer's rule: replace each column of A with rhs = (-da, -db, 0).
2294        let dx = inv
2295            * (-da * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
2296                + db * (na.y() * t_hat.z() - na.z() * t_hat.y()));
2297        let dy = inv
2298            * (da * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
2299                - db * (na.x() * t_hat.z() - na.z() * t_hat.x()));
2300        let dz = inv
2301            * (-da * (nb.x() * t_hat.y() - nb.y() * t_hat.x())
2302                + db * (na.x() * t_hat.y() - na.y() * t_hat.x()));
2303        let candidate = Point3::new(p.x() + dx, p.y() + dy, p.z() + dz);
2304
2305        // Divergence guard: if the correction moves farther from both
2306        // surfaces, abandon Newton and return the best point so far.
2307        let (uc, vc) = project_analytic(a, candidate, u_range_a, v_range_a);
2308        let (ud, vd) = project_analytic(b, candidate, u_range_b, v_range_b);
2309        let pc_a = surf_a(uc, vc);
2310        let pc_b = surf_b(ud, vd);
2311        let cv = Vec3::new(candidate.x(), candidate.y(), candidate.z());
2312        let da_new = (cv - Vec3::new(pc_a.x(), pc_a.y(), pc_a.z()))
2313            .dot(norm_a(uc, vc))
2314            .abs();
2315        let db_new = (cv - Vec3::new(pc_b.x(), pc_b.y(), pc_b.z()))
2316            .dot(norm_b(ud, vd))
2317            .abs();
2318        if da_new > da.abs() && db_new > db.abs() {
2319            return p;
2320        }
2321
2322        p = candidate;
2323    }
2324    p
2325}
2326
2327/// March along the intersection of two surfaces from a seed point.
2328///
2329/// Uses the cross product of surface normals as the tangent direction
2330/// and projects back onto both surfaces using analytical projection
2331/// (for cylinders/spheres) or grid search (fallback).
2332#[allow(clippy::too_many_arguments)]
2333fn march_analytic_intersection(
2334    a: &AnalyticSurface<'_>,
2335    b: &AnalyticSurface<'_>,
2336    surf_a: &dyn Fn(f64, f64) -> Point3,
2337    norm_a: &dyn Fn(f64, f64) -> Vec3,
2338    surf_b: &dyn Fn(f64, f64) -> Point3,
2339    norm_b: &dyn Fn(f64, f64) -> Vec3,
2340    seed: Point3,
2341    u_range_a: (f64, f64),
2342    v_range_a: (f64, f64),
2343    u_range_b: (f64, f64),
2344    v_range_b: (f64, f64),
2345    initial_step: f64,
2346    u_periodic_a: bool,
2347    u_periodic_b: bool,
2348) -> Vec<Point3> {
2349    let max_steps = 500;
2350    let h_min = 1e-6;
2351    let h_max = initial_step * 4.0;
2352    // Fixed closure threshold: the adaptive step `h` varies with curvature
2353    // and can shrink below the actual miss distance at the seed re-approach.
2354    // Use `initial_step * 5` to robustly detect closure on the first pass.
2355    let closure_dist = initial_step * 5.0;
2356    // Angular thresholds for curvature-adaptive stepping.
2357    let max_angle = 10.0_f64.to_radians();
2358    let min_angle = 2.0_f64.to_radians();
2359
2360    // March forward from seed, collecting points.
2361    let mut forward = Vec::new();
2362    // March backward from seed, collecting points (reversed at end).
2363    let mut backward = Vec::new();
2364
2365    for (direction, points) in [(1.0_f64, &mut forward), (-1.0_f64, &mut backward)] {
2366        let mut current = seed;
2367        let mut h = initial_step;
2368        let mut prev_tangent: Option<Vec3> = None;
2369
2370        for _ in 0..max_steps {
2371            let (ua, va) = project_analytic(a, current, u_range_a, v_range_a);
2372            let (ub, vb) = project_analytic(b, current, u_range_b, v_range_b);
2373
2374            let na = norm_a(ua, va);
2375            let nb = norm_b(ub, vb);
2376
2377            let tangent = na.cross(nb);
2378            let t_len = tangent.length();
2379            if t_len < 1e-10 {
2380                break;
2381            }
2382            let t_dir = tangent * (direction / t_len);
2383
2384            // Curvature-adaptive step: check angular deviation from previous tangent.
2385            if let Some(prev_t) = prev_tangent {
2386                let cos_angle = prev_t.dot(t_dir).clamp(-1.0, 1.0);
2387                let angle = cos_angle.acos();
2388                if angle > max_angle && h > h_min {
2389                    h = (h * 0.5).max(h_min);
2390                } else if angle < min_angle {
2391                    h = (h * 2.0).min(h_max);
2392                }
2393            }
2394            prev_tangent = Some(t_dir);
2395
2396            let next = Point3::new(
2397                h.mul_add(t_dir.x(), current.x()),
2398                h.mul_add(t_dir.y(), current.y()),
2399                h.mul_add(t_dir.z(), current.z()),
2400            );
2401
2402            let (ua2, va2) = project_analytic(a, next, u_range_a, v_range_a);
2403            let (ub2, vb2) = project_analytic(b, next, u_range_b, v_range_b);
2404
2405            let pa = surf_a(ua2, va2);
2406            let pb = surf_b(ub2, vb2);
2407            let mid = Point3::new(
2408                (pa.x() + pb.x()) * 0.5,
2409                (pa.y() + pb.y()) * 0.5,
2410                (pa.z() + pb.z()) * 0.5,
2411            );
2412            let out_a = (!u_periodic_a && (ua2 <= u_range_a.0 || ua2 >= u_range_a.1))
2413                || va2 <= v_range_a.0
2414                || va2 >= v_range_a.1;
2415            let out_b = (!u_periodic_b && (ub2 <= u_range_b.0 || ub2 >= u_range_b.1))
2416                || vb2 <= v_range_b.0
2417                || vb2 >= v_range_b.1;
2418
2419            if out_a || out_b {
2420                break;
2421            }
2422
2423            // Check for loop closure — if we've collected enough points and
2424            // the current point is close to the seed, the curve is closed.
2425            // Require ≥10 steps to avoid premature closure near the seed.
2426            let dist_to_seed = (mid - seed).length();
2427            if points.len() > 10 && dist_to_seed < closure_dist {
2428                points.push(seed);
2429                break;
2430            }
2431
2432            points.push(mid);
2433            current = mid;
2434        }
2435    }
2436
2437    // Assemble result: backward (reversed) + seed + forward
2438    backward.reverse();
2439    let mut result = backward;
2440    result.push(seed);
2441    result.append(&mut forward);
2442
2443    // Refine all points onto the intersection curve via Newton correction.
2444    for pt in &mut result {
2445        *pt = correct_to_intersection(
2446            a, b, surf_a, norm_a, surf_b, norm_b, *pt, u_range_a, v_range_a, u_range_b, v_range_b,
2447            5,
2448        );
2449    }
2450
2451    result
2452}
2453
2454/// Project a 3D point onto an analytic surface using the surface's
2455/// analytical projection method. Falls back to grid search for surface
2456/// types without analytical projection.
2457fn project_analytic(
2458    surface: &AnalyticSurface<'_>,
2459    point: Point3,
2460    u_range: (f64, f64),
2461    v_range: (f64, f64),
2462) -> (f64, f64) {
2463    match surface {
2464        AnalyticSurface::Cylinder(cyl) => {
2465            let (u, v) = cyl.project_point(point);
2466            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
2467        }
2468        AnalyticSurface::Sphere(sphere) => {
2469            let (u, v) = sphere.project_point(point);
2470            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
2471        }
2472        AnalyticSurface::Cone(cone) => {
2473            let (u, v) = cone.project_point(point);
2474            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
2475        }
2476        AnalyticSurface::Torus(torus) => {
2477            let (u, v) = torus.project_point(point);
2478            (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
2479        }
2480    }
2481}
2482
2483/// Returns `true` if the surface's u-parameter is periodic (wraps around 2π).
2484/// All current `AnalyticSurface` variants have periodic u — this is trivially
2485/// true today but exists as a guard for future non-periodic analytic types.
2486fn is_u_periodic(surface: &AnalyticSurface<'_>) -> bool {
2487    matches!(
2488        surface,
2489        AnalyticSurface::Cylinder(_)
2490            | AnalyticSurface::Cone(_)
2491            | AnalyticSurface::Sphere(_)
2492            | AnalyticSurface::Torus(_)
2493    )
2494}
2495
2496/// Extract closures and parameter ranges for an analytic surface.
2497#[allow(clippy::type_complexity)]
2498fn surface_closures<'a>(
2499    surface: &'a AnalyticSurface<'a>,
2500) -> (
2501    Box<dyn Fn(f64, f64) -> Point3 + 'a>,
2502    Box<dyn Fn(f64, f64) -> Vec3 + 'a>,
2503    (f64, f64),
2504    (f64, f64),
2505) {
2506    match surface {
2507        AnalyticSurface::Cylinder(cyl) => (
2508            Box::new(|u, v| cyl.evaluate(u, v)),
2509            Box::new(|u, v| cyl.normal(u, v)),
2510            (0.0, TAU),
2511            (-1.0, 1.0),
2512        ),
2513        AnalyticSurface::Cone(cone) => (
2514            Box::new(|u, v| cone.evaluate(u, v)),
2515            Box::new(|u, v| cone.normal(u, v)),
2516            (0.0, TAU),
2517            (0.01, 2.0),
2518        ),
2519        AnalyticSurface::Sphere(sphere) => (
2520            Box::new(|u, v| sphere.evaluate(u, v)),
2521            Box::new(|u, v| sphere.normal(u, v)),
2522            (0.0, TAU),
2523            (-FRAC_PI_2, FRAC_PI_2),
2524        ),
2525        AnalyticSurface::Torus(torus) => (
2526            Box::new(|u, v| torus.evaluate(u, v)),
2527            Box::new(|u, v| torus.normal(u, v)),
2528            (0.0, TAU),
2529            (0.0, TAU),
2530        ),
2531    }
2532}
2533
2534#[cfg(test)]
2535#[allow(clippy::unwrap_used, clippy::expect_used)]
2536mod tests {
2537    use super::*;
2538    use crate::tolerance::Tolerance;
2539
2540    #[test]
2541    fn plane_cylinder_perpendicular() {
2542        let cyl =
2543            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
2544                .unwrap();
2545
2546        // Horizontal plane at z=3 -- produces a circle at height 3.
2547        let curves = intersect_plane_cylinder(&cyl, Vec3::new(0.0, 0.0, 1.0), 3.0).unwrap();
2548        assert!(!curves.is_empty(), "should find intersection curve");
2549        assert!(
2550            curves[0].points.len() > 10,
2551            "should have many sample points"
2552        );
2553
2554        let tol = Tolerance::loose();
2555        for pt in &curves[0].points {
2556            assert!(
2557                tol.approx_eq(pt.point.z(), 3.0),
2558                "z should be ~3.0, got {}",
2559                pt.point.z()
2560            );
2561            let r = pt.point.x().hypot(pt.point.y());
2562            assert!(tol.approx_eq(r, 2.0), "radius should be ~2.0, got {r}");
2563        }
2564    }
2565
2566    #[test]
2567    fn plane_sphere_equator() {
2568        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 3.0).unwrap();
2569
2570        let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
2571        assert!(!curves.is_empty());
2572
2573        let tol = Tolerance::loose();
2574        for pt in &curves[0].points {
2575            assert!(
2576                tol.approx_eq(pt.point.z(), 0.0),
2577                "z should be ~0, got {}",
2578                pt.point.z()
2579            );
2580            let r = pt.point.x().hypot(pt.point.y());
2581            assert!(tol.approx_eq(r, 3.0), "radius should be ~3.0, got {r}");
2582        }
2583    }
2584
2585    #[test]
2586    fn plane_sphere_no_intersection() {
2587        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
2588
2589        let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 5.0).unwrap();
2590        assert!(curves.is_empty());
2591    }
2592
2593    #[test]
2594    fn plane_cone_cross_section() {
2595        let cone = ConicalSurface::new(
2596            Point3::new(0.0, 0.0, 0.0),
2597            Vec3::new(0.0, 0.0, 1.0),
2598            std::f64::consts::FRAC_PI_4,
2599        )
2600        .unwrap();
2601
2602        let curves = intersect_plane_cone(&cone, Vec3::new(0.0, 0.0, 1.0), 1.0).unwrap();
2603        assert!(!curves.is_empty(), "should find intersection with cone");
2604    }
2605
2606    /// The 1u gridfinity spacer lip fuse corner (#1570): the body's lip
2607    /// recess cone (45 deg, opening downward) meets the tool's lip cone
2608    /// (45 deg, opening upward) with axes offset 0.25mm in x and y. Equal
2609    /// half-angle tangents put the whole intersection on the radical plane,
2610    /// so the section is one exact ellipse; the marcher shredded this into
2611    /// ~64 closed micro-loops per pair.
2612    #[test]
2613    fn offset_parallel_equal_angle_cones_give_one_exact_ellipse() {
2614        let c1 = ConicalSurface::new(
2615            Point3::new(
2616                -16.999_999_999_999_975,
2617                -16.999_999_999_999_975,
2618                5.849_999_999_999_951,
2619            ),
2620            Vec3::new(0.0, 0.0, -1.0),
2621            0.785_398_163_397_433_5,
2622        )
2623        .unwrap();
2624        let c2 = ConicalSurface::new(
2625            Point3::new(
2626                -16.750_000_000_000_036,
2627                -16.750_000_000_000_018,
2628                0.749_999_999_999_881,
2629            ),
2630            Vec3::new(0.0, 0.0, 1.0),
2631            0.785_398_163_397_467_6,
2632        )
2633        .unwrap();
2634
2635        let curves = exact_cone_cone(&c1, &c2)
2636            .unwrap()
2637            .expect("offset parallel equal-angle cones must take the radical-plane path");
2638        assert_eq!(curves.len(), 1, "expected exactly one section conic");
2639        assert!(
2640            matches!(curves[0], ExactIntersectionCurve::Ellipse(_)),
2641            "expected an ellipse section, got {:?}",
2642            curves[0]
2643        );
2644        let ExactIntersectionCurve::Ellipse(ellipse) = &curves[0] else {
2645            return;
2646        };
2647
2648        // Every sample must lie on BOTH cones: distance to the axis equals
2649        // tan(half_angle) times the axial distance from the apex, on the
2650        // real nappe of each.
2651        for i in 0..16 {
2652            let p = crate::traits::ParametricCurve::evaluate(ellipse, TAU * f64::from(i) / 16.0);
2653            for (cone, label) in [(&c1, "c1"), (&c2, "c2")] {
2654                let rel = p - cone.apex();
2655                let rel_v = Vec3::new(rel.x(), rel.y(), rel.z());
2656                let axial = rel_v.dot(cone.axis());
2657                let radial = (rel_v - cone.axis() * axial).length();
2658                assert!(
2659                    axial > 0.0,
2660                    "{label}: sample on phantom nappe (axial {axial})"
2661                );
2662                let expect = cone.half_angle().tan() * axial;
2663                assert!(
2664                    (radial - expect).abs() < 1e-9,
2665                    "{label}: sample off surface by {}",
2666                    (radial - expect).abs()
2667                );
2668            }
2669        }
2670    }
2671
2672    /// Opposed cones whose real nappes occupy disjoint half-spaces share a
2673    /// radical-plane conic only on the phantom nappe — the exact path must
2674    /// report a definitive empty intersection, not defer to the marcher.
2675    #[test]
2676    fn offset_parallel_cones_opening_apart_have_no_real_intersection() {
2677        let c1 = ConicalSurface::new(
2678            Point3::new(0.0, 0.0, 5.0),
2679            Vec3::new(0.0, 0.0, -1.0),
2680            std::f64::consts::FRAC_PI_4,
2681        )
2682        .unwrap();
2683        let c2 = ConicalSurface::new(
2684            Point3::new(0.25, 0.25, 20.0),
2685            Vec3::new(0.0, 0.0, 1.0),
2686            std::f64::consts::FRAC_PI_4,
2687        )
2688        .unwrap();
2689        let curves = exact_cone_cone(&c1, &c2)
2690            .unwrap()
2691            .expect("radical-plane path");
2692        assert!(curves.is_empty(), "disjoint nappes must yield no curves");
2693    }
2694
2695    /// Unequal half-angles keep a quadratic term in the pencil — no plane
2696    /// reduction exists, so the exact path must defer to the marcher.
2697    #[test]
2698    fn offset_parallel_cones_with_unequal_angles_defer() {
2699        let c1 = ConicalSurface::new(
2700            Point3::new(0.0, 0.0, 5.0),
2701            Vec3::new(0.0, 0.0, -1.0),
2702            std::f64::consts::FRAC_PI_4,
2703        )
2704        .unwrap();
2705        let c2 = ConicalSurface::new(Point3::new(0.25, 0.25, 0.5), Vec3::new(0.0, 0.0, 1.0), 0.6)
2706            .unwrap();
2707        assert!(exact_cone_cone(&c1, &c2).unwrap().is_none());
2708    }
2709
2710    #[test]
2711    fn coaxial_cones_cross_at_single_circle() {
2712        // Two coaxial truncated cones (outer base r10->top r8, inner r9->r8
2713        // over height 10) cross where their radii match: z=10, r=8. The
2714        // intersection must be ONE clean circle, not the dozens of degenerate
2715        // micro-curves the general marcher produces at near-tangency.
2716        let outer = ConicalSurface::new(
2717            Point3::new(0.0, 0.0, 50.0),
2718            Vec3::new(0.0, 0.0, -1.0),
2719            5.0_f64.atan(),
2720        )
2721        .unwrap();
2722        let inner = ConicalSurface::new(
2723            Point3::new(0.0, 0.0, 90.0),
2724            Vec3::new(0.0, 0.0, -1.0),
2725            10.0_f64.atan(),
2726        )
2727        .unwrap();
2728
2729        let curves = intersect_analytic_analytic_bounded(
2730            AnalyticSurface::Cone(&outer),
2731            AnalyticSurface::Cone(&inner),
2732            32,
2733            None,
2734            None,
2735        )
2736        .unwrap();
2737
2738        assert_eq!(
2739            curves.len(),
2740            1,
2741            "coaxial cones crossing at one circle must yield exactly one curve, got {}",
2742            curves.len()
2743        );
2744        for p in &curves[0].points {
2745            let r = p.point.x().hypot(p.point.y());
2746            assert!(
2747                (p.point.z() - 10.0).abs() < 1e-6 && (r - 8.0).abs() < 1e-6,
2748                "intersection point off the expected z=10,r=8 circle: {:?}",
2749                p.point
2750            );
2751        }
2752    }
2753
2754    #[test]
2755    fn plane_torus_cross_section() {
2756        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 5.0, 1.0).unwrap();
2757
2758        let curves = intersect_plane_torus(&torus, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
2759        assert!(
2760            !curves.is_empty(),
2761            "should find intersection curves with torus"
2762        );
2763    }
2764
2765    /// Signed distance of a point to a z-axis torus centred at the origin:
2766    /// `sqrt((sqrt(x^2+y^2) - R)^2 + z^2) - r`.
2767    fn torus_implicit(p: Point3, major: f64, minor: f64) -> f64 {
2768        let rho = p.x().hypot(p.y());
2769        ((rho - major).hypot(p.z())) - minor
2770    }
2771
2772    /// The gridfinity lightweight base's failing corner, reduced: a cavity
2773    /// corner-round cone (apex below the floor, 45 deg, axis +z) crossed by a
2774    /// parallel-axis boss cylinder. The general marcher returned ~49 overlapping
2775    /// partial traces of one curve here; the algebraic path must return exactly
2776    /// the two branches, each ON both surfaces and inside the cone's v-hint.
2777    #[test]
2778    fn parallel_cone_cylinder_gives_two_exact_branches() {
2779        use crate::traits::ParametricCurve;
2780        let cone = ConicalSurface::new(
2781            Point3::new(-5.45, -36.55, -4.85),
2782            Vec3::new(0.0, 0.0, 1.0),
2783            std::f64::consts::FRAC_PI_4,
2784        )
2785        .unwrap();
2786        let cyl = CylindricalSurface::new(
2787            Point3::new(-8.0, -34.0, -5.0),
2788            Vec3::new(0.0, 0.0, 1.0),
2789            4.45,
2790        )
2791        .unwrap();
2792        // The cone face spans z in [-3.8, -3.0]; v = (z - apex_z) / sin(45 deg).
2793        let v_hint = (1.484_924_240_492_058, 2.616_295_090_390_43);
2794        let curves = intersect_analytic_analytic_bounded(
2795            AnalyticSurface::Cone(&cone),
2796            AnalyticSurface::Cylinder(&cyl),
2797            32,
2798            Some(v_hint),
2799            Some((0.0, 2.5)),
2800        )
2801        .unwrap();
2802
2803        assert_eq!(curves.len(), 2, "expected exactly the two branches");
2804        for c in &curves {
2805            let (t0, t1) = c.curve.domain();
2806            for k in 0..=32 {
2807                let t = (t1 - t0).mul_add(f64::from(k) / 32.0, t0);
2808                let p = ParametricCurve::evaluate(&c.curve, t);
2809                // On the cylinder: radial distance from its axis is the radius.
2810                let radial = ((p.x() + 8.0).powi(2) + (p.y() + 34.0).powi(2)).sqrt();
2811                assert!((radial - 4.45).abs() < 1e-6, "off cylinder: {radial}");
2812                // On the cone: radial distance from its axis is z - apex_z.
2813                let cone_r = ((p.x() + 5.45).powi(2) + (p.y() + 36.55).powi(2)).sqrt();
2814                assert!((cone_r - (p.z() + 4.85)).abs() < 1e-6, "off cone at {p:?}");
2815                // Inside the cone face's own v-window (the hint is respected).
2816                assert!(p.z() >= -3.8 - 1e-9 && p.z() <= -3.0 + 1e-9, "z={}", p.z());
2817            }
2818        }
2819    }
2820
2821    /// A coaxial pair has no radical line; the algebraic path must defer rather
2822    /// than divide by a zero axis separation.
2823    #[test]
2824    fn coaxial_cone_cylinder_defers_to_other_paths() {
2825        let cone = ConicalSurface::new(
2826            Point3::new(0.0, 0.0, 0.0),
2827            Vec3::new(0.0, 0.0, 1.0),
2828            std::f64::consts::FRAC_PI_4,
2829        )
2830        .unwrap();
2831        let cyl =
2832            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
2833                .unwrap();
2834        assert!(
2835            algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
2836                .unwrap()
2837                .is_none()
2838        );
2839    }
2840
2841    #[test]
2842    fn oblique_cone_cylinder_defers_to_other_paths() {
2843        let cone = ConicalSurface::new(
2844            Point3::new(0.0, 0.0, 0.0),
2845            Vec3::new(0.0, 0.0, 1.0),
2846            std::f64::consts::FRAC_PI_4,
2847        )
2848        .unwrap();
2849        let cyl =
2850            CylindricalSurface::new(Point3::new(3.0, 0.0, 1.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
2851                .unwrap();
2852        assert!(
2853            algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
2854                .unwrap()
2855                .is_none()
2856        );
2857    }
2858
2859    #[test]
2860    fn plane_torus_lobe_closes_and_stays_on_surface() {
2861        use crate::traits::ParametricCurve;
2862        let (major, minor) = (10.0, 3.0);
2863        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
2864
2865        // The census cutting planes (y=-4, x=6) each cut the +x and -x tube lobes
2866        // in a CLOSED oval. The greedy marcher stops one grid step short of
2867        // closing; the wrap-close must make every fitted lobe close exactly.
2868        for (n, d) in [
2869            (Vec3::new(0.0, -1.0, 0.0), 4.0),  // y = -4
2870            (Vec3::new(-1.0, 0.0, 0.0), -6.0), // x = 6
2871            (Vec3::new(0.0, 0.0, 1.0), 0.0),   // z = 0 -> two concentric circles
2872        ] {
2873            let curves = intersect_plane_torus(&torus, n, d).unwrap();
2874            assert!(!curves.is_empty(), "plane n={n:?} d={d} found no curves");
2875            for c in &curves {
2876                let p0 = ParametricCurve::evaluate(&c.curve, 0.0);
2877                let p1 = ParametricCurve::evaluate(&c.curve, 1.0);
2878                assert!(
2879                    (p0 - p1).length() < 1e-7,
2880                    "lobe not closed: gap={} (n={n:?} d={d})",
2881                    (p0 - p1).length()
2882                );
2883                // Every fitted sample stays on the torus (shape-preserving).
2884                for k in 0..=64 {
2885                    let t = f64::from(k) / 64.0;
2886                    let p = ParametricCurve::evaluate(&c.curve, t);
2887                    assert!(
2888                        torus_implicit(p, major, minor).abs() < 1e-2,
2889                        "off-surface point {p:?} implicit={}",
2890                        torus_implicit(p, major, minor)
2891                    );
2892                }
2893            }
2894        }
2895    }
2896
2897    #[test]
2898    fn plane_torus_inner_tangent_figure_eight_stays_open() {
2899        use crate::traits::ParametricCurve;
2900        let (major, minor) = (10.0, 3.0);
2901        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
2902
2903        // A plane tangent to the inner equator (x = major - minor = 7) cuts a
2904        // self-touching figure-eight. The marcher traces it as a single chain
2905        // whose end lands on the opposite lobe — FAR from its start (gap is many
2906        // point-spacings). The wrap-close must NOT force-close this into a wrong
2907        // loop; it must stay OPEN so a self-touching curve is never sealed.
2908        let curves =
2909            intersect_plane_torus(&torus, Vec3::new(-1.0, 0.0, 0.0), -(major - minor)).unwrap();
2910        assert!(!curves.is_empty(), "inner-tangent plane found no curves");
2911        let max_gap = curves
2912            .iter()
2913            .map(|c| {
2914                let p0 = ParametricCurve::evaluate(&c.curve, 0.0);
2915                let p1 = ParametricCurve::evaluate(&c.curve, 1.0);
2916                (p0 - p1).length()
2917            })
2918            .fold(0.0_f64, f64::max);
2919        assert!(
2920            max_gap > 1e-2,
2921            "figure-eight chain was wrongly force-closed (max end-gap={max_gap})"
2922        );
2923    }
2924
2925    #[test]
2926    fn line_torus_box_edge_crossing_is_exact() {
2927        // The census box edge x=6, y=-4 (z varying) crosses the torus (R=10,r=3)
2928        // at z = ±sqrt(r² − (rho−R)²), rho = hypot(6,4) ≈ 7.2111 → z ≈ ±1.1055.
2929        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
2930        let ts = intersect_line_torus(
2931            &torus,
2932            Point3::new(6.0, -4.0, -5.0),
2933            Vec3::new(0.0, 0.0, 1.0),
2934        );
2935        // Vertical line through (6,-4) meets the tube twice.
2936        assert_eq!(ts.len(), 2, "expected 2 crossings, got {ts:?}");
2937        let zs: Vec<f64> = ts.iter().map(|t| -5.0 + t).collect();
2938        let rho = 6.0_f64.hypot(4.0);
2939        let z_exp = (9.0 - (rho - 10.0).powi(2)).sqrt();
2940        assert!(
2941            (zs[0] - (-z_exp)).abs() < 1e-9,
2942            "z0={} exp={}",
2943            zs[0],
2944            -z_exp
2945        );
2946        assert!((zs[1] - z_exp).abs() < 1e-9, "z1={} exp={}", zs[1], z_exp);
2947        // Each crossing lies on the torus.
2948        for &t in &ts {
2949            let p = Point3::new(6.0, -4.0, -5.0 + t);
2950            let rho = p.x().hypot(p.y());
2951            let impl_v = (rho - 10.0).hypot(p.z()) - 3.0;
2952            assert!(impl_v.abs() < 1e-9, "off-torus impl={impl_v}");
2953        }
2954    }
2955
2956    #[test]
2957    fn line_torus_miss_and_tangent() {
2958        let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
2959        // A vertical line at rho beyond the outer rim (x=20) misses entirely.
2960        let miss = intersect_line_torus(
2961            &torus,
2962            Point3::new(20.0, 0.0, 0.0),
2963            Vec3::new(0.0, 0.0, 1.0),
2964        );
2965        assert!(miss.is_empty(), "expected no crossings, got {miss:?}");
2966        // The z-axis (rho=0) passes through the hole — no intersection.
2967        let axis =
2968            intersect_line_torus(&torus, Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0));
2969        assert!(axis.is_empty(), "z-axis should miss the tube, got {axis:?}");
2970    }
2971
2972    #[test]
2973    fn dispatch_via_analytic_surface() {
2974        let cyl =
2975            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
2976                .unwrap();
2977        let curves = intersect_plane_analytic(
2978            AnalyticSurface::Cylinder(&cyl),
2979            Vec3::new(0.0, 0.0, 1.0),
2980            0.0,
2981        )
2982        .unwrap();
2983        assert!(!curves.is_empty());
2984    }
2985
2986    #[test]
2987    fn perpendicular_cylinders_intersect() {
2988        let cyl_z =
2989            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
2990                .unwrap();
2991        let cyl_x =
2992            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
2993                .unwrap();
2994
2995        let curves = intersect_analytic_analytic(
2996            AnalyticSurface::Cylinder(&cyl_z),
2997            AnalyticSurface::Cylinder(&cyl_x),
2998            16,
2999        )
3000        .unwrap();
3001
3002        assert!(
3003            !curves.is_empty(),
3004            "perpendicular cylinders should intersect"
3005        );
3006
3007        for c in &curves {
3008            assert!(
3009                c.points.len() >= 2,
3010                "intersection curve should have >= 2 points, got {}",
3011                c.points.len()
3012            );
3013        }
3014    }
3015
3016    #[test]
3017    fn sphere_cylinder_intersect() {
3018        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
3019        let cyl =
3020            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
3021                .unwrap();
3022
3023        let curves = intersect_analytic_analytic(
3024            AnalyticSurface::Sphere(&sphere),
3025            AnalyticSurface::Cylinder(&cyl),
3026            16,
3027        )
3028        .unwrap();
3029
3030        // A sphere of radius 2 and a cylinder of radius 1, both centered
3031        // at the origin, should intersect (the cylinder passes through
3032        // the sphere).
3033        assert!(!curves.is_empty(), "sphere and cylinder should intersect");
3034    }
3035
3036    #[test]
3037    fn exact_sphere_cylinder_coaxial_two_circles() {
3038        // Sphere r=6 at origin, coaxial cylinder r=3 along z: two latitude
3039        // circles at z = ±sqrt(36-9) = ±sqrt(27), each of radius 3.
3040        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
3041        let cyl =
3042            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
3043                .unwrap();
3044        let circles = exact_sphere_cylinder(&sphere, &cyl)
3045            .unwrap()
3046            .expect("coaxial case returns Some");
3047        assert_eq!(circles.len(), 2, "through-bore meets the sphere twice");
3048        let mut zs: Vec<f64> = circles
3049            .iter()
3050            .filter_map(|c| match c {
3051                ExactIntersectionCurve::Circle(circle) => {
3052                    assert!(
3053                        (circle.radius() - 3.0).abs() < 1e-9,
3054                        "rim radius == cyl radius"
3055                    );
3056                    Some(circle.center().z())
3057                }
3058                _ => None,
3059            })
3060            .collect();
3061        assert_eq!(zs.len(), 2, "both sections must be exact circles");
3062        zs.sort_by(f64::total_cmp);
3063        let z = 27.0_f64.sqrt();
3064        assert!((zs[0] + z).abs() < 1e-9 && (zs[1] - z).abs() < 1e-9);
3065    }
3066
3067    #[test]
3068    fn exact_sphere_cylinder_non_coaxial_defers() {
3069        // Cylinder axis offset from the sphere center → quartic curve, deferred.
3070        let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
3071        let cyl =
3072            CylindricalSurface::new(Point3::new(2.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
3073                .unwrap();
3074        assert!(
3075            exact_sphere_cylinder(&sphere, &cyl).unwrap().is_none(),
3076            "non-coaxial sphere/cylinder defers to the marcher"
3077        );
3078    }
3079
3080    #[test]
3081    fn disjoint_cylinders_no_intersection() {
3082        let cyl_a =
3083            CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
3084                .unwrap();
3085        let cyl_b =
3086            CylindricalSurface::new(Point3::new(5.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
3087                .unwrap();
3088
3089        let curves = intersect_analytic_analytic(
3090            AnalyticSurface::Cylinder(&cyl_a),
3091            AnalyticSurface::Cylinder(&cyl_b),
3092            16,
3093        )
3094        .unwrap();
3095
3096        assert!(curves.is_empty(), "disjoint cylinders should not intersect");
3097    }
3098
3099    // ── Oblique plane × cone conic (ellipse / parabola / hyperbola) ──────
3100
3101    /// Collect 3D points from a returned exact curve, sampling analytic forms.
3102    fn collect_points(curve: &ExactIntersectionCurve) -> Vec<Point3> {
3103        use crate::traits::ParametricCurve;
3104        match curve {
3105            ExactIntersectionCurve::Circle(c) => (0..=64)
3106                .map(|i| ParametricCurve::evaluate(c, TAU * f64::from(i) / 64.0))
3107                .collect(),
3108            ExactIntersectionCurve::Ellipse(e) => (0..=64)
3109                .map(|i| ParametricCurve::evaluate(e, TAU * f64::from(i) / 64.0))
3110                .collect(),
3111            ExactIntersectionCurve::Points(pts) => pts.clone(),
3112        }
3113    }
3114
3115    /// Assert every returned point lies on the plane and the cone surface, on
3116    /// the real (`v >= 0`) nappe, and within a sane axial bound.
3117    fn assert_on_plane_and_cone(
3118        curves: &[ExactIntersectionCurve],
3119        cone: &ConicalSurface,
3120        n: Vec3,
3121        d: f64,
3122        z_bound: (f64, f64),
3123    ) {
3124        assert!(!curves.is_empty(), "expected at least one section curve");
3125        let mut total = 0;
3126        for curve in curves {
3127            for p in collect_points(curve) {
3128                total += 1;
3129                let plane_err = (n.x() * p.x() + n.y() * p.y() + n.z() * p.z() - d).abs();
3130                assert!(
3131                    plane_err < 1e-9,
3132                    "point off plane by {plane_err:.2e}: {p:?}"
3133                );
3134                let (u, v) = cone.project_point(p);
3135                let q = cone.evaluate(u, v);
3136                let cone_err =
3137                    ((p.x() - q.x()).powi(2) + (p.y() - q.y()).powi(2) + (p.z() - q.z()).powi(2))
3138                        .sqrt();
3139                assert!(cone_err < 1e-7, "point off cone by {cone_err:.2e}: {p:?}");
3140                assert!(v >= -1e-9, "point on phantom nappe (v={v:.4}): {p:?}");
3141                assert!(
3142                    p.z() >= z_bound.0 - 1e-6 && p.z() <= z_bound.1 + 1e-6,
3143                    "point z={:.4} outside sane bound {z_bound:?}: {p:?}",
3144                    p.z()
3145                );
3146            }
3147        }
3148        assert!(total >= 8, "too few section points ({total})");
3149    }
3150
3151    #[test]
3152    fn oblique_plane_cone_ellipse_is_exact_and_on_both() {
3153        // 45°-half-angle cone (axis +z). A plane tilted only ~16.7° off horizontal
3154        // has plane-axis angle ≈ 73° > 45° (the cone's half-opening from axis) →
3155        // ellipse. Must come back as an exact Ellipse, fully on both surfaces.
3156        let cone = ConicalSurface::new(
3157            Point3::new(0.0, 0.0, 0.0),
3158            Vec3::new(0.0, 0.0, 1.0),
3159            std::f64::consts::FRAC_PI_4,
3160        )
3161        .unwrap();
3162        let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
3163        // Plane through (0,0,5): d = n·(0,0,5).
3164        let d = n.z() * 5.0;
3165        let curves = exact_plane_cone(&cone, n, d).unwrap();
3166        assert!(
3167            curves
3168                .iter()
3169                .any(|c| matches!(c, ExactIntersectionCurve::Ellipse(_))),
3170            "oblique steep plane × cone must yield an exact Ellipse"
3171        );
3172        // The ellipse straddles z=5; with the 0.3 tilt the z-extent stays modest.
3173        assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 12.0));
3174    }
3175
3176    #[test]
3177    fn oblique_plane_cone_wrong_nappe_is_empty() {
3178        // Same ellipse-regime plane as above, but offset to the FAR side of the
3179        // apex (z=-5). The +z cone's real (v≥0) nappe is not met — only the
3180        // phantom v<0 nappe — so the result must be EMPTY, not a phantom ellipse.
3181        let cone = ConicalSurface::new(
3182            Point3::new(0.0, 0.0, 0.0),
3183            Vec3::new(0.0, 0.0, 1.0),
3184            std::f64::consts::FRAC_PI_4,
3185        )
3186        .unwrap();
3187        let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
3188        let d = n.z() * -5.0;
3189        let curves = exact_plane_cone(&cone, n, d).unwrap();
3190        assert!(
3191            curves.is_empty(),
3192            "plane on the phantom-nappe side must yield no real curve, got {}",
3193            curves.len()
3194        );
3195    }
3196
3197    #[test]
3198    fn oblique_plane_cone_parabola_on_both_single_branch() {
3199        // Plane normal at exactly 45° to the axis (= the cone half-opening) → the
3200        // plane is parallel to a generator → parabola. One unbounded branch.
3201        let cone = ConicalSurface::new(
3202            Point3::new(0.0, 0.0, 0.0),
3203            Vec3::new(0.0, 0.0, 1.0),
3204            std::f64::consts::FRAC_PI_4,
3205        )
3206        .unwrap();
3207        let n = Vec3::new(1.0, 0.0, 1.0).normalize().unwrap();
3208        let d = n.x() * 3.0 + n.z() * 3.0; // through (3,0,3)
3209        let curves = exact_plane_cone(&cone, n, d).unwrap();
3210        assert_eq!(
3211            curves.len(),
3212            1,
3213            "a parabola is a single branch, got {}",
3214            curves.len()
3215        );
3216        // Bounded by r_max = 32·|e|; |e| here is O(few), so allow a wide z window.
3217        assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 400.0));
3218    }
3219
3220    #[test]
3221    fn oblique_plane_cone_hyperbola_real_nappe_only() {
3222        // Faithful scooplabel lip-foot geometry: a 45° cone with axis −z and
3223        // apex at (−59,−59,15.85) (a bin corner), cut by the upper ramp tread
3224        // plane n=(0,0.99518,0.09802), d=−58.36056. The plane is nearly parallel
3225        // to the axis (cos≈0.098) → plane-axis angle ≈ 5.6° < 45° → hyperbola.
3226        // The downward real nappe is hit by exactly one branch; the phantom
3227        // upward nappe (and the asymptote runaway) must NOT appear, and the arc
3228        // must stay near the apex (the plane is ~1.2 mm from it).
3229        let cone = ConicalSurface::new(
3230            Point3::new(-59.0, -59.0, 15.85),
3231            Vec3::new(0.0, 0.0, -1.0),
3232            std::f64::consts::FRAC_PI_4,
3233        )
3234        .unwrap();
3235        let n = Vec3::new(0.0, 0.995_18, 0.098_02).normalize().unwrap();
3236        let d = -58.360_56;
3237        let cos_theta = n.dot(cone.axis()).abs();
3238        assert!(cos_theta < 0.2, "expected a shallow (hyperbola) plane");
3239        let curves = exact_plane_cone(&cone, n, d).unwrap();
3240        // Real downward nappe only: never above the apex (z=15.85). The vertex is
3241        // ~1.2 mm from the apex, so the bounded arc stays within a few mm of it.
3242        assert_on_plane_and_cone(&curves, &cone, n, d, (5.0, 15.85));
3243        // Every returned curve is sampled Points (no false Circle/Ellipse).
3244        for c in &curves {
3245            assert!(
3246                matches!(c, ExactIntersectionCurve::Points(_)),
3247                "hyperbola must be sampled Points, not a closed conic"
3248            );
3249        }
3250    }
3251}