Skip to main content

ogeom_intersect/
section.rs

1//! Where two surfaces meet: the one call.
2//!
3//! Everything else in this crate is a stage: closed forms, seeding, tracing,
4//! fitting. This is the function an application calls, and the one `ogeom-bool`
5//! builds on: give it two surfaces, get back what they do to each other,
6//! with the analytic path taken where it exists and the marched-and-fitted
7//! path where it does not. The caller does not choose; the pair does.
8//!
9//! *Elsewhere* this is `GeomAPI_IntSS` over `IntPatch`/`GeomInt`: one entry
10//! point hiding an analytic dispatch and a walking intersector.
11//!
12//! # What a section curve carries
13//!
14//! Three descriptions, because three consumers: the curve in space for the
15//! edge, and a pcurve per surface for the faces; face splitting happens in
16//! parameter space, and a curve a face cannot express is one it cannot be
17//! split along. Analytic results carry exact pcurves where the projection has
18//! a closed form and `None` where it does not; fitted results always carry
19//! fitted pcurves, because the tracer recorded the parameters as it walked.
20//!
21//! A pcurve here is **same-parameter** with its 3D curve: evaluating either at
22//! the same `t` lands on the same point of the intersection. That is the claim
23//! `docs/DATA_MODEL.md` ยง6 makes edges carry, and it is arranged here by
24//! construction (the 2D curves inherit the 3D curve's own parameterization)
25//! rather than asserted and repaired later.
26
27use ogeom_core::{OgeomResult, Tolerances, ogeom_bail};
28use ogeom_geom::{
29    Circle2d, Curve, Curve2d as _, Curve3d, Ellipse2d, Line2d, PlanarCurve, Surface,
30    SurfaceGeometry,
31};
32use ogeom_math::{Circle2, Ellipse2, Frame2, Point, Point2};
33
34use crate::approx::approximate_branch;
35use crate::contact::trace_tangential;
36use crate::march::{Marching, branches};
37use crate::surface::{Meeting, surface_surface};
38
39/// How to intersect, when the general path runs.
40#[derive(Debug, Clone, Copy, PartialEq)]
41pub struct IntersectOptions {
42    /// The tolerance the fitted curves are held to.
43    pub tolerance: f64,
44    /// The marching settings, for pairs with no closed form.
45    pub marching: Marching,
46}
47
48impl Default for IntersectOptions {
49    fn default() -> Self {
50        Self {
51            tolerance: 1e-6,
52            marching: Marching::default(),
53        }
54    }
55}
56
57/// One curve of a section, with its parameter-space descriptions.
58#[derive(Debug, Clone, PartialEq)]
59pub struct SectionCurve {
60    /// The curve in space.
61    pub curve: Curve,
62    /// The curve in the first surface's parameter space, where it has one.
63    ///
64    /// Always present for a fitted curve. For an exact curve, present when the
65    /// projection has a closed form (a line on a plane, a circle on the
66    /// cylinder it wraps) and `None` where it does not, which is a statement
67    /// about the projection rather than about the curve.
68    pub on_a: Option<PlanarCurve>,
69    /// The same, on the second surface.
70    pub on_b: Option<PlanarCurve>,
71    /// How far this curve may sit from the true intersection.
72    ///
73    /// Zero for an exact curve. For a fitted one, the trace's chord tolerance
74    /// plus the fit's reported error: the sum of the stated parts.
75    pub tolerance: f64,
76    /// Whether the curve came from a closed form.
77    pub exact: bool,
78    /// Whether it is a closed loop.
79    pub closed: bool,
80    /// Whether the surfaces *touch* along this curve rather than crossing
81    /// it.
82    ///
83    /// A tangential contact is a real curve (the two surfaces meet there,
84    /// and a drawing has to show it), but it carries no boundary parity:
85    /// neither surface passes through the other, so nothing is inside on
86    /// one side and outside on the other. Consumers that classify by
87    /// crossing must leave these out of that arithmetic; consumers that
88    /// draw or measure contact want them.
89    pub tangential: bool,
90}
91
92/// What two surfaces do to each other.
93#[derive(Debug, Clone, PartialEq)]
94pub enum SurfaceIntersection {
95    /// They do not meet.
96    ///
97    /// From the general path this means *no crossing was found at the seeding
98    /// resolution*: a branch thinner than the sampling grid is invisible to
99    /// it, and the completeness instrument in `tests/support/coverage.rs` is
100    /// what checks.
101    Apart,
102    /// They touch at isolated points without crossing.
103    Touching(Vec<Point>),
104    /// They meet along these curves.
105    Along(Vec<SectionCurve>),
106    /// They are the same surface wherever they overlap.
107    Same,
108}
109
110/// Where two surfaces meet.
111///
112/// The analytic path answers the pairs with closed forms, exactly, with
113/// tolerance zero. Every other pair is seeded, traced and fitted to
114/// `options.tolerance`, after a pair without a closed form is first measured
115/// for coincidence: two patches lying on one another to within
116/// `options.tolerance` wherever they overlap are [`Same`]. One call, and the
117/// pair decides the path.
118///
119/// # Errors
120///
121/// [`OgeomError::Construction`](ogeom_core::OgeomError::Construction) if the options
122/// are unusable. A pair the marcher finds nothing for is [`Apart`], not an
123/// error; see that variant for what it can and cannot claim.
124///
125/// [`Apart`]: SurfaceIntersection::Apart
126/// [`Same`]: SurfaceIntersection::Same
127pub fn intersect_surfaces(
128    a: &SurfaceGeometry,
129    b: &SurfaceGeometry,
130    options: IntersectOptions,
131    tol: Tolerances,
132) -> OgeomResult<SurfaceIntersection> {
133    if !options.tolerance.is_finite() || options.tolerance <= 0.0 {
134        ogeom_bail!(
135            Construction,
136            "a tolerance of {} is not a distance",
137            options.tolerance
138        );
139    }
140
141    // A plane all but along a drum's axis meets it in an ellipse
142    // kilometres long, whose parameter is too coarse a ruler for the few
143    // millimetres of it the drum's height holds: a crossing solved on it
144    // lands tens of microns off. Over that height it is two lines.
145    if let Some(sections) = near_parallel_plane_drum(a, b, tol) {
146        return Ok(if sections.is_empty() {
147            SurfaceIntersection::Apart
148        } else {
149            SurfaceIntersection::Along(sections)
150        });
151    }
152    match surface_surface(a, b, tol) {
153        Ok(Meeting::Apart) => Ok(SurfaceIntersection::Apart),
154        Ok(Meeting::Same) => Ok(SurfaceIntersection::Same),
155        Ok(Meeting::Touching(points)) => Ok(SurfaceIntersection::Touching(points)),
156        Ok(Meeting::Along(curves)) => {
157            let sections: Vec<SectionCurve> = curves
158                .into_iter()
159                .filter_map(|curve| exact_section(curve, a, b, tol))
160                .collect();
161            Ok(if sections.is_empty() {
162                // Every curve fell outside the surfaces' stated extents: the
163                // unbounded geometries meet, the surfaces as given do not.
164                SurfaceIntersection::Apart
165            } else {
166                SurfaceIntersection::Along(sections)
167            })
168        }
169        // No closed form for this pair. Coincidence is measured first: the
170        // marcher seeds on sign changes, and a pair that never separates
171        // has none, so what it would trace over a coincident pair is noise
172        // under a section's name, and costs seconds to produce.
173        Err(_) if surfaces_coincide(a, b, options.tolerance, tol) => Ok(SurfaceIntersection::Same),
174        // Otherwise the marcher, unless the pair is two drums all but
175        // parallel.
176        Err(_) => match near_parallel_drums(a, b, tol)
177            .or_else(|| ball_through_drum(a, b, tol))
178            .or_else(|| axial_plane_revolution(a, b, tol))
179            .or_else(|| plane_along_spline_lines(a, b, tol))
180        {
181            Some(sections) if sections.is_empty() => Ok(SurfaceIntersection::Apart),
182            Some(sections) => Ok(SurfaceIntersection::Along(sections)),
183            None => marched(a, b, options, tol),
184        },
185    }
186}
187
188/// Whether two surfaces are one surface wherever they overlap, measured to
189/// `reach`.
190///
191/// The closed forms answer this for the pairs they know. Where there is no
192/// closed form it does not stop being a fair question (two patches restated
193/// from one plane are the same surface, and nothing in their control points
194/// says so), but it stops being answerable exactly, so it is measured, and
195/// only for the pairs the analytic layer has declined.
196///
197/// Sampled on the *smaller* window, because the answer is about the region
198/// the two share and a stated window is not that region: a plane's own
199/// extends for a billion units either way, and a grid over it samples
200/// nothing. A sample whose foot lands on the rim of the other is skipped
201/// rather than counted against: the other patch simply does not reach that
202/// far, and a distance measured to its rim is about the window, not the
203/// surface.
204///
205/// One-sided by construction: a pair that crosses puts interior samples well
206/// off the other, so it cannot pass, and a pair this cannot resolve is
207/// marched.
208fn surfaces_coincide(
209    a: &SurfaceGeometry,
210    b: &SurfaceGeometry,
211    reach: f64,
212    tol: Tolerances,
213) -> bool {
214    /// Samples per direction over the window, and how many must land inside
215    /// the other before agreement means anything.
216    const GRID: usize = 6;
217    const EVIDENCE: usize = 4;
218
219    let span = |s: &SurfaceGeometry| -> f64 {
220        let ((ua, ub), (va, vb)) = s.domain();
221        (ub - ua).abs().max((vb - va).abs())
222    };
223    let (sampled, against) = if span(a) <= span(b) { (a, b) } else { (b, a) };
224    let ((ua, ub), (va, vb)) = sampled.domain();
225    if !(ua.is_finite() && ub.is_finite() && va.is_finite() && vb.is_finite()) {
226        return false;
227    }
228    let ((wu0, wu1), (wv0, wv1)) = against.domain();
229    // A twentieth of the window in from each rim: enough that a foot the
230    // search pinned to the rim is not read as one the surface truly reaches.
231    let (mu, mv) = ((wu1 - wu0) * 0.05, (wv1 - wv0) * 0.05);
232
233    let mut evidence = 0_usize;
234    for i in 0..=GRID {
235        for j in 0..=GRID {
236            #[allow(clippy::cast_precision_loss)]
237            let u = ua + (ub - ua) * (i as f64 / GRID as f64);
238            #[allow(clippy::cast_precision_loss)]
239            let v = va + (vb - va) * (j as f64 / GRID as f64);
240            let Ok(p) = sampled.point_at(u, v, tol) else {
241                return false;
242            };
243            let Ok(foot) = ogeom_geom::project_on_surface(against, p, 16, tol) else {
244                return false;
245            };
246            let (fu, fv) = foot.parameters;
247            if fu <= wu0 + mu || fu >= wu1 - mu || fv <= wv0 + mv || fv >= wv1 - mv {
248                continue;
249            }
250            if foot.distance > reach {
251                return false;
252            }
253            evidence += 1;
254        }
255    }
256    evidence >= EVIDENCE
257}
258
259/// A plane through the axis of a surface of revolution whose profile lies
260/// in a plane through that axis: the profile turned to each angle that sets
261/// its plane on the cut, a column of the revolution's chart.
262///
263/// Marched, such a section runs through the pole wherever the profile meets
264/// the axis, where the chart pinches to a point and the march stalls. Here
265/// the profile is cut where it crosses the axis, and each piece is turned to
266/// both angles, the one setting its side of the axis on each half of the
267/// cut: a revolution whose profile crosses the axis covers the section
268/// twice, once from each column, and a face on either column finds its own
269/// piece. `None` for any other plane or profile, and where the turns fall
270/// outside the sweep the answer is empty.
271fn axial_plane_revolution(
272    a: &SurfaceGeometry,
273    b: &SurfaceGeometry,
274    tol: Tolerances,
275) -> Option<Vec<SectionCurve>> {
276    const SAMPLES: u32 = 64;
277    let (plane, revolution, plane_first) = match (a, b) {
278        (SurfaceGeometry::Plane(p), SurfaceGeometry::Revolution(r)) => (p, r, true),
279        (SurfaceGeometry::Revolution(r), SurfaceGeometry::Plane(p)) => (p, r, false),
280        _ => return None,
281    };
282    let cut = plane.plane();
283    let axis = revolution.axis();
284    let normal = cut.normal();
285    if normal.dot(axis.direction).abs() > tol.angular()
286        || cut.signed_distance_to(axis.location).abs() > tol.confusion()
287    {
288        return None;
289    }
290    let profile = revolution.curve();
291    let (v0, v1) = profile.domain();
292    let at = |k: u32| v0 + (v1 - v0) * f64::from(k) / f64::from(SAMPLES);
293    let radial = |v: f64| {
294        let p = profile.point_at(v, tol).ok()?;
295        Some(p - axis.project(p))
296    };
297    // The profile's own side of the axis, from its point furthest off it.
298    let mut widest = ogeom_math::Vector::ZERO;
299    for k in 0..=SAMPLES {
300        let r = radial(at(k))?;
301        if r.magnitude() > widest.magnitude() {
302            widest = r;
303        }
304    }
305    let side = ogeom_math::Direction::new(widest, tol).ok()?;
306    let across = axis.direction.cross_with(side.vector());
307    // Every point of the profile in the plane of the axis and that side.
308    let offset = |v: f64| radial(v).map(|r| (r.dot(side.vector()), r.dot(across)));
309    for k in 0..=SAMPLES {
310        let (_, off) = offset(at(k))?;
311        if off.abs() > tol.confusion() {
312            return None;
313        }
314    }
315    // The pieces between the profile's crossings of the axis, each crossing
316    // narrowed by bisection.
317    let mut cuts = vec![v0];
318    for k in 0..SAMPLES {
319        let (mut lo, mut hi) = (at(k), at(k + 1));
320        let (s_lo, s_hi) = (offset(lo)?.0, offset(hi)?.0);
321        if s_lo.abs() <= tol.confusion() || s_lo * s_hi >= 0.0 {
322            continue;
323        }
324        for _ in 0..80 {
325            let mid = f64::midpoint(lo, hi);
326            if offset(mid)?.0 * s_lo > 0.0 {
327                lo = mid;
328            } else {
329                hi = mid;
330            }
331        }
332        cuts.push(f64::midpoint(lo, hi));
333    }
334    cuts.push(v1);
335    // The turns setting the profile's side on the cut's two halves.
336    let out = axis.direction.cross_with(normal.vector());
337    let first = across.dot(out).atan2(side.vector().dot(out));
338    let (u0, u1) = revolution.domain().0;
339    let turns: Vec<f64> = [first, first + core::f64::consts::PI]
340        .into_iter()
341        .filter_map(|u| {
342            let u = u0 + (u - u0).rem_euclid(core::f64::consts::TAU);
343            let u = if (u - u0 - core::f64::consts::TAU).abs() <= tol.angular() {
344                u0
345            } else {
346                u
347            };
348            (u <= u1 + tol.angular()).then_some(u.min(u1))
349        })
350        .collect();
351    let mut sections = Vec::new();
352    for &u in &turns {
353        let turned = ogeom_geom::Transformable::transformed(
354            profile,
355            &ogeom_math::Transform::rotation(axis, u),
356            tol,
357        )
358        .ok()?;
359        for piece in cuts.windows(2) {
360            let (va, vb) = (piece[0], piece[1]);
361            if vb - va <= tol.parametric() {
362                continue;
363            }
364            let curve: Curve = ogeom_geom::TrimmedCurve::new(turned.clone(), va, vb, tol)
365                .ok()?
366                .into();
367            let column: PlanarCurve = Line2d::over(
368                ogeom_math::Axis2::new(Point2::new(u, 0.0), ogeom_math::Direction2::Y),
369                va,
370                vb,
371            )
372            .ok()?
373            .into();
374            let flat = exact_pcurve(&curve, (va, vb), a_or_b(plane_first, a, b), tol);
375            let (on_a, on_b) = if plane_first {
376                (flat, Some(column))
377            } else {
378                (Some(column), flat)
379            };
380            sections.push(SectionCurve {
381                on_a,
382                on_b,
383                tolerance: 0.0,
384                exact: true,
385                closed: false,
386                tangential: false,
387                curve,
388            });
389        }
390    }
391    Some(sections)
392}
393
394/// A plane holding whole columns or rows of a spline surface, and meeting
395/// it nowhere else: those iso lines, exactly.
396///
397/// A surface of revolution converted to a spline and scaled keeps its
398/// meridians as columns, and a plane through its axis holds two of them,
399/// one often the seam along the chart's border. Marched, such a section
400/// runs along the chart's edge or through its poles and is not found. An
401/// iso line lies in the plane where every control point of it does, which
402/// is a root of each control point's weighted distance to the plane, found
403/// along the chart. The answer stands only where a grid over the chart
404/// finds the surface on one side of the plane between the lines found;
405/// anything else meets the plane elsewhere too and is marched.
406fn plane_along_spline_lines(
407    a: &SurfaceGeometry,
408    b: &SurfaceGeometry,
409    tol: Tolerances,
410) -> Option<Vec<SectionCurve>> {
411    const SAMPLES: u32 = 96;
412    let (plane, spline, plane_first) = match (a, b) {
413        (SurfaceGeometry::Plane(p), SurfaceGeometry::BSpline(s)) => (p.plane(), s, true),
414        (SurfaceGeometry::BSpline(s), SurfaceGeometry::Plane(p)) => (p.plane(), s, false),
415        _ => return None,
416    };
417    let distance = |p: Point| plane.signed_distance_to(p);
418    let ((u0, u1), (v0, v1)) = spline.domain();
419    // An iso line's control points' weighted distances to the plane, and
420    // whether the line has any length.
421    let line_at = |along_u: bool, t: f64| -> Option<ogeom_geom::BSplineCurve> {
422        if along_u {
423            spline.iso_u_curve(t, tol).ok()
424        } else {
425            spline.iso_v_curve(t, tol).ok()
426        }
427    };
428    let weighted = |curve: &ogeom_geom::BSplineCurve| -> Vec<f64> {
429        curve
430            .control_points()
431            .iter()
432            .map(|w| w.weight * distance(w.point()))
433            .collect()
434    };
435    let lies_in = |curve: &ogeom_geom::BSplineCurve| {
436        curve
437            .control_points()
438            .iter()
439            .all(|w| distance(w.point()).abs() <= tol.confusion())
440    };
441    let has_length = |curve: &ogeom_geom::BSplineCurve| {
442        let first = curve.control_points()[0].point();
443        curve
444            .control_points()
445            .iter()
446            .any(|w| w.point().distance(first) > tol.confusion())
447    };
448    // The iso lines of one family lying in the plane: the chart's borders,
449    // and every root of the control point that strays furthest.
450    let found = |along_u: bool| -> Option<Vec<f64>> {
451        let (lo, hi) = if along_u { (u0, u1) } else { (v0, v1) };
452        let at = |k: u32| lo + (hi - lo) * f64::from(k) / f64::from(SAMPLES);
453        let rows: Vec<Vec<f64>> = (0..=SAMPLES)
454            .map(|k| line_at(along_u, at(k)).map(|c| weighted(&c)))
455            .collect::<Option<_>>()?;
456        let count = rows[0].len();
457        if rows.iter().any(|r| r.len() != count) {
458            return None;
459        }
460        let widest = (0..count).max_by(|&i, &j| {
461            let spread = |i: usize| rows.iter().fold(0.0_f64, |m, r| m.max(r[i].abs()));
462            spread(i).total_cmp(&spread(j))
463        })?;
464        let mut roots = vec![lo, hi];
465        for k in 0..SAMPLES {
466            let (mut a, mut b) = (at(k), at(k + 1));
467            let (da, db) = (rows[k as usize][widest], rows[k as usize + 1][widest]);
468            if da == 0.0 {
469                roots.push(a);
470                continue;
471            }
472            if da * db > 0.0 {
473                continue;
474            }
475            let sign = da.signum();
476            for _ in 0..80 {
477                let mid = f64::midpoint(a, b);
478                let d = weighted(&line_at(along_u, mid)?)[widest];
479                if d * sign > 0.0 {
480                    a = mid;
481                } else {
482                    b = mid;
483                }
484            }
485            roots.push(f64::midpoint(a, b));
486        }
487        roots.sort_by(f64::total_cmp);
488        roots.dedup_by(|x, y| (*x - *y).abs() <= tol.parametric());
489        Some(
490            roots
491                .into_iter()
492                .filter(|&t| line_at(along_u, t).is_some_and(|c| lies_in(&c) && has_length(&c)))
493                .collect(),
494        )
495    };
496    let columns = found(true)?;
497    let rows = found(false)?;
498    if columns.is_empty() && rows.is_empty() {
499        return None;
500    }
501    // The chart cut by the lines found into cells: the surface keeps to one
502    // side of the plane within each, or it meets the plane elsewhere too.
503    let strip = |lines: &[f64], t: f64| lines.iter().filter(|&&x| x < t).count();
504    let near_line = |lines: &[f64], t: f64, span: f64| {
505        lines
506            .iter()
507            .any(|&x| (x - t).abs() <= span / f64::from(SAMPLES) * 0.25)
508    };
509    let mut sides: std::collections::HashMap<(usize, usize), f64> =
510        std::collections::HashMap::new();
511    let band = tol.confusion() * 10.0;
512    for i in 0..=SAMPLES {
513        let u = u0 + (u1 - u0) * (f64::from(i) + 0.5) / f64::from(SAMPLES + 1);
514        if near_line(&columns, u, u1 - u0) {
515            continue;
516        }
517        for j in 0..=SAMPLES {
518            let v = v0 + (v1 - v0) * (f64::from(j) + 0.5) / f64::from(SAMPLES + 1);
519            if near_line(&rows, v, v1 - v0) {
520                continue;
521            }
522            let d = distance(spline.point_at(u, v, tol).ok()?);
523            if d.abs() <= band {
524                continue;
525            }
526            let cell = (strip(&columns, u), strip(&rows, v));
527            match sides.get(&cell) {
528                Some(side) if side * d < 0.0 => return None,
529                Some(_) => {}
530                None => {
531                    sides.insert(cell, d.signum());
532                }
533            }
534        }
535    }
536    // Each line must be a crossing, the cells either side of it on
537    // opposite sides of the plane (across the border of a closed chart,
538    // the cells at its two ends). A line the surface only touches, or with
539    // no cell beside it to say, is a tangency the marcher and the contact
540    // handling answer, and so is the whole pair.
541    let closed_u = spline.is_closed_u(tol);
542    let closed_v = spline.is_closed_v(tol);
543    let side_of = |cu: Option<usize>, cv: Option<usize>| -> Option<f64> {
544        let mut found = sides
545            .iter()
546            .filter(|((u, v), _)| cu.is_none_or(|c| c == *u) && cv.is_none_or(|c| c == *v))
547            .map(|(_, s)| *s);
548        let first = found.next()?;
549        found.all(|s| s == first).then_some(first)
550    };
551    let crosses = |k: usize, count: usize, closed: bool, cell: &dyn Fn(usize) -> Option<f64>| {
552        let below = cell(k).or_else(|| closed.then(|| (0..=count).rev().find_map(cell)).flatten());
553        let above = cell(k + 1).or_else(|| closed.then(|| (0..=count).find_map(cell)).flatten());
554        matches!((below, above), (Some(x), Some(y)) if x * y < 0.0)
555    };
556    for k in 0..columns.len() {
557        if !crosses(k, columns.len(), closed_u, &|c| side_of(Some(c), None)) {
558            return None;
559        }
560    }
561    for k in 0..rows.len() {
562        if !crosses(k, rows.len(), closed_v, &|c| side_of(None, Some(c))) {
563            return None;
564        }
565    }
566    let mut sections = Vec::new();
567    let mut emit = |along_u: bool, t: f64| -> Option<()> {
568        let iso = line_at(along_u, t)?;
569        let curve: Curve = iso.into();
570        let range = curve.domain();
571        let chart: PlanarCurve = if along_u {
572            Line2d::over(
573                ogeom_math::Axis2::new(Point2::new(t, 0.0), ogeom_math::Direction2::Y),
574                range.0,
575                range.1,
576            )
577        } else {
578            Line2d::over(
579                ogeom_math::Axis2::new(Point2::new(0.0, t), ogeom_math::Direction2::X),
580                range.0,
581                range.1,
582            )
583        }
584        .ok()?
585        .into();
586        let flat = exact_pcurve(&curve, range, a_or_b(plane_first, a, b), tol)?;
587        let (on_a, on_b) = if plane_first {
588            (Some(flat), Some(chart))
589        } else {
590            (Some(chart), Some(flat))
591        };
592        sections.push(SectionCurve {
593            on_a,
594            on_b,
595            tolerance: 0.0,
596            exact: true,
597            closed: curve.is_closed(tol),
598            tangential: false,
599            curve,
600        });
601        Some(())
602    };
603    // Every line found: the chart's two borders across a closed surface
604    // are one line in space, stated once.
605    for (k, &u) in columns.iter().enumerate() {
606        if closed_u
607            && k + 1 == columns.len()
608            && k > 0
609            && columns[0] == u0
610            && (u - u1).abs() <= tol.parametric()
611        {
612            continue;
613        }
614        emit(true, u)?;
615    }
616    for (k, &v) in rows.iter().enumerate() {
617        if closed_v
618            && k + 1 == rows.len()
619            && k > 0
620            && rows[0] == v0
621            && (v - v1).abs() <= tol.parametric()
622        {
623            continue;
624        }
625        emit(false, v)?;
626    }
627    Some(sections)
628}
629
630/// The first surface where `first` holds, else the second.
631fn a_or_b<'s>(first: bool, a: &'s SurfaceGeometry, b: &'s SurfaceGeometry) -> &'s SurfaceGeometry {
632    if first { a } else { b }
633}
634
635/// Two drums whose axes are all but parallel, over the height they share.
636///
637/// Parallel drums meet in straight lines along their axes, and drums whose
638/// axes lean a ten-thousandth apart (a drilled hole beside a fillet of a
639/// converted mesh, each axis fitted to its own facets) meet in a quartic
640/// that departs from those lines by less than a micron over any height a
641/// part has. Marched, it comes back as fitted curves that cost seconds to
642/// cross and wander where the drums nearly touch. Here each is solved in
643/// the cross-sections along the shared height and kept as the line through
644/// its ends where every station lies near it, that departure stated as the
645/// section's tolerance.
646///
647/// `None` where the axes lean further, where the drums do not cross
648/// cleanly at every station (a crossing starting part way up, or a near
649/// touch), or where a station strays: the marcher answers those. An empty
650/// answer is drums that share no height.
651fn near_parallel_drums(
652    a: &SurfaceGeometry,
653    b: &SurfaceGeometry,
654    tol: Tolerances,
655) -> Option<Vec<SectionCurve>> {
656    const LEAN: f64 = 1e-3;
657    let (SurfaceGeometry::Cylinder(sa), SurfaceGeometry::Cylinder(sb)) = (a, b) else {
658        return None;
659    };
660    let (ca, cb) = (sa.cylinder(), sb.cylinder());
661    let (axis_a, axis_b) = (ca.axis(), cb.axis());
662    let (da, db) = (axis_a.direction.vector(), axis_b.direction.vector());
663    let (ra, rb) = (ca.radius(), cb.radius());
664    let cos = da.dot(db);
665    if da.cross(db).magnitude() > LEAN || cos.abs() < 0.5 {
666        return None;
667    }
668    let (pa, pb) = (axis_a.location, axis_b.location);
669    // The shared height, measured along the first axis.
670    let (_, (a0, a1)) = a.domain();
671    let (_, (b0, b1)) = b.domain();
672    let along = |v: f64| (pb - pa).dot(da) + v * cos;
673    let (lo, hi) = (
674        a0.min(a1).max(along(b0).min(along(b1))),
675        a0.max(a1).min(along(b0).max(along(b1))),
676    );
677    if !(lo.is_finite() && hi.is_finite()) {
678        return None;
679    }
680    if hi - lo <= tol.confusion() {
681        return Some(Vec::new());
682    }
683    // Where the two cross-sections at a station meet, left and right of
684    // the line of centres: the second drum's section is an ellipse only a
685    // square of its lean away from a circle, a stated part of the stray.
686    let meet = |z: f64| -> Option<[Point; 2]> {
687        let centre_a = pa + da * z;
688        let s = (centre_a - pb).dot(da) / cos;
689        let centre_b = pb + db * s;
690        let mut between = centre_b - centre_a;
691        between = between - da * between.dot(da);
692        let d = between.magnitude();
693        // Axes, or a touch, well inside the weld distance are one: the
694        // sliver between the drums is welded rather than sectioned. Half
695        // of it, so a sliver at the weld distance itself is sectioned
696        // whole rather than lost between the two readings.
697        let margin = tol.confusion() * 50.0;
698        if d <= margin || d >= ra + rb - margin || d <= (ra - rb).abs() + margin {
699            return None;
700        }
701        let x = (d * d + ra * ra - rb * rb) / (2.0 * d);
702        let h = (ra * ra - x * x).max(0.0).sqrt();
703        let ex = between / d;
704        let ey = da.cross(ex);
705        Some([centre_a + ex * x + ey * h, centre_a + ex * x - ey * h])
706    };
707    lines_through_stations(lo, hi, meet, rb * (1.0 / cos.abs() - 1.0), tol)
708}
709
710/// How far a near-parallel pair's sections may stray from the true
711/// crossing: what a fitted section typically carries.
712const NEAR_PARALLEL_STRAY: f64 = 1e-5;
713
714/// The two curves a near-parallel pair meets in over the height `lo..hi`,
715/// from where `meet` puts the crossing at each height: the line through the
716/// ends where every station lies within a micron of it, else a cubic
717/// through the stations at their heights, checked midway between them.
718/// Either is kept within [`NEAR_PARALLEL_STRAY`], the departure stated as
719/// its tolerance. `None` where a station has no clean crossing or the
720/// curve strays.
721fn lines_through_stations(
722    lo: f64,
723    hi: f64,
724    meet: impl Fn(f64) -> Option<[Point; 2]>,
725    stated: f64,
726    tol: Tolerances,
727) -> Option<Vec<SectionCurve>> {
728    const STATIONS: u32 = 32;
729    const STRAIGHT: f64 = 1e-6;
730    let at = |k: f64| (hi - lo).mul_add(k / f64::from(STATIONS), lo);
731    let heights: Vec<f64> = (0..=STATIONS).map(|k| at(f64::from(k))).collect();
732    let met: Vec<[Point; 2]> = heights.iter().map(|&z| meet(z)).collect::<Option<_>>()?;
733    let between: Vec<[Point; 2]> = (0..STATIONS)
734        .map(|k| meet(at(f64::from(k) + 0.5)))
735        .collect::<Option<_>>()?;
736    let mut out = Vec::with_capacity(2);
737    for side in 0..2 {
738        let (from, to) = (met[0][side], met[met.len() - 1][side]);
739        let span = to - from;
740        let length = span.magnitude();
741        if length <= tol.confusion() {
742            return None;
743        }
744        let off_line = |p: Point| {
745            let t = (p - from).dot(span) / (length * length);
746            p.distance(from + span * t)
747        };
748        let stray = met
749            .iter()
750            .chain(&between)
751            .map(|pair| off_line(pair[side]))
752            .fold(0.0_f64, f64::max);
753        let (curve, stray): (Curve, f64) = if stray <= STRAIGHT {
754            (
755                ogeom_geom::LineCurve::segment(from, to, tol).ok()?.into(),
756                stray,
757            )
758        } else {
759            let points: Vec<Point> = met.iter().map(|pair| pair[side]).collect();
760            let fitted =
761                ogeom_geom::fit::fit_points_at(&heights, &points, 3, tol.confusion(), tol).ok()?;
762            let curve: Curve = fitted.curve.into();
763            let mut worst = fitted.error;
764            for (k, pair) in (0..STATIONS).zip(&between) {
765                let p = curve.point_at(at(f64::from(k) + 0.5), tol).ok()?;
766                worst = worst.max(p.distance(pair[side]));
767            }
768            (curve, worst)
769        };
770        let tolerance = stray + stated + tol.confusion();
771        if tolerance > NEAR_PARALLEL_STRAY {
772            return None;
773        }
774        out.push(SectionCurve {
775            curve,
776            on_a: None,
777            on_b: None,
778            tolerance,
779            exact: false,
780            closed: false,
781            tangential: false,
782        });
783    }
784    Some(out)
785}
786
787/// A drum passing clean through a ball: every line along the drum meets
788/// the ball twice, within the drum's height.
789///
790/// Then each of the two loops the drum and ball meet in is a function of
791/// the angle round the drum: at each angle, where the line along the drum
792/// enters and leaves the ball is a quadratic's two roots. The loops are
793/// sampled so, exactly, and fitted closed, the fit's error stated as the
794/// section's tolerance. Marched instead, a drum that all but grazes the
795/// ball's far side leaves loops long and thin, and the trace wanders along
796/// them past any bound. `None` where some line misses or grazes the ball,
797/// or leaves the drum's height: the marcher answers those.
798fn ball_through_drum(
799    a: &SurfaceGeometry,
800    b: &SurfaceGeometry,
801    tol: Tolerances,
802) -> Option<Vec<SectionCurve>> {
803    const SAMPLES: u32 = 256;
804    const STRAY: f64 = 1e-5;
805    let (ball, drum, ball_first) = match (a, b) {
806        (SurfaceGeometry::Sphere(s), SurfaceGeometry::Cylinder(c)) => (s, c, true),
807        (SurfaceGeometry::Cylinder(c), SurfaceGeometry::Sphere(s)) => (s, c, false),
808        _ => return None,
809    };
810    let (sphere, cylinder) = (ball.sphere(), drum.cylinder());
811    let frame = cylinder.frame();
812    let (x, y, d) = (frame.x().vector(), frame.y().vector(), frame.z().vector());
813    let (origin, r) = (frame.origin(), cylinder.radius());
814    let (centre, big) = (sphere.centre(), sphere.radius());
815    let ball_frame = sphere.frame();
816    let (_, (h0, h1)) = drum.domain();
817    // A line that only just meets the ball leaves the loop turning sharply
818    // there; a tenth of the drum's radius of chord inside the ball keeps
819    // the loops smooth enough to fit.
820    let margin = r * 0.1;
821    // Where the line along the drum at `angle` enters and leaves the ball.
822    let heights = |angle: f64| -> Option<[f64; 2]> {
823        let foot = origin + (x * angle.cos() + y * angle.sin()) * r;
824        let w = foot - centre;
825        let half = d.dot(w);
826        let disc = half.mul_add(half, -(w.dot(w) - big * big));
827        if disc <= margin * margin {
828            return None;
829        }
830        let root = disc.sqrt();
831        let pair = [-half - root, -half + root];
832        pair.iter().all(|v| *v >= h0 && *v <= h1).then_some(pair)
833    };
834    let at = |angle: f64, v: f64| origin + (x * angle.cos() + y * angle.sin()) * r + d * v;
835    // The ball's longitude and latitude of a point, as its chart reads them.
836    let on_ball = |p: Point, before: Option<Point2>| -> Point2 {
837        let local = ball_frame.to_local(p);
838        let lat = local.z.atan2(local.x.hypot(local.y));
839        let mut lon = local.y.atan2(local.x).rem_euclid(core::f64::consts::TAU);
840        if let Some(prev) = before {
841            while lon - prev.x > core::f64::consts::PI {
842                lon -= core::f64::consts::TAU;
843            }
844            while prev.x - lon > core::f64::consts::PI {
845                lon += core::f64::consts::TAU;
846            }
847        }
848        Point2::new(lon, lat)
849    };
850    let angle_of = |k: f64| core::f64::consts::TAU * k / f64::from(SAMPLES);
851    let params: Vec<f64> = (0..=SAMPLES).map(|k| angle_of(f64::from(k))).collect();
852    let mut sampled: Vec<[f64; 2]> = Vec::with_capacity(params.len());
853    for &angle in &params {
854        sampled.push(heights(angle)?);
855    }
856    let mut out = Vec::with_capacity(2);
857    for side in 0..2 {
858        let points: Vec<Point> = params
859            .iter()
860            .zip(&sampled)
861            .map(|(&angle, pair)| at(angle, pair[side]))
862            .collect();
863        let on_drum: Vec<Point2> = params
864            .iter()
865            .zip(&sampled)
866            .map(|(&angle, pair)| Point2::new(angle, pair[side]))
867            .collect();
868        let mut on_sphere: Vec<Point2> = Vec::with_capacity(points.len());
869        for p in &points {
870            let q = on_ball(*p, on_sphere.last().copied());
871            on_sphere.push(q);
872        }
873        let target = tol.confusion() * 10.0;
874        let curve: Curve = ogeom_geom::fit::fit_points_at(&params, &points, 3, target, tol)
875            .ok()?
876            .curve
877            .into();
878        let drum_image: PlanarCurve =
879            ogeom_geom::fit::fit_points_2d_at(&params, &on_drum, 3, target, tol)
880                .ok()?
881                .curve
882                .into();
883        let ball_image: PlanarCurve =
884            ogeom_geom::fit::fit_points_2d_at(&params, &on_sphere, 3, target, tol)
885                .ok()?
886                .curve
887                .into();
888        // Checked at the samples and midway between them: the curve, and
889        // each surface read through its image, against the true meeting.
890        let mut stray = 0.0_f64;
891        for k in 0..(2 * SAMPLES) {
892            let angle = angle_of(f64::from(k) / 2.0);
893            let truth = at(angle, heights(angle)?[side]);
894            let on_curve = curve.point_at(angle, tol).ok()?;
895            let uv = drum_image.point_at(angle, tol).ok()?;
896            let through_drum = drum.point_at(uv.x, uv.y, tol).ok()?;
897            let uv = ball_image.point_at(angle, tol).ok()?;
898            let through_ball = ball.point_at(uv.x, uv.y, tol).ok()?;
899            stray = stray
900                .max(truth.distance(on_curve))
901                .max(truth.distance(through_drum))
902                .max(truth.distance(through_ball));
903        }
904        let tolerance = stray.max(tol.confusion());
905        if tolerance > STRAY {
906            return None;
907        }
908        let (on_a, on_b) = if ball_first {
909            (ball_image, drum_image)
910        } else {
911            (drum_image, ball_image)
912        };
913        out.push(SectionCurve {
914            curve,
915            on_a: Some(on_a),
916            on_b: Some(on_b),
917            tolerance,
918            exact: false,
919            closed: true,
920            tangential: false,
921        });
922    }
923    Some(out)
924}
925
926/// A plane leaning all but along a drum's axis, over the drum's height.
927///
928/// The closed form is an ellipse whose long axis is the drum's radius over
929/// the lean, kilometres for a facet group fitted a hundred-thousandth off
930/// a hole's axis. Its parameter spans the few millimetres the drum holds in
931/// a millionth of a turn, and crossings solved on it are only as good as
932/// that ruler. The crossing is solved instead in the drum's cross-sections
933/// along its height and kept as two lines where they hold, as
934/// [`near_parallel_drums`] does. `None` where the lean is exactly nothing
935/// (the closed form's lines are exact) or more than a thousandth, or where
936/// the plane does not cross the drum cleanly all the way up.
937fn near_parallel_plane_drum(
938    a: &SurfaceGeometry,
939    b: &SurfaceGeometry,
940    tol: Tolerances,
941) -> Option<Vec<SectionCurve>> {
942    const LEAN: f64 = 1e-3;
943    const SPAN: f64 = 3e4;
944    let (plane, drum, surface) = match (a, b) {
945        (SurfaceGeometry::Plane(p), SurfaceGeometry::Cylinder(c)) => (p.plane(), c.cylinder(), b),
946        (SurfaceGeometry::Cylinder(c), SurfaceGeometry::Plane(p)) => (p.plane(), c.cylinder(), a),
947        _ => return None,
948    };
949    let axis = drum.axis();
950    let (d, r) = (axis.direction.vector(), drum.radius());
951    let n = plane.normal().vector();
952    let lean = n.dot(d).abs();
953    // Only where the ellipse is thirty metres or more across: there a
954    // parameter solved to its last billionth lands tens of nanometres off in
955    // space, past the weld of a face with tight edges. A shorter one is
956    // ruler enough, and its closed form crosses faster than a fitted curve.
957    if lean <= tol.angular() || lean > LEAN || r / lean < SPAN {
958        return None;
959    }
960    let across = n - d * n.dot(d);
961    let k = across.magnitude();
962    let e1 = across / k;
963    let e2 = d.cross(e1);
964    let (_, (lo, hi)) = surface.domain();
965    if !(lo.is_finite() && hi.is_finite()) || hi - lo <= tol.confusion() {
966        return None;
967    }
968    let meet = |z: f64| -> Option<[Point; 2]> {
969        let centre = axis.location + d * z;
970        let u = -plane.signed_distance_to(centre) / k;
971        let margin = tol.confusion() * 1e3;
972        if u.abs() >= r - margin {
973            return None;
974        }
975        let w = r.mul_add(r, -(u * u)).sqrt();
976        Some([centre + e1 * u + e2 * w, centre + e1 * u - e2 * w])
977    };
978    lines_through_stations(lo, hi, meet, 0.0, tol)
979}
980
981/// An exact curve dressed as a section, clipped to the surfaces it lies on.
982///
983/// The analytic layer works on the unbounded geometry (a plane and a cylinder
984/// meet in unbounded lines), but the *surfaces* carry finite extents, and a
985/// section running a billion units past both is not something an edge can be
986/// built on. A line is clipped to the parameter interval where it is inside
987/// both extents, through its exact pcurves; a curve wholly outside either
988/// extent is dropped, or the boolean above would see a phantom edge on a
989/// region the face does not have.
990///
991/// A *closed* curve partially outside an extent is kept whole: cutting it into
992/// arcs is the restriction problem, and the restriction that matters is the
993/// face's trim, which is the boolean's job. The extent here is only the
994/// surface's parameterization window.
995fn exact_section(
996    curve: Curve,
997    a: &SurfaceGeometry,
998    b: &SurfaceGeometry,
999    tol: Tolerances,
1000) -> Option<SectionCurve> {
1001    let closed = match &curve {
1002        Curve::Circle(_) | Curve::Ellipse(_) => true,
1003        _ => curve.is_closed(tol),
1004    };
1005    let range = curve.domain();
1006    let on_a = exact_pcurve(&curve, range, a, tol);
1007    let on_b = exact_pcurve(&curve, range, b, tol);
1008
1009    if let Curve::Line(_) = &curve {
1010        // Clip through whichever pcurves exist; a missing pcurve leaves that
1011        // surface's extent unenforced, which errs long rather than wrong.
1012        let mut interval = curve.domain();
1013        if let Some(p) = &on_a {
1014            interval = intersect_intervals(interval, inside_box(p, a))?;
1015        }
1016        if let Some(p) = &on_b {
1017            interval = intersect_intervals(interval, inside_box(p, b))?;
1018        }
1019        let (lo, hi) = interval;
1020        let Curve::Line(line) = &curve else {
1021            unreachable!()
1022        };
1023        let clipped: Curve = ogeom_geom::LineCurve::over(line.axis(), lo, hi)
1024            .ok()?
1025            .into();
1026        let clip2 = |p: &PlanarCurve| -> Option<PlanarCurve> {
1027            let PlanarCurve::Line(l) = p else {
1028                return Some(p.clone());
1029            };
1030            Some(Line2d::over(l.axis(), lo, hi).ok()?.into())
1031        };
1032        let (ca, cb) = (on_a.as_ref().and_then(clip2), on_b.as_ref().and_then(clip2));
1033        let tangential = touching_along(&clipped, ca.as_ref(), cb.as_ref(), a, b, tol);
1034        return Some(SectionCurve {
1035            on_a: ca,
1036            on_b: cb,
1037            tolerance: 0.0,
1038            exact: true,
1039            closed: false,
1040            tangential,
1041            curve: clipped,
1042        });
1043    }
1044
1045    // A closed curve: dropped only when wholly outside an extent it has a
1046    // pcurve to check against.
1047    for (pcurve, surface) in [(&on_a, a), (&on_b, b)] {
1048        if let Some(p) = pcurve
1049            && !touches_box(p, surface, tol)
1050        {
1051            return None;
1052        }
1053    }
1054    let tangential = touching_along(&curve, on_a.as_ref(), on_b.as_ref(), a, b, tol);
1055    Some(SectionCurve {
1056        on_a,
1057        on_b,
1058        tolerance: 0.0,
1059        exact: true,
1060        closed,
1061        tangential,
1062        curve,
1063    })
1064}
1065
1066/// Whether the surfaces touch along an exact curve rather than crossing it:
1067/// their normals parallel at stations along its length.
1068///
1069/// Decided through the curve's own pcurves, which is where the normals can
1070/// be read without inverting anything. A curve missing a pcurve on either
1071/// surface is reported as a crossing, the honest default, since a section
1072/// nobody can place in a chart is one nothing can classify as contact
1073/// either.
1074fn touching_along(
1075    curve: &Curve,
1076    on_a: Option<&PlanarCurve>,
1077    on_b: Option<&PlanarCurve>,
1078    a: &SurfaceGeometry,
1079    b: &SurfaceGeometry,
1080    tol: Tolerances,
1081) -> bool {
1082    // The chart position of a sample: through the pcurve where one exists,
1083    // through the surface's own closed-form inversion where not. A meridian
1084    // through a sphere's poles has no pcurve (its longitude jumps half a
1085    // turn at each pole), but every *point* of it inverts fine, and a
1086    // tangency that would be missed for want of a pcurve becomes a crossing
1087    // section lying along a face's own boundary, which is the worst thing a
1088    // section can be.
1089    let sample_uv = |pc: Option<&PlanarCurve>,
1090                     surface: &SurfaceGeometry,
1091                     t: f64|
1092     -> Option<ogeom_math::Point2> {
1093        if let Some(pc) = pc {
1094            return pc.point_at(t, tol).ok();
1095        }
1096        let p = curve.point_at(t, tol).ok()?;
1097        chart_inversion(surface, p, tol)
1098    };
1099    let (lo, hi) = curve.domain();
1100    // Offsets chosen off the round fractions, so a curve through a chart
1101    // degeneracy (a meridian's poles sit at quarters of its turn) is
1102    // sampled beside the degenerate points rather than on them. A sample
1103    // whose inversion still fails is skipped: the point says nothing,
1104    // not that the surfaces cross.
1105    let mut judged = 0_usize;
1106    for f in [0.07, 0.19, 0.37, 0.53, 0.71, 0.89] {
1107        let t = (hi - lo).mul_add(f, lo);
1108        let (Some(ua), Some(ub)) = (sample_uv(on_a, a, t), sample_uv(on_b, b, t)) else {
1109            continue;
1110        };
1111        let (Ok(na), Ok(nb)) = (a.normal_at(ua.x, ua.y, tol), b.normal_at(ub.x, ub.y, tol)) else {
1112            continue;
1113        };
1114        if na.vector().cross(nb.vector()).magnitude() > 1e-6 {
1115            return false;
1116        }
1117        judged += 1;
1118    }
1119    judged >= 3
1120}
1121
1122/// A point's chart position on an analytic surface, by closed form.
1123fn chart_inversion(
1124    surface: &SurfaceGeometry,
1125    p: ogeom_math::Point,
1126    tol: Tolerances,
1127) -> Option<ogeom_math::Point2> {
1128    use ogeom_math::elementary;
1129    let (u, v) = match surface {
1130        SurfaceGeometry::Plane(s) => elementary::plane_parameters(&s.plane(), p),
1131        SurfaceGeometry::Cylinder(s) => {
1132            elementary::cylinder_parameters(&s.cylinder(), p, tol).ok()?
1133        }
1134        SurfaceGeometry::Cone(s) => elementary::cone_parameters(&s.cone(), p, tol).ok()?,
1135        SurfaceGeometry::Sphere(s) => elementary::sphere_parameters(&s.sphere(), p, tol).ok()?,
1136        SurfaceGeometry::Torus(s) => elementary::torus_parameters(&s.torus(), p, tol).ok()?,
1137        _ => return None,
1138    };
1139    Some(ogeom_math::Point2::new(u, v))
1140}
1141
1142/// The parameter interval over which a 2D line stays inside a surface's
1143/// parameter box. `None` when it never enters.
1144fn inside_box(pcurve: &PlanarCurve, surface: &SurfaceGeometry) -> Option<(f64, f64)> {
1145    // The pcurve as a point and a rate along its own parameter: a line, or
1146    // a degree-one spline of two points (a cone's ruling), linear in it.
1147    let (o, d) = match pcurve {
1148        PlanarCurve::Line(line) => {
1149            let axis = line.axis();
1150            (axis.location, axis.direction.vector())
1151        }
1152        PlanarCurve::BSpline(spline)
1153            if spline.knots().degree() == 1 && spline.control_points().len() == 2 =>
1154        {
1155            let (t0, t1) = spline.knots().domain();
1156            let (p0, p1) = (
1157                spline.control_points()[0].point(),
1158                spline.control_points()[1].point(),
1159            );
1160            if t1 <= t0 {
1161                return None;
1162            }
1163            let rate = (p1 - p0) / (t1 - t0);
1164            (p0 - rate * t0, rate)
1165        }
1166        _ => return None,
1167    };
1168    let ((ua, ub), (va, vb)) = surface.domain();
1169
1170    // The slab test, one axis at a time.
1171    let mut lo = f64::NEG_INFINITY;
1172    let mut hi = f64::INFINITY;
1173    for (origin, direction, low, high) in [(o.x, d.x, ua, ub), (o.y, d.y, va, vb)] {
1174        if direction.abs() <= f64::MIN_POSITIVE {
1175            if origin < low || origin > high {
1176                return None;
1177            }
1178            continue;
1179        }
1180        let (a, b) = ((low - origin) / direction, (high - origin) / direction);
1181        let (near, far) = if a < b { (a, b) } else { (b, a) };
1182        lo = lo.max(near);
1183        hi = hi.min(far);
1184    }
1185    if lo >= hi {
1186        return None;
1187    }
1188    Some((lo, hi))
1189}
1190
1191/// Whether a closed pcurve may pass through the surface's box.
1192fn touches_box(pcurve: &PlanarCurve, surface: &SurfaceGeometry, tol: Tolerances) -> bool {
1193    use ogeom_geom::Curve2d;
1194    let ((ua, ub), (va, vb)) = surface.domain();
1195    let (lo, hi) = pcurve.domain();
1196    // Asked of the spans between samples, not the samples alone: a plane all
1197    // but parallel to a cylinder's axis meets it in an ellipse kilometres
1198    // long, whose image on the cylinder's chart sweeps through a window a few
1199    // millimetres tall in a sliver of its turn, between any two samples.
1200    // Each span is taken as its chord's box widened by the chord's length,
1201    // which holds the curve between them wherever it bends no tighter than
1202    // the samples are apart. Kept wrongly, a curve costs a section the trim
1203    // then cuts to nothing; dropped wrongly, the faces never split.
1204    const SPANS: u32 = 64;
1205    let points: Vec<Option<ogeom_math::Point2>> = (0..=SPANS)
1206        .map(|i| {
1207            pcurve
1208                .point_at(lo + (hi - lo) * f64::from(i) / f64::from(SPANS), tol)
1209                .ok()
1210        })
1211        .collect();
1212    points.windows(2).any(|pair| {
1213        let (Some(p), Some(q)) = (pair[0], pair[1]) else {
1214            return false;
1215        };
1216        let pad = p.distance(q);
1217        // Periodic directions always contain; only a bounded one excludes.
1218        let u_ok =
1219            surface.is_periodic_u() || (p.x.max(q.x) + pad >= ua && p.x.min(q.x) - pad <= ub);
1220        let v_ok =
1221            surface.is_periodic_v() || (p.y.max(q.y) + pad >= va && p.y.min(q.y) - pad <= vb);
1222        u_ok && v_ok
1223    })
1224}
1225
1226/// The overlap of two intervals. `None` when they miss.
1227fn intersect_intervals(a: (f64, f64), b: Option<(f64, f64)>) -> Option<(f64, f64)> {
1228    let b = b?;
1229    let (lo, hi) = (a.0.max(b.0), a.1.min(b.1));
1230    if lo >= hi {
1231        return None;
1232    }
1233    Some((lo, hi))
1234}
1235
1236/// The general path: seed, trace, fit.
1237fn marched(
1238    a: &SurfaceGeometry,
1239    b: &SurfaceGeometry,
1240    options: IntersectOptions,
1241    tol: Tolerances,
1242) -> OgeomResult<SurfaceIntersection> {
1243    let traced = branches(a, b, options.marching, tol)?;
1244    if traced.is_empty() {
1245        return Ok(SurfaceIntersection::Apart);
1246    }
1247    let mut out = Vec::with_capacity(traced.len());
1248    let mut contacts: Vec<crate::march::Traced> = Vec::new();
1249    for branch in &traced {
1250        // A branch along which the two surfaces share their normal is a
1251        // tangency, not a crossing: the marcher's seeding cannot tell the
1252        // noise floor of a tangential valley from a genuine sign change, and
1253        // what it traces there is a stalled fragment of the valley, not a
1254        // section. The valley is still a curve, though, and the tangential
1255        // walker is the one that can follow it, so the fragment becomes a
1256        // seed rather than a discard, and what comes back is marked as
1257        // contact so nobody classifies by it.
1258        if branch_is_tangential(a, b, branch, tol)? {
1259            if let Some(contact) = walk_contact(a, b, branch, &contacts, options.marching, tol)? {
1260                contacts.push(contact);
1261            }
1262            continue;
1263        }
1264        if branch.stopped == crate::march::Stopped::RanOut {
1265            ogeom_bail!(
1266                NotDone,
1267                "a marched section ran out of its point budget before \
1268                 finishing; the seam is longer than the chord affords and \
1269                 fitting the truncation would state a curve that is not there"
1270            );
1271        }
1272        // A fit past its budget is still honest data: the error it reached
1273        // is carried on the record and every consumer widens by it: an
1274        // imported part's ragged pair can trace branches nothing fits, and
1275        // those sections fall outside every trim downstream. Only a trace
1276        // cut off by the point budget, refused above, states a curve that
1277        // is not there. (A boolean marching an *exact* pair whose image has
1278        // no closed form holds its own marched sections to a budget, in
1279        // its own fallback, where a miss is a miss.)
1280        for fitted in fitted_in_pieces(a, b, branch, options.tolerance, tol)? {
1281            out.push(SectionCurve {
1282                curve: fitted.curve.into(),
1283                on_a: Some(fitted.on_a.into()),
1284                on_b: Some(fitted.on_b.into()),
1285                // The sum of the stated parts: the trace is within its chord of
1286                // the truth, the fit within its error of the trace.
1287                tolerance: options.marching.chord + fitted.fit_error,
1288                exact: false,
1289                closed: fitted.closed,
1290                tangential: false,
1291            });
1292        }
1293    }
1294    for contact in &contacts {
1295        let fitted = approximate_branch(a, b, contact, options.tolerance, tol)?;
1296        out.push(SectionCurve {
1297            curve: fitted.curve.into(),
1298            on_a: Some(fitted.on_a.into()),
1299            on_b: Some(fitted.on_b.into()),
1300            tolerance: options.marching.chord + fitted.fit_error,
1301            exact: false,
1302            closed: fitted.closed,
1303            tangential: true,
1304        });
1305    }
1306    if out.is_empty() {
1307        return Ok(SurfaceIntersection::Apart);
1308    }
1309    Ok(SurfaceIntersection::Along(out))
1310}
1311
1312/// A traced branch fitted, in pieces where whole it will not fit.
1313///
1314/// A trace winding several turns round a drum (a thread's flank meeting a
1315/// bore) is long and turns the same way throughout, and one fit of it can
1316/// run out of room and come back with an error of the drum's size. An open
1317/// branch whose fit misses by more than a hundred times its tolerance, or
1318/// strays farther from the trace than the finest step the marcher took
1319/// along it, is split at its middle sample and each half fitted the same
1320/// way, down to a floor of samples and depth; the pieces meet at the shared
1321/// sample. The marcher shortens its step where the section turns sharply
1322/// (round a neck a thousandth wide where a drill all but touches a torus),
1323/// and a fit missing by more than that step there wobbles across the neck.
1324/// A closed branch is split the same way, its two halves open and meeting
1325/// at both ends: a loop round a thin drum lying all but tangent inside a
1326/// wider one turns sharply at its tip, and fitted whole it can come back
1327/// off the trace by the drum's size. A fit that misses its tolerance by
1328/// less stands whole, its error stated: a caller takes one curve per branch
1329/// where it can, and a few microns do not warrant more. So does a branch no
1330/// split helps.
1331fn fitted_in_pieces(
1332    a: &SurfaceGeometry,
1333    b: &SurfaceGeometry,
1334    branch: &crate::march::Traced,
1335    tolerance: f64,
1336    tol: Tolerances,
1337) -> OgeomResult<Vec<crate::approx::IntersectionCurve>> {
1338    const DEPTH: u32 = 6;
1339    const FLOOR: usize = 16;
1340    fn go(
1341        a: &SurfaceGeometry,
1342        b: &SurfaceGeometry,
1343        branch: &crate::march::Traced,
1344        tolerance: f64,
1345        depth: u32,
1346        tol: Tolerances,
1347    ) -> OgeomResult<Vec<crate::approx::IntersectionCurve>> {
1348        let whole = approximate_branch(a, b, branch, tolerance, tol)?;
1349        // The finest step the marcher took between the branch's ends: the
1350        // first and last steps land on a patch edge or close the loop, and
1351        // their length says nothing of how sharply the section turns.
1352        let points = &branch.points;
1353        let inner = points.get(1..points.len().saturating_sub(1)).unwrap_or(&[]);
1354        let step = inner
1355            .windows(2)
1356            .map(|w| w[0].distance(w[1]))
1357            .fold(f64::INFINITY, f64::min);
1358        if whole.met
1359            || whole.fit_error <= step.min(tolerance * 1e2)
1360            || depth == 0
1361            || branch.points.len() < 2 * FLOOR
1362        {
1363            return Ok(vec![whole]);
1364        }
1365        let middle = branch.points.len() / 2;
1366        // A half of a loop is open: it stops where the other half starts.
1367        let stopped = if branch.closed() {
1368            crate::march::Stopped::Stalled
1369        } else {
1370            branch.stopped
1371        };
1372        let half = |range: core::ops::RangeInclusive<usize>| crate::march::Traced {
1373            points: branch.points[range.clone()].to_vec(),
1374            on_a: branch.on_a[range.clone()].to_vec(),
1375            on_b: branch.on_b[range].to_vec(),
1376            stopped,
1377        };
1378        let mut pieces = go(a, b, &half(0..=middle), tolerance, depth - 1, tol)?;
1379        pieces.extend(go(
1380            a,
1381            b,
1382            &half(middle..=branch.points.len() - 1),
1383            tolerance,
1384            depth - 1,
1385            tol,
1386        )?);
1387        // Worse in pieces than whole (a trace that is noise, not length):
1388        // the whole stands.
1389        let worst = pieces.iter().map(|p| p.fit_error).fold(0.0_f64, f64::max);
1390        Ok(if worst < whole.fit_error {
1391            pieces
1392        } else {
1393            vec![whole]
1394        })
1395    }
1396    go(a, b, branch, tolerance, DEPTH, tol)
1397}
1398
1399/// Follow the contact a tangential fragment sits on, unless one already
1400/// traced covers it.
1401///
1402/// A tangential valley hands the crossing marcher several stalled fragments
1403/// (the seeds converge onto the contact from wherever they started and
1404/// wander there), so the fragments are candidates for *one* curve, not
1405/// several. A fragment whose middle already lies on a traced contact is one
1406/// of those repeats.
1407fn walk_contact(
1408    a: &SurfaceGeometry,
1409    b: &SurfaceGeometry,
1410    fragment: &crate::march::Traced,
1411    already: &[crate::march::Traced],
1412    marching: Marching,
1413    tol: Tolerances,
1414) -> OgeomResult<Option<crate::march::Traced>> {
1415    let middle = fragment.points.len() / 2;
1416    let Some(point) = fragment.points.get(middle).copied() else {
1417        return Ok(None);
1418    };
1419    for traced in already {
1420        // Traced points sit a step apart, so "on this curve" has to allow
1421        // half a step of gap to the nearest sample plus the chord budget.
1422        let spacing = traced
1423            .points
1424            .windows(2)
1425            .map(|w| w[0].distance(w[1]))
1426            .fold(0.0f64, f64::max);
1427        let near = traced
1428            .points
1429            .iter()
1430            .map(|p| p.distance(point))
1431            .fold(f64::INFINITY, f64::min);
1432        if near <= spacing.mul_add(0.5, marching.chord.max(tol.confusion())) {
1433            return Ok(None);
1434        }
1435    }
1436    let seed = crate::march::Contact {
1437        point,
1438        on_a: fragment.on_a[middle],
1439        on_b: fragment.on_b[middle],
1440    };
1441    // The walker refuses a seed that is not a contact; that refusal is an
1442    // answer, not a failure: the fragment simply had nothing to follow.
1443    // A walk that stalls where it started says the same thing in points:
1444    // too few to fit, so there is no contact curve to report here.
1445    Ok(trace_tangential(a, b, seed, marching, tol)
1446        .ok()
1447        .filter(|traced| traced.points.len() >= 4))
1448}
1449
1450/// Whether a traced branch runs along a tangency of the two surfaces:
1451/// their normals parallel, sampled along its length.
1452fn branch_is_tangential(
1453    a: &SurfaceGeometry,
1454    b: &SurfaceGeometry,
1455    branch: &crate::march::Traced,
1456    tol: Tolerances,
1457) -> OgeomResult<bool> {
1458    use ogeom_geom::Surface as _;
1459    let count = branch.points.len();
1460    if count == 0 {
1461        return Ok(true);
1462    }
1463    for k in 0..5 {
1464        let i = (k * (count - 1)) / 4;
1465        let (ua, va) = branch.on_a[i.min(count - 1)];
1466        let (ub, vb) = branch.on_b[i.min(count - 1)];
1467        let (dau, dav) = a.d1_at(ua, va, tol)?;
1468        let (dbu, dbv) = b.d1_at(ub, vb, tol)?;
1469        let na = dau.cross(dav);
1470        let nb = dbu.cross(dbv);
1471        let (ma, mb) = (na.magnitude(), nb.magnitude());
1472        if ma <= tol.confusion() || mb <= tol.confusion() {
1473            continue;
1474        }
1475        // The threshold carries the fitted world: a blend surface within a
1476        // fit tolerance of true tangency crosses its host at an angle that
1477        // grows as the square root of that tolerance, and calling such a
1478        // graze transversal splits faces along slivers no classifier can
1479        // hold. Genuinely transversal analytic pairs meeting under two
1480        // degrees are the pathology, not the rule.
1481        if na.cross(nb).magnitude() / (ma * mb) > 3e-2 {
1482            return Ok(false);
1483        }
1484    }
1485    Ok(true)
1486}
1487
1488/// The exact pcurve of a curve lying on a surface, where the projection has
1489/// a closed form; `None` where it does not.
1490///
1491/// Public because the boolean's same-domain handling needs it: two faces on
1492/// one geometric surface may still carry different charts, and the other
1493/// face's boundary edges have to be spoken in this face's parameters before
1494/// they can split it.
1495#[must_use]
1496pub fn exact_pcurve_of(
1497    curve: &Curve,
1498    surface: &SurfaceGeometry,
1499    tol: Tolerances,
1500) -> Option<PlanarCurve> {
1501    exact_pcurve(curve, curve.domain(), surface, tol)
1502}
1503
1504/// As [`exact_pcurve_of`], with the parameter range the caller actually
1505/// uses.
1506///
1507/// A curve's chart image can depend on *which part* of the curve is meant: a
1508/// ruling on a cone crosses the apex, and its angle on the far nappe is half
1509/// a turn from its angle on the near one. The curve's own domain may span
1510/// both (an imported line's usually does), so a caller that knows its edge's
1511/// range must say so, or the exact projection may answer for the wrong side.
1512#[must_use]
1513pub fn exact_pcurve_over(
1514    curve: &Curve,
1515    range: (f64, f64),
1516    surface: &SurfaceGeometry,
1517    tol: Tolerances,
1518) -> Option<PlanarCurve> {
1519    exact_pcurve(curve, range, surface, tol)
1520}
1521
1522/// The exact pcurve of an analytic curve on an analytic surface, where the
1523/// projection has a closed form.
1524///
1525/// Same-parameter by construction: each 2D curve inherits the 3D curve's own
1526/// parameterization, so the two evaluate to the same point of the intersection
1527/// at the same `t`. The cases are the ones where that inheritance is exact;
1528/// anything else returns `None` rather than a fit, because an *exact* result
1529/// with a fitted pcurve would be a curve whose descriptions disagree by an
1530/// amount nothing on it records.
1531fn exact_pcurve(
1532    curve: &Curve,
1533    range: (f64, f64),
1534    surface: &SurfaceGeometry,
1535    tol: Tolerances,
1536) -> Option<PlanarCurve> {
1537    // A trim is a statement about *where* on a curve, not about what it is:
1538    // the basis carries the shape and the trim shares its parameter, so the
1539    // pcurve is the basis's own pcurve trimmed the same way. Answered here
1540    // rather than in every surface's own case, because the answer does not
1541    // depend on the surface at all. A *reversed* trim renumbers, and is left
1542    // alone rather than mis-read.
1543    if let Curve::Trimmed(trimmed) = curve
1544        && !trimmed.is_reversed()
1545    {
1546        let window = ogeom_geom::Curve3d::domain(&**trimmed);
1547        let basis = exact_pcurve(trimmed.basis(), range, surface, tol)?;
1548        return ogeom_geom::Trimmed2d::new(basis, window.0, window.1, tol)
1549            .ok()
1550            .map(Into::into);
1551    }
1552    // The cases below read a circle's or an ellipse's frame as the way its
1553    // parameter runs, so one running backwards is read as its forward
1554    // spelling, the same point at every parameter.
1555    let forward = match curve {
1556        Curve::Circle(c) if c.is_reversed() => Some(Curve::Circle(c.forward(tol).ok()?)),
1557        Curve::Ellipse(e) if e.is_reversed() => Some(Curve::Ellipse(e.forward(tol).ok()?)),
1558        _ => None,
1559    };
1560    if let Some(forward) = forward {
1561        return exact_pcurve(&forward, range, surface, tol);
1562    }
1563    match surface {
1564        SurfaceGeometry::Plane(p) => on_plane(curve, p.plane(), tol),
1565        SurfaceGeometry::Cylinder(c) => on_cylinder(curve, range, c.cylinder(), tol),
1566        SurfaceGeometry::Sphere(s) => on_sphere(curve, range, s.sphere(), tol),
1567        SurfaceGeometry::Torus(t) => on_torus(curve, range, t.torus(), tol),
1568        SurfaceGeometry::Cone(c) => on_cone(curve, range, c.cone(), tol),
1569        _ => None,
1570    }
1571}
1572
1573/// The parameter window of a circle's pcurve that inherits the circle's own
1574/// parameter: the whole turn, widened to the range the edge uses. An arc
1575/// whose range runs past the turn's end (its start late in the turn, its
1576/// end past the circle's origin) is read on the same straight chart line
1577/// continued, not wrapped.
1578fn circle_window(range: (f64, f64)) -> (f64, f64) {
1579    let tau = core::f64::consts::TAU;
1580    if range.0.is_finite() && range.1.is_finite() {
1581        (range.0.min(range.1).min(0.0), range.0.max(range.1).max(tau))
1582    } else {
1583        (0.0, tau)
1584    }
1585}
1586
1587/// The pcurve of a curve on a cone, for the two straight-line families.
1588///
1589/// A ruling (through the apex, on the surface) runs at constant `u`; a
1590/// circle perpendicular to the axis, centred on it, with the radius the cone
1591/// has at that height, runs at constant `v`. Both inherit the 3D curve's own
1592/// parameter, the circle with phase and winding exactly as the cylinder case.
1593/// The ruling's angle is measured over `range`, because the same line has
1594/// the opposite angle on the other side of the apex.
1595fn on_cone(
1596    curve: &Curve,
1597    range: (f64, f64),
1598    cone: ogeom_math::Cone,
1599    tol: Tolerances,
1600) -> Option<PlanarCurve> {
1601    let frame = cone.frame();
1602    let axis_z = frame.z().vector();
1603    let tau = core::f64::consts::TAU;
1604    match curve {
1605        Curve::Circle(c) => {
1606            let circle = c.circle();
1607            if circle.frame().z().vector().cross(axis_z).magnitude() > tol.angular() {
1608                return None;
1609            }
1610            let local = frame.to_local(circle.centre());
1611            if local.x.hypot(local.y) > tol.confusion() {
1612                return None;
1613            }
1614            // The cone's radius at the circle's height must be the circle's,
1615            // or (past the apex, on the far nappe, where the radius runs
1616            // negative) its negative: the same parallel half a turn round.
1617            let expected = cone
1618                .half_angle()
1619                .tan()
1620                .mul_add(local.z, cone.reference_radius());
1621            let turned = if (expected - circle.radius()).abs() <= tol.confusion() * 10.0 {
1622                0.0
1623            } else if (expected + circle.radius()).abs() <= tol.confusion() * 10.0 {
1624                core::f64::consts::PI
1625            } else {
1626                return None;
1627            };
1628            let start = circle.centre() + circle.frame().x().vector() * circle.radius();
1629            let at = frame.to_local(start);
1630            let phase = at.y.atan2(at.x) + turned;
1631            let winding = circle.frame().z().vector().dot(axis_z).signum();
1632            let towards =
1633                ogeom_math::Direction2::new(ogeom_math::Vector2::new(winding, 0.0), tol).ok()?;
1634            Some(
1635                Line2d::over(
1636                    ogeom_math::Axis2::new(Point2::new(phase, local.z), towards),
1637                    circle_window(range).0,
1638                    circle_window(range).1,
1639                )
1640                .ok()?
1641                .into(),
1642            )
1643        }
1644        Curve::Line(line) => {
1645            // A ruling: verified by sample, not assumed: three points on
1646            // the surface pin a line to it.
1647            let axis = line.axis();
1648            let on = |t: f64| {
1649                let p = axis.location + axis.direction.vector() * t;
1650                cone.distance_to(p) <= tol.confusion() * 10.0
1651            };
1652            if !on(0.0) || !on(1.0) || !on(-1.0) {
1653                return None;
1654            }
1655            // A ruling reaching the tip may be *stated* from the apex
1656            // itself (where the angle is atan2(0, 0), garbage) and its
1657            // own domain usually spans both nappes, where the angles differ
1658            // by half a turn. Measure the angle at whichever end of the
1659            // *used* range stands farthest from the axis: that is the side
1660            // the caller means.
1661            let (lo, hi) = if range.0.is_finite() && range.1.is_finite() && range.0 != range.1 {
1662                range
1663            } else {
1664                line.domain()
1665            };
1666            // Only the used range votes. The line's own origin is stated
1667            // wherever the file likes (some writers park it hundreds of
1668            // kilometres down the infinite line, past the apex on the other
1669            // nappe), and letting it compete reads the angle half a turn
1670            // from the side the edge actually uses.
1671            let mut local: Option<ogeom_math::Point> = None;
1672            for t in [lo, hi] {
1673                if !t.is_finite() {
1674                    continue;
1675                }
1676                let candidate = frame.to_local(axis.location + axis.direction.vector() * t);
1677                if local.is_none_or(|held| candidate.x.hypot(candidate.y) > held.x.hypot(held.y)) {
1678                    local = Some(candidate);
1679                }
1680            }
1681            let local = local?;
1682            if local.x.hypot(local.y) <= tol.confusion() {
1683                return None;
1684            }
1685            let u = local.y.atan2(local.x).rem_euclid(tau);
1686            // Same-parameter exactly: a degree-one spline over the used
1687            // range maps t linearly onto the chart column, whatever rate
1688            // the slant climbs at.
1689            let v_at = |t: f64| {
1690                frame
1691                    .to_local(axis.location + axis.direction.vector() * t)
1692                    .z
1693            };
1694            let knots = ogeom_math::KnotVector::new(vec![lo, lo, hi, hi], 1).ok()?;
1695            Some(
1696                ogeom_geom::BSpline2d::new(
1697                    knots,
1698                    vec![Point2::new(u, v_at(lo)), Point2::new(u, v_at(hi))],
1699                    tol,
1700                )
1701                .ok()?
1702                .into(),
1703            )
1704        }
1705        _ => None,
1706    }
1707}
1708
1709/// The pcurve of a circle on a torus, for the two families that are straight
1710/// lines in `(u, v)`.
1711///
1712/// A *parallel* (centred on the axis, in a plane perpendicular to it) runs
1713/// at constant `v`; a *tube circle* (minor radius, centred on the tube's
1714/// spine, in a plane through the axis) runs at constant `u`. Both inherit
1715/// the circle's own angle, phase and winding included, exactly as the
1716/// cylinder case does. Fillet faces are tori more often than not, so the
1717/// STEP reader is the chief consumer.
1718fn on_torus(
1719    curve: &Curve,
1720    range: (f64, f64),
1721    torus: ogeom_math::Torus,
1722    tol: Tolerances,
1723) -> Option<PlanarCurve> {
1724    let Curve::Circle(c) = curve else {
1725        return None;
1726    };
1727    let circle = c.circle();
1728    let frame = torus.frame();
1729    let axis_z = frame.z().vector();
1730    let normal = circle.frame().z().vector();
1731    let local = frame.to_local(circle.centre());
1732
1733    // A parallel of the sweep.
1734    if normal.cross(axis_z).magnitude() <= tol.angular()
1735        && local.x.hypot(local.y) <= tol.confusion()
1736    {
1737        let sin_v = local.z / torus.minor_radius();
1738        // On its own side of the axis, or (on a spindle, whose tube swallows
1739        // the axis) on the tube's folded half past it, where the sweep's
1740        // radius runs negative: the same parallel half a turn round.
1741        let (cos_v, turned) = [
1742            (circle.radius() - torus.major_radius(), 0.0),
1743            (
1744                -circle.radius() - torus.major_radius(),
1745                core::f64::consts::PI,
1746            ),
1747        ]
1748        .into_iter()
1749        .map(|(reach, turned)| (reach / torus.minor_radius(), turned))
1750        .find(|(cos_v, _)| (sin_v.hypot(*cos_v) - 1.0).abs() <= tol.confusion())?;
1751        let v = sin_v.atan2(cos_v);
1752        let start = circle.centre() + circle.frame().x().vector() * circle.radius();
1753        let at = frame.to_local(start);
1754        let phase = at.y.atan2(at.x) + turned;
1755        let winding = normal.dot(axis_z).signum();
1756        let towards =
1757            ogeom_math::Direction2::new(ogeom_math::Vector2::new(winding, 0.0), tol).ok()?;
1758        return Some(
1759            Line2d::over(
1760                ogeom_math::Axis2::new(Point2::new(phase, v), towards),
1761                circle_window(range).0,
1762                circle_window(range).1,
1763            )
1764            .ok()?
1765            .into(),
1766        );
1767    }
1768
1769    // A circle of the tube.
1770    if (circle.radius() - torus.minor_radius()).abs() <= tol.confusion()
1771        && normal.dot(axis_z).abs() <= tol.angular()
1772        && (local.x.hypot(local.y) - torus.major_radius()).abs() <= tol.confusion()
1773        && local.z.abs() <= tol.confusion()
1774    {
1775        let u = local.y.atan2(local.x);
1776        let radial = frame.x().vector() * u.cos() + frame.y().vector() * u.sin();
1777        let xc = circle.frame().x().vector();
1778        let phase = xc.dot(axis_z).atan2(xc.dot(radial));
1779        let winding = normal.dot(radial.cross(axis_z)).signum();
1780        let towards =
1781            ogeom_math::Direction2::new(ogeom_math::Vector2::new(0.0, winding), tol).ok()?;
1782        return Some(
1783            Line2d::over(
1784                ogeom_math::Axis2::new(Point2::new(u, phase), towards),
1785                circle_window(range).0,
1786                circle_window(range).1,
1787            )
1788            .ok()?
1789            .into(),
1790        );
1791    }
1792    None
1793}
1794
1795/// Project a curve lying in a plane into the plane's own coordinates.
1796///
1797/// Exact for a line, a circle and an ellipse: the plane's frame is orthonormal,
1798/// so lengths and the curves' own parameterizations survive the projection
1799/// unchanged.
1800fn on_plane(curve: &Curve, plane: ogeom_math::Plane, tol: Tolerances) -> Option<PlanarCurve> {
1801    let frame = plane.frame();
1802    let flat = |p: Point| {
1803        let local = frame.to_local(p);
1804        Point2::new(local.x, local.y)
1805    };
1806    let flat_direction = |d: ogeom_math::Direction| {
1807        let tip = flat(frame.origin() + d.vector());
1808        ogeom_math::Direction2::new(tip - flat(frame.origin()), tol).ok()
1809    };
1810    match curve {
1811        Curve::Line(line) => {
1812            let axis = line.axis();
1813            let through = flat(axis.location);
1814            let direction = flat_direction(axis.direction)?;
1815            let (lo, hi) = line.domain();
1816            Some(
1817                Line2d::over(ogeom_math::Axis2::new(through, direction), lo, hi)
1818                    .ok()?
1819                    .into(),
1820            )
1821        }
1822        Curve::Circle(c) => {
1823            let circle = c.circle();
1824            let frame2 = Frame2::from_axes(
1825                flat(circle.centre()),
1826                flat_direction(circle.frame().x())?,
1827                flat_direction(circle.frame().y())?,
1828                tol,
1829            )
1830            .ok()?;
1831            Some(Circle2d::new(Circle2::new(frame2, circle.radius(), tol).ok()?).into())
1832        }
1833        Curve::Ellipse(e) => {
1834            let ellipse = e.ellipse();
1835            let frame2 = Frame2::from_axes(
1836                flat(ellipse.centre()),
1837                flat_direction(ellipse.frame().x())?,
1838                flat_direction(ellipse.frame().y())?,
1839                tol,
1840            )
1841            .ok()?;
1842            Some(
1843                Ellipse2d::new(
1844                    Ellipse2::new(frame2, ellipse.major_radius(), ellipse.minor_radius(), tol)
1845                        .ok()?,
1846                )
1847                .into(),
1848            )
1849        }
1850        Curve::BSpline(b) => {
1851            // Affine invariance: a (rational) B-spline in the plane projects
1852            // into the plane's own coordinates control point by control
1853            // point, knots and weights untouched: exact, and same-parameter
1854            // by construction.
1855            let control = b
1856                .control_points()
1857                .iter()
1858                .map(|w| ogeom_math::Weighted::new(flat((*w).point()), w.weight, tol))
1859                .collect::<Result<Vec<_>, _>>()
1860                .ok()?;
1861            Some(
1862                ogeom_geom::BSpline2d::rational(b.knots().clone(), control)
1863                    .ok()?
1864                    .into(),
1865            )
1866        }
1867        _ => None,
1868    }
1869}
1870
1871/// The pcurve of a curve on a cylinder, where it is a straight line in
1872/// parameter space.
1873///
1874/// A line along the axis runs at constant `u`; a full circle around it runs at
1875/// constant `v`. Both are lines in `(u, v)`, exactly, and both inherit the 3D
1876/// curve's own parameter: height for the line, angle for the circle.
1877fn on_cylinder(
1878    curve: &Curve,
1879    range: (f64, f64),
1880    cylinder: ogeom_math::Cylinder,
1881    tol: Tolerances,
1882) -> Option<PlanarCurve> {
1883    let axis = cylinder.axis();
1884    let frame = cylinder.frame();
1885    match curve {
1886        Curve::Line(line) => {
1887            // Parallel to the axis, on the surface.
1888            let direction = line.axis().direction;
1889            let along = direction.dot(axis.direction);
1890            if !direction.is_parallel(axis.direction, tol) {
1891                return None;
1892            }
1893            let through = line.axis().location;
1894            if (axis.distance_to(through) - cylinder.radius()).abs() > tol.confusion() {
1895                return None;
1896            }
1897            let local = frame.to_local(through);
1898            let u = local.y.atan2(local.x).rem_euclid(core::f64::consts::TAU);
1899            // The 3D line's parameter is length from its origin; at constant u
1900            // the pcurve's `v` runs at the same rate, signed by whether the
1901            // line runs with the axis or against it.
1902            let (lo, hi) = line.domain();
1903            let start = Point2::new(u, local.z);
1904            let towards =
1905                ogeom_math::Direction2::new(ogeom_math::Vector2::new(0.0, along.signum()), tol)
1906                    .ok()?;
1907            Some(
1908                Line2d::over(ogeom_math::Axis2::new(start, towards), lo, hi)
1909                    .ok()?
1910                    .into(),
1911            )
1912        }
1913        Curve::Circle(c) => {
1914            let circle = c.circle();
1915            // Perpendicular to the axis, centred on it, of the same radius.
1916            if circle
1917                .frame()
1918                .z()
1919                .cross_with(axis.direction.vector())
1920                .magnitude()
1921                > tol.angular()
1922            {
1923                return None;
1924            }
1925            if axis.distance_to(circle.centre()) > tol.confusion() {
1926                return None;
1927            }
1928            if (circle.radius() - cylinder.radius()).abs() > tol.confusion() {
1929                return None;
1930            }
1931            let local = frame.to_local(circle.centre());
1932            // Where the circle's own angle zero sits in the cylinder's angle,
1933            // and which way its parameter runs around the axis. A section
1934            // circle inherits its winding from the pair that made it, and one
1935            // wound against the cylinder's `u` (a circle cut by a plane whose
1936            // normal opposes the axis) runs its pcurve in `-u`. Written `+u`
1937            // unconditionally, the pcurve evaluates half a turn away from the
1938            // curve, and the face's arrangement tears along a seam that is
1939            // not there.
1940            let start = circle.centre() + circle.frame().x().vector() * circle.radius();
1941            let at = frame.to_local(start);
1942            let phase = at.y.atan2(at.x);
1943            let winding = circle.frame().z().dot(axis.direction).signum();
1944            let towards =
1945                ogeom_math::Direction2::new(ogeom_math::Vector2::new(winding, 0.0), tol).ok()?;
1946            Some(
1947                Line2d::over(
1948                    ogeom_math::Axis2::new(Point2::new(phase, local.z), towards),
1949                    circle_window(range).0,
1950                    circle_window(range).1,
1951                )
1952                .ok()?
1953                .into(),
1954            )
1955        }
1956        Curve::Ellipse(_) => {
1957            // An oblique plane's section: its plan projection is the
1958            // cylinder's own cross-section circle traced *uniformly*, so
1959            // the chart trace is u = sยทt + ฯ†, v = cโ‚€ + aยทcos t + bยทsin t:
1960            // the trig-affine family. Derived from the curve's own
1961            // evaluations and verified by sample, never assumed.
1962            use ogeom_geom::Curve3d as _;
1963            let tau = core::f64::consts::TAU;
1964            let local = |t: f64| -> Option<ogeom_math::Point> {
1965                Some(frame.to_local(curve.point_at(t, tol).ok()?))
1966            };
1967            let l0 = local(0.0)?;
1968            let lq = local(tau / 4.0)?;
1969            let lh = local(tau / 2.0)?;
1970            // On the surface at all: plan radius must be the cylinder's.
1971            let r = cylinder.radius();
1972            for l in [&l0, &lq, &lh] {
1973                if (l.x.hypot(l.y) - r).abs() > tol.confusion() * 10.0 {
1974                    return None;
1975                }
1976            }
1977            let phase = l0.y.atan2(l0.x);
1978            // Winding from the quarter-turn sample: uniform tracing puts it
1979            // a quarter turn away, one side or the other.
1980            let uq = lq.y.atan2(lq.x);
1981            let step = (uq - phase).rem_euclid(tau);
1982            let winding = if (step - tau / 4.0).abs() < 1e-6 {
1983                1.0
1984            } else if (step - 3.0 * tau / 4.0).abs() < 1e-6 {
1985                -1.0
1986            } else {
1987                return None;
1988            };
1989            // Height coefficients from three samples.
1990            let c0 = f64::midpoint(l0.z, lh.z);
1991            let a = (l0.z - lh.z) / 2.0;
1992            let b = lq.z - c0;
1993            // The trig formula is global (cosine wraps, the linear angle
1994            // unwraps the chart), so the pcurve lives on whatever range the
1995            // edge actually spans, a loop crossing the period included.
1996            let candidate = ogeom_geom::Trig2d::new(
1997                Point2::new(phase, c0),
1998                ogeom_math::Vector2::new(winding, 0.0),
1999                ogeom_math::Vector2::new(0.0, a),
2000                ogeom_math::Vector2::new(0.0, b),
2001                range,
2002            )
2003            .ok()?;
2004            // The same-parameter law, verified at points the derivation
2005            // never touched, inside the range the edge will use.
2006            use ogeom_geom::Curve2d as _;
2007            for i in 0..7 {
2008                let t = range.0 + (range.1 - range.0) * (0.09 + 0.13 * f64::from(i)) / 0.91;
2009                let l = local(t)?;
2010                let chart = candidate.point_at(t, tol).ok()?;
2011                let du = (chart.x - l.y.atan2(l.x)).rem_euclid(tau);
2012                if du.min(tau - du) > 1e-9 {
2013                    return None;
2014                }
2015                if (chart.y - l.z).abs() > tol.confusion() * 10.0 {
2016                    return None;
2017                }
2018            }
2019            Some(PlanarCurve::Trig(candidate))
2020        }
2021        _ => None,
2022    }
2023}
2024
2025/// The pcurve of half a meridian: a great circle through both poles,
2026/// restricted to one side of them.
2027///
2028/// The whole circle has no chart image a single curve can carry (its
2029/// longitude jumps by half a turn at each pole), but each *half* does, and it
2030/// is a straight line. Writing the circle's own parameter as `t` and the
2031/// sphere's axis as `Z = cos ฮฑยทX + sin ฮฑยทY` in the circle's own frame, the
2032/// point's height above the equator is `rยทcos(t โˆ’ ฮฑ)`, so the latitude is
2033/// `asin(cos(t โˆ’ ฮฑ))`, which on `t โˆ’ ฮฑ โˆˆ [0, ฯ€]` is exactly `ฯ€/2 โˆ’ (t โˆ’ ฮฑ)`,
2034/// affine in `t`, with slope one. The longitude is constant on that half and
2035/// half a turn away on the other. So the pcurve is a vertical line in the
2036/// chart, sharing the circle's parameter exactly, and the caller's `range` is
2037/// what says which half is meant.
2038///
2039/// The half is not assumed: the returned line is lifted back through the
2040/// sphere at stations along the range and compared against the circle, so a
2041/// misread orientation is caught here rather than downstream.
2042fn on_meridian(
2043    curve: &ogeom_geom::CircleCurve,
2044    range: (f64, f64),
2045    sphere: ogeom_math::Sphere,
2046    tol: Tolerances,
2047) -> Option<PlanarCurve> {
2048    let circle = curve.circle();
2049    // A reversed circle runs its own angle backwards, and the shifted angle
2050    // below is measured in the *curve's* parameter, so the sign travels with
2051    // it: the sweep flips and so do both the latitude's slope and which half
2052    // of the circle a range names.
2053    let sweep = if curve.is_reversed() { -1.0 } else { 1.0 };
2054    let frame = sphere.frame();
2055    let z = frame.z().vector();
2056    // A great circle: the sphere's own centre and radius, in a plane holding
2057    // the axis. Anything else is not a meridian.
2058    if circle.centre().distance(sphere.centre()) > tol.confusion() {
2059        return None;
2060    }
2061    if (circle.radius() - sphere.radius()).abs() > tol.confusion() {
2062        return None;
2063    }
2064    let (cx, cy) = (circle.frame().x().vector(), circle.frame().y().vector());
2065    let (xz, yz) = (cx.dot(z), cy.dot(z));
2066    // The axis must lie *in* the circle's plane, or the circle is neither a
2067    // parallel nor a meridian and has no closed-form chart image at all.
2068    if xz.hypot(yz) < 1.0 - tol.angular() {
2069        return None;
2070    }
2071    let raw_alpha = yz.atan2(xz);
2072    // `w` is the circle's own horizontal direction: the axis turned a quarter
2073    // turn within the circle's plane.
2074    let w = cx * -raw_alpha.sin() + cy * raw_alpha.cos();
2075    let local = frame.to_local(sphere.centre() + w);
2076    let longitude = local.y.atan2(local.x);
2077
2078    let half = core::f64::consts::PI;
2079    let mid = f64::midpoint(range.0, range.1);
2080    // Where the range sits relative to the poles, in the shifted angle
2081    // `x = sweepยทt โˆ’ ฮฑ` that measures the descent from the north pole.
2082    let x_mid = (sweep * mid - raw_alpha).rem_euclid(core::f64::consts::TAU);
2083    let x_mid = if x_mid > half {
2084        x_mid - core::f64::consts::TAU
2085    } else {
2086        x_mid
2087    };
2088    let span = sweep * (range.1 - range.0);
2089    let (mut x0, mut x1) = (x_mid - span / 2.0, x_mid + span / 2.0);
2090    if x0 > x1 {
2091        core::mem::swap(&mut x0, &mut x1);
2092    }
2093    // The turn count `ฮฑ` was written with is what decides whether the
2094    // latitude comes out inside the chart or a whole turn away from it, so
2095    // the branch the range actually sits on is the one the line is built
2096    // from.
2097    let alpha = sweep.mul_add(mid, -x_mid);
2098    let slack = tol.parametric().max(1e-9);
2099    let (axis_point, towards) = if x0 >= -slack && x1 <= half + slack {
2100        // The descending half: latitude ฯ€/2 โˆ’ (sweepยทt โˆ’ ฮฑ), longitude
2101        // constant.
2102        (
2103            Point2::new(longitude, half.mul_add(0.5, alpha)),
2104            ogeom_math::Vector2::new(0.0, -sweep),
2105        )
2106    } else if x0 >= -half - slack && x1 <= slack {
2107        // The ascending half, half a turn round the chart.
2108        (
2109            Point2::new(longitude + half, half.mul_add(0.5, -alpha)),
2110            ogeom_math::Vector2::new(0.0, sweep),
2111        )
2112    } else {
2113        // The range straddles a pole: no one line covers it.
2114        return None;
2115    };
2116    let towards = ogeom_math::Direction2::new(towards, tol).ok()?;
2117    let margin = (range.1 - range.0) * 0.25;
2118    let line: PlanarCurve = Line2d::over(
2119        ogeom_math::Axis2::new(axis_point, towards),
2120        range.0 - margin,
2121        range.1 + margin,
2122    )
2123    .ok()?
2124    .into();
2125
2126    // Measured, not assumed: the chart line lifted back through the sphere is
2127    // the circle it claims to be.
2128    for k in 0..=4 {
2129        let t = (range.1 - range.0).mul_add(f64::from(k) / 4.0, range.0);
2130        let uv = line.point_at(t, tol).ok()?;
2131        let lifted = ogeom_math::elementary::sphere_at(&sphere, uv.x, uv.y).point;
2132        let want = curve.point_at(t, tol).ok()?;
2133        if lifted.distance(want) > tol.confusion() {
2134            return None;
2135        }
2136    }
2137    Some(line)
2138}
2139
2140/// The pcurve of a circle on a sphere: a parallel of latitude, or one half of
2141/// a meridian.
2142fn on_sphere(
2143    curve: &Curve,
2144    range: (f64, f64),
2145    sphere: ogeom_math::Sphere,
2146    tol: Tolerances,
2147) -> Option<PlanarCurve> {
2148    let Curve::Circle(c) = curve else {
2149        return None;
2150    };
2151    let circle = c.circle();
2152    let frame = sphere.frame();
2153    // Perpendicular to the sphere's axis and centred on it: a parallel of
2154    // latitude, which is a horizontal line in (longitude, latitude).
2155    if circle
2156        .frame()
2157        .z()
2158        .cross_with(frame.z().vector())
2159        .magnitude()
2160        > tol.angular()
2161    {
2162        return on_meridian(c, range, sphere, tol);
2163    }
2164    let local = frame.to_local(circle.centre());
2165    if local.x.abs() > tol.confusion() || local.y.abs() > tol.confusion() {
2166        return None;
2167    }
2168    let latitude = (local.z / sphere.radius()).clamp(-1.0, 1.0).asin();
2169    // Sanity: the circle's radius must be the parallel's.
2170    if (circle.radius() - sphere.radius() * latitude.cos()).abs() > tol.confusion() {
2171        return None;
2172    }
2173    let start = circle.centre() + circle.frame().x().vector() * circle.radius();
2174    let at = frame.to_local(start);
2175    let phase = at.y.atan2(at.x);
2176    // Phase and winding exactly as the cylinder case: a parallel whose own
2177    // axis opposes the sphere's marches its angle *down* the longitude.
2178    let winding = circle.frame().z().vector().dot(frame.z().vector()).signum();
2179    let towards = ogeom_math::Direction2::new(ogeom_math::Vector2::new(winding, 0.0), tol).ok()?;
2180    Some(
2181        Line2d::over(
2182            ogeom_math::Axis2::new(Point2::new(phase, latitude), towards),
2183            circle_window(range).0,
2184            circle_window(range).1,
2185        )
2186        .ok()?
2187        .into(),
2188    )
2189}
2190
2191#[cfg(test)]
2192#[allow(clippy::unwrap_used, clippy::expect_used)]
2193mod tests {
2194    use super::*;
2195    use ogeom_geom::{Curve2d, Curve3d, CylinderSurface, PlaneSurface, SphereSurface};
2196    use ogeom_math::{Cylinder, Direction, Frame, Plane, Sphere, Vector};
2197
2198    const T: Tolerances = Tolerances::millimetres();
2199
2200    fn sphere(centre: Point, radius: f64) -> SurfaceGeometry {
2201        SphereSurface::new(Sphere::centred(centre, radius, T).unwrap()).into()
2202    }
2203
2204    fn cylinder(axis: Vector, radius: f64) -> SurfaceGeometry {
2205        let frame = Frame::new(
2206            Point::ORIGIN,
2207            Direction::new(axis, T).unwrap(),
2208            Direction::from_cross(axis, Vector::new(0.3, 0.5, 0.9), T).unwrap(),
2209            T,
2210        )
2211        .unwrap();
2212        CylinderSurface::new(Cylinder::new(frame, radius, T).unwrap(), (-4.0, 4.0))
2213            .unwrap()
2214            .into()
2215    }
2216
2217    fn plane(origin: Point, normal: Vector) -> SurfaceGeometry {
2218        PlaneSurface::over(
2219            Plane::through(origin, Direction::new(normal, T).unwrap()),
2220            (-6.0, 6.0),
2221            (-6.0, 6.0),
2222        )
2223        .unwrap()
2224        .into()
2225    }
2226
2227    /// Same-parameter: pcurve lifted through its surface equals the 3D curve,
2228    /// at the same parameter, everywhere sampled.
2229    fn assert_same_parameter(
2230        section: &SectionCurve,
2231        surface: &SurfaceGeometry,
2232        pcurve: &PlanarCurve,
2233        samples: usize,
2234    ) {
2235        let (lo, hi) = section.curve.domain();
2236        let (plo, phi) = pcurve.domain();
2237        assert!(
2238            (lo - plo).abs() < 1e-9 && (hi - phi).abs() < 1e-9,
2239            "domains disagree: [{lo}, {hi}] against [{plo}, {phi}]"
2240        );
2241        for i in 0..=samples {
2242            #[allow(clippy::cast_precision_loss)]
2243            let t = lo + (hi - lo) * i as f64 / samples as f64;
2244            let on_curve = section.curve.point_at(t, T).unwrap();
2245            let at = pcurve.point_at(t, T).unwrap();
2246            let lifted = surface.point_at(at.x, at.y, T).unwrap();
2247            assert!(
2248                on_curve.is_equal(lifted, T),
2249                "at t = {t}: curve {on_curve:?}, lifted {lifted:?}"
2250            );
2251        }
2252    }
2253
2254    #[test]
2255    fn an_analytic_pair_comes_back_exact_with_matching_pcurves() {
2256        // A plane through a cylinder's axis: two lines, and every description
2257        // agrees at the same parameter, which is the claim edges carry and
2258        // booleans rely on.
2259        let drum = cylinder(Vector::Z, 2.0);
2260        let cut = plane(Point::ORIGIN, Vector::X);
2261        let SurfaceIntersection::Along(curves) =
2262            intersect_surfaces(&drum, &cut, IntersectOptions::default(), T).unwrap()
2263        else {
2264            panic!("a plane through a cylinder meets it along curves");
2265        };
2266        assert_eq!(curves.len(), 2);
2267        for section in &curves {
2268            assert!(section.exact);
2269            assert!((section.tolerance - 0.0).abs() < f64::EPSILON);
2270            let on_a = section.on_a.as_ref().expect("a line has a cylinder pcurve");
2271            let on_b = section.on_b.as_ref().expect("and a plane pcurve");
2272            assert_same_parameter(section, &drum, on_a, 50);
2273            assert_same_parameter(section, &cut, on_b, 50);
2274        }
2275    }
2276
2277    #[test]
2278    fn an_oblique_cut_gives_the_ellipse_a_trig_pcurve_on_the_drum() {
2279        // The oblique ellipse's pcurve runs linearly in the chart angle and
2280        // sinusoidally in height (the trig-affine family), exactly,
2281        // same-parameter, both sides.
2282        let drum = cylinder(Vector::Z, 2.0);
2283        let angle: f64 = 0.5;
2284        let cut = plane(Point::ORIGIN, Vector::new(0.0, angle.sin(), angle.cos()));
2285        let SurfaceIntersection::Along(curves) =
2286            intersect_surfaces(&drum, &cut, IntersectOptions::default(), T).unwrap()
2287        else {
2288            panic!("an oblique plane meets the cylinder along its ellipse");
2289        };
2290        assert_eq!(curves.len(), 1);
2291        let section = &curves[0];
2292        assert!(section.exact);
2293        assert!(matches!(section.curve, Curve::Ellipse(_)));
2294        let on_drum = section
2295            .on_a
2296            .as_ref()
2297            .expect("the oblique ellipse now carries its cylinder pcurve");
2298        assert!(
2299            matches!(on_drum, PlanarCurve::Trig(_)),
2300            "the chart trace is trig-affine: {on_drum:?}"
2301        );
2302        assert_same_parameter(section, &drum, on_drum, 60);
2303        let on_plane = section.on_b.as_ref().expect("and its plane pcurve");
2304        assert_same_parameter(section, &cut, on_plane, 60);
2305    }
2306
2307    #[test]
2308    fn a_perpendicular_cut_gives_a_circle_with_a_straight_pcurve() {
2309        let drum = cylinder(Vector::Z, 2.0);
2310        let cut = plane(Point::new(0.0, 0.0, 1.0), Vector::Z);
2311        let SurfaceIntersection::Along(curves) =
2312            intersect_surfaces(&drum, &cut, IntersectOptions::default(), T).unwrap()
2313        else {
2314            panic!("expected curves");
2315        };
2316        assert_eq!(curves.len(), 1);
2317        let section = &curves[0];
2318        assert!(section.closed);
2319        assert!(matches!(section.curve, Curve::Circle(_)));
2320        // On the cylinder the circle is a horizontal line in (u, v).
2321        assert!(matches!(
2322            section.on_a.as_ref().unwrap(),
2323            PlanarCurve::Line(_)
2324        ));
2325        assert_same_parameter(section, &drum, section.on_a.as_ref().unwrap(), 60);
2326        assert_same_parameter(section, &cut, section.on_b.as_ref().unwrap(), 60);
2327    }
2328
2329    #[test]
2330    fn coaxial_cylinder_and_sphere_give_circles_with_pcurves_on_both() {
2331        let drum = cylinder(Vector::Z, 1.5);
2332        let ball = sphere(Point::ORIGIN, 3.0);
2333        let SurfaceIntersection::Along(curves) =
2334            intersect_surfaces(&drum, &ball, IntersectOptions::default(), T).unwrap()
2335        else {
2336            panic!("expected curves");
2337        };
2338        assert_eq!(curves.len(), 2);
2339        for section in &curves {
2340            assert!(section.exact);
2341            assert_same_parameter(section, &drum, section.on_a.as_ref().unwrap(), 40);
2342            assert_same_parameter(section, &ball, section.on_b.as_ref().unwrap(), 40);
2343        }
2344    }
2345
2346    fn torus(origin: Point, axis: Vector, major: f64, minor: f64) -> SurfaceGeometry {
2347        let frame = Frame::new(
2348            origin,
2349            Direction::new(axis, T).unwrap(),
2350            Direction::from_cross(axis, Vector::new(0.3, 0.5, 0.9), T).unwrap(),
2351            T,
2352        )
2353        .unwrap();
2354        ogeom_geom::TorusSurface::new(ogeom_math::Torus::new(frame, major, minor, T).unwrap())
2355            .into()
2356    }
2357
2358    #[test]
2359    fn an_axis_normal_plane_meets_a_torus_in_two_parallels_with_pcurves() {
2360        let ring = torus(Point::ORIGIN, Vector::Z, 2.0, 0.5);
2361        let cut = plane(Point::new(0.0, 0.0, 0.3), Vector::Z);
2362        let SurfaceIntersection::Along(curves) =
2363            intersect_surfaces(&ring, &cut, IntersectOptions::default(), T).unwrap()
2364        else {
2365            panic!("an axis-normal plane through the tube meets it along curves");
2366        };
2367        assert_eq!(curves.len(), 2);
2368        let spread = 0.5_f64.mul_add(0.5, -(0.3 * 0.3)).sqrt();
2369        let mut radii: Vec<f64> = curves
2370            .iter()
2371            .map(|s| {
2372                let Curve::Circle(c) = &s.curve else {
2373                    panic!("a parallel is a circle");
2374                };
2375                c.circle().radius()
2376            })
2377            .collect();
2378        radii.sort_by(|a, b| a.partial_cmp(b).unwrap());
2379        assert!((radii[0] - (2.0 - spread)).abs() < 1e-12);
2380        assert!((radii[1] - (2.0 + spread)).abs() < 1e-12);
2381        for section in &curves {
2382            assert!(section.exact);
2383            assert_same_parameter(section, &ring, section.on_a.as_ref().unwrap(), 48);
2384            assert_same_parameter(section, &cut, section.on_b.as_ref().unwrap(), 48);
2385        }
2386    }
2387
2388    #[test]
2389    fn the_plane_a_ball_rolls_on_touches_its_torus_along_the_circle_it_rolled() {
2390        // Tangency with length is reported as the curve it is (the way a
2391        // tangent plane reports its line on a cylinder), because the blend
2392        // machinery builds faces whose boundaries are exactly these circles,
2393        // and a Touching with no curve in it would read as a refusal upstream.
2394        let ring = torus(Point::ORIGIN, Vector::Z, 2.0, 0.5);
2395        let cut = plane(Point::new(0.0, 0.0, 0.5), Vector::Z);
2396        let SurfaceIntersection::Along(curves) =
2397            intersect_surfaces(&ring, &cut, IntersectOptions::default(), T).unwrap()
2398        else {
2399            panic!("the rolling plane touches along a circle, not at points");
2400        };
2401        assert_eq!(curves.len(), 1);
2402        let Curve::Circle(c) = &curves[0].curve else {
2403            panic!("the tangency is a circle");
2404        };
2405        assert!((c.circle().radius() - 2.0).abs() < 1e-12);
2406        assert_same_parameter(&curves[0], &ring, curves[0].on_a.as_ref().unwrap(), 48);
2407        assert_same_parameter(&curves[0], &cut, curves[0].on_b.as_ref().unwrap(), 48);
2408    }
2409
2410    #[test]
2411    fn a_coaxial_cylinder_meets_a_torus_in_two_parallels_and_touches_in_one() {
2412        let ring = torus(Point::ORIGIN, Vector::Z, 2.0, 0.5);
2413        let drum = cylinder(Vector::Z, 2.2);
2414        let SurfaceIntersection::Along(curves) =
2415            intersect_surfaces(&drum, &ring, IntersectOptions::default(), T).unwrap()
2416        else {
2417            panic!("a coaxial cylinder through the tube meets it along curves");
2418        };
2419        assert_eq!(curves.len(), 2);
2420        for section in &curves {
2421            assert!(section.exact);
2422            let Curve::Circle(c) = &section.curve else {
2423                panic!("a parallel is a circle");
2424            };
2425            assert!((c.circle().radius() - 2.2).abs() < 1e-12);
2426            assert_same_parameter(section, &drum, section.on_a.as_ref().unwrap(), 48);
2427            assert_same_parameter(section, &ring, section.on_b.as_ref().unwrap(), 48);
2428        }
2429
2430        // Tangent at the tube's outer equator: one circle, with both pcurves.
2431        let grazing = cylinder(Vector::Z, 2.5);
2432        let SurfaceIntersection::Along(touch) =
2433            intersect_surfaces(&grazing, &ring, IntersectOptions::default(), T).unwrap()
2434        else {
2435            panic!("the grazing cylinder touches along the equator");
2436        };
2437        assert_eq!(touch.len(), 1);
2438        assert_same_parameter(&touch[0], &grazing, touch[0].on_a.as_ref().unwrap(), 48);
2439        assert_same_parameter(&touch[0], &ring, touch[0].on_b.as_ref().unwrap(), 48);
2440    }
2441
2442    #[test]
2443    fn coaxial_tori_are_the_same_or_meet_in_parallels() {
2444        let ring = torus(Point::ORIGIN, Vector::Z, 2.0, 0.5);
2445        assert!(matches!(
2446            intersect_surfaces(&ring, &ring.clone(), IntersectOptions::default(), T).unwrap(),
2447            SurfaceIntersection::Same
2448        ));
2449
2450        // The same tube lifted half a radius: the profile circles cross
2451        // twice, and each crossing revolves into a parallel shared exactly.
2452        let lifted = torus(Point::new(0.0, 0.0, 0.5), Vector::Z, 2.0, 0.5);
2453        let SurfaceIntersection::Along(curves) =
2454            intersect_surfaces(&ring, &lifted, IntersectOptions::default(), T).unwrap()
2455        else {
2456            panic!("lifted coaxial tori meet along curves");
2457        };
2458        assert_eq!(curves.len(), 2);
2459        for section in &curves {
2460            assert!(section.exact);
2461            assert_same_parameter(section, &ring, section.on_a.as_ref().unwrap(), 48);
2462            assert_same_parameter(section, &lifted, section.on_b.as_ref().unwrap(), 48);
2463        }
2464    }
2465
2466    #[test]
2467    fn a_pair_with_no_closed_form_comes_back_fitted_with_pcurves() {
2468        // Crossed cylinders: the marched path, end to end through one call.
2469        let a = cylinder(Vector::Z, 1.0);
2470        let b = cylinder(Vector::X, 1.6);
2471        let options = IntersectOptions {
2472            tolerance: 1e-5,
2473            marching: Marching {
2474                chord: 1e-5,
2475                ..Marching::default()
2476            },
2477        };
2478        let SurfaceIntersection::Along(curves) = intersect_surfaces(&a, &b, options, T).unwrap()
2479        else {
2480            panic!("crossed cylinders meet along curves");
2481        };
2482        assert_eq!(curves.len(), 2);
2483        for section in &curves {
2484            assert!(!section.exact);
2485            assert!(section.closed);
2486            assert!(
2487                section.tolerance <= 1e-5 + 1e-4,
2488                "got {}",
2489                section.tolerance
2490            );
2491            assert!(section.on_a.is_some() && section.on_b.is_some());
2492
2493            // The fitted curve lies on both cylinders to its stated tolerance.
2494            let (lo, hi) = section.curve.domain();
2495            for i in 0..=200 {
2496                #[allow(clippy::cast_precision_loss)]
2497                let t = lo + (hi - lo) * f64::from(i) / 200.0;
2498                let p = section.curve.point_at(t, T).unwrap();
2499                let (SurfaceGeometry::Cylinder(x), SurfaceGeometry::Cylinder(y)) = (&a, &b) else {
2500                    unreachable!()
2501                };
2502                let off = x
2503                    .cylinder()
2504                    .distance_to(p)
2505                    .abs()
2506                    .max(y.cylinder().distance_to(p).abs());
2507                assert!(
2508                    off <= section.tolerance * 2.0,
2509                    "at t = {t} the fitted curve is {off:e} off, tolerance {}",
2510                    section.tolerance
2511                );
2512            }
2513        }
2514    }
2515
2516    /// A plane all but parallel to a drum's axis meets it in an ellipse ten
2517    /// metres long, which crosses the drum's few units of height only in a
2518    /// sliver of its turn. It is still a section of the two.
2519    #[test]
2520    fn a_plane_all_but_along_the_axis_still_meets_a_short_drum() {
2521        let drum = cylinder(Vector::Z, 1.0);
2522        let wall: SurfaceGeometry = PlaneSurface::over(
2523            Plane::through(
2524                Point::new(0.0, 0.6, 0.0),
2525                Direction::new(Vector::new(0.0, 1.0, 1e-4), T).unwrap(),
2526            ),
2527            (-1e9, 1e9),
2528            (-1e9, 1e9),
2529        )
2530        .unwrap()
2531        .into();
2532        let met = intersect_surfaces(&wall, &drum, IntersectOptions::default(), T).unwrap();
2533        let SurfaceIntersection::Along(sections) = met else {
2534            panic!("the wall crosses the drum: {met:?}");
2535        };
2536        assert_eq!(sections.len(), 1);
2537        let curve = &sections[0].curve;
2538        let (lo, hi) = curve.domain();
2539        let inside = (0..=100_000).any(|k| {
2540            let p = curve
2541                .point_at(lo + (hi - lo) * f64::from(k) / 100_000.0, T)
2542                .unwrap();
2543            p.z.abs() <= 4.0
2544        });
2545        assert!(inside, "and the section runs through the drum's height");
2546    }
2547
2548    /// Every point of a section within its stated tolerance of both
2549    /// surfaces, sampled along it.
2550    fn on_both(section: &SectionCurve, a: &SurfaceGeometry, b: &SurfaceGeometry) {
2551        let (lo, hi) = section.curve.domain();
2552        for k in 0..=64 {
2553            let p = section
2554                .curve
2555                .point_at(lo + (hi - lo) * f64::from(k) / 64.0, T)
2556                .unwrap();
2557            for surface in [a, b] {
2558                let off = match surface {
2559                    SurfaceGeometry::Plane(plane) => plane.plane().signed_distance_to(p).abs(),
2560                    SurfaceGeometry::Cylinder(drum) => {
2561                        let axis = drum.cylinder().axis();
2562                        let rel = p - axis.location;
2563                        let d = axis.direction.vector();
2564                        ((rel - d * rel.dot(d)).magnitude() - drum.cylinder().radius()).abs()
2565                    }
2566                    _ => unreachable!("planes and drums only"),
2567                };
2568                assert!(
2569                    off <= section.tolerance + 1e-9,
2570                    "{p:?} is {off:e} off, stated {:e}",
2571                    section.tolerance
2572                );
2573            }
2574        }
2575    }
2576
2577    /// A plane leaning two hundred-thousandths off a drum's axis, grazing
2578    /// it: the closed form's ellipse is fifty metres long, its parameter
2579    /// too coarse for the drum's eight units of height. The two sections
2580    /// come back as curves along that height, within their stated
2581    /// tolerance of both surfaces.
2582    #[test]
2583    fn a_plane_all_but_along_a_drums_axis_meets_it_in_two_near_lines() {
2584        let drum = cylinder(Vector::Z, 1.0);
2585        let wall: SurfaceGeometry = PlaneSurface::over(
2586            Plane::through(
2587                Point::new(0.0, 0.99, 0.0),
2588                Direction::new(Vector::new(0.0, 1.0, 2e-5), T).unwrap(),
2589            ),
2590            (-1e9, 1e9),
2591            (-1e9, 1e9),
2592        )
2593        .unwrap()
2594        .into();
2595        let met = intersect_surfaces(&wall, &drum, IntersectOptions::default(), T).unwrap();
2596        let SurfaceIntersection::Along(sections) = met else {
2597            panic!("the wall crosses the drum: {met:?}");
2598        };
2599        assert_eq!(sections.len(), 2);
2600        for section in &sections {
2601            assert!(section.tolerance > 0.0 && section.tolerance <= 1e-5);
2602            on_both(section, &wall, &drum);
2603        }
2604    }
2605
2606    /// Two drums whose axes lean five hundred-thousandths apart meet in two
2607    /// curves all but straight, returned as such over the height they share
2608    /// rather than marched.
2609    #[test]
2610    fn drums_all_but_parallel_meet_in_two_near_lines() {
2611        let drill = cylinder(Vector::Z, 1.0);
2612        let frame = Frame::new(
2613            Point::new(1.5, 0.0, 0.0),
2614            Direction::new(Vector::new(5e-5, 0.0, 1.0), T).unwrap(),
2615            Direction::X,
2616            T,
2617        )
2618        .unwrap();
2619        let bore: SurfaceGeometry =
2620            CylinderSurface::new(Cylinder::new(frame, 1.0, T).unwrap(), (-3.0, 3.0))
2621                .unwrap()
2622                .into();
2623        let met = intersect_surfaces(&drill, &bore, IntersectOptions::default(), T).unwrap();
2624        let SurfaceIntersection::Along(sections) = met else {
2625            panic!("the drums cross: {met:?}");
2626        };
2627        assert_eq!(sections.len(), 2);
2628        for section in &sections {
2629            assert!(!section.exact && section.tolerance <= 1e-5);
2630            let (lo, hi) = section.curve.domain();
2631            let (p, q) = (
2632                section.curve.point_at(lo, T).unwrap(),
2633                section.curve.point_at(hi, T).unwrap(),
2634            );
2635            assert!(
2636                (p.z - q.z).abs() > 5.9,
2637                "over the shared height: {p:?} {q:?}"
2638            );
2639            on_both(section, &drill, &bore);
2640        }
2641    }
2642
2643    #[test]
2644    fn exact_lines_are_clipped_to_the_surfaces_extents() {
2645        // The analytic layer answers for the unbounded geometry; the surfaces
2646        // are finite. A section line a billion units long is not something an
2647        // edge can be built on, and one wholly outside the extents is a
2648        // phantom.
2649        let drum = cylinder(Vector::Z, 2.0);
2650        let cut = plane(Point::ORIGIN, Vector::X);
2651        let SurfaceIntersection::Along(curves) =
2652            intersect_surfaces(&drum, &cut, IntersectOptions::default(), T).unwrap()
2653        else {
2654            panic!("expected curves");
2655        };
2656        for section in &curves {
2657            let (lo, hi) = section.curve.domain();
2658            // Bounded by the cylinder's height, not by LINE_EXTENT.
2659            assert!(
2660                hi - lo <= 8.0 + 1e-9,
2661                "the line was not clipped: [{lo}, {hi}]"
2662            );
2663            let start = section.curve.point_at(lo, T).unwrap();
2664            let end = section.curve.point_at(hi, T).unwrap();
2665            assert!(start.z >= -4.0 - 1e-9 && end.z <= 4.0 + 1e-9);
2666        }
2667
2668        // A circle at a height the bounded cylinder does not reach is not an
2669        // intersection of these surfaces, however truly the unbounded ones
2670        // meet there.
2671        let high = plane(Point::new(0.0, 0.0, 10.0), Vector::Z);
2672        assert_eq!(
2673            intersect_surfaces(&drum, &high, IntersectOptions::default(), T).unwrap(),
2674            SurfaceIntersection::Apart
2675        );
2676    }
2677
2678    #[test]
2679    fn the_degenerate_answers_pass_through() {
2680        assert_eq!(
2681            intersect_surfaces(
2682                &sphere(Point::ORIGIN, 1.0),
2683                &sphere(Point::new(5.0, 0.0, 0.0), 1.0),
2684                IntersectOptions::default(),
2685                T
2686            )
2687            .unwrap(),
2688            SurfaceIntersection::Apart
2689        );
2690        assert_eq!(
2691            intersect_surfaces(
2692                &sphere(Point::ORIGIN, 1.0),
2693                &sphere(Point::ORIGIN, 1.0),
2694                IntersectOptions::default(),
2695                T
2696            )
2697            .unwrap(),
2698            SurfaceIntersection::Same
2699        );
2700        assert!(matches!(
2701            intersect_surfaces(
2702                &plane(Point::ORIGIN, Vector::Z),
2703                &sphere(Point::new(0.0, 0.0, 2.0), 2.0),
2704                IntersectOptions::default(),
2705                T
2706            )
2707            .unwrap(),
2708            SurfaceIntersection::Touching(ref p) if p.len() == 1
2709        ));
2710    }
2711
2712    #[test]
2713    fn unusable_options_are_refused() {
2714        let a = sphere(Point::ORIGIN, 1.0);
2715        let b = plane(Point::ORIGIN, Vector::Z);
2716        for tolerance in [0.0, -1.0, f64::NAN] {
2717            let options = IntersectOptions {
2718                tolerance,
2719                ..IntersectOptions::default()
2720            };
2721            assert!(intersect_surfaces(&a, &b, options, T).is_err());
2722        }
2723    }
2724
2725    #[test]
2726    fn a_circle_wound_against_the_axis_keeps_its_pcurve_same_parameter() {
2727        // A plane whose normal opposes the cylinder's axis cuts a circle
2728        // wound against the cylinder's `u`, and the pcurve must run in `-u`
2729        // with it. Written `+u` unconditionally, the pcurve evaluates half a
2730        // turn away from the curve and every face built on the section tears
2731        // in parameter space. Both windings are pinned by lifting the pcurve
2732        // through the surface and demanding the curve's own point back.
2733        let drum: SurfaceGeometry = CylinderSurface::new(
2734            Cylinder::new(
2735                Frame::new(Point::new(2.0, 2.0, -1.0), Direction::Z, Direction::X, T).unwrap(),
2736                0.5,
2737                T,
2738            )
2739            .unwrap(),
2740            (0.0, 3.0),
2741        )
2742        .unwrap()
2743        .into();
2744        for normal in [Direction::Z, -Direction::Z] {
2745            let frame = Frame::new(Point::ORIGIN, normal, Direction::X, T).unwrap();
2746            let ground: SurfaceGeometry =
2747                PlaneSurface::over(Plane::new(frame), (-4.0, 4.0), (-4.0, 4.0))
2748                    .unwrap()
2749                    .into();
2750            let met = intersect_surfaces(&ground, &drum, IntersectOptions::default(), T).unwrap();
2751            let SurfaceIntersection::Along(curves) = met else {
2752                panic!("a plane through a cylinder sections it");
2753            };
2754            for sc in &curves {
2755                let pcurve = sc
2756                    .on_b
2757                    .as_ref()
2758                    .expect("a circle on its cylinder has a pcurve");
2759                let (lo, hi) = sc.curve.domain();
2760                for i in 0..8 {
2761                    let t = lo + (hi - lo) * f64::from(i) / 8.0;
2762                    let p3 = sc.curve.point_at(t, T).unwrap();
2763                    let uv = pcurve.point_at(t, T).unwrap();
2764                    let lifted = drum
2765                        .point_at(uv.x.rem_euclid(core::f64::consts::TAU), uv.y, T)
2766                        .unwrap();
2767                    assert!(
2768                        p3.distance(lifted) < 1e-9,
2769                        "normal {normal:?}, t {t}: pcurve lifts {lifted:?} against {p3:?}"
2770                    );
2771                }
2772            }
2773        }
2774    }
2775
2776    /// A plane through a ball's own axis cuts a meridian. The whole circle has
2777    /// no chart image (its longitude jumps half a turn at each pole), but
2778    /// each half is a straight line in the chart, exactly, at the circle's own
2779    /// parameter. Pinned by lifting the line back through the sphere and
2780    /// demanding the circle's point, on every half of every orientation.
2781    #[test]
2782    fn a_meridian_half_has_an_exact_line_for_a_pcurve() {
2783        use ogeom_geom::Surface as _;
2784        let half = core::f64::consts::PI;
2785        for (centre, radius) in [(Point::ORIGIN, 4.0), (Point::new(1.0, -2.0, 0.5), 1.25)] {
2786            let ball = sphere(centre, radius);
2787            let SurfaceGeometry::Sphere(s) = &ball else {
2788                panic!("a sphere surface");
2789            };
2790            // Three planes through the axis, at different azimuths, so the
2791            // constant longitude is not accidentally zero.
2792            for azimuth in [0.0_f64, 0.7, 2.4] {
2793                let normal = Vector::new(-azimuth.sin(), azimuth.cos(), 0.0);
2794                let cut = plane(centre, normal);
2795                let SurfaceIntersection::Along(curves) =
2796                    intersect_surfaces(&ball, &cut, IntersectOptions::default(), T).unwrap()
2797                else {
2798                    panic!("a plane through the centre meets the ball along a circle");
2799                };
2800                assert_eq!(curves.len(), 1, "one great circle");
2801                let circle = &curves[0].curve;
2802                assert!(curves[0].exact);
2803                // The whole circle has no chart image; each half does.
2804                assert!(
2805                    exact_pcurve_over(circle, circle.domain(), &ball, T).is_none(),
2806                    "the whole meridian has no single chart image"
2807                );
2808                for (lo, hi) in [(0.0, half), (half, 2.0 * half), (0.3, half - 0.1)] {
2809                    let pcurve = exact_pcurve_over(circle, (lo, hi), &ball, T)
2810                        .expect("half a meridian has an exact pcurve");
2811                    assert!(
2812                        matches!(pcurve, PlanarCurve::Line(_)),
2813                        "and it is a straight line in the chart"
2814                    );
2815                    for i in 0..=16 {
2816                        let t = (hi - lo).mul_add(f64::from(i) / 16.0, lo);
2817                        let want = circle.point_at(t, T).unwrap();
2818                        let uv = pcurve.point_at(t, T).unwrap();
2819                        assert!(
2820                            uv.y >= -half.mul_add(0.5, 1e-12) && uv.y <= half.mul_add(0.5, 1e-12),
2821                            "the latitude stays inside the chart: {}",
2822                            uv.y
2823                        );
2824                        let lifted = ball
2825                            .point_at(uv.x.rem_euclid(core::f64::consts::TAU), uv.y, T)
2826                            .unwrap();
2827                        assert!(
2828                            want.distance(lifted) < 1e-9,
2829                            "azimuth {azimuth}, t {t}: {lifted:?} against {want:?}"
2830                        );
2831                    }
2832                }
2833                // A range straddling a pole has none, and says so rather than
2834                // answering for one side.
2835                assert!(
2836                    exact_pcurve_over(circle, (half - 0.2, half + 0.2), &ball, T).is_none(),
2837                    "a range across a pole has no one line"
2838                );
2839                let _ = s;
2840            }
2841        }
2842    }
2843
2844    /// A trim says *where* on a curve, not what it is. The basis carries the
2845    /// shape and the trim shares its parameter, so a trimmed curve's pcurve is
2846    /// the basis's own pcurve trimmed the same way, on every surface, since
2847    /// the answer does not depend on the surface at all.
2848    ///
2849    /// A fillet's own end cap is a plane and the edges bounding it are trimmed
2850    /// curves. Without this, the boolean refuses the coincidence because it
2851    /// cannot put a trimmed curve into a chart it plainly lies in.
2852    #[test]
2853    fn a_trimmed_curve_carries_its_basis_pcurve_trimmed_the_same_way() {
2854        use ogeom_geom::TrimmedCurve;
2855        let drum = cylinder(Vector::Z, 2.0);
2856        let ground = plane(Point::new(0.0, 0.0, 1.0), Vector::Z);
2857        // The circle where they meet, and a quarter of it.
2858        let SurfaceIntersection::Along(curves) =
2859            intersect_surfaces(&drum, &ground, IntersectOptions::default(), T).unwrap()
2860        else {
2861            panic!("a plane across a cylinder meets it in a circle");
2862        };
2863        let whole = curves[0].curve.clone();
2864        let (lo, hi) = whole.domain();
2865        let quarter: Curve = TrimmedCurve::new(whole.clone(), lo + 0.3, lo + (hi - lo) / 4.0, T)
2866            .unwrap()
2867            .into();
2868
2869        for surface in [&drum, &ground] {
2870            let full = exact_pcurve_of(&whole, surface, T).expect("the whole circle has one");
2871            let part = exact_pcurve_of(&quarter, surface, T).expect("and so does a quarter of it");
2872            // Same parameter, same point: the trim changed the range and
2873            // nothing else.
2874            let (a, b) = quarter.domain();
2875            for i in 0..=8 {
2876                let t = (b - a).mul_add(f64::from(i) / 8.0, a);
2877                let (whole_at, part_at) =
2878                    (full.point_at(t, T).unwrap(), part.point_at(t, T).unwrap());
2879                assert!(
2880                    whole_at.distance(part_at) < 1e-12,
2881                    "the trim carries the basis: {whole_at:?} against {part_at:?}"
2882                );
2883                // And it lifts back onto the curve it came from.
2884                let lifted = surface
2885                    .point_at(part_at.x.rem_euclid(core::f64::consts::TAU), part_at.y, T)
2886                    .or_else(|_| surface.point_at(part_at.x, part_at.y, T))
2887                    .unwrap();
2888                assert!(
2889                    lifted.distance(quarter.point_at(t, T).unwrap()) < 1e-9,
2890                    "same-parameter, still"
2891                );
2892            }
2893        }
2894    }
2895
2896    /// An arc whose range runs past the end of its circle's turn (from late
2897    /// in the turn across the circle's origin) has a pcurve on a surface of
2898    /// revolution over that whole range, the same point at every parameter
2899    /// of it.
2900    #[test]
2901    fn an_arc_across_its_circles_origin_has_a_pcurve_over_its_range() {
2902        let drum = cylinder(Vector::Z, 2.0);
2903        let ball = sphere(Point::ORIGIN, 2.0);
2904        let ground = plane(Point::ORIGIN, Vector::Z);
2905        for surface in [&drum, &ball] {
2906            let SurfaceIntersection::Along(curves) =
2907                intersect_surfaces(surface, &ground, IntersectOptions::default(), T).unwrap()
2908            else {
2909                panic!("a plane through the axis's normal meets it in a circle");
2910            };
2911            let circle = curves[0].curve.clone();
2912            let tau = core::f64::consts::TAU;
2913            for range in [(4.7, tau + 1.0), (-1.0, 1.5)] {
2914                let pcurve = exact_pcurve_over(&circle, range, surface, T).expect("a parallel");
2915                for i in 0..=8 {
2916                    let t = (range.1 - range.0).mul_add(f64::from(i) / 8.0, range.0);
2917                    let at = pcurve.point_at(t, T).unwrap();
2918                    let lifted = surface.point_at(at.x.rem_euclid(tau), at.y, T).unwrap();
2919                    assert!(
2920                        lifted.distance(circle.point_at(t, T).unwrap()) < 1e-9,
2921                        "{range:?} at {t}"
2922                    );
2923                }
2924            }
2925        }
2926    }
2927
2928    /// A plane through a cone's apex: tangent, it touches along one ruling;
2929    /// steeper, it holds two; shallower, it meets the apex alone. Every
2930    /// ruling lies on both surfaces and stays within the cone's window.
2931    #[test]
2932    fn a_plane_through_a_cones_apex_holds_its_rulings() {
2933        use ogeom_geom::ConeSurface;
2934        let frame = Frame::new(
2935            Point::new(100.0, 200.0, 300.0),
2936            Direction::Z,
2937            Direction::X,
2938            T,
2939        )
2940        .unwrap();
2941        let cone = ogeom_math::Cone::new(frame, 10.0, core::f64::consts::FRAC_PI_4, T).unwrap();
2942        let surface: SurfaceGeometry = ConeSurface::new(cone, (-5.0, 50.0)).unwrap().into();
2943        let apex = Point::new(100.0, 200.0, 290.0);
2944        let plane = |normal: Vector| -> SurfaceGeometry {
2945            PlaneSurface::new(Plane::through(apex, Direction::new(normal, T).unwrap())).into()
2946        };
2947        let cases = [
2948            (Vector::new(1.0, 0.0, -1.0), 1, true),
2949            (Vector::new(1.0, 0.0, 0.0), 2, false),
2950        ];
2951        for (normal, count, tangent) in cases {
2952            let cut = plane(normal);
2953            let SurfaceIntersection::Along(sections) =
2954                intersect_surfaces(&surface, &cut, IntersectOptions::default(), T).unwrap()
2955            else {
2956                panic!("{normal:?}: rulings");
2957            };
2958            assert_eq!(sections.len(), count, "{normal:?}");
2959            for section in &sections {
2960                assert_eq!(section.tangential, tangent, "{normal:?}");
2961                let (lo, hi) = section.curve.domain();
2962                for k in 0..=4 {
2963                    let p = section
2964                        .curve
2965                        .point_at(lo + (hi - lo) * f64::from(k) / 4.0, T)
2966                        .unwrap();
2967                    assert!(cone.distance_to(p) < 1e-9, "{p:?} on the cone");
2968                    let height = p.z - 300.0;
2969                    assert!(
2970                        (-5.0 - 1e-9..=50.0 + 1e-9).contains(&height),
2971                        "{p:?} in the window"
2972                    );
2973                }
2974            }
2975        }
2976        let shallow = plane(Vector::new(0.2, 0.0, 1.0));
2977        assert!(matches!(
2978            intersect_surfaces(&surface, &shallow, IntersectOptions::default(), T).unwrap(),
2979            SurfaceIntersection::Touching(_) | SurfaceIntersection::Apart
2980        ));
2981    }
2982
2983    #[test]
2984    fn a_far_stated_ruling_reads_its_angle_on_the_used_nappe() {
2985        use ogeom_geom::ConeSurface;
2986        // A 45-degree cone opening along +z, reference radius 24 at the
2987        // frame's origin; a ruling at chart angle 0.01, exactly as a real
2988        // file states it: the line's own origin parked seven hundred
2989        // kilometres down the infinite line, past the apex on the other
2990        // nappe. Only the used range may vote on the angle, or the pcurve
2991        // lands half a turn away and the face triangulates as a fan across
2992        // the whole chart.
2993        let cone =
2994            ogeom_math::Cone::new(Frame::WORLD, 24.0, core::f64::consts::FRAC_PI_4, T).unwrap();
2995        let surface: SurfaceGeometry = ConeSurface::new(cone, (-1e5, 1e5)).unwrap().into();
2996        let u_true = 0.01_f64;
2997        let radial = Vector::new(u_true.cos(), u_true.sin(), 0.0);
2998        // The ruling climbs outward at 45 degrees; its stated origin sits
2999        // far beyond the apex (z = -24 on this cone), on the other nappe.
3000        let direction =
3001            Direction::new((radial + Vector::new(0.0, 0.0, 1.0)) / 2f64.sqrt(), T).unwrap();
3002        let far = -7.0e5;
3003        let origin = Point::ORIGIN + radial * 24.0 + direction.vector() * far;
3004        let line = ogeom_geom::LineCurve::over(
3005            ogeom_math::Axis::new(origin, direction),
3006            far.abs() - 1.0,
3007            far.abs() + 1.0,
3008        )
3009        .unwrap();
3010        let curve: Curve = line.into();
3011        let range = ogeom_geom::Curve3d::domain(&curve);
3012        let pcurve = exact_pcurve_over(&curve, range, &surface, T).expect("a ruling inverts");
3013        let at = pcurve.point_at(range.0, T).unwrap();
3014        let tau = core::f64::consts::TAU;
3015        let gap = (at.x - u_true)
3016            .rem_euclid(tau)
3017            .min(tau - (at.x - u_true).rem_euclid(tau));
3018        assert!(
3019            gap < 1e-6,
3020            "the ruling's chart angle must be the used side's: got u {} against {u_true}",
3021            at.x
3022        );
3023    }
3024
3025    /// A thin drum crossing a wide one obliquely, its far side passing two
3026    /// hundredths of a millimetre inside the wide wall: two loops (the
3027    /// second cut short by the wide drum's end), each turning sharply at
3028    /// the tip where the drums all but touch. Each comes back as curves
3029    /// within a few microns of both drums; the whole first loop fitted as
3030    /// one misses its trace by millimetres.
3031    #[test]
3032    fn loops_turning_sharply_where_drums_all_but_touch_fit_in_pieces() {
3033        let drum = |origin: Point, axis: Vector, x: Vector, radius: f64, height: (f64, f64)| {
3034            let frame = Frame::new(
3035                origin,
3036                Direction::new(axis, T).unwrap(),
3037                Direction::new(x, T).unwrap(),
3038                T,
3039            )
3040            .unwrap();
3041            let cylinder = Cylinder::new(frame, radius, T).unwrap();
3042            (
3043                cylinder,
3044                SurfaceGeometry::from(CylinderSurface::new(cylinder, height).unwrap()),
3045            )
3046        };
3047        let radius = 3.175;
3048        let (thin_drum, thin) = drum(
3049            Point::new(10.994_218_762_109_735, 53.975, -209.55),
3050            Vector::new(0.0, 0.0, -1.0),
3051            Vector::new(-1.0, 0.0, 0.0),
3052            radius,
3053            (-1000.0, 1000.0),
3054        );
3055        let (wide_drum, wide) = drum(
3056            Point::new(
3057                -14.478_610_818_124_423,
3058                3.999_371_635_181_902,
3059                -277.138_401_510_994_7,
3060            ),
3061            Vector::new(
3062                -0.565_016_635_381_368_8,
3063                0.528_780_602_945_684_7,
3064                0.633_361_883_673_714_3,
3065            ),
3066            Vector::new(0.0, 0.767_637_390_304_296_3, -0.640_884_417_821_817),
3067            57.088_766_757_544_09,
3068            (0.0, 171.306_147_621_762_6),
3069        );
3070        let options = IntersectOptions {
3071            tolerance: 1e-5,
3072            marching: crate::Marching {
3073                chord: 1e-5,
3074                ..crate::Marching::default()
3075            },
3076        };
3077        let SurfaceIntersection::Along(curves) =
3078            intersect_surfaces(&thin, &wide, options, T).unwrap()
3079        else {
3080            panic!("the drums cross");
3081        };
3082        let mut length = 0.0;
3083        for section in &curves {
3084            assert!(!section.tangential);
3085            assert!(
3086                section.tolerance < 1e-3,
3087                "a section states {} of doubt",
3088                section.tolerance
3089            );
3090            let (lo, hi) = section.curve.domain();
3091            let mut previous = section.curve.point_at(lo, T).unwrap();
3092            for i in 1..=400 {
3093                let t = lo + (hi - lo) * f64::from(i) / 400.0;
3094                let p = section.curve.point_at(t, T).unwrap();
3095                let off = thin_drum
3096                    .distance_to(p)
3097                    .abs()
3098                    .max(wide_drum.distance_to(p).abs());
3099                assert!(off < 1e-3, "a section stands {off} off the drums");
3100                length += previous.distance(p);
3101                previous = p;
3102            }
3103        }
3104        // Each loop runs the thin drum's girth stretched along the wide
3105        // wall: the two together far longer than two girths.
3106        assert!(
3107            length > 4.0 * core::f64::consts::PI * radius,
3108            "the sections cover {length}"
3109        );
3110    }
3111
3112    #[test]
3113    fn coincidence_is_measured_over_the_overlap_and_nowhere_else() {
3114        // Patches restated from planes: the geometry no longer says "plane",
3115        // which is the whole reason this measurement exists.
3116        let patch = |plane: ogeom_math::Plane, u: (f64, f64), v: (f64, f64)| {
3117            let surface: SurfaceGeometry = PlaneSurface::over(plane, u, v).unwrap().into();
3118            SurfaceGeometry::from(surface.to_bspline(T).unwrap())
3119        };
3120        let reach = T.confusion() * 1e2;
3121
3122        // Two windows on one plane, overlapping over a quarter of each. They
3123        // are the same surface exactly where they meet, which is the claim.
3124        let here = patch(ogeom_math::Plane::XY, (0.0, 10.0), (0.0, 10.0));
3125        let over = patch(ogeom_math::Plane::XY, (5.0, 15.0), (5.0, 15.0));
3126        assert!(surfaces_coincide(&here, &over, reach, T));
3127
3128        // The same plane lifted clear of itself is not the same surface, and
3129        // a plane square to it crosses rather than coincides: the case that
3130        // must keep marching, since a crossing has a section to find.
3131        let above = patch(
3132            ogeom_math::Plane::new(
3133                Frame::new(Point::new(0.0, 0.0, 1.0), Direction::Z, Direction::X, T).unwrap(),
3134            ),
3135            (0.0, 10.0),
3136            (0.0, 10.0),
3137        );
3138        assert!(!surfaces_coincide(&here, &above, reach, T));
3139        let across = patch(
3140            ogeom_math::Plane::new(
3141                Frame::new(Point::new(5.0, 0.0, 0.0), Direction::X, Direction::Y, T).unwrap(),
3142            ),
3143            (0.0, 10.0),
3144            (0.0, 10.0),
3145        );
3146        assert!(!surfaces_coincide(&here, &across, reach, T));
3147    }
3148}