1use 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#[derive(Debug, Clone, Copy, PartialEq)]
41pub struct IntersectOptions {
42 pub tolerance: f64,
44 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#[derive(Debug, Clone, PartialEq)]
59pub struct SectionCurve {
60 pub curve: Curve,
62 pub on_a: Option<PlanarCurve>,
69 pub on_b: Option<PlanarCurve>,
71 pub tolerance: f64,
76 pub exact: bool,
78 pub closed: bool,
80 pub tangential: bool,
90}
91
92#[derive(Debug, Clone, PartialEq)]
94pub enum SurfaceIntersection {
95 Apart,
102 Touching(Vec<Point>),
104 Along(Vec<SectionCurve>),
106 Same,
108}
109
110pub 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 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 SurfaceIntersection::Apart
165 } else {
166 SurfaceIntersection::Along(sections)
167 })
168 }
169 Err(_) if surfaces_coincide(a, b, options.tolerance, tol) => Ok(SurfaceIntersection::Same),
174 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
188fn surfaces_coincide(
209 a: &SurfaceGeometry,
210 b: &SurfaceGeometry,
211 reach: f64,
212 tol: Tolerances,
213) -> bool {
214 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 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
259fn 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 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 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 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 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
394fn 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 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 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 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 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 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
630fn a_or_b<'s>(first: bool, a: &'s SurfaceGeometry, b: &'s SurfaceGeometry) -> &'s SurfaceGeometry {
632 if first { a } else { b }
633}
634
635fn 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 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 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 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
710const NEAR_PARALLEL_STRAY: f64 = 1e-5;
713
714fn 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
787fn 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 let margin = r * 0.1;
821 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 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 ¶ms {
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(¶ms, &points, 3, target, tol)
875 .ok()?
876 .curve
877 .into();
878 let drum_image: PlanarCurve =
879 ogeom_geom::fit::fit_points_2d_at(¶ms, &on_drum, 3, target, tol)
880 .ok()?
881 .curve
882 .into();
883 let ball_image: PlanarCurve =
884 ogeom_geom::fit::fit_points_2d_at(¶ms, &on_sphere, 3, target, tol)
885 .ok()?
886 .curve
887 .into();
888 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
926fn 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 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
981fn 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 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 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
1066fn 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 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 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
1122fn 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
1142fn inside_box(pcurve: &PlanarCurve, surface: &SurfaceGeometry) -> Option<(f64, f64)> {
1145 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 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
1191fn 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 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 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
1226fn 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
1236fn 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 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 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 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
1312fn fitted_in_pieces(
1328 a: &SurfaceGeometry,
1329 b: &SurfaceGeometry,
1330 branch: &crate::march::Traced,
1331 tolerance: f64,
1332 tol: Tolerances,
1333) -> OgeomResult<Vec<crate::approx::IntersectionCurve>> {
1334 const DEPTH: u32 = 6;
1335 const FLOOR: usize = 16;
1336 fn go(
1337 a: &SurfaceGeometry,
1338 b: &SurfaceGeometry,
1339 branch: &crate::march::Traced,
1340 tolerance: f64,
1341 depth: u32,
1342 tol: Tolerances,
1343 ) -> OgeomResult<Vec<crate::approx::IntersectionCurve>> {
1344 let whole = approximate_branch(a, b, branch, tolerance, tol)?;
1345 let step = branch
1346 .points
1347 .windows(2)
1348 .map(|w| w[0].distance(w[1]))
1349 .fold(0.0_f64, f64::max);
1350 if whole.met
1351 || whole.fit_error <= step.min(tolerance * 1e2)
1352 || depth == 0
1353 || branch.points.len() < 2 * FLOOR
1354 {
1355 return Ok(vec![whole]);
1356 }
1357 let middle = branch.points.len() / 2;
1358 let stopped = if branch.closed() {
1360 crate::march::Stopped::Stalled
1361 } else {
1362 branch.stopped
1363 };
1364 let half = |range: core::ops::RangeInclusive<usize>| crate::march::Traced {
1365 points: branch.points[range.clone()].to_vec(),
1366 on_a: branch.on_a[range.clone()].to_vec(),
1367 on_b: branch.on_b[range].to_vec(),
1368 stopped,
1369 };
1370 let mut pieces = go(a, b, &half(0..=middle), tolerance, depth - 1, tol)?;
1371 pieces.extend(go(
1372 a,
1373 b,
1374 &half(middle..=branch.points.len() - 1),
1375 tolerance,
1376 depth - 1,
1377 tol,
1378 )?);
1379 let worst = pieces.iter().map(|p| p.fit_error).fold(0.0_f64, f64::max);
1382 Ok(if worst < whole.fit_error {
1383 pieces
1384 } else {
1385 vec![whole]
1386 })
1387 }
1388 go(a, b, branch, tolerance, DEPTH, tol)
1389}
1390
1391fn walk_contact(
1400 a: &SurfaceGeometry,
1401 b: &SurfaceGeometry,
1402 fragment: &crate::march::Traced,
1403 already: &[crate::march::Traced],
1404 marching: Marching,
1405 tol: Tolerances,
1406) -> OgeomResult<Option<crate::march::Traced>> {
1407 let middle = fragment.points.len() / 2;
1408 let Some(point) = fragment.points.get(middle).copied() else {
1409 return Ok(None);
1410 };
1411 for traced in already {
1412 let spacing = traced
1415 .points
1416 .windows(2)
1417 .map(|w| w[0].distance(w[1]))
1418 .fold(0.0f64, f64::max);
1419 let near = traced
1420 .points
1421 .iter()
1422 .map(|p| p.distance(point))
1423 .fold(f64::INFINITY, f64::min);
1424 if near <= spacing.mul_add(0.5, marching.chord.max(tol.confusion())) {
1425 return Ok(None);
1426 }
1427 }
1428 let seed = crate::march::Contact {
1429 point,
1430 on_a: fragment.on_a[middle],
1431 on_b: fragment.on_b[middle],
1432 };
1433 Ok(trace_tangential(a, b, seed, marching, tol)
1438 .ok()
1439 .filter(|traced| traced.points.len() >= 4))
1440}
1441
1442fn branch_is_tangential(
1445 a: &SurfaceGeometry,
1446 b: &SurfaceGeometry,
1447 branch: &crate::march::Traced,
1448 tol: Tolerances,
1449) -> OgeomResult<bool> {
1450 use ogeom_geom::Surface as _;
1451 let count = branch.points.len();
1452 if count == 0 {
1453 return Ok(true);
1454 }
1455 for k in 0..5 {
1456 let i = (k * (count - 1)) / 4;
1457 let (ua, va) = branch.on_a[i.min(count - 1)];
1458 let (ub, vb) = branch.on_b[i.min(count - 1)];
1459 let (dau, dav) = a.d1_at(ua, va, tol)?;
1460 let (dbu, dbv) = b.d1_at(ub, vb, tol)?;
1461 let na = dau.cross(dav);
1462 let nb = dbu.cross(dbv);
1463 let (ma, mb) = (na.magnitude(), nb.magnitude());
1464 if ma <= tol.confusion() || mb <= tol.confusion() {
1465 continue;
1466 }
1467 if na.cross(nb).magnitude() / (ma * mb) > 3e-2 {
1474 return Ok(false);
1475 }
1476 }
1477 Ok(true)
1478}
1479
1480#[must_use]
1488pub fn exact_pcurve_of(
1489 curve: &Curve,
1490 surface: &SurfaceGeometry,
1491 tol: Tolerances,
1492) -> Option<PlanarCurve> {
1493 exact_pcurve(curve, curve.domain(), surface, tol)
1494}
1495
1496#[must_use]
1505pub fn exact_pcurve_over(
1506 curve: &Curve,
1507 range: (f64, f64),
1508 surface: &SurfaceGeometry,
1509 tol: Tolerances,
1510) -> Option<PlanarCurve> {
1511 exact_pcurve(curve, range, surface, tol)
1512}
1513
1514fn exact_pcurve(
1524 curve: &Curve,
1525 range: (f64, f64),
1526 surface: &SurfaceGeometry,
1527 tol: Tolerances,
1528) -> Option<PlanarCurve> {
1529 if let Curve::Trimmed(trimmed) = curve
1536 && !trimmed.is_reversed()
1537 {
1538 let window = ogeom_geom::Curve3d::domain(&**trimmed);
1539 let basis = exact_pcurve(trimmed.basis(), range, surface, tol)?;
1540 return ogeom_geom::Trimmed2d::new(basis, window.0, window.1, tol)
1541 .ok()
1542 .map(Into::into);
1543 }
1544 match surface {
1545 SurfaceGeometry::Plane(p) => on_plane(curve, p.plane(), tol),
1546 SurfaceGeometry::Cylinder(c) => on_cylinder(curve, range, c.cylinder(), tol),
1547 SurfaceGeometry::Sphere(s) => on_sphere(curve, range, s.sphere(), tol),
1548 SurfaceGeometry::Torus(t) => on_torus(curve, t.torus(), tol),
1549 SurfaceGeometry::Cone(c) => on_cone(curve, range, c.cone(), tol),
1550 _ => None,
1551 }
1552}
1553
1554fn on_cone(
1563 curve: &Curve,
1564 range: (f64, f64),
1565 cone: ogeom_math::Cone,
1566 tol: Tolerances,
1567) -> Option<PlanarCurve> {
1568 let frame = cone.frame();
1569 let axis_z = frame.z().vector();
1570 let tau = core::f64::consts::TAU;
1571 match curve {
1572 Curve::Circle(c) => {
1573 let circle = c.circle();
1574 if circle.frame().z().vector().cross(axis_z).magnitude() > tol.angular() {
1575 return None;
1576 }
1577 let local = frame.to_local(circle.centre());
1578 if local.x.hypot(local.y) > tol.confusion() {
1579 return None;
1580 }
1581 let expected = cone
1585 .half_angle()
1586 .tan()
1587 .mul_add(local.z, cone.reference_radius());
1588 let turned = if (expected - circle.radius()).abs() <= tol.confusion() * 10.0 {
1589 0.0
1590 } else if (expected + circle.radius()).abs() <= tol.confusion() * 10.0 {
1591 core::f64::consts::PI
1592 } else {
1593 return None;
1594 };
1595 let start = circle.centre() + circle.frame().x().vector() * circle.radius();
1596 let at = frame.to_local(start);
1597 let phase = at.y.atan2(at.x) + turned;
1598 let winding = circle.frame().z().vector().dot(axis_z).signum();
1599 let towards =
1600 ogeom_math::Direction2::new(ogeom_math::Vector2::new(winding, 0.0), tol).ok()?;
1601 Some(
1602 Line2d::over(
1603 ogeom_math::Axis2::new(Point2::new(phase, local.z), towards),
1604 0.0,
1605 tau,
1606 )
1607 .ok()?
1608 .into(),
1609 )
1610 }
1611 Curve::Line(line) => {
1612 let axis = line.axis();
1615 let on = |t: f64| {
1616 let p = axis.location + axis.direction.vector() * t;
1617 cone.distance_to(p) <= tol.confusion() * 10.0
1618 };
1619 if !on(0.0) || !on(1.0) || !on(-1.0) {
1620 return None;
1621 }
1622 let (lo, hi) = if range.0.is_finite() && range.1.is_finite() && range.0 != range.1 {
1629 range
1630 } else {
1631 line.domain()
1632 };
1633 let mut local: Option<ogeom_math::Point> = None;
1639 for t in [lo, hi] {
1640 if !t.is_finite() {
1641 continue;
1642 }
1643 let candidate = frame.to_local(axis.location + axis.direction.vector() * t);
1644 if local.is_none_or(|held| candidate.x.hypot(candidate.y) > held.x.hypot(held.y)) {
1645 local = Some(candidate);
1646 }
1647 }
1648 let local = local?;
1649 if local.x.hypot(local.y) <= tol.confusion() {
1650 return None;
1651 }
1652 let u = local.y.atan2(local.x).rem_euclid(tau);
1653 let v_at = |t: f64| {
1657 frame
1658 .to_local(axis.location + axis.direction.vector() * t)
1659 .z
1660 };
1661 let knots = ogeom_math::KnotVector::new(vec![lo, lo, hi, hi], 1).ok()?;
1662 Some(
1663 ogeom_geom::BSpline2d::new(
1664 knots,
1665 vec![Point2::new(u, v_at(lo)), Point2::new(u, v_at(hi))],
1666 tol,
1667 )
1668 .ok()?
1669 .into(),
1670 )
1671 }
1672 _ => None,
1673 }
1674}
1675
1676fn on_torus(curve: &Curve, torus: ogeom_math::Torus, tol: Tolerances) -> Option<PlanarCurve> {
1686 let Curve::Circle(c) = curve else {
1687 return None;
1688 };
1689 let circle = c.circle();
1690 let frame = torus.frame();
1691 let axis_z = frame.z().vector();
1692 let normal = circle.frame().z().vector();
1693 let local = frame.to_local(circle.centre());
1694 let tau = core::f64::consts::TAU;
1695
1696 if normal.cross(axis_z).magnitude() <= tol.angular()
1698 && local.x.hypot(local.y) <= tol.confusion()
1699 {
1700 let sin_v = local.z / torus.minor_radius();
1701 let (cos_v, turned) = [
1705 (circle.radius() - torus.major_radius(), 0.0),
1706 (
1707 -circle.radius() - torus.major_radius(),
1708 core::f64::consts::PI,
1709 ),
1710 ]
1711 .into_iter()
1712 .map(|(reach, turned)| (reach / torus.minor_radius(), turned))
1713 .find(|(cos_v, _)| (sin_v.hypot(*cos_v) - 1.0).abs() <= tol.confusion())?;
1714 let v = sin_v.atan2(cos_v);
1715 let start = circle.centre() + circle.frame().x().vector() * circle.radius();
1716 let at = frame.to_local(start);
1717 let phase = at.y.atan2(at.x) + turned;
1718 let winding = normal.dot(axis_z).signum();
1719 let towards =
1720 ogeom_math::Direction2::new(ogeom_math::Vector2::new(winding, 0.0), tol).ok()?;
1721 return Some(
1722 Line2d::over(
1723 ogeom_math::Axis2::new(Point2::new(phase, v), towards),
1724 0.0,
1725 tau,
1726 )
1727 .ok()?
1728 .into(),
1729 );
1730 }
1731
1732 if (circle.radius() - torus.minor_radius()).abs() <= tol.confusion()
1734 && normal.dot(axis_z).abs() <= tol.angular()
1735 && (local.x.hypot(local.y) - torus.major_radius()).abs() <= tol.confusion()
1736 && local.z.abs() <= tol.confusion()
1737 {
1738 let u = local.y.atan2(local.x);
1739 let radial = frame.x().vector() * u.cos() + frame.y().vector() * u.sin();
1740 let xc = circle.frame().x().vector();
1741 let phase = xc.dot(axis_z).atan2(xc.dot(radial));
1742 let winding = normal.dot(radial.cross(axis_z)).signum();
1743 let towards =
1744 ogeom_math::Direction2::new(ogeom_math::Vector2::new(0.0, winding), tol).ok()?;
1745 return Some(
1746 Line2d::over(
1747 ogeom_math::Axis2::new(Point2::new(u, phase), towards),
1748 0.0,
1749 tau,
1750 )
1751 .ok()?
1752 .into(),
1753 );
1754 }
1755 None
1756}
1757
1758fn on_plane(curve: &Curve, plane: ogeom_math::Plane, tol: Tolerances) -> Option<PlanarCurve> {
1764 let frame = plane.frame();
1765 let flat = |p: Point| {
1766 let local = frame.to_local(p);
1767 Point2::new(local.x, local.y)
1768 };
1769 let flat_direction = |d: ogeom_math::Direction| {
1770 let tip = flat(frame.origin() + d.vector());
1771 ogeom_math::Direction2::new(tip - flat(frame.origin()), tol).ok()
1772 };
1773 match curve {
1774 Curve::Line(line) => {
1775 let axis = line.axis();
1776 let through = flat(axis.location);
1777 let direction = flat_direction(axis.direction)?;
1778 let (lo, hi) = line.domain();
1779 Some(
1780 Line2d::over(ogeom_math::Axis2::new(through, direction), lo, hi)
1781 .ok()?
1782 .into(),
1783 )
1784 }
1785 Curve::Circle(c) => {
1786 let circle = c.circle();
1787 let frame2 = Frame2::from_axes(
1788 flat(circle.centre()),
1789 flat_direction(circle.frame().x())?,
1790 flat_direction(circle.frame().y())?,
1791 tol,
1792 )
1793 .ok()?;
1794 Some(Circle2d::new(Circle2::new(frame2, circle.radius(), tol).ok()?).into())
1795 }
1796 Curve::Ellipse(e) => {
1797 let ellipse = e.ellipse();
1798 let frame2 = Frame2::from_axes(
1799 flat(ellipse.centre()),
1800 flat_direction(ellipse.frame().x())?,
1801 flat_direction(ellipse.frame().y())?,
1802 tol,
1803 )
1804 .ok()?;
1805 Some(
1806 Ellipse2d::new(
1807 Ellipse2::new(frame2, ellipse.major_radius(), ellipse.minor_radius(), tol)
1808 .ok()?,
1809 )
1810 .into(),
1811 )
1812 }
1813 Curve::BSpline(b) => {
1814 let control = b
1819 .control_points()
1820 .iter()
1821 .map(|w| ogeom_math::Weighted::new(flat((*w).point()), w.weight, tol))
1822 .collect::<Result<Vec<_>, _>>()
1823 .ok()?;
1824 Some(
1825 ogeom_geom::BSpline2d::rational(b.knots().clone(), control)
1826 .ok()?
1827 .into(),
1828 )
1829 }
1830 _ => None,
1831 }
1832}
1833
1834fn on_cylinder(
1841 curve: &Curve,
1842 range: (f64, f64),
1843 cylinder: ogeom_math::Cylinder,
1844 tol: Tolerances,
1845) -> Option<PlanarCurve> {
1846 let axis = cylinder.axis();
1847 let frame = cylinder.frame();
1848 match curve {
1849 Curve::Line(line) => {
1850 let direction = line.axis().direction;
1852 let along = direction.dot(axis.direction);
1853 if !direction.is_parallel(axis.direction, tol) {
1854 return None;
1855 }
1856 let through = line.axis().location;
1857 if (axis.distance_to(through) - cylinder.radius()).abs() > tol.confusion() {
1858 return None;
1859 }
1860 let local = frame.to_local(through);
1861 let u = local.y.atan2(local.x).rem_euclid(core::f64::consts::TAU);
1862 let (lo, hi) = line.domain();
1866 let start = Point2::new(u, local.z);
1867 let towards =
1868 ogeom_math::Direction2::new(ogeom_math::Vector2::new(0.0, along.signum()), tol)
1869 .ok()?;
1870 Some(
1871 Line2d::over(ogeom_math::Axis2::new(start, towards), lo, hi)
1872 .ok()?
1873 .into(),
1874 )
1875 }
1876 Curve::Circle(c) => {
1877 let circle = c.circle();
1878 if circle
1880 .frame()
1881 .z()
1882 .cross_with(axis.direction.vector())
1883 .magnitude()
1884 > tol.angular()
1885 {
1886 return None;
1887 }
1888 if axis.distance_to(circle.centre()) > tol.confusion() {
1889 return None;
1890 }
1891 if (circle.radius() - cylinder.radius()).abs() > tol.confusion() {
1892 return None;
1893 }
1894 let local = frame.to_local(circle.centre());
1895 let start = circle.centre() + circle.frame().x().vector() * circle.radius();
1904 let at = frame.to_local(start);
1905 let phase = at.y.atan2(at.x);
1906 let winding = circle.frame().z().dot(axis.direction).signum();
1907 let towards =
1908 ogeom_math::Direction2::new(ogeom_math::Vector2::new(winding, 0.0), tol).ok()?;
1909 Some(
1910 Line2d::over(
1911 ogeom_math::Axis2::new(Point2::new(phase, local.z), towards),
1912 0.0,
1913 core::f64::consts::TAU,
1914 )
1915 .ok()?
1916 .into(),
1917 )
1918 }
1919 Curve::Ellipse(_) => {
1920 use ogeom_geom::Curve3d as _;
1926 let tau = core::f64::consts::TAU;
1927 let local = |t: f64| -> Option<ogeom_math::Point> {
1928 Some(frame.to_local(curve.point_at(t, tol).ok()?))
1929 };
1930 let l0 = local(0.0)?;
1931 let lq = local(tau / 4.0)?;
1932 let lh = local(tau / 2.0)?;
1933 let r = cylinder.radius();
1935 for l in [&l0, &lq, &lh] {
1936 if (l.x.hypot(l.y) - r).abs() > tol.confusion() * 10.0 {
1937 return None;
1938 }
1939 }
1940 let phase = l0.y.atan2(l0.x);
1941 let uq = lq.y.atan2(lq.x);
1944 let step = (uq - phase).rem_euclid(tau);
1945 let winding = if (step - tau / 4.0).abs() < 1e-6 {
1946 1.0
1947 } else if (step - 3.0 * tau / 4.0).abs() < 1e-6 {
1948 -1.0
1949 } else {
1950 return None;
1951 };
1952 let c0 = f64::midpoint(l0.z, lh.z);
1954 let a = (l0.z - lh.z) / 2.0;
1955 let b = lq.z - c0;
1956 let candidate = ogeom_geom::Trig2d::new(
1960 Point2::new(phase, c0),
1961 ogeom_math::Vector2::new(winding, 0.0),
1962 ogeom_math::Vector2::new(0.0, a),
1963 ogeom_math::Vector2::new(0.0, b),
1964 range,
1965 )
1966 .ok()?;
1967 use ogeom_geom::Curve2d as _;
1970 for i in 0..7 {
1971 let t = range.0 + (range.1 - range.0) * (0.09 + 0.13 * f64::from(i)) / 0.91;
1972 let l = local(t)?;
1973 let chart = candidate.point_at(t, tol).ok()?;
1974 let du = (chart.x - l.y.atan2(l.x)).rem_euclid(tau);
1975 if du.min(tau - du) > 1e-9 {
1976 return None;
1977 }
1978 if (chart.y - l.z).abs() > tol.confusion() * 10.0 {
1979 return None;
1980 }
1981 }
1982 Some(PlanarCurve::Trig(candidate))
1983 }
1984 _ => None,
1985 }
1986}
1987
1988fn on_meridian(
2006 curve: &ogeom_geom::CircleCurve,
2007 range: (f64, f64),
2008 sphere: ogeom_math::Sphere,
2009 tol: Tolerances,
2010) -> Option<PlanarCurve> {
2011 let circle = curve.circle();
2012 let sweep = if curve.is_reversed() { -1.0 } else { 1.0 };
2017 let frame = sphere.frame();
2018 let z = frame.z().vector();
2019 if circle.centre().distance(sphere.centre()) > tol.confusion() {
2022 return None;
2023 }
2024 if (circle.radius() - sphere.radius()).abs() > tol.confusion() {
2025 return None;
2026 }
2027 let (cx, cy) = (circle.frame().x().vector(), circle.frame().y().vector());
2028 let (xz, yz) = (cx.dot(z), cy.dot(z));
2029 if xz.hypot(yz) < 1.0 - tol.angular() {
2032 return None;
2033 }
2034 let raw_alpha = yz.atan2(xz);
2035 let w = cx * -raw_alpha.sin() + cy * raw_alpha.cos();
2038 let local = frame.to_local(sphere.centre() + w);
2039 let longitude = local.y.atan2(local.x);
2040
2041 let half = core::f64::consts::PI;
2042 let mid = f64::midpoint(range.0, range.1);
2043 let x_mid = (sweep * mid - raw_alpha).rem_euclid(core::f64::consts::TAU);
2046 let x_mid = if x_mid > half {
2047 x_mid - core::f64::consts::TAU
2048 } else {
2049 x_mid
2050 };
2051 let span = sweep * (range.1 - range.0);
2052 let (mut x0, mut x1) = (x_mid - span / 2.0, x_mid + span / 2.0);
2053 if x0 > x1 {
2054 core::mem::swap(&mut x0, &mut x1);
2055 }
2056 let alpha = sweep.mul_add(mid, -x_mid);
2061 let slack = tol.parametric().max(1e-9);
2062 let (axis_point, towards) = if x0 >= -slack && x1 <= half + slack {
2063 (
2066 Point2::new(longitude, half.mul_add(0.5, alpha)),
2067 ogeom_math::Vector2::new(0.0, -sweep),
2068 )
2069 } else if x0 >= -half - slack && x1 <= slack {
2070 (
2072 Point2::new(longitude + half, half.mul_add(0.5, -alpha)),
2073 ogeom_math::Vector2::new(0.0, sweep),
2074 )
2075 } else {
2076 return None;
2078 };
2079 let towards = ogeom_math::Direction2::new(towards, tol).ok()?;
2080 let margin = (range.1 - range.0) * 0.25;
2081 let line: PlanarCurve = Line2d::over(
2082 ogeom_math::Axis2::new(axis_point, towards),
2083 range.0 - margin,
2084 range.1 + margin,
2085 )
2086 .ok()?
2087 .into();
2088
2089 for k in 0..=4 {
2092 let t = (range.1 - range.0).mul_add(f64::from(k) / 4.0, range.0);
2093 let uv = line.point_at(t, tol).ok()?;
2094 let lifted = ogeom_math::elementary::sphere_at(&sphere, uv.x, uv.y).point;
2095 let want = curve.point_at(t, tol).ok()?;
2096 if lifted.distance(want) > tol.confusion() {
2097 return None;
2098 }
2099 }
2100 Some(line)
2101}
2102
2103fn on_sphere(
2106 curve: &Curve,
2107 range: (f64, f64),
2108 sphere: ogeom_math::Sphere,
2109 tol: Tolerances,
2110) -> Option<PlanarCurve> {
2111 let Curve::Circle(c) = curve else {
2112 return None;
2113 };
2114 let circle = c.circle();
2115 let frame = sphere.frame();
2116 if circle
2119 .frame()
2120 .z()
2121 .cross_with(frame.z().vector())
2122 .magnitude()
2123 > tol.angular()
2124 {
2125 return on_meridian(c, range, sphere, tol);
2126 }
2127 let local = frame.to_local(circle.centre());
2128 if local.x.abs() > tol.confusion() || local.y.abs() > tol.confusion() {
2129 return None;
2130 }
2131 let latitude = (local.z / sphere.radius()).clamp(-1.0, 1.0).asin();
2132 if (circle.radius() - sphere.radius() * latitude.cos()).abs() > tol.confusion() {
2134 return None;
2135 }
2136 let start = circle.centre() + circle.frame().x().vector() * circle.radius();
2137 let at = frame.to_local(start);
2138 let phase = at.y.atan2(at.x);
2139 let winding = circle.frame().z().vector().dot(frame.z().vector()).signum();
2142 let towards = ogeom_math::Direction2::new(ogeom_math::Vector2::new(winding, 0.0), tol).ok()?;
2143 Some(
2144 Line2d::over(
2145 ogeom_math::Axis2::new(Point2::new(phase, latitude), towards),
2146 0.0,
2147 core::f64::consts::TAU,
2148 )
2149 .ok()?
2150 .into(),
2151 )
2152}
2153
2154#[cfg(test)]
2155#[allow(clippy::unwrap_used, clippy::expect_used)]
2156mod tests {
2157 use super::*;
2158 use ogeom_geom::{Curve2d, Curve3d, CylinderSurface, PlaneSurface, SphereSurface};
2159 use ogeom_math::{Cylinder, Direction, Frame, Plane, Sphere, Vector};
2160
2161 const T: Tolerances = Tolerances::millimetres();
2162
2163 fn sphere(centre: Point, radius: f64) -> SurfaceGeometry {
2164 SphereSurface::new(Sphere::centred(centre, radius, T).unwrap()).into()
2165 }
2166
2167 fn cylinder(axis: Vector, radius: f64) -> SurfaceGeometry {
2168 let frame = Frame::new(
2169 Point::ORIGIN,
2170 Direction::new(axis, T).unwrap(),
2171 Direction::from_cross(axis, Vector::new(0.3, 0.5, 0.9), T).unwrap(),
2172 T,
2173 )
2174 .unwrap();
2175 CylinderSurface::new(Cylinder::new(frame, radius, T).unwrap(), (-4.0, 4.0))
2176 .unwrap()
2177 .into()
2178 }
2179
2180 fn plane(origin: Point, normal: Vector) -> SurfaceGeometry {
2181 PlaneSurface::over(
2182 Plane::through(origin, Direction::new(normal, T).unwrap()),
2183 (-6.0, 6.0),
2184 (-6.0, 6.0),
2185 )
2186 .unwrap()
2187 .into()
2188 }
2189
2190 fn assert_same_parameter(
2193 section: &SectionCurve,
2194 surface: &SurfaceGeometry,
2195 pcurve: &PlanarCurve,
2196 samples: usize,
2197 ) {
2198 let (lo, hi) = section.curve.domain();
2199 let (plo, phi) = pcurve.domain();
2200 assert!(
2201 (lo - plo).abs() < 1e-9 && (hi - phi).abs() < 1e-9,
2202 "domains disagree: [{lo}, {hi}] against [{plo}, {phi}]"
2203 );
2204 for i in 0..=samples {
2205 #[allow(clippy::cast_precision_loss)]
2206 let t = lo + (hi - lo) * i as f64 / samples as f64;
2207 let on_curve = section.curve.point_at(t, T).unwrap();
2208 let at = pcurve.point_at(t, T).unwrap();
2209 let lifted = surface.point_at(at.x, at.y, T).unwrap();
2210 assert!(
2211 on_curve.is_equal(lifted, T),
2212 "at t = {t}: curve {on_curve:?}, lifted {lifted:?}"
2213 );
2214 }
2215 }
2216
2217 #[test]
2218 fn an_analytic_pair_comes_back_exact_with_matching_pcurves() {
2219 let drum = cylinder(Vector::Z, 2.0);
2223 let cut = plane(Point::ORIGIN, Vector::X);
2224 let SurfaceIntersection::Along(curves) =
2225 intersect_surfaces(&drum, &cut, IntersectOptions::default(), T).unwrap()
2226 else {
2227 panic!("a plane through a cylinder meets it along curves");
2228 };
2229 assert_eq!(curves.len(), 2);
2230 for section in &curves {
2231 assert!(section.exact);
2232 assert!((section.tolerance - 0.0).abs() < f64::EPSILON);
2233 let on_a = section.on_a.as_ref().expect("a line has a cylinder pcurve");
2234 let on_b = section.on_b.as_ref().expect("and a plane pcurve");
2235 assert_same_parameter(section, &drum, on_a, 50);
2236 assert_same_parameter(section, &cut, on_b, 50);
2237 }
2238 }
2239
2240 #[test]
2241 fn an_oblique_cut_gives_the_ellipse_a_trig_pcurve_on_the_drum() {
2242 let drum = cylinder(Vector::Z, 2.0);
2246 let angle: f64 = 0.5;
2247 let cut = plane(Point::ORIGIN, Vector::new(0.0, angle.sin(), angle.cos()));
2248 let SurfaceIntersection::Along(curves) =
2249 intersect_surfaces(&drum, &cut, IntersectOptions::default(), T).unwrap()
2250 else {
2251 panic!("an oblique plane meets the cylinder along its ellipse");
2252 };
2253 assert_eq!(curves.len(), 1);
2254 let section = &curves[0];
2255 assert!(section.exact);
2256 assert!(matches!(section.curve, Curve::Ellipse(_)));
2257 let on_drum = section
2258 .on_a
2259 .as_ref()
2260 .expect("the oblique ellipse now carries its cylinder pcurve");
2261 assert!(
2262 matches!(on_drum, PlanarCurve::Trig(_)),
2263 "the chart trace is trig-affine: {on_drum:?}"
2264 );
2265 assert_same_parameter(section, &drum, on_drum, 60);
2266 let on_plane = section.on_b.as_ref().expect("and its plane pcurve");
2267 assert_same_parameter(section, &cut, on_plane, 60);
2268 }
2269
2270 #[test]
2271 fn a_perpendicular_cut_gives_a_circle_with_a_straight_pcurve() {
2272 let drum = cylinder(Vector::Z, 2.0);
2273 let cut = plane(Point::new(0.0, 0.0, 1.0), Vector::Z);
2274 let SurfaceIntersection::Along(curves) =
2275 intersect_surfaces(&drum, &cut, IntersectOptions::default(), T).unwrap()
2276 else {
2277 panic!("expected curves");
2278 };
2279 assert_eq!(curves.len(), 1);
2280 let section = &curves[0];
2281 assert!(section.closed);
2282 assert!(matches!(section.curve, Curve::Circle(_)));
2283 assert!(matches!(
2285 section.on_a.as_ref().unwrap(),
2286 PlanarCurve::Line(_)
2287 ));
2288 assert_same_parameter(section, &drum, section.on_a.as_ref().unwrap(), 60);
2289 assert_same_parameter(section, &cut, section.on_b.as_ref().unwrap(), 60);
2290 }
2291
2292 #[test]
2293 fn coaxial_cylinder_and_sphere_give_circles_with_pcurves_on_both() {
2294 let drum = cylinder(Vector::Z, 1.5);
2295 let ball = sphere(Point::ORIGIN, 3.0);
2296 let SurfaceIntersection::Along(curves) =
2297 intersect_surfaces(&drum, &ball, IntersectOptions::default(), T).unwrap()
2298 else {
2299 panic!("expected curves");
2300 };
2301 assert_eq!(curves.len(), 2);
2302 for section in &curves {
2303 assert!(section.exact);
2304 assert_same_parameter(section, &drum, section.on_a.as_ref().unwrap(), 40);
2305 assert_same_parameter(section, &ball, section.on_b.as_ref().unwrap(), 40);
2306 }
2307 }
2308
2309 fn torus(origin: Point, axis: Vector, major: f64, minor: f64) -> SurfaceGeometry {
2310 let frame = Frame::new(
2311 origin,
2312 Direction::new(axis, T).unwrap(),
2313 Direction::from_cross(axis, Vector::new(0.3, 0.5, 0.9), T).unwrap(),
2314 T,
2315 )
2316 .unwrap();
2317 ogeom_geom::TorusSurface::new(ogeom_math::Torus::new(frame, major, minor, T).unwrap())
2318 .into()
2319 }
2320
2321 #[test]
2322 fn an_axis_normal_plane_meets_a_torus_in_two_parallels_with_pcurves() {
2323 let ring = torus(Point::ORIGIN, Vector::Z, 2.0, 0.5);
2324 let cut = plane(Point::new(0.0, 0.0, 0.3), Vector::Z);
2325 let SurfaceIntersection::Along(curves) =
2326 intersect_surfaces(&ring, &cut, IntersectOptions::default(), T).unwrap()
2327 else {
2328 panic!("an axis-normal plane through the tube meets it along curves");
2329 };
2330 assert_eq!(curves.len(), 2);
2331 let spread = 0.5_f64.mul_add(0.5, -(0.3 * 0.3)).sqrt();
2332 let mut radii: Vec<f64> = curves
2333 .iter()
2334 .map(|s| {
2335 let Curve::Circle(c) = &s.curve else {
2336 panic!("a parallel is a circle");
2337 };
2338 c.circle().radius()
2339 })
2340 .collect();
2341 radii.sort_by(|a, b| a.partial_cmp(b).unwrap());
2342 assert!((radii[0] - (2.0 - spread)).abs() < 1e-12);
2343 assert!((radii[1] - (2.0 + spread)).abs() < 1e-12);
2344 for section in &curves {
2345 assert!(section.exact);
2346 assert_same_parameter(section, &ring, section.on_a.as_ref().unwrap(), 48);
2347 assert_same_parameter(section, &cut, section.on_b.as_ref().unwrap(), 48);
2348 }
2349 }
2350
2351 #[test]
2352 fn the_plane_a_ball_rolls_on_touches_its_torus_along_the_circle_it_rolled() {
2353 let ring = torus(Point::ORIGIN, Vector::Z, 2.0, 0.5);
2358 let cut = plane(Point::new(0.0, 0.0, 0.5), Vector::Z);
2359 let SurfaceIntersection::Along(curves) =
2360 intersect_surfaces(&ring, &cut, IntersectOptions::default(), T).unwrap()
2361 else {
2362 panic!("the rolling plane touches along a circle, not at points");
2363 };
2364 assert_eq!(curves.len(), 1);
2365 let Curve::Circle(c) = &curves[0].curve else {
2366 panic!("the tangency is a circle");
2367 };
2368 assert!((c.circle().radius() - 2.0).abs() < 1e-12);
2369 assert_same_parameter(&curves[0], &ring, curves[0].on_a.as_ref().unwrap(), 48);
2370 assert_same_parameter(&curves[0], &cut, curves[0].on_b.as_ref().unwrap(), 48);
2371 }
2372
2373 #[test]
2374 fn a_coaxial_cylinder_meets_a_torus_in_two_parallels_and_touches_in_one() {
2375 let ring = torus(Point::ORIGIN, Vector::Z, 2.0, 0.5);
2376 let drum = cylinder(Vector::Z, 2.2);
2377 let SurfaceIntersection::Along(curves) =
2378 intersect_surfaces(&drum, &ring, IntersectOptions::default(), T).unwrap()
2379 else {
2380 panic!("a coaxial cylinder through the tube meets it along curves");
2381 };
2382 assert_eq!(curves.len(), 2);
2383 for section in &curves {
2384 assert!(section.exact);
2385 let Curve::Circle(c) = §ion.curve else {
2386 panic!("a parallel is a circle");
2387 };
2388 assert!((c.circle().radius() - 2.2).abs() < 1e-12);
2389 assert_same_parameter(section, &drum, section.on_a.as_ref().unwrap(), 48);
2390 assert_same_parameter(section, &ring, section.on_b.as_ref().unwrap(), 48);
2391 }
2392
2393 let grazing = cylinder(Vector::Z, 2.5);
2395 let SurfaceIntersection::Along(touch) =
2396 intersect_surfaces(&grazing, &ring, IntersectOptions::default(), T).unwrap()
2397 else {
2398 panic!("the grazing cylinder touches along the equator");
2399 };
2400 assert_eq!(touch.len(), 1);
2401 assert_same_parameter(&touch[0], &grazing, touch[0].on_a.as_ref().unwrap(), 48);
2402 assert_same_parameter(&touch[0], &ring, touch[0].on_b.as_ref().unwrap(), 48);
2403 }
2404
2405 #[test]
2406 fn coaxial_tori_are_the_same_or_meet_in_parallels() {
2407 let ring = torus(Point::ORIGIN, Vector::Z, 2.0, 0.5);
2408 assert!(matches!(
2409 intersect_surfaces(&ring, &ring.clone(), IntersectOptions::default(), T).unwrap(),
2410 SurfaceIntersection::Same
2411 ));
2412
2413 let lifted = torus(Point::new(0.0, 0.0, 0.5), Vector::Z, 2.0, 0.5);
2416 let SurfaceIntersection::Along(curves) =
2417 intersect_surfaces(&ring, &lifted, IntersectOptions::default(), T).unwrap()
2418 else {
2419 panic!("lifted coaxial tori meet along curves");
2420 };
2421 assert_eq!(curves.len(), 2);
2422 for section in &curves {
2423 assert!(section.exact);
2424 assert_same_parameter(section, &ring, section.on_a.as_ref().unwrap(), 48);
2425 assert_same_parameter(section, &lifted, section.on_b.as_ref().unwrap(), 48);
2426 }
2427 }
2428
2429 #[test]
2430 fn a_pair_with_no_closed_form_comes_back_fitted_with_pcurves() {
2431 let a = cylinder(Vector::Z, 1.0);
2433 let b = cylinder(Vector::X, 1.6);
2434 let options = IntersectOptions {
2435 tolerance: 1e-5,
2436 marching: Marching {
2437 chord: 1e-5,
2438 ..Marching::default()
2439 },
2440 };
2441 let SurfaceIntersection::Along(curves) = intersect_surfaces(&a, &b, options, T).unwrap()
2442 else {
2443 panic!("crossed cylinders meet along curves");
2444 };
2445 assert_eq!(curves.len(), 2);
2446 for section in &curves {
2447 assert!(!section.exact);
2448 assert!(section.closed);
2449 assert!(
2450 section.tolerance <= 1e-5 + 1e-4,
2451 "got {}",
2452 section.tolerance
2453 );
2454 assert!(section.on_a.is_some() && section.on_b.is_some());
2455
2456 let (lo, hi) = section.curve.domain();
2458 for i in 0..=200 {
2459 #[allow(clippy::cast_precision_loss)]
2460 let t = lo + (hi - lo) * f64::from(i) / 200.0;
2461 let p = section.curve.point_at(t, T).unwrap();
2462 let (SurfaceGeometry::Cylinder(x), SurfaceGeometry::Cylinder(y)) = (&a, &b) else {
2463 unreachable!()
2464 };
2465 let off = x
2466 .cylinder()
2467 .distance_to(p)
2468 .abs()
2469 .max(y.cylinder().distance_to(p).abs());
2470 assert!(
2471 off <= section.tolerance * 2.0,
2472 "at t = {t} the fitted curve is {off:e} off, tolerance {}",
2473 section.tolerance
2474 );
2475 }
2476 }
2477 }
2478
2479 #[test]
2483 fn a_plane_all_but_along_the_axis_still_meets_a_short_drum() {
2484 let drum = cylinder(Vector::Z, 1.0);
2485 let wall: SurfaceGeometry = PlaneSurface::over(
2486 Plane::through(
2487 Point::new(0.0, 0.6, 0.0),
2488 Direction::new(Vector::new(0.0, 1.0, 1e-4), T).unwrap(),
2489 ),
2490 (-1e9, 1e9),
2491 (-1e9, 1e9),
2492 )
2493 .unwrap()
2494 .into();
2495 let met = intersect_surfaces(&wall, &drum, IntersectOptions::default(), T).unwrap();
2496 let SurfaceIntersection::Along(sections) = met else {
2497 panic!("the wall crosses the drum: {met:?}");
2498 };
2499 assert_eq!(sections.len(), 1);
2500 let curve = §ions[0].curve;
2501 let (lo, hi) = curve.domain();
2502 let inside = (0..=100_000).any(|k| {
2503 let p = curve
2504 .point_at(lo + (hi - lo) * f64::from(k) / 100_000.0, T)
2505 .unwrap();
2506 p.z.abs() <= 4.0
2507 });
2508 assert!(inside, "and the section runs through the drum's height");
2509 }
2510
2511 fn on_both(section: &SectionCurve, a: &SurfaceGeometry, b: &SurfaceGeometry) {
2514 let (lo, hi) = section.curve.domain();
2515 for k in 0..=64 {
2516 let p = section
2517 .curve
2518 .point_at(lo + (hi - lo) * f64::from(k) / 64.0, T)
2519 .unwrap();
2520 for surface in [a, b] {
2521 let off = match surface {
2522 SurfaceGeometry::Plane(plane) => plane.plane().signed_distance_to(p).abs(),
2523 SurfaceGeometry::Cylinder(drum) => {
2524 let axis = drum.cylinder().axis();
2525 let rel = p - axis.location;
2526 let d = axis.direction.vector();
2527 ((rel - d * rel.dot(d)).magnitude() - drum.cylinder().radius()).abs()
2528 }
2529 _ => unreachable!("planes and drums only"),
2530 };
2531 assert!(
2532 off <= section.tolerance + 1e-9,
2533 "{p:?} is {off:e} off, stated {:e}",
2534 section.tolerance
2535 );
2536 }
2537 }
2538 }
2539
2540 #[test]
2546 fn a_plane_all_but_along_a_drums_axis_meets_it_in_two_near_lines() {
2547 let drum = cylinder(Vector::Z, 1.0);
2548 let wall: SurfaceGeometry = PlaneSurface::over(
2549 Plane::through(
2550 Point::new(0.0, 0.99, 0.0),
2551 Direction::new(Vector::new(0.0, 1.0, 2e-5), T).unwrap(),
2552 ),
2553 (-1e9, 1e9),
2554 (-1e9, 1e9),
2555 )
2556 .unwrap()
2557 .into();
2558 let met = intersect_surfaces(&wall, &drum, IntersectOptions::default(), T).unwrap();
2559 let SurfaceIntersection::Along(sections) = met else {
2560 panic!("the wall crosses the drum: {met:?}");
2561 };
2562 assert_eq!(sections.len(), 2);
2563 for section in §ions {
2564 assert!(section.tolerance > 0.0 && section.tolerance <= 1e-5);
2565 on_both(section, &wall, &drum);
2566 }
2567 }
2568
2569 #[test]
2573 fn drums_all_but_parallel_meet_in_two_near_lines() {
2574 let drill = cylinder(Vector::Z, 1.0);
2575 let frame = Frame::new(
2576 Point::new(1.5, 0.0, 0.0),
2577 Direction::new(Vector::new(5e-5, 0.0, 1.0), T).unwrap(),
2578 Direction::X,
2579 T,
2580 )
2581 .unwrap();
2582 let bore: SurfaceGeometry =
2583 CylinderSurface::new(Cylinder::new(frame, 1.0, T).unwrap(), (-3.0, 3.0))
2584 .unwrap()
2585 .into();
2586 let met = intersect_surfaces(&drill, &bore, IntersectOptions::default(), T).unwrap();
2587 let SurfaceIntersection::Along(sections) = met else {
2588 panic!("the drums cross: {met:?}");
2589 };
2590 assert_eq!(sections.len(), 2);
2591 for section in §ions {
2592 assert!(!section.exact && section.tolerance <= 1e-5);
2593 let (lo, hi) = section.curve.domain();
2594 let (p, q) = (
2595 section.curve.point_at(lo, T).unwrap(),
2596 section.curve.point_at(hi, T).unwrap(),
2597 );
2598 assert!(
2599 (p.z - q.z).abs() > 5.9,
2600 "over the shared height: {p:?} {q:?}"
2601 );
2602 on_both(section, &drill, &bore);
2603 }
2604 }
2605
2606 #[test]
2607 fn exact_lines_are_clipped_to_the_surfaces_extents() {
2608 let drum = cylinder(Vector::Z, 2.0);
2613 let cut = plane(Point::ORIGIN, Vector::X);
2614 let SurfaceIntersection::Along(curves) =
2615 intersect_surfaces(&drum, &cut, IntersectOptions::default(), T).unwrap()
2616 else {
2617 panic!("expected curves");
2618 };
2619 for section in &curves {
2620 let (lo, hi) = section.curve.domain();
2621 assert!(
2623 hi - lo <= 8.0 + 1e-9,
2624 "the line was not clipped: [{lo}, {hi}]"
2625 );
2626 let start = section.curve.point_at(lo, T).unwrap();
2627 let end = section.curve.point_at(hi, T).unwrap();
2628 assert!(start.z >= -4.0 - 1e-9 && end.z <= 4.0 + 1e-9);
2629 }
2630
2631 let high = plane(Point::new(0.0, 0.0, 10.0), Vector::Z);
2635 assert_eq!(
2636 intersect_surfaces(&drum, &high, IntersectOptions::default(), T).unwrap(),
2637 SurfaceIntersection::Apart
2638 );
2639 }
2640
2641 #[test]
2642 fn the_degenerate_answers_pass_through() {
2643 assert_eq!(
2644 intersect_surfaces(
2645 &sphere(Point::ORIGIN, 1.0),
2646 &sphere(Point::new(5.0, 0.0, 0.0), 1.0),
2647 IntersectOptions::default(),
2648 T
2649 )
2650 .unwrap(),
2651 SurfaceIntersection::Apart
2652 );
2653 assert_eq!(
2654 intersect_surfaces(
2655 &sphere(Point::ORIGIN, 1.0),
2656 &sphere(Point::ORIGIN, 1.0),
2657 IntersectOptions::default(),
2658 T
2659 )
2660 .unwrap(),
2661 SurfaceIntersection::Same
2662 );
2663 assert!(matches!(
2664 intersect_surfaces(
2665 &plane(Point::ORIGIN, Vector::Z),
2666 &sphere(Point::new(0.0, 0.0, 2.0), 2.0),
2667 IntersectOptions::default(),
2668 T
2669 )
2670 .unwrap(),
2671 SurfaceIntersection::Touching(ref p) if p.len() == 1
2672 ));
2673 }
2674
2675 #[test]
2676 fn unusable_options_are_refused() {
2677 let a = sphere(Point::ORIGIN, 1.0);
2678 let b = plane(Point::ORIGIN, Vector::Z);
2679 for tolerance in [0.0, -1.0, f64::NAN] {
2680 let options = IntersectOptions {
2681 tolerance,
2682 ..IntersectOptions::default()
2683 };
2684 assert!(intersect_surfaces(&a, &b, options, T).is_err());
2685 }
2686 }
2687
2688 #[test]
2689 fn a_circle_wound_against_the_axis_keeps_its_pcurve_same_parameter() {
2690 let drum: SurfaceGeometry = CylinderSurface::new(
2697 Cylinder::new(
2698 Frame::new(Point::new(2.0, 2.0, -1.0), Direction::Z, Direction::X, T).unwrap(),
2699 0.5,
2700 T,
2701 )
2702 .unwrap(),
2703 (0.0, 3.0),
2704 )
2705 .unwrap()
2706 .into();
2707 for normal in [Direction::Z, -Direction::Z] {
2708 let frame = Frame::new(Point::ORIGIN, normal, Direction::X, T).unwrap();
2709 let ground: SurfaceGeometry =
2710 PlaneSurface::over(Plane::new(frame), (-4.0, 4.0), (-4.0, 4.0))
2711 .unwrap()
2712 .into();
2713 let met = intersect_surfaces(&ground, &drum, IntersectOptions::default(), T).unwrap();
2714 let SurfaceIntersection::Along(curves) = met else {
2715 panic!("a plane through a cylinder sections it");
2716 };
2717 for sc in &curves {
2718 let pcurve = sc
2719 .on_b
2720 .as_ref()
2721 .expect("a circle on its cylinder has a pcurve");
2722 let (lo, hi) = sc.curve.domain();
2723 for i in 0..8 {
2724 let t = lo + (hi - lo) * f64::from(i) / 8.0;
2725 let p3 = sc.curve.point_at(t, T).unwrap();
2726 let uv = pcurve.point_at(t, T).unwrap();
2727 let lifted = drum
2728 .point_at(uv.x.rem_euclid(core::f64::consts::TAU), uv.y, T)
2729 .unwrap();
2730 assert!(
2731 p3.distance(lifted) < 1e-9,
2732 "normal {normal:?}, t {t}: pcurve lifts {lifted:?} against {p3:?}"
2733 );
2734 }
2735 }
2736 }
2737 }
2738
2739 #[test]
2745 fn a_meridian_half_has_an_exact_line_for_a_pcurve() {
2746 use ogeom_geom::Surface as _;
2747 let half = core::f64::consts::PI;
2748 for (centre, radius) in [(Point::ORIGIN, 4.0), (Point::new(1.0, -2.0, 0.5), 1.25)] {
2749 let ball = sphere(centre, radius);
2750 let SurfaceGeometry::Sphere(s) = &ball else {
2751 panic!("a sphere surface");
2752 };
2753 for azimuth in [0.0_f64, 0.7, 2.4] {
2756 let normal = Vector::new(-azimuth.sin(), azimuth.cos(), 0.0);
2757 let cut = plane(centre, normal);
2758 let SurfaceIntersection::Along(curves) =
2759 intersect_surfaces(&ball, &cut, IntersectOptions::default(), T).unwrap()
2760 else {
2761 panic!("a plane through the centre meets the ball along a circle");
2762 };
2763 assert_eq!(curves.len(), 1, "one great circle");
2764 let circle = &curves[0].curve;
2765 assert!(curves[0].exact);
2766 assert!(
2768 exact_pcurve_over(circle, circle.domain(), &ball, T).is_none(),
2769 "the whole meridian has no single chart image"
2770 );
2771 for (lo, hi) in [(0.0, half), (half, 2.0 * half), (0.3, half - 0.1)] {
2772 let pcurve = exact_pcurve_over(circle, (lo, hi), &ball, T)
2773 .expect("half a meridian has an exact pcurve");
2774 assert!(
2775 matches!(pcurve, PlanarCurve::Line(_)),
2776 "and it is a straight line in the chart"
2777 );
2778 for i in 0..=16 {
2779 let t = (hi - lo).mul_add(f64::from(i) / 16.0, lo);
2780 let want = circle.point_at(t, T).unwrap();
2781 let uv = pcurve.point_at(t, T).unwrap();
2782 assert!(
2783 uv.y >= -half.mul_add(0.5, 1e-12) && uv.y <= half.mul_add(0.5, 1e-12),
2784 "the latitude stays inside the chart: {}",
2785 uv.y
2786 );
2787 let lifted = ball
2788 .point_at(uv.x.rem_euclid(core::f64::consts::TAU), uv.y, T)
2789 .unwrap();
2790 assert!(
2791 want.distance(lifted) < 1e-9,
2792 "azimuth {azimuth}, t {t}: {lifted:?} against {want:?}"
2793 );
2794 }
2795 }
2796 assert!(
2799 exact_pcurve_over(circle, (half - 0.2, half + 0.2), &ball, T).is_none(),
2800 "a range across a pole has no one line"
2801 );
2802 let _ = s;
2803 }
2804 }
2805 }
2806
2807 #[test]
2816 fn a_trimmed_curve_carries_its_basis_pcurve_trimmed_the_same_way() {
2817 use ogeom_geom::TrimmedCurve;
2818 let drum = cylinder(Vector::Z, 2.0);
2819 let ground = plane(Point::new(0.0, 0.0, 1.0), Vector::Z);
2820 let SurfaceIntersection::Along(curves) =
2822 intersect_surfaces(&drum, &ground, IntersectOptions::default(), T).unwrap()
2823 else {
2824 panic!("a plane across a cylinder meets it in a circle");
2825 };
2826 let whole = curves[0].curve.clone();
2827 let (lo, hi) = whole.domain();
2828 let quarter: Curve = TrimmedCurve::new(whole.clone(), lo + 0.3, lo + (hi - lo) / 4.0, T)
2829 .unwrap()
2830 .into();
2831
2832 for surface in [&drum, &ground] {
2833 let full = exact_pcurve_of(&whole, surface, T).expect("the whole circle has one");
2834 let part = exact_pcurve_of(&quarter, surface, T).expect("and so does a quarter of it");
2835 let (a, b) = quarter.domain();
2838 for i in 0..=8 {
2839 let t = (b - a).mul_add(f64::from(i) / 8.0, a);
2840 let (whole_at, part_at) =
2841 (full.point_at(t, T).unwrap(), part.point_at(t, T).unwrap());
2842 assert!(
2843 whole_at.distance(part_at) < 1e-12,
2844 "the trim carries the basis: {whole_at:?} against {part_at:?}"
2845 );
2846 let lifted = surface
2848 .point_at(part_at.x.rem_euclid(core::f64::consts::TAU), part_at.y, T)
2849 .or_else(|_| surface.point_at(part_at.x, part_at.y, T))
2850 .unwrap();
2851 assert!(
2852 lifted.distance(quarter.point_at(t, T).unwrap()) < 1e-9,
2853 "same-parameter, still"
2854 );
2855 }
2856 }
2857 }
2858 #[test]
2862 fn a_plane_through_a_cones_apex_holds_its_rulings() {
2863 use ogeom_geom::ConeSurface;
2864 let frame = Frame::new(
2865 Point::new(100.0, 200.0, 300.0),
2866 Direction::Z,
2867 Direction::X,
2868 T,
2869 )
2870 .unwrap();
2871 let cone = ogeom_math::Cone::new(frame, 10.0, core::f64::consts::FRAC_PI_4, T).unwrap();
2872 let surface: SurfaceGeometry = ConeSurface::new(cone, (-5.0, 50.0)).unwrap().into();
2873 let apex = Point::new(100.0, 200.0, 290.0);
2874 let plane = |normal: Vector| -> SurfaceGeometry {
2875 PlaneSurface::new(Plane::through(apex, Direction::new(normal, T).unwrap())).into()
2876 };
2877 let cases = [
2878 (Vector::new(1.0, 0.0, -1.0), 1, true),
2879 (Vector::new(1.0, 0.0, 0.0), 2, false),
2880 ];
2881 for (normal, count, tangent) in cases {
2882 let cut = plane(normal);
2883 let SurfaceIntersection::Along(sections) =
2884 intersect_surfaces(&surface, &cut, IntersectOptions::default(), T).unwrap()
2885 else {
2886 panic!("{normal:?}: rulings");
2887 };
2888 assert_eq!(sections.len(), count, "{normal:?}");
2889 for section in §ions {
2890 assert_eq!(section.tangential, tangent, "{normal:?}");
2891 let (lo, hi) = section.curve.domain();
2892 for k in 0..=4 {
2893 let p = section
2894 .curve
2895 .point_at(lo + (hi - lo) * f64::from(k) / 4.0, T)
2896 .unwrap();
2897 assert!(cone.distance_to(p) < 1e-9, "{p:?} on the cone");
2898 let height = p.z - 300.0;
2899 assert!(
2900 (-5.0 - 1e-9..=50.0 + 1e-9).contains(&height),
2901 "{p:?} in the window"
2902 );
2903 }
2904 }
2905 }
2906 let shallow = plane(Vector::new(0.2, 0.0, 1.0));
2907 assert!(matches!(
2908 intersect_surfaces(&surface, &shallow, IntersectOptions::default(), T).unwrap(),
2909 SurfaceIntersection::Touching(_) | SurfaceIntersection::Apart
2910 ));
2911 }
2912
2913 #[test]
2914 fn a_far_stated_ruling_reads_its_angle_on_the_used_nappe() {
2915 use ogeom_geom::ConeSurface;
2916 let cone =
2924 ogeom_math::Cone::new(Frame::WORLD, 24.0, core::f64::consts::FRAC_PI_4, T).unwrap();
2925 let surface: SurfaceGeometry = ConeSurface::new(cone, (-1e5, 1e5)).unwrap().into();
2926 let u_true = 0.01_f64;
2927 let radial = Vector::new(u_true.cos(), u_true.sin(), 0.0);
2928 let direction =
2931 Direction::new((radial + Vector::new(0.0, 0.0, 1.0)) / 2f64.sqrt(), T).unwrap();
2932 let far = -7.0e5;
2933 let origin = Point::ORIGIN + radial * 24.0 + direction.vector() * far;
2934 let line = ogeom_geom::LineCurve::over(
2935 ogeom_math::Axis::new(origin, direction),
2936 far.abs() - 1.0,
2937 far.abs() + 1.0,
2938 )
2939 .unwrap();
2940 let curve: Curve = line.into();
2941 let range = ogeom_geom::Curve3d::domain(&curve);
2942 let pcurve = exact_pcurve_over(&curve, range, &surface, T).expect("a ruling inverts");
2943 let at = pcurve.point_at(range.0, T).unwrap();
2944 let tau = core::f64::consts::TAU;
2945 let gap = (at.x - u_true)
2946 .rem_euclid(tau)
2947 .min(tau - (at.x - u_true).rem_euclid(tau));
2948 assert!(
2949 gap < 1e-6,
2950 "the ruling's chart angle must be the used side's: got u {} against {u_true}",
2951 at.x
2952 );
2953 }
2954
2955 #[test]
2962 fn loops_turning_sharply_where_drums_all_but_touch_fit_in_pieces() {
2963 let drum = |origin: Point, axis: Vector, x: Vector, radius: f64, height: (f64, f64)| {
2964 let frame = Frame::new(
2965 origin,
2966 Direction::new(axis, T).unwrap(),
2967 Direction::new(x, T).unwrap(),
2968 T,
2969 )
2970 .unwrap();
2971 let cylinder = Cylinder::new(frame, radius, T).unwrap();
2972 (
2973 cylinder,
2974 SurfaceGeometry::from(CylinderSurface::new(cylinder, height).unwrap()),
2975 )
2976 };
2977 let radius = 3.175;
2978 let (thin_drum, thin) = drum(
2979 Point::new(10.994_218_762_109_735, 53.975, -209.55),
2980 Vector::new(0.0, 0.0, -1.0),
2981 Vector::new(-1.0, 0.0, 0.0),
2982 radius,
2983 (-1000.0, 1000.0),
2984 );
2985 let (wide_drum, wide) = drum(
2986 Point::new(
2987 -14.478_610_818_124_423,
2988 3.999_371_635_181_902,
2989 -277.138_401_510_994_7,
2990 ),
2991 Vector::new(
2992 -0.565_016_635_381_368_8,
2993 0.528_780_602_945_684_7,
2994 0.633_361_883_673_714_3,
2995 ),
2996 Vector::new(0.0, 0.767_637_390_304_296_3, -0.640_884_417_821_817),
2997 57.088_766_757_544_09,
2998 (0.0, 171.306_147_621_762_6),
2999 );
3000 let options = IntersectOptions {
3001 tolerance: 1e-5,
3002 marching: crate::Marching {
3003 chord: 1e-5,
3004 ..crate::Marching::default()
3005 },
3006 };
3007 let SurfaceIntersection::Along(curves) =
3008 intersect_surfaces(&thin, &wide, options, T).unwrap()
3009 else {
3010 panic!("the drums cross");
3011 };
3012 let mut length = 0.0;
3013 for section in &curves {
3014 assert!(!section.tangential);
3015 assert!(
3016 section.tolerance < 1e-3,
3017 "a section states {} of doubt",
3018 section.tolerance
3019 );
3020 let (lo, hi) = section.curve.domain();
3021 let mut previous = section.curve.point_at(lo, T).unwrap();
3022 for i in 1..=400 {
3023 let t = lo + (hi - lo) * f64::from(i) / 400.0;
3024 let p = section.curve.point_at(t, T).unwrap();
3025 let off = thin_drum
3026 .distance_to(p)
3027 .abs()
3028 .max(wide_drum.distance_to(p).abs());
3029 assert!(off < 1e-3, "a section stands {off} off the drums");
3030 length += previous.distance(p);
3031 previous = p;
3032 }
3033 }
3034 assert!(
3037 length > 4.0 * core::f64::consts::PI * radius,
3038 "the sections cover {length}"
3039 );
3040 }
3041
3042 #[test]
3043 fn coincidence_is_measured_over_the_overlap_and_nowhere_else() {
3044 let patch = |plane: ogeom_math::Plane, u: (f64, f64), v: (f64, f64)| {
3047 let surface: SurfaceGeometry = PlaneSurface::over(plane, u, v).unwrap().into();
3048 SurfaceGeometry::from(surface.to_bspline(T).unwrap())
3049 };
3050 let reach = T.confusion() * 1e2;
3051
3052 let here = patch(ogeom_math::Plane::XY, (0.0, 10.0), (0.0, 10.0));
3055 let over = patch(ogeom_math::Plane::XY, (5.0, 15.0), (5.0, 15.0));
3056 assert!(surfaces_coincide(&here, &over, reach, T));
3057
3058 let above = patch(
3062 ogeom_math::Plane::new(
3063 Frame::new(Point::new(0.0, 0.0, 1.0), Direction::Z, Direction::X, T).unwrap(),
3064 ),
3065 (0.0, 10.0),
3066 (0.0, 10.0),
3067 );
3068 assert!(!surfaces_coincide(&here, &above, reach, T));
3069 let across = patch(
3070 ogeom_math::Plane::new(
3071 Frame::new(Point::new(5.0, 0.0, 0.0), Direction::X, Direction::Y, T).unwrap(),
3072 ),
3073 (0.0, 10.0),
3074 (0.0, 10.0),
3075 );
3076 assert!(!surfaces_coincide(&here, &across, reach, T));
3077 }
3078}