1use crate::madd::Madd;
8use std::f64::consts::{FRAC_PI_2, TAU};
9
10use crate::MathError;
11use crate::aabb::Aabb3;
12use crate::curves::{Circle3D, Ellipse3D, Hyperbola3D, Line3D, Parabola3D};
13use crate::frame::Frame3;
14use crate::nurbs::curve::NurbsCurve;
15use crate::nurbs::fitting::interpolate;
16use crate::nurbs::intersection::{IntersectionCurve, IntersectionPoint};
17use crate::surfaces::{ConicalSurface, CylindricalSurface, SphericalSurface, ToroidalSurface};
18use crate::tolerance::Tolerance;
19use crate::vec::{Point3, Vec3};
20
21#[derive(Debug, Clone)]
23pub enum ExactIntersectionCurve {
24 Circle(Circle3D),
26 Ellipse(Ellipse3D),
28 Points(Vec<Point3>),
30}
31
32#[derive(Debug, Clone)]
34#[non_exhaustive]
35pub enum PlaneSection {
36 Circle(Circle3D),
38 Ellipse(Ellipse3D),
40 Line {
44 line: Line3D,
46 ray: bool,
48 },
49 Point(Point3),
51 Points(Vec<Point3>),
53 Parabola(Parabola3D),
55 Hyperbola(Hyperbola3D),
58}
59
60impl From<ExactIntersectionCurve> for PlaneSection {
61 fn from(curve: ExactIntersectionCurve) -> Self {
62 match curve {
63 ExactIntersectionCurve::Circle(circle) => Self::Circle(circle),
64 ExactIntersectionCurve::Ellipse(ellipse) => Self::Ellipse(ellipse),
65 ExactIntersectionCurve::Points(points) => Self::Points(points),
66 }
67 }
68}
69
70pub fn exact_plane_section(
85 surface: AnalyticSurface<'_>,
86 normal: Vec3,
87 d: f64,
88) -> Result<Vec<PlaneSection>, MathError> {
89 match surface {
90 AnalyticSurface::Cylinder(cyl) if normal.dot(cyl.axis()).abs() < 1e-10 => {
91 return plane_cylinder_rulings(cyl, normal, d);
92 }
93 AnalyticSurface::Cone(cone) if plane_holds_apex(cone, normal, d) => {
94 return plane_cone_apex_rulings(cone, normal);
95 }
96 AnalyticSurface::Cone(cone) => {
97 if let Some(open) = plane_cone_open_section(cone, normal, d)? {
98 return Ok(open);
99 }
100 }
101 AnalyticSurface::Sphere(sphere) => {
102 let h = dot_np(normal, sphere.center()) - d;
103 let r = sphere.radius();
104 if (r - h.abs()).abs() <= TOUCH * r {
105 return Ok(vec![PlaneSection::Point(Point3::new(
106 h.madd(-normal.x(), sphere.center().x()),
107 h.madd(-normal.y(), sphere.center().y()),
108 h.madd(-normal.z(), sphere.center().z()),
109 ))]);
110 }
111 }
112 AnalyticSurface::Cylinder(_) | AnalyticSurface::Torus(_) => {}
113 }
114 Ok(exact_plane_analytic(surface, normal, d)?
115 .into_iter()
116 .map(PlaneSection::from)
117 .collect())
118}
119
120const PARABOLIC: f64 = 1e-12;
123
124const HYPERBOLIC: f64 = 1e-6;
128
129#[allow(clippy::many_single_char_names)]
136fn plane_cone_open_section(
137 cone: &ConicalSurface,
138 normal: Vec3,
139 d: f64,
140) -> Result<Option<Vec<PlaneSection>>, MathError> {
141 let axis = cone.axis();
142 let c = normal.dot(axis);
143 let p2 = c.madd(-c, 1.0).max(0.0);
144 let p = p2.sqrt();
145 let rise = cone.half_angle().sin();
146 let k = rise * rise;
147 let a_coeff = p2 - k;
148 let eccentric = a_coeff / k;
149 let m = axis - normal * c;
150 let m_len = m.length();
151 if m_len < 1e-12 || eccentric < -PARABOLIC || (eccentric > PARABOLIC && eccentric <= HYPERBOLIC)
152 {
153 return Ok(None);
154 }
155 let e1 = m * (1.0 / m_len);
156 let e2 = normal.cross(e1);
157 let apex = cone.apex();
158 let e = d - dot_np(normal, apex);
159 let origin = apex + normal * e;
160 let real = |s: f64| e.madd(c, s * p) >= 0.0;
163 let holds = |q: Point3| {
166 let w = q - apex;
167 let reach = w.length();
168 reach.is_finite() && (w.dot(axis) - rise * reach).abs() <= 1e-9 * (1.0 + reach)
169 };
170 if eccentric <= PARABOLIC {
171 let ecp = e * c * p;
174 let vertex_s = -e * (c * c - k) / (2.0 * c * p);
175 let focal = ecp.abs() / (2.0 * k);
176 if !(vertex_s.is_finite() && focal > 0.0 && focal.is_finite()) {
177 return Ok(None);
178 }
179 if !real(vertex_s) {
180 return Ok(Some(Vec::new()));
181 }
182 let parabola = Parabola3D::with_axes(origin + e1 * vertex_s, e1 * ecp.signum(), e2, focal)?;
183 if ![0.0, focal, -focal]
184 .iter()
185 .all(|&t| holds(parabola.evaluate(t)))
186 {
187 return Ok(None);
188 }
189 return Ok(Some(vec![PlaneSection::Parabola(parabola)]));
190 }
191 let centre_s = -e * c * p / a_coeff;
194 let rhs = e * e * k * (1.0 - k) / a_coeff;
195 let (real_axis, imaginary_axis) = ((rhs / a_coeff).sqrt(), (rhs / k).sqrt());
196 if !(real_axis > 0.0 && imaginary_axis > 0.0 && centre_s.is_finite()) {
197 return Ok(None);
198 }
199 let toward = if real(centre_s + real_axis) { e1 } else { -e1 };
200 let hyperbola = Hyperbola3D::with_axes(
201 origin + e1 * centre_s,
202 real_axis,
203 imaginary_axis,
204 toward,
205 e2,
206 )?;
207 if ![0.0, 1.0, -1.0]
208 .iter()
209 .all(|&t| holds(hyperbola.evaluate(t)))
210 {
211 return Ok(None);
212 }
213 Ok(Some(vec![PlaneSection::Hyperbola(hyperbola)]))
214}
215
216const TOUCH: f64 = 4.0 * f64::EPSILON;
219
220fn plane_cylinder_rulings(
223 cyl: &CylindricalSurface,
224 normal: Vec3,
225 d: f64,
226) -> Result<Vec<PlaneSection>, MathError> {
227 let (a, b) = (normal.dot(cyl.x_axis()), normal.dot(cyl.y_axis()));
230 let amp = a.hypot(b);
231 if amp < 1e-12 {
232 return Ok(vec![]);
233 }
234 let ratio = (d - dot_np(normal, cyl.origin())) / (cyl.radius() * amp);
235 if ratio.abs() > 1.0 + TOUCH {
236 return Ok(vec![]);
237 }
238 let phi = b.atan2(a);
239 let spread = ratio.clamp(-1.0, 1.0).acos();
240 let at = if ratio.abs() >= 1.0 - TOUCH {
241 vec![phi + spread]
242 } else {
243 vec![phi + spread, phi - spread]
244 };
245 at.into_iter()
246 .map(|u| {
247 Ok(PlaneSection::Line {
248 line: Line3D::new(cyl.evaluate(u, 0.0), cyl.axis())?,
249 ray: false,
250 })
251 })
252 .collect()
253}
254
255fn plane_holds_apex(cone: &ConicalSurface, normal: Vec3, d: f64) -> bool {
257 let apex = cone.apex() - Point3::new(0.0, 0.0, 0.0);
258 (normal.dot(apex) - d).abs() <= TOUCH * (1.0 + apex.length() + d.abs())
259}
260
261fn plane_cone_apex_rulings(
265 cone: &ConicalSurface,
266 normal: Vec3,
267) -> Result<Vec<PlaneSection>, MathError> {
268 let (sin_a, cos_a) = cone.half_angle().sin_cos();
271 let a = cos_a * normal.dot(cone.x_axis());
272 let b = cos_a * normal.dot(cone.y_axis());
273 let c = sin_a * normal.dot(cone.axis());
274 let amp = a.hypot(b);
275 let apex = cone.apex();
276 if amp < 1e-12 * c.abs().max(1.0) {
277 return Ok(vec![PlaneSection::Point(apex)]);
278 }
279 let ratio = -c / amp;
280 if ratio.abs() > 1.0 + TOUCH {
281 return Ok(vec![PlaneSection::Point(apex)]);
282 }
283 let phi = b.atan2(a);
284 let spread = ratio.clamp(-1.0, 1.0).acos();
285 let at = if ratio.abs() >= 1.0 - TOUCH {
286 vec![phi + spread]
287 } else {
288 vec![phi + spread, phi - spread]
289 };
290 at.into_iter()
291 .map(|u| {
292 Ok(PlaneSection::Line {
293 line: Line3D::new(apex, cone.evaluate(u, 1.0) - apex)?,
294 ray: true,
295 })
296 })
297 .collect()
298}
299
300pub fn exact_plane_analytic(
315 surface: AnalyticSurface<'_>,
316 plane_normal: Vec3,
317 plane_d: f64,
318) -> Result<Vec<ExactIntersectionCurve>, MathError> {
319 exact_plane_analytic_reaching(surface, plane_normal, plane_d, 0.0)
320}
321
322pub fn exact_plane_analytic_reaching(
330 surface: AnalyticSurface<'_>,
331 plane_normal: Vec3,
332 plane_d: f64,
333 reach: f64,
334) -> Result<Vec<ExactIntersectionCurve>, MathError> {
335 match surface {
336 AnalyticSurface::Cylinder(cyl) => exact_plane_cylinder(cyl, plane_normal, plane_d),
337 AnalyticSurface::Sphere(sphere) => exact_plane_sphere(sphere, plane_normal, plane_d),
338 AnalyticSurface::Cone(cone) if plane_holds_apex(cone, plane_normal, plane_d) => Ok(vec![]),
339 AnalyticSurface::Cone(cone) => exact_plane_cone(cone, plane_normal, plane_d, reach),
340 AnalyticSurface::Torus(torus) => {
341 if let Some(circles) = exact_plane_torus(torus, plane_normal, plane_d)? {
342 return Ok(circles);
343 }
344 if let Some(loops) = plane_torus_winding_loops(torus, plane_normal, plane_d, 128) {
345 return Ok(loops
346 .into_iter()
347 .map(ExactIntersectionCurve::Points)
348 .collect());
349 }
350 let chains = sample_plane_torus(torus, plane_normal, plane_d)?;
352 Ok(chains
353 .into_iter()
354 .map(ExactIntersectionCurve::Points)
355 .collect())
356 }
357 }
358}
359
360fn exact_plane_torus(
374 torus: &ToroidalSurface,
375 normal: Vec3,
376 d: f64,
377) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
378 let len = normal.length();
379 let n = normal.normalize()?;
380 let d = d / len;
381 let axis = torus.z_axis();
382 let center = torus.center();
383 let (big, small) = (torus.major_radius(), torus.minor_radius());
384 let height = d - dot_np(n, center);
385 let along = n.dot(axis);
386 if along.abs() > 1.0 - 1e-10 {
387 if height.abs() >= small - 1e-10 * small {
388 if height.abs() > small + 1e-10 * small {
389 return Ok(Some(Vec::new()));
390 }
391 if big <= 1e-10 * small
398 || axis.cross(n).length() > 1e-12
399 || (small - height.abs()).abs() > crate::tolerance::Tolerance::default().linear
400 {
401 return Ok(None);
402 }
403 let middle = center + n * height;
404 return Ok(Some(vec![ExactIntersectionCurve::Circle(Circle3D::new(
405 middle, n, big,
406 )?)]));
407 }
408 let reach = small.madd(small, -(height * height)).sqrt();
409 if big - reach <= 1e-10 * big {
410 return Ok(None);
411 }
412 let middle = center + n * height;
413 return Ok(Some(vec![
414 ExactIntersectionCurve::Circle(Circle3D::new(middle, n, big + reach)?),
415 ExactIntersectionCurve::Circle(Circle3D::new(middle, n, big - reach)?),
416 ]));
417 }
418 if along.abs() < 1e-10 && height.abs() < 1e-10 * (big + small) {
419 let out = axis.cross(n).normalize()?;
420 return Ok(Some(vec![
421 ExactIntersectionCurve::Circle(Circle3D::new(center + out * big, n, small)?),
422 ExactIntersectionCurve::Circle(Circle3D::new(center - out * big, n, small)?),
423 ]));
424 }
425 Ok(None)
426}
427
428fn exact_plane_cylinder(
434 cyl: &CylindricalSurface,
435 normal: Vec3,
436 d: f64,
437) -> Result<Vec<ExactIntersectionCurve>, MathError> {
438 let axis = cyl.axis();
439 let cos_theta = normal.dot(axis).abs();
440 let r = cyl.radius();
441
442 if cos_theta < 1e-10 {
443 return Ok(vec![]);
446 }
447
448 let n_dot_axis = normal.dot(axis);
451 let n_dot_origin = dot_np(normal, cyl.origin());
452 let t = (d - n_dot_origin) / n_dot_axis;
453 let center_on_axis = Point3::new(
454 cyl.origin().x() + t * axis.x(),
455 cyl.origin().y() + t * axis.y(),
456 cyl.origin().z() + t * axis.z(),
457 );
458
459 if cos_theta > 1.0 - 1e-10 {
460 let circle = Circle3D::new(center_on_axis, normal, r)?;
462 Ok(vec![ExactIntersectionCurve::Circle(circle)])
463 } else {
464 let semi_minor = r;
468 let semi_major = r / cos_theta;
469
470 let axis_proj = Vec3::new(
474 axis.x() - n_dot_axis * normal.x(),
475 axis.y() - n_dot_axis * normal.y(),
476 axis.z() - n_dot_axis * normal.z(),
477 );
478 let u_axis = axis_proj.normalize()?;
479 let v_axis = normal.cross(u_axis);
480
481 let ellipse = Ellipse3D::with_axes(
482 center_on_axis,
483 normal,
484 semi_major,
485 semi_minor,
486 u_axis,
487 v_axis,
488 )?;
489 Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)])
490 }
491}
492
493fn exact_plane_sphere(
497 sphere: &SphericalSurface,
498 normal: Vec3,
499 d: f64,
500) -> Result<Vec<ExactIntersectionCurve>, MathError> {
501 let h = dot_np(normal, sphere.center()) - d;
502 let r = sphere.radius();
503
504 if r - h.abs() <= TOUCH * r {
507 return Ok(vec![]);
508 }
509
510 let circle_r = (r.madd(r, -(h * h))).sqrt();
511 let circle_center = Point3::new(
512 h.madd(-normal.x(), sphere.center().x()),
513 h.madd(-normal.y(), sphere.center().y()),
514 h.madd(-normal.z(), sphere.center().z()),
515 );
516
517 let circle = Circle3D::new(circle_center, normal, circle_r)?;
518 Ok(vec![ExactIntersectionCurve::Circle(circle)])
519}
520
521pub fn exact_sphere_sphere(
533 s1: &SphericalSurface,
534 s2: &SphericalSurface,
535) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
536 let delta = s2.center() - s1.center();
537 let d = delta.length();
538 let (r1, r2) = (s1.radius(), s2.radius());
539 let scale = r1.max(r2);
540 if d <= 1e-12 * scale {
541 return Ok(((r1 - r2).abs() > 1e-12 * scale).then(Vec::new));
543 }
544 let normal = delta * (1.0 / d);
545 let (centre, toward, r_small, r_big) = if r1 <= r2 {
548 (s1.center(), normal, r1, r2)
549 } else {
550 (s2.center(), -normal, r2, r1)
551 };
552 let along = d.madd(d, r_small.madd(r_small, -(r_big * r_big))) / (2.0 * d);
553 if along.abs() > r_small - 1e-10 * scale.max(1.0) {
554 return Ok(Some(Vec::new()));
555 }
556 let radius = r_small.madd(r_small, -(along * along)).sqrt();
557 let circle = Circle3D::new(centre + toward * along, normal, radius)?;
558 Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
559}
560
561fn exact_plane_cone(
570 cone: &ConicalSurface,
571 normal: Vec3,
572 d: f64,
573 reach: f64,
574) -> Result<Vec<ExactIntersectionCurve>, MathError> {
575 let axis = cone.axis();
576 let cos_theta = normal.dot(axis).abs();
577 let half_angle = cone.half_angle();
578
579 if cos_theta > 1.0 - 1e-10 {
580 let n_dot_axis = normal.dot(axis);
583 let n_dot_apex = dot_np(normal, cone.apex());
584 let t = (d - n_dot_apex) / n_dot_axis;
585
586 if t.abs() < 1e-10 {
591 return Ok(vec![]);
592 }
593
594 let center = Point3::new(
595 cone.apex().x() + t * axis.x(),
596 cone.apex().y() + t * axis.y(),
597 cone.apex().z() + t * axis.z(),
598 );
599 let circle_r = t.abs() * half_angle.cos() / half_angle.sin();
603 if circle_r < 1e-15 {
604 return Ok(vec![]);
605 }
606
607 let circle = Circle3D::new(center, normal, circle_r)?;
608 return Ok(vec![ExactIntersectionCurve::Circle(circle)]);
609 }
610
611 let c = normal.dot(axis);
623 let p2 = (1.0 - c * c).max(0.0);
624 let p = p2.sqrt();
625 let k = half_angle.sin().powi(2);
626 let a_coeff = p2 - k;
627
628 let m = Vec3::new(
630 axis.x() - c * normal.x(),
631 axis.y() - c * normal.y(),
632 axis.z() - c * normal.z(),
633 );
634 let m_len = m.length();
635 if m_len < 1e-12 {
636 let chains = sample_plane_cone(cone, normal, d, reach)?;
639 return Ok(chains
640 .into_iter()
641 .map(ExactIntersectionCurve::Points)
642 .collect());
643 }
644 let e1 = m * (1.0 / m_len);
645 let e2 = normal.cross(e1);
646 let apex = cone.apex();
647 let e = d - dot_np(normal, apex);
648
649 if a_coeff < -1e-9 {
652 let abs_a = -a_coeff; if e * c < 0.0 {
659 return Ok(vec![]);
660 }
661 let s_c = e * c * p / abs_a;
664 let rhs = e * e * k * (1.0 - k) / abs_a;
665 if rhs <= 0.0 {
666 return Ok(vec![]);
667 }
668 let semi_s = (rhs / abs_a).sqrt(); let semi_t = (rhs / k).sqrt(); if semi_s < 1e-12 || semi_t < 1e-12 {
671 return Ok(vec![]);
672 }
673 let center = apex + normal * e + e1 * s_c;
674 let (semi_major, semi_minor, u_axis, v_axis) = if semi_s >= semi_t {
675 (semi_s, semi_t, e1, e2)
676 } else {
677 (semi_t, semi_s, e2, e1)
678 };
679 let ellipse = Ellipse3D::with_axes(center, normal, semi_major, semi_minor, u_axis, v_axis)?;
680 return Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)]);
681 }
682
683 let chains = sample_plane_cone(cone, normal, d, reach)?;
686 Ok(chains
687 .into_iter()
688 .map(ExactIntersectionCurve::Points)
689 .collect())
690}
691
692#[allow(clippy::many_single_char_names)]
707pub fn plane_cone_conic_arc(
708 cone: &ConicalSurface,
709 normal: Vec3,
710 d: f64,
711 from: Point3,
712 to: Point3,
713) -> Result<Option<NurbsCurve>, MathError> {
714 let len = normal.length();
715 if len < 1e-15 {
716 return Err(MathError::ZeroVector);
717 }
718 let (normal, d) = (normal * (1.0 / len), d / len);
719 let axis = cone.axis();
720 let c = normal.dot(axis);
721 let p2 = (1.0 - c * c).max(0.0);
722 let p = p2.sqrt();
723 let k = cone.half_angle().sin().powi(2);
724 let a_coeff = p2 - k;
725 let m = Vec3::new(
726 axis.x() - c * normal.x(),
727 axis.y() - c * normal.y(),
728 axis.z() - c * normal.z(),
729 );
730 let m_len = m.length();
731 if m_len < 1e-12 || a_coeff < -1e-9 {
732 return Ok(None);
733 }
734 let e1 = m * (1.0 / m_len);
735 let e2 = normal.cross(e1);
736 let apex = cone.apex();
737 let e = d - dot_np(normal, apex);
738 let origin = apex + normal * e;
739 let plane_st = |q: Point3| {
740 let w = q - origin;
741 (w.dot(e1), w.dot(e2))
742 };
743 let ((s0, t0), (s1, t1)) = (plane_st(from), plane_st(to));
744 let scale = s0.abs().max(t0.abs()).max(s1.abs()).max(t1.abs()).max(1.0);
745 if e.abs() < 1e-9 * scale || (from - to).length() <= 1e-9 * scale {
746 return Ok(None);
747 }
748 let point = |s: f64, t: f64| origin + e1 * s + e2 * t;
749 let on_curve = |q: Point3, r: Point3| (q - r).length() <= 1e-6 * scale;
750 let (control, weights) = if a_coeff.abs() <= 1e-9 {
751 let lin = 2.0 * e * c * p;
753 if lin.abs() < 1e-12 * scale {
754 return Ok(None);
755 }
756 let (alpha, beta) = (k / lin, -e * e * (c * c - k) / lin);
757 if !on_curve(point(alpha * t0 * t0 + beta, t0), from)
758 || !on_curve(point(alpha * t1 * t1 + beta, t1), to)
759 {
760 return Ok(None);
761 }
762 let mid = point(alpha * t0 * t1 + beta, 0.5 * (t0 + t1));
763 (vec![from, mid, to], vec![1.0; 3])
764 } else {
765 let s_c = -e * c * p / a_coeff;
767 let r = e * e * k * (1.0 - k) / a_coeff;
768 if r <= 0.0 {
769 return Ok(None);
770 }
771 let (a, b) = ((r / a_coeff).sqrt(), (r / k).sqrt());
772 let (x0, x1) = (s0 - s_c, s1 - s_c);
773 if x0 * x1 <= 0.0 {
774 return Ok(None);
775 }
776 let side = x0.signum();
777 let hyperbola = |phi: f64| point(s_c + side * a * phi.cosh(), b * phi.sinh());
778 let (phi0, phi1) = ((t0 / b).asinh(), (t1 / b).asinh());
779 if !on_curve(hyperbola(phi0), from) || !on_curve(hyperbola(phi1), to) {
780 return Ok(None);
781 }
782 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
783 let pieces = ((phi1 - phi0).abs().ceil() as usize).max(1);
784 let mut control = vec![from];
785 let mut weights = vec![1.0];
786 for i in 0..pieces {
787 #[allow(clippy::cast_precision_loss)]
788 let (fa, fb) = (i as f64 / pieces as f64, (i + 1) as f64 / pieces as f64);
789 let (pa, pb) = (phi0 + (phi1 - phi0) * fa, phi0 + (phi1 - phi0) * fb);
790 let (mid, half) = (0.5 * (pa + pb), 0.5 * (pb - pa));
791 let w = half.cosh();
792 control.push(point(s_c + side * a * mid.cosh() / w, b * mid.sinh() / w));
793 weights.push(w);
794 control.push(if i + 1 == pieces { to } else { hyperbola(pb) });
795 weights.push(1.0);
796 }
797 (control, weights)
798 };
799 let pieces = (control.len() - 1) / 2;
800 let mut knots = vec![0.0; 3];
801 for i in 1..pieces {
802 #[allow(clippy::cast_precision_loss)]
803 knots.extend([i as f64; 2]);
804 }
805 #[allow(clippy::cast_precision_loss)]
806 knots.extend([pieces as f64; 3]);
807 let curve = NurbsCurve::new(2, knots, control, weights)?;
808 let (sin_a, cos_a) = cone.half_angle().sin_cos();
813 let off_cone = |q: Point3| {
814 let w = q - apex;
815 let h = w.dot(axis);
816 (w - axis * h)
817 .length()
818 .madd(sin_a, -(h.abs() * cos_a))
819 .abs()
820 };
821 for i in 0..pieces {
822 for f in [0.25, 0.5, 0.75] {
823 #[allow(clippy::cast_precision_loss)]
824 if off_cone(curve.evaluate(i as f64 + f)) > 1e-9 * scale {
825 return Ok(None);
826 }
827 }
828 }
829 Ok(Some(curve))
830}
831
832#[derive(Clone, Copy)]
834pub enum AnalyticSurface<'a> {
835 Cylinder(&'a CylindricalSurface),
837 Cone(&'a ConicalSurface),
839 Sphere(&'a SphericalSurface),
841 Torus(&'a ToroidalSurface),
843}
844
845fn dot_np(n: Vec3, p: Point3) -> f64 {
847 n.dot(Vec3::new(p.x(), p.y(), p.z()))
848}
849
850pub fn intersect_plane_analytic(
858 surface: AnalyticSurface<'_>,
859 normal: Vec3,
860 d: f64,
861) -> Result<Vec<IntersectionCurve>, MathError> {
862 match surface {
863 AnalyticSurface::Cylinder(cyl) => intersect_plane_cylinder(cyl, normal, d),
864 AnalyticSurface::Cone(cone) => intersect_plane_cone(cone, normal, d),
865 AnalyticSurface::Sphere(sphere) => intersect_plane_sphere(sphere, normal, d),
866 AnalyticSurface::Torus(torus) => intersect_plane_torus(torus, normal, d),
867 }
868}
869
870pub fn sample_plane_analytic(
881 surface: AnalyticSurface<'_>,
882 normal: Vec3,
883 d: f64,
884) -> Result<Vec<Vec<Point3>>, MathError> {
885 match surface {
886 AnalyticSurface::Cylinder(cyl) => sample_plane_cylinder(cyl, normal, d),
887 AnalyticSurface::Cone(cone) => sample_plane_cone(cone, normal, d, 0.0),
888 AnalyticSurface::Sphere(sphere) => sample_plane_sphere(sphere, normal, d),
889 AnalyticSurface::Torus(torus) => sample_plane_torus(torus, normal, d),
890 }
891}
892
893#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
895fn sample_plane_cylinder(
896 cyl: &CylindricalSurface,
897 normal: Vec3,
898 d: f64,
899) -> Result<Vec<Vec<Point3>>, MathError> {
900 let n_samples = 64_usize;
901 let mut points = Vec::with_capacity(n_samples + 1);
902
903 for i in 0..=n_samples {
904 let u = TAU * (i as f64) / (n_samples as f64);
905 let base = cyl.evaluate(u, 0.0);
906 let n_dot_axis = normal.dot(cyl.axis());
907 let n_dot_base = dot_np(normal, base);
908
909 if n_dot_axis.abs() < 1e-12 {
910 if (n_dot_base - d).abs() < 1e-6 {
911 points.push(base);
912 }
913 } else {
914 let v = (d - n_dot_base) / n_dot_axis;
915 if v.abs() <= 100.0 {
916 points.push(cyl.evaluate(u, v));
917 }
918 }
919 }
920
921 if points.len() < 2 {
922 Ok(vec![])
923 } else {
924 Ok(vec![points])
925 }
926}
927
928#[allow(clippy::cast_precision_loss)]
930fn sample_plane_sphere(
931 sphere: &SphericalSurface,
932 normal: Vec3,
933 d: f64,
934) -> Result<Vec<Vec<Point3>>, MathError> {
935 let h = dot_np(normal, sphere.center()) - d;
936 let r = sphere.radius();
937
938 if h.abs() > r - 1e-10 {
939 return Ok(vec![]);
940 }
941
942 let circle_r = (r.madd(r, -(h * h))).sqrt();
943 let circle_center = Point3::new(
944 h.madd(-normal.x(), sphere.center().x()),
945 h.madd(-normal.y(), sphere.center().y()),
946 h.madd(-normal.z(), sphere.center().z()),
947 );
948
949 let basis = Frame3::from_normal(circle_center, normal)?;
950 let u_dir = basis.x;
951 let v_dir = basis.y;
952
953 let n_samples = 64_usize;
954 let mut points = Vec::with_capacity(n_samples + 1);
955
956 for i in 0..=n_samples {
957 let theta = TAU * (i as f64) / (n_samples as f64);
958 let (sin_t, cos_t) = theta.sin_cos();
959 points.push(circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t));
960 }
961
962 Ok(vec![points])
963}
964
965#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
977fn sample_plane_cone(
978 cone: &ConicalSurface,
979 normal: Vec3,
980 d: f64,
981 reach: f64,
982) -> Result<Vec<Vec<Point3>>, MathError> {
983 let apex = cone.apex();
984 let n_dot_apex = dot_np(normal, apex);
985 let e = d - n_dot_apex;
986
987 let n_samples = 512_usize;
991 let mut vs: Vec<Option<f64>> = Vec::with_capacity(n_samples);
992 let mut v_min = f64::INFINITY;
993 for i in 0..n_samples {
994 let u = TAU * (i as f64) / (n_samples as f64);
995 let g = cone.evaluate(u, 1.0) - apex;
996 let n_dot_g = normal.dot(Vec3::new(g.x(), g.y(), g.z()));
997 if n_dot_g.abs() < 1e-12 {
998 vs.push(None);
999 continue;
1000 }
1001 let v = e / n_dot_g;
1002 if v >= -1e-12 {
1003 let v = v.max(0.0);
1004 v_min = v_min.min(v);
1005 vs.push(Some(v));
1006 } else {
1007 vs.push(None);
1008 }
1009 }
1010
1011 if !v_min.is_finite() {
1012 return Ok(Vec::new());
1013 }
1014
1015 let v_max = (8.0 * v_min).max(v_min + 4.0).max(reach);
1024
1025 let kept: Vec<Option<f64>> = vs.iter().map(|v| v.filter(|&v| v <= v_max)).collect();
1028
1029 let point_at = |u: f64, v: f64| -> Point3 {
1030 let g = cone.evaluate(u, 1.0) - apex;
1031 apex + g * v
1032 };
1033 #[allow(clippy::cast_precision_loss)]
1034 let u_of = |i: usize| TAU * (i as f64) / (n_samples as f64);
1035 let n_dot_g_at = |u: f64| -> f64 {
1036 let g = cone.evaluate(u, 1.0) - apex;
1037 normal.dot(Vec3::new(g.x(), g.y(), g.z()))
1038 };
1039
1040 if kept.iter().all(Option::is_some) {
1041 let mut pts: Vec<Point3> = kept
1043 .iter()
1044 .enumerate()
1045 .filter_map(|(i, v)| v.map(|v| point_at(u_of(i), v)))
1046 .collect();
1047 if let Some(&first) = pts.first() {
1048 pts.push(first);
1049 }
1050 return Ok(vec![pts]);
1051 }
1052
1053 let tail = |i_end: usize, forward: bool, kept: &[Option<f64>]| -> Vec<Point3> {
1062 let Some(v_end) = kept[i_end] else {
1063 return Vec::new();
1064 };
1065 let u_end = u_of(i_end);
1066 #[allow(clippy::cast_precision_loss)]
1067 let pitch = TAU / (n_samples as f64);
1068 let u_next = if forward {
1069 u_end + pitch
1070 } else {
1071 u_end - pitch
1072 };
1073 let target = e / v_max;
1074 let h_end = n_dot_g_at(u_end) - target;
1075 let h_next = n_dot_g_at(u_next) - target;
1076 if v_end >= v_max || h_end == 0.0 || h_end.signum() == h_next.signum() {
1077 return Vec::new();
1078 }
1079 let (mut lo, mut hi) = (u_end, u_next);
1080 for _ in 0..60 {
1081 let mid = f64::midpoint(lo, hi);
1082 if (n_dot_g_at(mid) - target).signum() == h_end.signum() {
1083 lo = mid;
1084 } else {
1085 hi = mid;
1086 }
1087 }
1088 let u_star = f64::midpoint(lo, hi);
1089 let tail_n = 8_usize;
1090 (1..=tail_n)
1091 .filter_map(|k| {
1092 #[allow(clippy::cast_precision_loss)]
1093 let u = u_end + (u_star - u_end) * (k as f64) / (tail_n as f64);
1094 let ng = n_dot_g_at(u);
1095 if ng.abs() < 1e-12 {
1096 return None;
1097 }
1098 let v = e / ng;
1099 (v >= -1e-12 && v <= v_max * (1.0 + 1e-9)).then(|| point_at(u, v.max(0.0)))
1100 })
1101 .collect()
1102 };
1103
1104 let gap = kept.iter().position(Option::is_none).unwrap_or(0);
1107 let mut chains: Vec<Vec<Point3>> = Vec::new();
1108 let mut run: Vec<usize> = Vec::new();
1109 let flush = |run: &mut Vec<usize>, chains: &mut Vec<Vec<Point3>>| {
1110 if run.len() >= 2 {
1111 let first = run[0];
1112 let last = run[run.len() - 1];
1113 let mut pts: Vec<Point3> = tail(first, false, &kept);
1114 pts.reverse();
1115 pts.extend(
1116 run.iter()
1117 .filter_map(|&i| kept[i].map(|v| point_at(u_of(i), v))),
1118 );
1119 pts.extend(tail(last, true, &kept));
1120 chains.push(pts);
1121 }
1122 run.clear();
1123 };
1124 for k in 0..n_samples {
1125 let idx = (gap + k) % n_samples;
1126 if kept[idx].is_some() {
1127 run.push(idx);
1128 } else {
1129 flush(&mut run, &mut chains);
1130 }
1131 }
1132 flush(&mut run, &mut chains);
1133 Ok(chains.into_iter().filter(|c| c.len() >= 2).collect())
1134}
1135
1136#[allow(clippy::unnecessary_wraps)] fn sample_plane_torus(
1142 torus: &ToroidalSurface,
1143 normal: Vec3,
1144 d: f64,
1145) -> Result<Vec<Vec<Point3>>, MathError> {
1146 Ok(plane_torus_loops(torus, normal, d, 128)
1147 .into_iter()
1148 .map(|run| run.into_iter().map(|p| p.point).collect())
1149 .collect())
1150}
1151
1152#[allow(clippy::cast_precision_loss)]
1162pub fn intersect_plane_cylinder(
1163 cyl: &CylindricalSurface,
1164 normal: Vec3,
1165 d: f64,
1166) -> Result<Vec<IntersectionCurve>, MathError> {
1167 let n_samples = 64_usize;
1168 let mut points_3d = Vec::new();
1169 let mut ipoints = Vec::new();
1170
1171 for i in 0..=n_samples {
1172 let u = TAU * (i as f64) / (n_samples as f64);
1173 let base = cyl.evaluate(u, 0.0);
1176 let n_dot_axis = normal.dot(cyl.axis());
1177 let n_dot_base = dot_np(normal, base);
1178
1179 if n_dot_axis.abs() < 1e-12 {
1180 if (n_dot_base - d).abs() < 1e-6 {
1182 let pt = base;
1183 points_3d.push(pt);
1184 ipoints.push(IntersectionPoint {
1185 point: pt,
1186 param1: (u, 0.0),
1187 param2: (0.0, 0.0),
1188 });
1189 }
1190 } else {
1191 let v = (d - n_dot_base) / n_dot_axis;
1192 if v.abs() <= 100.0 {
1194 let pt = cyl.evaluate(u, v);
1195 points_3d.push(pt);
1196 ipoints.push(IntersectionPoint {
1197 point: pt,
1198 param1: (u, v),
1199 param2: (0.0, 0.0),
1200 });
1201 }
1202 }
1203 }
1204
1205 build_curves_from_points(&points_3d, ipoints)
1206}
1207
1208#[allow(clippy::cast_precision_loss)]
1217pub fn intersect_plane_sphere(
1218 sphere: &SphericalSurface,
1219 normal: Vec3,
1220 d: f64,
1221) -> Result<Vec<IntersectionCurve>, MathError> {
1222 let h = dot_np(normal, sphere.center()) - d;
1223 let r = sphere.radius();
1224
1225 if h.abs() > r - 1e-10 {
1227 return Ok(vec![]);
1228 }
1229
1230 let circle_r = (r.madd(r, -(h * h))).sqrt();
1231 let circle_center = Point3::new(
1232 h.madd(-normal.x(), sphere.center().x()),
1233 h.madd(-normal.y(), sphere.center().y()),
1234 h.madd(-normal.z(), sphere.center().z()),
1235 );
1236
1237 let basis = Frame3::from_normal(circle_center, normal)?;
1239 let u_dir = basis.x;
1240 let v_dir = basis.y;
1241
1242 let n_samples = 64_usize;
1243 let mut points_3d = Vec::new();
1244 let mut ipoints = Vec::new();
1245
1246 for i in 0..=n_samples {
1247 let theta = TAU * (i as f64) / (n_samples as f64);
1248 let (sin_t, cos_t) = theta.sin_cos();
1249 let pt = circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t);
1250 points_3d.push(pt);
1251 ipoints.push(IntersectionPoint {
1252 point: pt,
1253 param1: (theta, 0.0),
1254 param2: (0.0, 0.0),
1255 });
1256 }
1257
1258 build_curves_from_points(&points_3d, ipoints)
1259}
1260
1261#[allow(clippy::cast_precision_loss)]
1270pub fn intersect_plane_cone(
1271 cone: &ConicalSurface,
1272 normal: Vec3,
1273 d: f64,
1274) -> Result<Vec<IntersectionCurve>, MathError> {
1275 let n_samples = 64_usize;
1276 let mut points_3d = Vec::new();
1277 let mut ipoints = Vec::new();
1278
1279 for i in 0..n_samples {
1280 let u = TAU * (i as f64) / (n_samples as f64);
1281 let apex = cone.apex();
1284 let n_dot_apex = dot_np(normal, apex);
1285 let p1 = cone.evaluate(u, 1.0);
1287 let dir = p1 - apex;
1288 let n_dot_dir = normal.dot(dir);
1289
1290 if n_dot_dir.abs() < 1e-12 {
1291 continue;
1292 }
1293
1294 let v = (d - n_dot_apex) / n_dot_dir;
1295 if v.abs() > 1e-10 && v.abs() < 100.0 {
1297 let pt = cone.evaluate(u, v);
1298 points_3d.push(pt);
1299 ipoints.push(IntersectionPoint {
1300 point: pt,
1301 param1: (u, v),
1302 param2: (0.0, 0.0),
1303 });
1304 }
1305 }
1306
1307 build_curves_from_points(&points_3d, ipoints)
1308}
1309
1310#[allow(clippy::unnecessary_wraps)]
1322pub fn intersect_plane_torus(
1323 torus: &ToroidalSurface,
1324 normal: Vec3,
1325 d: f64,
1326) -> Result<Vec<IntersectionCurve>, MathError> {
1327 let mut curves = Vec::new();
1331 for ipts in plane_torus_loops(torus, normal, d, 128) {
1332 let pts: Vec<Point3> = ipts.iter().map(|p| p.point).collect();
1333 if let Ok(curve) = interpolate(&pts, 3.min(pts.len() - 1)) {
1334 curves.push(IntersectionCurve {
1335 curve,
1336 points: ipts,
1337 });
1338 }
1339 }
1340
1341 Ok(curves)
1342}
1343
1344const PLANE_TORUS_LOOP_SAMPLES: (f64, f64) = (24.0, 512.0);
1347
1348#[allow(clippy::cast_precision_loss, clippy::too_many_lines)]
1371fn plane_torus_loops(
1372 torus: &ToroidalSurface,
1373 normal: Vec3,
1374 d: f64,
1375 n_v: usize,
1376) -> Vec<Vec<IntersectionPoint>> {
1377 let big_r = torus.major_radius();
1378 let small_r = torus.minor_radius();
1379 let a = normal.dot(torus.x_axis());
1380 let b = normal.dot(torus.y_axis());
1381 let c = normal.dot(torus.z_axis());
1382 let s = a.hypot(b);
1383 let phi = b.atan2(a);
1384 let d_local = d - dot_np(normal, torus.center());
1385 let point = |u: f64, v: f64| IntersectionPoint {
1386 point: torus.evaluate(u, v),
1387 param1: (u, v.rem_euclid(TAU)),
1388 param2: (0.0, 0.0),
1389 };
1390 let closed = |mut run: Vec<IntersectionPoint>| {
1391 run.push(run[0]);
1392 run
1393 };
1394
1395 if s < 1e-12 {
1397 if c.abs() < 1e-12 {
1398 return Vec::new();
1399 }
1400 let sin_v = d_local / (small_r * c);
1401 if sin_v.abs() > 1.0 + 1e-9 {
1402 return Vec::new();
1403 }
1404 let v0 = sin_v.clamp(-1.0, 1.0).asin();
1405 let v1 = std::f64::consts::PI - v0;
1406 let mut vs = vec![v0];
1407 let apart = (v1 - v0).rem_euclid(TAU);
1410 if apart.min(TAU - apart) > 1e-9 {
1411 vs.push(v1);
1412 }
1413 return vs
1414 .into_iter()
1415 .map(|v| {
1416 closed(
1417 (0..n_v)
1418 .map(|i| point(TAU * (i as f64) / (n_v as f64), v))
1419 .collect(),
1420 )
1421 })
1422 .collect();
1423 }
1424
1425 let length = normal.length();
1427 TorusSection {
1428 torus,
1429 phi,
1430 num: [d_local, 0.0, -small_r * c],
1431 den: [s * big_r, s * small_r],
1432 clearance: |p: Point3| (dot_np(normal, p) - d) / length,
1433 slack: 64.0 * f64::EPSILON * (big_r + small_r + d_local.abs() / length),
1434 }
1435 .loops(n_v, PLANE_TORUS_LOOP_SAMPLES)
1436}
1437
1438struct TorusSection<'a, F> {
1446 torus: &'a ToroidalSurface,
1447 phi: f64,
1448 num: [f64; 3],
1450 den: [f64; 2],
1452 clearance: F,
1454 slack: f64,
1456}
1457
1458impl<F: Fn(Point3) -> f64> TorusSection<'_, F> {
1459 fn rhs(&self, v: f64) -> f64 {
1460 let [n0, n1, n2] = self.num;
1461 let [d0, d1] = self.den;
1462 let (sin, cos) = v.sin_cos();
1463 n2.madd(sin, n1.madd(cos, n0)) / d1.madd(cos, d0)
1464 }
1465
1466 fn point(&self, u: f64, v: f64) -> IntersectionPoint {
1467 IntersectionPoint {
1468 point: self.torus.evaluate(u, v),
1469 param1: (u.rem_euclid(TAU), v.rem_euclid(TAU)),
1470 param2: (0.0, 0.0),
1471 }
1472 }
1473
1474 fn branch(&self, v: f64, sign: f64) -> IntersectionPoint {
1475 self.point(sign.madd(self.rhs(v).clamp(-1.0, 1.0).acos(), self.phi), v)
1476 }
1477
1478 fn node(&self, v: f64) -> IntersectionPoint {
1480 let u = if self.rhs(v) >= 0.0 {
1481 self.phi
1482 } else {
1483 self.phi + std::f64::consts::PI
1484 };
1485 self.point(u, v)
1486 }
1487
1488 fn depth(&self, v: f64) -> f64 {
1491 (self.clearance)(self.node(v).point).abs()
1492 }
1493
1494 fn crossings(&self) -> Vec<f64> {
1498 let [n0, n1, n2] = self.num;
1499 let [d0, d1] = self.den;
1500 let mut roots = Vec::with_capacity(4);
1501 for c in [1.0_f64, -1.0] {
1502 let (alpha, beta, gamma) = (c.madd(-d0, n0), c.madd(-d1, n1), n2);
1503 let m = beta.hypot(gamma);
1504 let ratio = -alpha / m;
1505 if !ratio.is_finite() || ratio.abs() > 1.0 + 1e-12 {
1506 continue;
1507 }
1508 let theta = gamma.atan2(beta);
1509 let delta = ratio.clamp(-1.0, 1.0).acos();
1510 roots.push((theta - delta).rem_euclid(TAU));
1511 roots.push((theta + delta).rem_euclid(TAU));
1512 }
1513 roots.sort_by(f64::total_cmp);
1514 roots
1515 }
1516
1517 fn runs(&self) -> Vec<(f64, f64, Option<f64>, bool)> {
1523 let roots = self.crossings();
1524 let n = roots.len();
1525 if n == 0 {
1526 let whole = self.rhs(0.0).abs() <= 1.0 && self.depth(0.0) > self.slack;
1527 return if whole {
1528 vec![(0.0, TAU, None, true)]
1529 } else {
1530 Vec::new()
1531 };
1532 }
1533 let arcs: Vec<(f64, f64)> = (0..n)
1534 .map(|i| {
1535 (
1536 roots[i],
1537 if i + 1 < n {
1538 roots[i + 1]
1539 } else {
1540 roots[0] + TAU
1541 },
1542 )
1543 })
1544 .collect();
1545 let middle = |i: usize| f64::midpoint(arcs[i].0, arcs[i].1);
1546 let inside: Vec<bool> = (0..n).map(|i| self.rhs(middle(i)).abs() <= 1.0).collect();
1547 let shallow: Vec<bool> = (0..n)
1548 .map(|i| self.depth(middle(i)) <= self.slack)
1549 .collect();
1550 let deep_beside = |i: usize, back: bool| {
1551 (1..n)
1552 .map(|j| if back { (i + n - j) % n } else { (i + j) % n })
1553 .find(|&j| !shallow[j])
1554 };
1555 let kept: Vec<bool> = (0..n)
1556 .map(|i| {
1557 if !shallow[i] {
1558 return inside[i];
1559 }
1560 matches!(
1561 (deep_beside(i, true), deep_beside(i, false)),
1562 (Some(a), Some(b)) if inside[a] && inside[b]
1563 )
1564 })
1565 .collect();
1566 let node_in = |from: usize, len: usize| {
1567 (0..len).find_map(|j| {
1568 let i = (from + j) % n;
1569 let wraps = if from + j >= n { TAU } else { 0.0 };
1570 shallow[i].then(|| middle(i) + wraps)
1571 })
1572 };
1573 let Some(first) = (0..n).find(|&i| kept[i] && !kept[(i + n - 1) % n]) else {
1574 return if kept.iter().all(|&k| k) {
1575 let node = node_in(0, n);
1576 let lo = node.unwrap_or(roots[0]);
1577 vec![(lo, lo + TAU, node, true)]
1578 } else {
1579 Vec::new()
1580 };
1581 };
1582 let mut runs = Vec::new();
1583 let mut j = 0;
1584 while j < n {
1585 let i = (first + j) % n;
1586 if !kept[i] {
1587 j += 1;
1588 continue;
1589 }
1590 let len = (0..n - j).take_while(|&k| kept[(i + k) % n]).count();
1591 let last = i + len - 1;
1592 let hi = arcs[last % n].1 + if last >= n { TAU } else { 0.0 };
1593 runs.push((arcs[i].0, hi, node_in(i, len), false));
1594 j += len;
1595 }
1596 runs
1597 }
1598
1599 #[allow(
1606 clippy::cast_precision_loss,
1607 clippy::cast_possible_truncation,
1608 clippy::cast_sign_loss
1609 )]
1610 fn loops(&self, n_v: usize, (fewest, most): (f64, f64)) -> Vec<Vec<IntersectionPoint>> {
1611 let closed = |mut run: Vec<IntersectionPoint>| {
1612 run.push(run[0]);
1613 run
1614 };
1615 let step = TAU / (n_v as f64);
1616 let mut loops = Vec::new();
1617 for (t_lo, t_hi, at_node, whole) in self.runs() {
1618 if whole {
1619 for sign in [1.0, -1.0] {
1620 loops.push(closed(match at_node {
1621 Some(v_node) => std::iter::once(self.node(v_node))
1622 .chain(
1623 (1..n_v).map(|i| self.branch((i as f64).madd(step, v_node), sign)),
1624 )
1625 .collect(),
1626 None => (0..n_v)
1627 .map(|i| self.branch((i as f64 + 0.5).madd(step, t_lo), sign))
1628 .collect(),
1629 }));
1630 }
1631 continue;
1632 }
1633 let len = ((t_hi - t_lo) / step).ceil();
1641 let probes = (len as usize).max(8);
1642 let (u_lo, u_hi) = (0..=probes)
1643 .map(|k| (t_hi - t_lo).madd(k as f64 / probes as f64, t_lo))
1644 .map(|v| self.rhs(v).clamp(-1.0, 1.0).acos())
1645 .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), u| {
1646 (lo.min(u), hi.max(u))
1647 });
1648 let m = len
1649 .max((n_v as f64) * (u_hi - u_lo) / std::f64::consts::PI)
1650 .max(fewest)
1651 .min(most)
1652 .ceil();
1653 let steps = m as usize;
1654 if let Some(v_node) = at_node {
1655 for (from, to) in [(v_node, t_lo), (v_node, t_hi)] {
1658 let along = |k: usize| {
1659 let f = 0.5 * (1.0 - (std::f64::consts::PI * k as f64 / m).cos());
1660 (to - from).madd(f, from)
1661 };
1662 let mut pts = vec![self.node(v_node)];
1663 pts.extend((1..=steps).map(|k| self.branch(along(k), 1.0)));
1664 pts.extend((1..steps).rev().map(|k| self.branch(along(k), -1.0)));
1665 loops.push(closed(pts));
1666 }
1667 } else {
1668 let at = |k: usize| {
1669 let f = 0.5 * (1.0 - (std::f64::consts::PI * k as f64 / m).cos());
1670 (t_hi - t_lo).madd(f, t_lo)
1671 };
1672 let mut pts: Vec<IntersectionPoint> =
1673 (0..=steps).map(|k| self.branch(at(k), 1.0)).collect();
1674 pts.extend((1..steps).rev().map(|k| self.branch(at(k), -1.0)));
1675 loops.push(closed(pts));
1676 }
1677 }
1678 loops
1679 }
1680
1681 fn between(&self, a: (f64, f64), b: (f64, f64)) -> IntersectionPoint {
1684 let half = |from: f64, to: f64| {
1685 let gap = (to - from + std::f64::consts::PI).rem_euclid(TAU) - std::f64::consts::PI;
1686 0.5_f64.madd(gap, from)
1687 };
1688 let (u, v) = (half(a.0, b.0), half(a.1, b.1));
1689 let off = self.rhs(v).clamp(-1.0, 1.0).acos();
1690 let miss =
1691 |w: f64| ((w - u + std::f64::consts::PI).rem_euclid(TAU) - std::f64::consts::PI).abs();
1692 let sign = if miss(self.phi + off) <= miss(self.phi - off) {
1693 1.0
1694 } else {
1695 -1.0
1696 };
1697 self.branch(v, sign)
1698 }
1699}
1700
1701#[allow(clippy::cast_precision_loss)]
1710fn plane_torus_winding_loops(
1711 torus: &ToroidalSurface,
1712 normal: Vec3,
1713 d: f64,
1714 n_v: usize,
1715) -> Option<Vec<Vec<Point3>>> {
1716 let big_r = torus.major_radius();
1717 let small_r = torus.minor_radius();
1718 let a = normal.dot(torus.x_axis());
1719 let b = normal.dot(torus.y_axis());
1720 let c = normal.dot(torus.z_axis());
1721 let s = a.hypot(b);
1722 if s < 1e-12 * normal.length() || small_r >= big_r {
1723 return None;
1724 }
1725 let phi = b.atan2(a);
1726 let d_local = d - dot_np(normal, torus.center());
1727 let rhs = |v: f64| (d_local - small_r * c * v.sin()) / (s * small_r.madd(v.cos(), big_r));
1728 let dense = 8 * n_v;
1729 if (0..dense).any(|i| rhs(TAU * i as f64 / dense as f64).abs() > 1.0 - 1e-3) {
1730 return None;
1731 }
1732 let mut loops = [Vec::with_capacity(n_v + 1), Vec::with_capacity(n_v + 1)];
1733 for i in 0..n_v {
1734 let v = TAU * i as f64 / n_v as f64;
1735 let delta = rhs(v).acos();
1736 loops[0].push(torus.evaluate(phi + delta, v));
1737 loops[1].push(torus.evaluate(phi - delta, v));
1738 }
1739 Some(
1740 loops
1741 .into_iter()
1742 .map(|mut run| {
1743 run.push(run[0]);
1744 run
1745 })
1746 .collect(),
1747 )
1748}
1749
1750#[must_use]
1764pub fn intersect_line_torus(torus: &ToroidalSurface, origin: Point3, dir: Vec3) -> Vec<f64> {
1765 let c = torus.center();
1766 let (xa, ya, za) = (torus.x_axis(), torus.y_axis(), torus.z_axis());
1767 let big_r = torus.major_radius();
1768 let small_r = torus.minor_radius();
1769
1770 let o = Vec3::new(origin.x() - c.x(), origin.y() - c.y(), origin.z() - c.z());
1772 let (a0, a1) = (xa.dot(o), xa.dot(dir));
1773 let (b0, b1) = (ya.dot(o), ya.dot(dir));
1774 let (c0, c1) = (za.dot(o), za.dot(dir));
1775
1776 let g2 = a1.madd(a1, b1.madd(b1, c1 * c1));
1778 let g1 = 2.0 * a1.madd(a0, b1.madd(b0, c1 * c0));
1779 let g0 = a0.madd(
1780 a0,
1781 b0.madd(b0, c0.madd(c0, big_r.madd(big_r, -small_r * small_r))),
1782 );
1783
1784 let four_rr = 4.0 * big_r * big_r;
1786 let h2 = four_rr * a1.madd(a1, b1 * b1);
1787 let h1 = four_rr * (2.0 * a1.madd(a0, b1 * b0));
1788 let h0 = four_rr * a0.madd(a0, b0 * b0);
1789
1790 let e4 = g2 * g2;
1792 let e3 = 2.0 * g2 * g1;
1793 let e2 = g1.madd(g1, 2.0 * g2 * g0) - h2;
1794 let e1 = 2.0f64.madd(g1 * g0, -h1);
1795 let e0 = g0.madd(g0, -h0);
1796
1797 let mut roots = real_roots_quartic(e4, e3, e2, e1, e0);
1798 let tube = |t: f64, across: bool| -> f64 {
1804 let p = origin + dir * t;
1805 let q = Vec3::new(p.x() - c.x(), p.y() - c.y(), p.z() - c.z());
1806 let (a, b, cc) = (xa.dot(q), ya.dot(q), za.dot(q));
1807 let centre = if across { -big_r } else { big_r };
1808 (a.hypot(b) - centre).hypot(cc) - small_r
1809 };
1810 for t in &mut roots {
1811 let across = big_r < small_r && tube(*t, true).abs() < tube(*t, false).abs();
1812 for _ in 0..8 {
1813 let eps = 1e-7;
1814 let f = tube(*t, across);
1815 let df = (tube(*t + eps, across) - tube(*t - eps, across)) / (2.0 * eps);
1816 if df.abs() <= 1e-12 {
1817 break;
1818 }
1819 let step = f / df;
1820 *t -= step;
1821 if step.abs() < 1e-14 * (1.0 + t.abs()) {
1822 break;
1823 }
1824 }
1825 }
1826 roots.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
1827 roots.dedup_by(|a, b| (*a - *b).abs() < 1e-9 * (1.0 + b.abs()));
1828 roots
1829}
1830
1831fn real_roots_quartic(c4: f64, c3: f64, c2: f64, c1: f64, c0: f64) -> Vec<f64> {
1834 if c4.abs() < 1e-14 {
1836 return real_roots_cubic(c3, c2, c1, c0);
1837 }
1838 let (a, b, c, d) = (c3 / c4, c2 / c4, c1 / c4, c0 / c4);
1840 let eval = |z: Complex| -> Complex {
1841 let mut acc = Complex::new(1.0, 0.0);
1843 acc = acc * z + Complex::new(a, 0.0);
1844 acc = acc * z + Complex::new(b, 0.0);
1845 acc = acc * z + Complex::new(c, 0.0);
1846 acc * z + Complex::new(d, 0.0)
1847 };
1848 let seed = Complex::new(0.4, 0.9);
1850 let mut r = [
1851 Complex::new(1.0, 0.0),
1852 seed,
1853 seed * seed,
1854 seed * seed * seed,
1855 ];
1856 for _ in 0..100 {
1857 let mut max_step = 0.0_f64;
1858 for i in 0..4 {
1859 let mut denom = Complex::new(1.0, 0.0);
1860 for j in 0..4 {
1861 if i != j {
1862 denom = denom * (r[i] - r[j]);
1863 }
1864 }
1865 if denom.norm() < 1e-300 {
1866 continue;
1867 }
1868 let step = eval(r[i]) / denom;
1869 r[i] = r[i] - step;
1870 max_step = max_step.max(step.norm());
1871 }
1872 if max_step < 1e-14 {
1873 break;
1874 }
1875 }
1876 let p_real = |x: f64| -> f64 { (((x + a) * x + b) * x + c) * x + d };
1883 let mut out: Vec<f64> = Vec::new();
1884 for z in r {
1885 if z.im.abs() >= 1e-7 {
1886 continue;
1887 }
1888 let x = z.re;
1889 let scale = 1.0 + a.abs() + b.abs() + c.abs() + d.abs() + x.abs().powi(4);
1892 if p_real(x).abs() > 1e-6 * scale {
1893 continue;
1894 }
1895 if out.iter().any(|&y| (y - x).abs() < 1e-9 * (1.0 + x.abs())) {
1896 continue;
1897 }
1898 out.push(x);
1899 }
1900 out
1901}
1902
1903fn real_roots_cubic(a: f64, b: f64, c: f64, d: f64) -> Vec<f64> {
1905 if a.abs() < 1e-14 {
1906 return real_roots_quadratic(b, c, d);
1907 }
1908 let (b, c, d) = (b / a, c / a, d / a);
1910 let p = c - b * b / 3.0;
1911 let q = 2.0 * b * b * b / 27.0 - b * c / 3.0 + d;
1912 let shift = -b / 3.0;
1913 let disc = q * q / 4.0 + p * p * p / 27.0;
1914 if disc > 1e-14 {
1915 let sq = disc.sqrt();
1916 let u = (-q / 2.0 + sq).cbrt();
1917 let v = (-q / 2.0 - sq).cbrt();
1918 vec![u + v + shift]
1919 } else if disc < -1e-14 {
1920 let m = 2.0 * (-p / 3.0).sqrt();
1922 let theta = (3.0 * q / (p * m)).clamp(-1.0, 1.0).acos() / 3.0;
1923 (0..3)
1924 .map(|k| {
1925 m.madd(
1926 (theta - 2.0 * std::f64::consts::PI * f64::from(k) / 3.0).cos(),
1927 shift,
1928 )
1929 })
1930 .collect()
1931 } else {
1932 let u = (-q / 2.0).cbrt();
1934 vec![2.0 * u + shift, -u + shift]
1935 }
1936}
1937
1938fn real_roots_quadratic(a: f64, b: f64, c: f64) -> Vec<f64> {
1940 if a.abs() < 1e-14 {
1941 if b.abs() < 1e-14 {
1942 return Vec::new();
1943 }
1944 return vec![-c / b];
1945 }
1946 let disc = b * b - 4.0 * a * c;
1947 if disc < 0.0 {
1948 Vec::new()
1949 } else {
1950 let sq = disc.sqrt();
1951 vec![(-b - sq) / (2.0 * a), (-b + sq) / (2.0 * a)]
1952 }
1953}
1954
1955#[derive(Clone, Copy)]
1957struct Complex {
1958 re: f64,
1959 im: f64,
1960}
1961
1962impl Complex {
1963 const fn new(re: f64, im: f64) -> Self {
1964 Self { re, im }
1965 }
1966 fn norm(self) -> f64 {
1967 self.re.hypot(self.im)
1968 }
1969}
1970
1971impl std::ops::Add for Complex {
1972 type Output = Self;
1973 fn add(self, o: Self) -> Self {
1974 Self::new(self.re + o.re, self.im + o.im)
1975 }
1976}
1977
1978impl std::ops::Sub for Complex {
1979 type Output = Self;
1980 fn sub(self, o: Self) -> Self {
1981 Self::new(self.re - o.re, self.im - o.im)
1982 }
1983}
1984
1985impl std::ops::Mul for Complex {
1986 type Output = Self;
1987 fn mul(self, o: Self) -> Self {
1988 Self::new(
1989 self.re.madd(o.re, -(self.im * o.im)),
1990 self.re.madd(o.im, self.im * o.re),
1991 )
1992 }
1993}
1994
1995impl std::ops::Div for Complex {
1996 type Output = Self;
1997 fn div(self, o: Self) -> Self {
1998 let den = o.re.madd(o.re, o.im * o.im);
1999 Self::new(
2000 self.re.madd(o.re, self.im * o.im) / den,
2001 self.im.madd(o.re, -(self.re * o.im)) / den,
2002 )
2003 }
2004}
2005
2006fn build_curves_from_points(
2010 points_3d: &[Point3],
2011 ipoints: Vec<IntersectionPoint>,
2012) -> Result<Vec<IntersectionCurve>, MathError> {
2013 if points_3d.len() < 2 {
2014 return Ok(vec![]);
2015 }
2016
2017 let degree = 3.min(points_3d.len() - 1);
2018 let curve = interpolate(points_3d, degree)?;
2019 Ok(vec![IntersectionCurve {
2020 curve,
2021 points: ipoints,
2022 }])
2023}
2024
2025#[allow(
2037 clippy::cast_precision_loss,
2038 clippy::too_many_lines,
2039 clippy::similar_names,
2040 clippy::unnecessary_wraps,
2041 clippy::type_complexity
2042)]
2043pub fn intersect_analytic_analytic(
2044 a: AnalyticSurface<'_>,
2045 b: AnalyticSurface<'_>,
2046 grid_res: usize,
2047) -> Result<Vec<IntersectionCurve>, MathError> {
2048 intersect_analytic_analytic_bounded(a, b, grid_res, None, None)
2049}
2050
2051pub fn intersect_analytic_analytic_bounded(
2062 a: AnalyticSurface<'_>,
2063 b: AnalyticSurface<'_>,
2064 grid_res: usize,
2065 v_range_hint_a: Option<(f64, f64)>,
2066 v_range_hint_b: Option<(f64, f64)>,
2067) -> Result<Vec<IntersectionCurve>, MathError> {
2068 intersect_analytic_analytic_impl(a, b, grid_res, v_range_hint_a, v_range_hint_b, None)
2069}
2070
2071pub fn intersect_analytic_analytic_in_region(
2084 a: AnalyticSurface<'_>,
2085 b: AnalyticSurface<'_>,
2086 grid_res: usize,
2087 v_range_hint_a: Option<(f64, f64)>,
2088 v_range_hint_b: Option<(f64, f64)>,
2089 region: Aabb3,
2090) -> Result<Vec<IntersectionCurve>, MathError> {
2091 intersect_analytic_analytic_impl(a, b, grid_res, v_range_hint_a, v_range_hint_b, Some(region))
2092}
2093
2094fn intersect_analytic_analytic_impl(
2095 a: AnalyticSurface<'_>,
2096 b: AnalyticSurface<'_>,
2097 grid_res: usize,
2098 v_range_hint_a: Option<(f64, f64)>,
2099 v_range_hint_b: Option<(f64, f64)>,
2100 region: Option<Aabb3>,
2101) -> Result<Vec<IntersectionCurve>, MathError> {
2102 if let Some(result) = try_algebraic_intersection(&a, &b, v_range_hint_a, v_range_hint_b)? {
2105 return Ok(result);
2106 }
2107
2108 let (surf_a, norm_a, u_range_a, default_v_a) = surface_closures(&a);
2109 let (surf_b, norm_b, u_range_b, default_v_b) = surface_closures(&b);
2110 let v_range_a = v_range_hint_a.unwrap_or(default_v_a);
2111 let v_range_b = v_range_hint_b.unwrap_or(default_v_b);
2112
2113 let diag_a = {
2115 let p00 = surf_a(u_range_a.0, v_range_a.0);
2116 let p11 = surf_a(u_range_a.1, v_range_a.1);
2117 (p00 - p11).length()
2118 };
2119 let diag_b = {
2120 let p00 = surf_b(u_range_b.0, v_range_b.0);
2121 let p11 = surf_b(u_range_b.1, v_range_b.1);
2122 (p00 - p11).length()
2123 };
2124 let char_size = diag_a.min(diag_b).max(0.1);
2125
2126 #[allow(clippy::type_complexity)]
2130 let mut seeds: Vec<(Point3, (f64, f64), (f64, f64))> = Vec::new();
2131 let seed_threshold = diag_a.max(diag_b).max(1.0) * 0.5;
2135 let mut min_dist = f64::INFINITY;
2136
2137 #[allow(clippy::cast_precision_loss)]
2138 for ia in 0..grid_res {
2139 for ja in 0..grid_res {
2140 let ua =
2141 u_range_a.0 + (u_range_a.1 - u_range_a.0) * (ia as f64 + 0.5) / (grid_res as f64);
2142 let va =
2143 v_range_a.0 + (v_range_a.1 - v_range_a.0) * (ja as f64 + 0.5) / (grid_res as f64);
2144
2145 let pa = surf_a(ua, va);
2146
2147 let (ub, vb) = project_analytic(&b, pa, u_range_b, v_range_b);
2149 let pb = surf_b(ub, vb);
2150 let dist = (pa - pb).length();
2151 min_dist = min_dist.min(dist);
2152
2153 if dist < seed_threshold {
2154 let mid = Point3::new(
2159 (pa.x() + pb.x()) * 0.5,
2160 (pa.y() + pb.y()) * 0.5,
2161 (pa.z() + pb.z()) * 0.5,
2162 );
2163 seeds.push((mid, (ua, va), (ub, vb)));
2164 }
2165 }
2166 }
2167
2168 let reject_dist = (char_size / grid_res as f64) * 3.0;
2177 if min_dist > reject_dist {
2178 return Ok(vec![]);
2179 }
2180
2181 if seeds.is_empty() {
2182 return Ok(vec![]);
2183 }
2184
2185 let march_step = (char_size * 0.02).clamp(0.005, 0.5);
2189 let dedup_radius = march_step * 10.0;
2190 let mut unique_seeds = Vec::new();
2191 for seed in &seeds {
2192 let dominated = unique_seeds
2193 .iter()
2194 .any(|s: &(Point3, (f64, f64), (f64, f64))| (s.0 - seed.0).length() < dedup_radius);
2195 if !dominated {
2196 unique_seeds.push(*seed);
2197 }
2198 }
2199
2200 let region = region.map(|r| r.expanded(2.0 * char_size / grid_res as f64));
2205 if let Some(r) = region {
2206 for seed in &mut unique_seeds {
2207 let mut p = seed.0;
2208 for _ in 0..8 {
2209 let (ua, va) = project_analytic(&a, p, u_range_a, v_range_a);
2210 let pa = surf_a(ua, va);
2211 let (ub, vb) = project_analytic(&b, pa, u_range_b, v_range_b);
2212 let pb = surf_b(ub, vb);
2213 p = Point3::new(
2214 (pa.x() + pb.x()) * 0.5,
2215 (pa.y() + pb.y()) * 0.5,
2216 (pa.z() + pb.z()) * 0.5,
2217 );
2218 if (pa - pb).length() < 1e-9 {
2219 break;
2220 }
2221 }
2222 seed.0 = p;
2223 }
2224 unique_seeds.retain(|seed| r.contains_point(seed.0));
2225 }
2226
2227 let mut curves = Vec::new();
2229 let mut used_seeds = vec![false; unique_seeds.len()];
2230
2231 for si in 0..unique_seeds.len() {
2232 if used_seeds[si] {
2233 continue;
2234 }
2235 used_seeds[si] = true;
2236
2237 let march_result = march_analytic_intersection(
2238 &a,
2239 &b,
2240 surf_a.as_ref(),
2241 norm_a.as_ref(),
2242 surf_b.as_ref(),
2243 norm_b.as_ref(),
2244 unique_seeds[si].0,
2245 u_range_a,
2246 v_range_a,
2247 u_range_b,
2248 v_range_b,
2249 march_step,
2250 is_u_periodic(&a),
2251 is_u_periodic(&b),
2252 region,
2253 );
2254
2255 if march_result.len() >= 2 {
2256 for (sj, other) in unique_seeds.iter().enumerate() {
2257 if !used_seeds[sj]
2258 && march_result
2259 .iter()
2260 .any(|p| (*p - other.0).length() < dedup_radius)
2261 {
2262 used_seeds[sj] = true;
2263 }
2264 }
2265
2266 let ipts: Vec<IntersectionPoint> = march_result
2267 .iter()
2268 .map(|&pt| IntersectionPoint {
2269 point: pt,
2270 param1: (0.0, 0.0),
2271 param2: (0.0, 0.0),
2272 })
2273 .collect();
2274
2275 let degree = 3.min(march_result.len() - 1);
2276 if let Ok(curve) = interpolate(&march_result, degree) {
2277 curves.push(IntersectionCurve {
2278 curve,
2279 points: ipts,
2280 });
2281 }
2282 }
2283 }
2284
2285 Ok(curves)
2286}
2287
2288#[allow(clippy::too_many_lines)]
2302fn try_algebraic_intersection(
2303 a: &AnalyticSurface<'_>,
2304 b: &AnalyticSurface<'_>,
2305 v_range_a: Option<(f64, f64)>,
2306 v_range_b: Option<(f64, f64)>,
2307) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
2308 match (a, b) {
2309 (AnalyticSurface::Cone(cone), AnalyticSurface::Cylinder(cyl)) => Ok(
2310 algebraic_parallel_cone_cylinder(cone, cyl, v_range_a, v_range_b)?
2311 .or_else(|| ruling_cone_cylinder(cone, cyl, true)),
2312 ),
2313 (AnalyticSurface::Cylinder(cyl), AnalyticSurface::Cone(cone)) => Ok(
2314 algebraic_parallel_cone_cylinder(cone, cyl, v_range_b, v_range_a)?
2315 .or_else(|| ruling_cone_cylinder(cone, cyl, false)),
2316 ),
2317 (AnalyticSurface::Sphere(s1), AnalyticSurface::Sphere(s2)) => {
2318 algebraic_sphere_sphere(s1, s2).map(Some)
2319 }
2320 (AnalyticSurface::Cylinder(c1), AnalyticSurface::Cylinder(c2)) => {
2321 let axis_dot = c1.axis().dot(c2.axis()).abs();
2322 if axis_dot > 1.0 - 1e-10 {
2323 let delta = c2.origin() - c1.origin();
2325 let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
2326 let along = delta_vec.dot(c1.axis());
2327 let perp = (delta_vec - c1.axis() * along).length();
2328 if perp < 1e-8 {
2329 if (c1.radius() - c2.radius()).abs() < 1e-8 {
2332 return Ok(None); }
2334 return Ok(Some(vec![])); }
2336 if let Some(rulings) = parallel_cylinders(c1, c2, v_range_a, v_range_b)? {
2337 return Ok(Some(rulings));
2338 }
2339 }
2340 algebraic_cylinder_cylinder(c1, c2)
2342 }
2343 (AnalyticSurface::Sphere(s), AnalyticSurface::Cylinder(c)) => {
2345 algebraic_sphere_cylinder(s, c, true)
2346 }
2347 (AnalyticSurface::Cylinder(c), AnalyticSurface::Sphere(s)) => {
2348 algebraic_sphere_cylinder(s, c, false)
2349 }
2350 (AnalyticSurface::Cone(c1), AnalyticSurface::Cone(c2)) => {
2351 if let Some(rulings) = shared_apex_cones(c1, c2, v_range_a, v_range_b)? {
2352 return Ok(Some(rulings));
2353 }
2354 algebraic_cone_cone(c1, c2)
2355 }
2356 (AnalyticSurface::Cone(cone), AnalyticSurface::Sphere(sphere)) => {
2357 Ok(ruling_cone_sphere(cone, sphere, true))
2358 }
2359 (AnalyticSurface::Sphere(sphere), AnalyticSurface::Cone(cone)) => {
2360 Ok(ruling_cone_sphere(cone, sphere, false))
2361 }
2362 (AnalyticSurface::Torus(t), AnalyticSurface::Cylinder(c)) => {
2363 if let Some(exacts) = exact_cylinder_torus(c, t)? {
2364 return exact_circle_curves(exacts, |p| (t.project_point(p), c.project_point(p)))
2365 .map(Some);
2366 }
2367 Ok(parallel_axis_torus_cylinder(t, c, true)
2368 .or_else(|| ruling_torus_cylinder(t, c, true)))
2369 }
2370 (AnalyticSurface::Cylinder(c), AnalyticSurface::Torus(t)) => {
2371 if let Some(exacts) = exact_cylinder_torus(c, t)? {
2372 return exact_circle_curves(exacts, |p| (c.project_point(p), t.project_point(p)))
2373 .map(Some);
2374 }
2375 Ok(parallel_axis_torus_cylinder(t, c, false)
2376 .or_else(|| ruling_torus_cylinder(t, c, false)))
2377 }
2378 (AnalyticSurface::Sphere(s), AnalyticSurface::Torus(t)) => {
2379 match exact_sphere_torus(s, t)? {
2380 Some(exacts) => {
2381 exact_circle_curves(exacts, |p| (s.project_point(p), t.project_point(p)))
2382 .map(Some)
2383 }
2384 None => Ok(sphere_torus_curves(s, t, true)),
2385 }
2386 }
2387 (AnalyticSurface::Torus(t), AnalyticSurface::Sphere(s)) => {
2388 match exact_sphere_torus(s, t)? {
2389 Some(exacts) => {
2390 exact_circle_curves(exacts, |p| (t.project_point(p), s.project_point(p)))
2391 .map(Some)
2392 }
2393 None => Ok(sphere_torus_curves(s, t, false)),
2394 }
2395 }
2396 (AnalyticSurface::Torus(t1), AnalyticSurface::Torus(t2)) => exact_torus_torus(t1, t2)?
2397 .map(|exacts| {
2398 exact_circle_curves(exacts, |p| (t1.project_point(p), t2.project_point(p)))
2399 })
2400 .transpose(),
2401 _ => Ok(None),
2402 }
2403}
2404
2405fn parallel_axis_torus_cylinder(
2412 torus: &ToroidalSurface,
2413 cyl: &CylindricalSurface,
2414 torus_first: bool,
2415) -> Option<Vec<IntersectionCurve>> {
2416 let axis = torus.z_axis();
2417 let along = cyl.axis().dot(axis);
2418 if along.abs() < 1.0 - 1e-10 {
2419 return None;
2420 }
2421 let offset = cyl.origin() - torus.center();
2422 if (offset - axis * offset.dot(axis)).length() < Tolerance::new().linear {
2423 return None;
2424 }
2425 let (major, minor) = (torus.major_radius(), torus.minor_radius());
2426 let roots = |u: f64| {
2427 let q = cyl.evaluate(u, 0.0) - torus.center();
2428 let height = q.dot(axis);
2429 let rho = (q - axis * height).length();
2430 let reach = minor * minor - (rho - major) * (rho - major);
2431 ruling_quadratic(1.0, 2.0 * along.signum() * height, height * height - reach)
2432 };
2433 let samples = ruling_samples(cyl, &roots);
2434 let loops = if samples.iter().all(Option::is_some) {
2435 closed_ruling_loops(cyl, &roots, &samples)
2436 } else {
2437 partial_ruling_loops(cyl, &roots, &samples)
2438 };
2439 if loops.is_empty() {
2440 return None;
2441 }
2442 Some(fit_ruling_loops(&loops, |p| {
2443 in_order(torus.project_point(p), cyl.project_point(p), torus_first)
2444 }))
2445}
2446
2447fn meridian_crossings(
2454 first: (f64, f64, f64),
2455 second: (f64, f64, f64),
2456 scale: f64,
2457) -> Option<Vec<(f64, f64)>> {
2458 let ((x1, z1, r1), (x2, z2, r2)) = (first, second);
2459 let (dx, dz) = (x2 - x1, z2 - z1);
2460 let dist = dx.hypot(dz);
2461 let slack = 1e-9 * scale;
2462 if dist < slack {
2463 return None;
2464 }
2465 let rounding = 8.0 * f64::EPSILON * (x1.abs() + x2.abs() + z1.abs() + z2.abs() + r1 + r2);
2466 if dist > r1 + r2 + rounding || dist < (r1 - r2).abs() - rounding {
2467 return Some(Vec::new());
2468 }
2469 let along = r2.madd(-r2, r1.madd(r1, dist * dist)) / (2.0 * dist);
2470 let across = r1.madd(r1, -(along * along)).max(0.0).sqrt();
2471 let (ux, uz) = (dx / dist, dz / dist);
2472 let sides: &[f64] = if 2.0 * across <= Tolerance::new().linear {
2473 &[0.0]
2474 } else {
2475 &[1.0, -1.0]
2476 };
2477 let mut crossings = Vec::with_capacity(sides.len());
2478 for side in sides {
2479 let rho = x1 + along * ux - side * across * uz;
2480 if rho <= slack {
2481 return None;
2482 }
2483 crossings.push((rho, z1 + along * uz + side * across * ux));
2484 }
2485 Some(crossings)
2486}
2487
2488fn exact_circle_curves(
2492 exacts: Vec<ExactIntersectionCurve>,
2493 params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
2494) -> Result<Vec<IntersectionCurve>, MathError> {
2495 let mut curves = Vec::with_capacity(exacts.len());
2496 for exact in exacts {
2497 match exact {
2498 ExactIntersectionCurve::Circle(circle) => {
2499 let points = (0..=32)
2500 .map(|i| {
2501 let point = circle.evaluate(TAU * f64::from(i) / 32.0);
2502 let (param1, param2) = params(point);
2503 IntersectionPoint {
2504 point,
2505 param1,
2506 param2,
2507 }
2508 })
2509 .collect();
2510 let r = circle.radius();
2511 let curve = conic_loop(circle.center(), circle.u_axis(), circle.v_axis(), r, r)?;
2512 curves.push(IntersectionCurve { curve, points });
2513 }
2514 ExactIntersectionCurve::Points(points) if points.len() == 1 => {
2516 let point = points[0];
2517 let (param1, param2) = params(point);
2518 curves.push(IntersectionCurve {
2519 curve: interpolate(&[point, point], 1)?,
2520 points: vec![IntersectionPoint {
2521 point,
2522 param1,
2523 param2,
2524 }],
2525 });
2526 }
2527 ExactIntersectionCurve::Ellipse(_) | ExactIntersectionCurve::Points(_) => {}
2528 }
2529 }
2530 Ok(curves)
2531}
2532
2533fn circles_about_axis(
2535 base: Point3,
2536 axis: Vec3,
2537 crossings: &[(f64, f64)],
2538) -> Result<Vec<ExactIntersectionCurve>, MathError> {
2539 crossings
2540 .iter()
2541 .map(|&(rho, z)| {
2542 Circle3D::new(base + axis * z, axis, rho).map(ExactIntersectionCurve::Circle)
2543 })
2544 .collect()
2545}
2546
2547pub fn exact_torus_torus(
2559 first: &ToroidalSurface,
2560 second: &ToroidalSurface,
2561) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2562 let axis = first.z_axis();
2563 let scale = first.major_radius() + second.major_radius();
2564 let offset = second.center() - first.center();
2565 if first.minor_radius() >= first.major_radius()
2567 || second.minor_radius() >= second.major_radius()
2568 || axis.cross(second.z_axis()).length() > 1e-9
2569 || offset.cross(axis).length() > 1e-9 * scale
2570 {
2571 return Ok(None);
2572 }
2573 let Some(crossings) = meridian_crossings(
2574 (first.major_radius(), 0.0, first.minor_radius()),
2575 (
2576 second.major_radius(),
2577 offset.dot(axis),
2578 second.minor_radius(),
2579 ),
2580 scale,
2581 ) else {
2582 return Ok(None);
2583 };
2584 circles_about_axis(first.center(), axis, &crossings).map(Some)
2585}
2586
2587pub fn exact_cylinder_torus(
2601 cylinder: &CylindricalSurface,
2602 torus: &ToroidalSurface,
2603) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2604 let axis = torus.z_axis();
2605 let scale = torus.major_radius() + cylinder.radius();
2606 let offset = cylinder.origin() - torus.center();
2607 let linear = crate::tolerance::Tolerance::default().linear;
2608 if axis.cross(cylinder.axis()).length() > 1e-9
2609 || offset.cross(axis).length() > 1e-9 * scale
2610 || cylinder.radius() + torus.major_radius() <= torus.minor_radius() + linear
2611 {
2612 return Ok(None);
2613 }
2614 let gap = cylinder.radius() - torus.major_radius();
2615 let small = torus.minor_radius();
2616 if (gap.abs() - small).abs() <= linear {
2620 return circles_about_axis(torus.center(), axis, &[(cylinder.radius(), 0.0)]).map(Some);
2621 }
2622 if gap.abs() > small {
2623 return Ok(Some(Vec::new()));
2624 }
2625 let height = small.madd(small, -(gap * gap)).sqrt();
2626 circles_about_axis(
2627 torus.center(),
2628 axis,
2629 &[(cylinder.radius(), height), (cylinder.radius(), -height)],
2630 )
2631 .map(Some)
2632}
2633
2634pub fn exact_sphere_torus(
2649 sphere: &SphericalSurface,
2650 torus: &ToroidalSurface,
2651) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2652 let axis = torus.z_axis();
2653 let scale = torus.major_radius() + sphere.radius();
2654 let offset = sphere.center() - torus.center();
2655 if torus.minor_radius() >= torus.major_radius() {
2657 return Ok(None);
2658 }
2659 if offset.cross(axis).length() > 1e-9 * scale {
2660 let radial = offset - axis * offset.dot(axis);
2666 let slack = 64.0
2667 * f64::EPSILON
2668 * (torus.major_radius() + torus.minor_radius() + sphere.radius() + offset.length());
2669 let stray = (radial.length() - torus.major_radius()).hypot(offset.dot(axis))
2670 + (sphere.radius() - torus.minor_radius()).abs();
2671 if stray <= slack.min(Tolerance::new().linear) {
2672 let along = axis.cross(radial).normalize()?;
2673 return Ok(Some(vec![ExactIntersectionCurve::Circle(Circle3D::new(
2674 sphere.center(),
2675 along,
2676 sphere.radius(),
2677 )?)]));
2678 }
2679 return Ok(
2680 off_axis_touch(sphere, torus).map(|p| vec![ExactIntersectionCurve::Points(vec![p])])
2681 );
2682 }
2683 let Some(crossings) = meridian_crossings(
2684 (0.0, offset.dot(axis), sphere.radius()),
2685 (torus.major_radius(), 0.0, torus.minor_radius()),
2686 scale,
2687 ) else {
2688 return Ok(None);
2689 };
2690 circles_about_axis(torus.center(), axis, &crossings).map(Some)
2691}
2692
2693const SPHERE_TORUS_LOOP_SAMPLES: (f64, f64) = (128.0, 1024.0);
2697
2698fn sphere_torus_section<'a>(
2707 sphere: &SphericalSurface,
2708 torus: &'a ToroidalSurface,
2709) -> Option<TorusSection<'a, impl Fn(Point3) -> f64>> {
2710 let (big, small, radius) = (torus.major_radius(), torus.minor_radius(), sphere.radius());
2711 let offset = sphere.center() - torus.center();
2712 let (a, b, h) = (
2713 offset.dot(torus.x_axis()),
2714 offset.dot(torus.y_axis()),
2715 offset.dot(torus.z_axis()),
2716 );
2717 let s = a.hypot(b);
2718 if small >= big || s <= 1e-9 * (big + radius) {
2719 return None;
2720 }
2721 let centre = sphere.center();
2722 Some(TorusSection {
2723 torus,
2724 phi: b.atan2(a),
2725 num: [
2726 big.madd(
2727 big,
2728 small.madd(small, h.madd(h, s.madd(s, -radius * radius))),
2729 ),
2730 2.0 * big * small,
2731 -2.0 * h * small,
2732 ],
2733 den: [2.0 * s * big, 2.0 * s * small],
2734 clearance: move |p: Point3| (p - centre).length() - radius,
2735 slack: 64.0 * f64::EPSILON * (big + small + radius + offset.length()),
2736 })
2737}
2738
2739const SPHERE_TORUS_FIT_ROUNDS: usize = 6;
2741
2742fn sphere_torus_curves(
2750 sphere: &SphericalSurface,
2751 torus: &ToroidalSurface,
2752 sphere_first: bool,
2753) -> Option<Vec<IntersectionCurve>> {
2754 let section = sphere_torus_section(sphere, torus)?;
2755 let tol = Tolerance::new().linear;
2756 let (big, small) = (torus.major_radius(), torus.minor_radius());
2757 let offset = sphere.center() - torus.center();
2762 let rise = offset.dot(torus.z_axis());
2763 let reach = (offset - torus.z_axis() * rise).length();
2764 let (nearest, farthest) = (
2765 ((reach - big).hypot(rise) - small).abs(),
2766 (reach + big).hypot(rise) + small,
2767 );
2768 let margin = 8.0 * f64::EPSILON * (big + small + offset.length() + sphere.radius());
2769 let crosses = sphere.radius() > nearest + margin && sphere.radius() < farthest - margin;
2770 let off = |p: Point3| {
2771 let local = p - torus.center();
2772 let (x, y, z) = (
2773 local.dot(torus.x_axis()),
2774 local.dot(torus.y_axis()),
2775 local.dot(torus.z_axis()),
2776 );
2777 let on_torus = (x.hypot(y) - big).hypot(z) - small;
2778 on_torus.abs().max((section.clearance)(p).abs())
2779 };
2780 let centre = sphere.center();
2784 let polish = |q: IntersectionPoint| {
2785 let (mut u, mut v) = q.param1;
2786 let mut best = q;
2787 for _ in 0..4 {
2788 let gap = (section.clearance)(best.point);
2789 let (sin_u, cos_u) = u.sin_cos();
2790 let (sin_v, cos_v) = v.sin_cos();
2791 let rho = small.madd(cos_v, big);
2792 let outward = torus.x_axis() * cos_u + torus.y_axis() * sin_u;
2793 let p_u = (torus.y_axis() * cos_u - torus.x_axis() * sin_u) * rho;
2794 let p_v = outward * (-small * sin_v) + torus.z_axis() * (small * cos_v);
2795 let away = best.point - centre;
2796 let normal = away * (1.0 / away.length());
2797 let (g_u, g_v) = (normal.dot(p_u), normal.dot(p_v));
2798 let (w_u, w_v) = (g_u / (rho * rho), g_v / (small * small));
2799 let reach = g_u.madd(w_u, g_v * w_v);
2800 if reach <= f64::MIN_POSITIVE {
2801 break;
2802 }
2803 let next = section.point(gap.madd(-w_u / reach, u), gap.madd(-w_v / reach, v));
2804 if (section.clearance)(next.point).abs() >= gap.abs() {
2805 break;
2806 }
2807 (u, v) = next.param1;
2808 best = next;
2809 }
2810 best
2811 };
2812 let loops = section.loops(256, SPHERE_TORUS_LOOP_SAMPLES);
2813 if loops.is_empty() && crosses {
2814 return None;
2815 }
2816 let mut curves = Vec::new();
2817 for points in loops {
2818 let mut points: Vec<IntersectionPoint> = points.into_iter().map(polish).collect();
2819 if points.iter().any(|q| off(q.point) > tol) {
2820 return None;
2821 }
2822 points.dedup_by(|b, a| (b.point - a.point).length() <= 1e-3 * tol);
2825 let mut rounds = 0;
2826 let curve = loop {
2827 let positions: Vec<Point3> = points.iter().map(|q| q.point).collect();
2828 let curve = interpolate(&positions, 3.min(positions.len() - 1)).ok()?;
2829 let params = crate::nurbs::fitting::chord_length_params(&positions);
2830 let strays: Vec<usize> = (0..positions.len() - 1)
2831 .filter(|&k| {
2832 off(curve.evaluate(f64::midpoint(params[k], params[k + 1]))) > 0.25 * tol
2833 })
2834 .collect();
2835 if strays.is_empty() {
2836 break curve;
2837 }
2838 if rounds == SPHERE_TORUS_FIT_ROUNDS {
2839 return None;
2840 }
2841 rounds += 1;
2842 for &k in strays.iter().rev() {
2843 let mid = polish(section.between(points[k].param1, points[k + 1].param1));
2844 if off(mid.point) > tol {
2845 return None;
2846 }
2847 points.insert(k + 1, mid);
2848 }
2849 };
2850 for q in &mut points {
2851 let (on_sphere, on_torus) = (sphere.project_point(q.point), q.param1);
2852 (q.param1, q.param2) = if sphere_first {
2853 (on_sphere, on_torus)
2854 } else {
2855 (on_torus, on_sphere)
2856 };
2857 }
2858 curves.push(IntersectionCurve { curve, points });
2859 }
2860 Some(curves)
2861}
2862
2863fn off_axis_touch(sphere: &SphericalSurface, torus: &ToroidalSurface) -> Option<Point3> {
2871 let axis = torus.z_axis();
2872 let (big, small, radius) = (torus.major_radius(), torus.minor_radius(), sphere.radius());
2873 let offset = sphere.center() - torus.center();
2874 let radial = offset - axis * offset.dot(axis);
2875 let out = radial * (1.0 / radial.length());
2876 let near = torus.center() + out * big;
2877 let far = torus.center() - out * big;
2878 let (to_near, to_far) = (sphere.center() - near, sphere.center() - far);
2879 let (d_near, d_far) = (to_near.length(), to_far.length());
2880 let slack = 64.0 * f64::EPSILON * (big + small + radius + offset.length());
2881 if d_near > slack
2884 && ((d_near - small - radius).abs() <= slack || (small - d_near - radius).abs() <= slack)
2885 {
2886 return Some(near + to_near * (small / d_near));
2887 }
2888 ((d_far + small - radius).abs() <= slack).then(|| far - to_far * (small / d_far))
2889}
2890
2891pub fn exact_cone_cone(
2916 c1: &ConicalSurface,
2917 c2: &ConicalSurface,
2918) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2919 let axis = c1.axis();
2920 let axis2 = c2.axis();
2921
2922 if axis.dot(axis2).abs() < 1.0 - 1e-10 {
2924 return Ok(None); }
2926 let apex1 = c1.apex();
2927 let apex2 = c2.apex();
2928 let delta = apex2 - apex1;
2929 let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
2930 let along = delta_v.dot(axis);
2931 if (delta_v - axis * along).length() > 1e-8 {
2932 return offset_parallel_cone_cone(c1, c2);
2933 }
2934
2935 let (s1, s2) = (c1.half_angle().sin(), c2.half_angle().sin());
2936 if s1.abs() < 1e-12 || s2.abs() < 1e-12 {
2937 return Ok(None); }
2939 let m1 = c1.half_angle().cos() / s1;
2940 let m2 = c2.half_angle().cos() / s2;
2941 let sigma = if axis.dot(axis2) >= 0.0 { 1.0 } else { -1.0 };
2942 let d2 = along; let denom = m1 - m2 * sigma;
2945 if denom.abs() < 1e-12 {
2946 if sigma > 0.0 && d2.abs() < 1e-9 {
2949 return Ok(None);
2950 }
2951 return Ok(Some(vec![]));
2952 }
2953
2954 let t_star = (-m2 * sigma * d2) / denom;
2955 let radius = m1 * t_star;
2956 if radius < 1e-12 {
2957 return Ok(Some(vec![])); }
2959
2960 let center = Point3::new(
2961 apex1.x() + axis.x() * t_star,
2962 apex1.y() + axis.y() * t_star,
2963 apex1.z() + axis.z() * t_star,
2964 );
2965 let circle = Circle3D::new(center, axis, radius)?;
2966 Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
2967}
2968
2969fn offset_parallel_cone_cone(
2980 c1: &ConicalSurface,
2981 c2: &ConicalSurface,
2982) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
2983 if c1.half_angle().sin().abs() < 1e-12 || c2.half_angle().sin().abs() < 1e-12 {
2984 return Ok(None); }
2986 let t1 = c1.half_angle().tan();
2987 let t2 = c2.half_angle().tan();
2988 if !t1.is_finite() || !t2.is_finite() {
2989 return Ok(None);
2990 }
2991 if (t1 - t2).abs() > 1e-9 * (1.0 + t1.abs().max(t2.abs())) {
2992 return Ok(None);
2993 }
2994
2995 let w = c1.axis();
2996 let apex1 = c1.apex();
2997 let apex2 = c2.apex();
2998 let delta = apex2 - apex1;
2999 let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
3000 let s = delta_v.dot(w);
3001 let tm = 0.5 * (t1 + t2);
3002 let k = 1.0 + tm * tm;
3003
3004 let n = (delta_v - w * (k * s)) * 2.0;
3008 let n_len = n.length();
3009 if n_len < 1e-12 {
3010 return Ok(None);
3011 }
3012 let n_hat = n * (1.0 / n_len);
3013 let d = (dot_np(n, apex1) + delta_v.dot(delta_v) - k * s * s) / n_len;
3014
3015 let axis2 = c2.axis();
3021 let scale = 1.0 + delta_v.length();
3022 let mut out = Vec::new();
3023 for curve in exact_plane_cone(c1, n_hat, d, 0.0)? {
3024 let samples: Vec<Point3> = match &curve {
3025 ExactIntersectionCurve::Circle(c) => (0..4)
3026 .map(|i| crate::traits::ParametricCurve::evaluate(c, TAU * f64::from(i) / 4.0))
3027 .collect(),
3028 ExactIntersectionCurve::Ellipse(e) => (0..4)
3029 .map(|i| crate::traits::ParametricCurve::evaluate(e, TAU * f64::from(i) / 4.0))
3030 .collect(),
3031 ExactIntersectionCurve::Points(_) => return Ok(None),
3032 };
3033 let on_real_nappe = |p: &Point3| {
3034 let rel = *p - apex2;
3035 Vec3::new(rel.x(), rel.y(), rel.z()).dot(axis2) >= -1e-9 * scale
3036 };
3037 let hits = samples.iter().filter(|p| on_real_nappe(p)).count();
3038 match hits {
3039 0 => {}
3040 4 => out.push(curve),
3041 _ => return Ok(None),
3042 }
3043 }
3044 Ok(Some(out))
3045}
3046
3047pub fn exact_cone_cylinder(
3067 cone: &ConicalSurface,
3068 cyl: &CylindricalSurface,
3069) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3070 let axis = cone.axis();
3071 let cyl_axis = cyl.axis();
3072
3073 if axis.dot(cyl_axis).abs() < 1.0 - 1e-10 {
3075 return Ok(None);
3076 }
3077 let apex = cone.apex();
3078 let delta = apex - cyl.origin();
3079 let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
3080 let along = delta_v.dot(cyl_axis);
3081 if (delta_v - cyl_axis * along).length() > 1e-8 {
3082 return Ok(None);
3083 }
3084
3085 let s = cone.half_angle().sin();
3086 if s.abs() < 1e-12 {
3087 return Ok(None); }
3089 let m = cone.half_angle().cos() / s; if m.abs() < 1e-12 {
3091 return Ok(None); }
3093
3094 let t_star = cyl.radius() / m; if t_star.abs() < 1e-12 {
3096 return Ok(Some(vec![])); }
3098 let center = Point3::new(
3099 apex.x() + axis.x() * t_star,
3100 apex.y() + axis.y() * t_star,
3101 apex.z() + axis.z() * t_star,
3102 );
3103 let circle = Circle3D::new(center, axis, cyl.radius())?;
3104 Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
3105}
3106
3107fn conic_loop(centre: Point3, u: Vec3, v: Vec3, a: f64, b: f64) -> Result<NurbsCurve, MathError> {
3112 let w = std::f64::consts::FRAC_1_SQRT_2;
3113 let corners: [(f64, f64); 9] = [
3114 (1.0, 0.0),
3115 (1.0, 1.0),
3116 (0.0, 1.0),
3117 (-1.0, 1.0),
3118 (-1.0, 0.0),
3119 (-1.0, -1.0),
3120 (0.0, -1.0),
3121 (1.0, -1.0),
3122 (1.0, 0.0),
3123 ];
3124 let points = corners
3125 .iter()
3126 .map(|&(x, y)| centre + u * (a * x) + v * (b * y))
3127 .collect();
3128 let weights = vec![1.0, w, 1.0, w, 1.0, w, 1.0, w, 1.0];
3129 let knots = vec![
3130 0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0,
3131 ];
3132 NurbsCurve::new(2, knots, points, weights)
3133}
3134
3135fn shared_apex_cones(
3147 c1: &ConicalSurface,
3148 c2: &ConicalSurface,
3149 v1: Option<(f64, f64)>,
3150 v2: Option<(f64, f64)>,
3151) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3152 let (Some(v1), Some(v2)) = (v1, v2) else {
3153 return Ok(None);
3154 };
3155 let (a1, a2, apex) = (c1.axis(), c2.axis(), c1.apex());
3156 let across = a1.cross(a2);
3157 let sin = across.length();
3158 if sin < 1e-9 {
3159 return Ok(None);
3160 }
3161 let reach = v1.0.abs().max(v1.1.abs()).max(v2.0.abs()).max(v2.1.abs());
3162 let scale = reach.max((apex - Point3::new(0.0, 0.0, 0.0)).length());
3163 if (c2.apex() - apex).length() > 64.0 * f64::EPSILON * scale {
3164 return Ok(None);
3165 }
3166 let normal = across * (1.0 / sin);
3167 let tol = Tolerance::new().linear;
3168 if f64::EPSILON * reach > 0.1 * tol * sin {
3172 return Ok(None);
3173 }
3174 let toward = normal.cross(a1);
3176 let cos = a1.dot(a2);
3177 let (s1, s2) = (c1.half_angle().sin(), c2.half_angle().sin());
3178 let params = |cone: &ConicalSurface, p: Point3| {
3180 let (u, v) = cone.project_point(p);
3181 if v < 0.0 {
3182 ((u + std::f64::consts::PI).rem_euclid(TAU), v)
3183 } else {
3184 (u, v)
3185 }
3186 };
3187 let mut curves = Vec::new();
3188 for nappe in [1.0, -1.0] {
3189 let t2 = nappe * s2;
3190 let side = cos.madd(-s1, t2) / sin;
3191 let foot = a1 * s1 + toward * side;
3192 let lift_sq = s1.madd(-s1, side.madd(-side, 1.0));
3193 let rounding = 4.0 * f64::EPSILON;
3194 let lifts = if lift_sq.abs() <= rounding {
3195 if (2.0 * rounding).sqrt() * reach > 10.0 * tol {
3200 return Ok(None);
3201 }
3202 vec![0.0]
3203 } else if lift_sq < 0.0 {
3204 Vec::new()
3205 } else if 2.0 * lift_sq.sqrt() * reach <= tol {
3206 vec![0.0]
3207 } else {
3208 vec![lift_sq.sqrt(), -lift_sq.sqrt()]
3209 };
3210 let along2 = if nappe > 0.0 { v2 } else { (-v2.1, -v2.0) };
3211 let (lo, hi) = (v1.0.max(along2.0), v1.1.min(along2.1));
3212 if hi - lo <= tol {
3213 continue;
3214 }
3215 for lift in lifts {
3216 let d = (foot + normal * lift).normalize()?;
3217 let pieces = if lo < 0.0 && hi > 0.0 {
3218 vec![(lo, 0.0), (0.0, hi)]
3219 } else {
3220 vec![(lo, hi)]
3221 };
3222 for (from, to) in pieces {
3223 curves.push(ruling_segment(apex + d * from, apex + d * to, |p| {
3224 (params(c1, p), params(c2, p))
3225 })?);
3226 }
3227 }
3228 }
3229 Ok(Some(curves))
3230}
3231
3232fn crossing_equal_cylinders(
3245 c1: &CylindricalSurface,
3246 c2: &CylindricalSurface,
3247) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3248 let (d1, d2, r) = (c1.axis(), c2.axis(), c1.radius());
3249 if (c2.radius() - r).abs() > 8.0 * f64::EPSILON * r {
3250 return Ok(None);
3251 }
3252 let bisectors = [d1 - d2, d1 + d2];
3257 let tol = Tolerance::new().linear;
3258 if bisectors
3259 .iter()
3260 .any(|b| 2.0 * r * f64::EPSILON > 1e-3 * tol * b.dot(*b))
3261 {
3262 return Ok(None);
3263 }
3264 let across = d1.cross(d2);
3265 let sin = across.length();
3266 let normal = across * (1.0 / sin);
3267 let w = c1.origin() - c2.origin();
3268 let cos = d1.dot(d2);
3269 let along = cos.madd(d2.dot(w), -d1.dot(w)) / (sin * sin);
3270 let centre = c1.origin() + d1 * along;
3271 let scale = r.max((centre - Point3::new(0.0, 0.0, 0.0)).length());
3275 if w.dot(normal).abs() > 64.0 * f64::EPSILON * scale {
3276 return Ok(None);
3277 }
3278 let majors = bisectors.map(|bisector| {
3281 let length = bisector.length();
3282 let major = (bisector * (1.0 / length)).cross(normal);
3283 let major = if major.dot(d1) < 0.0 { -major } else { major };
3284 (major, 2.0 * r / length)
3285 });
3286 let corner = std::f64::consts::FRAC_1_SQRT_2;
3287 let half = [(1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0)];
3288 let mut curves = Vec::with_capacity(2);
3289 for side in [1.0, -1.0] {
3290 let [(m1, a1), (m2, a2)] = majors;
3291 let out = half
3292 .iter()
3293 .map(|&(x, y)| centre + normal * (side * r * x) + m1 * (side * a1 * y));
3294 let back = half[1..]
3295 .iter()
3296 .map(|&(x, y)| centre - normal * (side * r * x) + m2 * (side * a2 * y));
3297 let curve = NurbsCurve::new(
3298 2,
3299 vec![
3300 0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0,
3301 ],
3302 out.chain(back).collect(),
3303 vec![1.0, corner, 1.0, corner, 1.0, corner, 1.0, corner, 1.0],
3304 )?;
3305 #[allow(clippy::cast_precision_loss)]
3306 let points = (0..=32)
3307 .map(|i| {
3308 let point = curve.evaluate(i as f64 / 32.0);
3309 IntersectionPoint {
3310 point,
3311 param1: c1.project_point(point),
3312 param2: c2.project_point(point),
3313 }
3314 })
3315 .collect();
3316 curves.push(IntersectionCurve { curve, points });
3317 }
3318 Ok(Some(curves))
3319}
3320
3321fn algebraic_cone_cone(
3330 c1: &ConicalSurface,
3331 c2: &ConicalSurface,
3332) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3333 let Some(exacts) = exact_cone_cone(c1, c2)? else {
3334 return Ok(None);
3335 };
3336 let mut curves = Vec::new();
3337 for exact in exacts {
3338 let n_samples = 33;
3339 let mut points = Vec::with_capacity(n_samples);
3340 #[allow(clippy::cast_precision_loss)]
3341 for i in 0..n_samples {
3342 let theta = TAU * i as f64 / (n_samples - 1) as f64;
3343 let pt = match &exact {
3344 ExactIntersectionCurve::Circle(circle) => {
3345 crate::traits::ParametricCurve::evaluate(circle, theta)
3346 }
3347 ExactIntersectionCurve::Ellipse(ellipse) => {
3348 crate::traits::ParametricCurve::evaluate(ellipse, theta)
3349 }
3350 ExactIntersectionCurve::Points(_) => break,
3351 };
3352 points.push(IntersectionPoint {
3353 point: pt,
3354 param1: (0.0, 0.0),
3355 param2: (0.0, 0.0),
3356 });
3357 }
3358 let curve = match &exact {
3359 ExactIntersectionCurve::Circle(c) => {
3360 conic_loop(c.center(), c.u_axis(), c.v_axis(), c.radius(), c.radius())?
3361 }
3362 ExactIntersectionCurve::Ellipse(e) => conic_loop(
3363 e.center(),
3364 e.u_axis(),
3365 e.v_axis(),
3366 e.semi_major(),
3367 e.semi_minor(),
3368 )?,
3369 ExactIntersectionCurve::Points(_) => continue,
3370 };
3371 curves.push(IntersectionCurve { curve, points });
3372 }
3373 Ok(Some(curves))
3374}
3375
3376pub fn exact_sphere_cylinder(
3396 sphere: &SphericalSurface,
3397 cyl: &CylindricalSurface,
3398) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3399 let sc = sphere.center();
3400 let r_sphere = sphere.radius();
3401 let co = cyl.origin();
3402 let axis = cyl.axis();
3403 let r_cyl = cyl.radius();
3404
3405 let delta = sc - co;
3407 let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
3408 let along = delta_vec.dot(axis);
3409 let perp_vec = delta_vec - axis * along;
3410 let d_perp = perp_vec.length();
3411
3412 if d_perp > 1e-7 {
3415 return Ok(None);
3416 }
3417
3418 if r_cyl > r_sphere + 1e-10 {
3421 return Ok(Some(vec![]));
3422 }
3423 let z_sq = r_sphere * r_sphere - r_cyl * r_cyl;
3424 if z_sq < 0.0 {
3425 return Ok(Some(vec![]));
3426 }
3427 let z = z_sq.sqrt();
3428
3429 let center_axis_pt = Point3::new(
3432 co.x() + axis.x() * along,
3433 co.y() + axis.y() * along,
3434 co.z() + axis.z() * along,
3435 );
3436
3437 let mut circles = Vec::new();
3438 let offsets: &[f64] = if z < 1e-10 { &[0.0] } else { &[z, -z] };
3439 for &z_offset in offsets {
3440 let center = Point3::new(
3441 center_axis_pt.x() + axis.x() * z_offset,
3442 center_axis_pt.y() + axis.y() * z_offset,
3443 center_axis_pt.z() + axis.z() * z_offset,
3444 );
3445 let circle = Circle3D::new(center, axis, r_cyl)?;
3446 circles.push(ExactIntersectionCurve::Circle(circle));
3447 }
3448 Ok(Some(circles))
3449}
3450
3451pub fn exact_cone_sphere(
3469 cone: &ConicalSurface,
3470 sphere: &SphericalSurface,
3471) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
3472 let offset = cone.apex() - sphere.center();
3473 let along = offset.dot(cone.axis());
3474 if (offset - cone.axis() * along).length() > 1e-7 {
3475 return Ok(None);
3476 }
3477 let lin_tol = Tolerance::new().linear;
3478 let (sin_a, cos_a) = cone.half_angle().sin_cos();
3479 let (far_sq, radius_sq) = (offset.dot(offset), sphere.radius() * sphere.radius());
3480 let b = 2.0 * sin_a * along;
3481 let (disc, far, near) = ruling_quadratic(1.0, b, far_sq - radius_sq);
3482 let noise = 16.0 * f64::EPSILON * 4.0f64.madd(far_sq + radius_sq, b * b);
3485 if disc < -noise {
3486 return Ok(Some(vec![]));
3487 }
3488 let roots: &[f64] = if far - near < lin_tol {
3489 &[far]
3490 } else {
3491 &[near, far]
3492 };
3493 let mut circles = Vec::new();
3494 for &v in roots {
3495 if v * cos_a > lin_tol {
3496 let centre = cone.apex() + cone.axis() * (v * sin_a);
3497 let circle = Circle3D::new(centre, cone.axis(), v * cos_a)?;
3498 circles.push(ExactIntersectionCurve::Circle(circle));
3499 }
3500 }
3501 Ok(Some(circles))
3502}
3503
3504fn algebraic_sphere_cylinder(
3513 sphere: &SphericalSurface,
3514 cyl: &CylindricalSurface,
3515 sphere_first: bool,
3516) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3517 let Some(exacts) = exact_sphere_cylinder(sphere, cyl)? else {
3518 return Ok(off_axis_sphere_cylinder(sphere, cyl, sphere_first));
3519 };
3520
3521 let mut curves = Vec::new();
3522 for exact in exacts {
3523 let ExactIntersectionCurve::Circle(circle) = exact else {
3524 continue;
3525 };
3526 let n_samples = 33;
3527 let mut points = Vec::with_capacity(n_samples);
3528 #[allow(clippy::cast_precision_loss)]
3529 for i in 0..n_samples {
3530 let theta = TAU * i as f64 / (n_samples - 1) as f64;
3531 let pt = crate::traits::ParametricCurve::evaluate(&circle, theta);
3532 let (param1, param2) = in_order(
3533 sphere.project_point(pt),
3534 cyl.project_point(pt),
3535 sphere_first,
3536 );
3537 points.push(IntersectionPoint {
3538 point: pt,
3539 param1,
3540 param2,
3541 });
3542 }
3543 let r = circle.radius();
3544 let curve = conic_loop(circle.center(), circle.u_axis(), circle.v_axis(), r, r)?;
3545 curves.push(IntersectionCurve { curve, points });
3546 }
3547
3548 Ok(Some(curves))
3549}
3550
3551fn off_axis_sphere_cylinder(
3560 sphere: &SphericalSurface,
3561 cyl: &CylindricalSurface,
3562 sphere_first: bool,
3563) -> Option<Vec<IntersectionCurve>> {
3564 let (centre, radius) = (sphere.center(), sphere.radius());
3565 let axis = cyl.axis();
3566 let offset = centre - cyl.origin();
3567 let axis_distance = (offset - axis * offset.dot(axis)).length();
3568 let lin_tol = Tolerance::new().linear;
3569 if axis_distance > radius + cyl.radius() + lin_tol
3570 || axis_distance + radius < cyl.radius() - lin_tol
3571 {
3572 return Some(Vec::new());
3573 }
3574 let roots = |u: f64| {
3575 let q = cyl.evaluate(u, 0.0) - centre;
3576 ruling_quadratic(1.0, 2.0 * q.dot(axis), q.dot(q) - radius * radius)
3577 };
3578 let samples = ruling_samples(cyl, &roots);
3579 let loops = if samples.iter().all(Option::is_some) {
3580 closed_ruling_loops(cyl, &roots, &samples)
3581 } else {
3582 partial_ruling_loops(cyl, &roots, &samples)
3583 };
3584 if loops.is_empty() {
3585 return None;
3586 }
3587 Some(fit_ruling_loops(&loops, |p| {
3588 in_order(sphere.project_point(p), cyl.project_point(p), sphere_first)
3589 }))
3590}
3591
3592const fn in_order(a: (f64, f64), b: (f64, f64), a_first: bool) -> ((f64, f64), (f64, f64)) {
3595 if a_first { (a, b) } else { (b, a) }
3596}
3597
3598fn parallel_cylinders(
3608 c1: &CylindricalSurface,
3609 c2: &CylindricalSurface,
3610 v_range_1: Option<(f64, f64)>,
3611 v_range_2: Option<(f64, f64)>,
3612) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3613 let axis = c1.axis();
3614 let delta = c2.origin() - c1.origin();
3615 let along = delta.dot(axis);
3616 let across = delta - axis * along;
3617 let d = across.length();
3618 let (r1, r2) = (c1.radius(), c2.radius());
3619 let flip = c2.axis().dot(axis);
3621 let ranges = [
3622 v_range_1,
3623 v_range_2.map(|(a, b)| (along + a * flip, along + b * flip)),
3624 ];
3625 let (lo, hi) = ranges
3626 .into_iter()
3627 .flatten()
3628 .fold((f64::NEG_INFINITY, f64::INFINITY), |(lo, hi), (a, b)| {
3629 (lo.max(a.min(b)), hi.min(a.max(b)))
3630 });
3631 if !lo.is_finite() || !hi.is_finite() {
3632 return Ok(None);
3633 }
3634 let rounding = 8.0 * f64::EPSILON * (r1 + r2 + d);
3635 if d > r1 + r2 + rounding || d < (r1 - r2).abs() - rounding || hi <= lo {
3636 return Ok(Some(Vec::new()));
3637 }
3638 let toward = across * (1.0 / d);
3639 let side = axis.cross(toward);
3640 let x = r2.madd(-r2, d.madd(d, r1 * r1)) / (2.0 * d);
3641 let y = r1.madd(r1, -(x * x)).max(0.0).sqrt();
3642 let linear = Tolerance::new().linear;
3643 let feet = if 2.0 * y <= linear {
3644 vec![toward * x]
3645 } else {
3646 vec![toward * x + side * y, toward * x - side * y]
3647 };
3648 let on_second = |p: Point3| {
3649 let w = p - c2.origin();
3650 ((w - c2.axis() * w.dot(c2.axis())).length() - r2).abs() <= linear
3651 };
3652 let mut rulings = Vec::with_capacity(feet.len());
3653 for foot in feet {
3654 let base = c1.origin() + foot;
3655 let (from, to) = (base + axis * lo, base + axis * hi);
3656 if !on_second(from) || !on_second(to) {
3657 return Ok(None);
3658 }
3659 rulings.push(ruling_segment(from, to, |p| {
3660 (c1.project_point(p), c2.project_point(p))
3661 })?);
3662 }
3663 Ok(Some(rulings))
3664}
3665
3666fn ruling_segment(
3669 from: Point3,
3670 to: Point3,
3671 params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
3672) -> Result<IntersectionCurve, MathError> {
3673 let curve = NurbsCurve::new(1, vec![0.0, 0.0, 1.0, 1.0], vec![from, to], vec![1.0, 1.0])?;
3674 let points = [from, from + (to - from) * 0.5, to]
3675 .into_iter()
3676 .map(|point| {
3677 let (param1, param2) = params(point);
3678 IntersectionPoint {
3679 point,
3680 param1,
3681 param2,
3682 }
3683 })
3684 .collect();
3685 Ok(IntersectionCurve { curve, points })
3686}
3687
3688#[allow(clippy::too_many_lines, clippy::unnecessary_wraps)]
3702fn algebraic_cylinder_cylinder(
3703 c1: &CylindricalSurface,
3704 c2: &CylindricalSurface,
3705) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
3706 if let Some(halves) = crossing_equal_cylinders(c1, c2)? {
3707 return Ok(Some(halves));
3708 }
3709 let alpha = c1.axis().dot(c2.axis());
3710 let a_coeff = 1.0 - alpha * alpha;
3711
3712 if a_coeff.abs() < 1e-12 {
3714 return Ok(None);
3715 }
3716
3717 let r1 = c1.radius();
3718 let r2 = c2.radius();
3719 let o1 = c1.origin();
3720 let o2 = c2.origin();
3721 let a1 = c1.axis();
3722 let a2 = c2.axis();
3723
3724 let delta = Vec3::new(o1.x() - o2.x(), o1.y() - o2.y(), o1.z() - o2.z());
3727 let cross = a1.cross(a2);
3728 let cross_len = cross.length();
3729 if cross_len > 1e-12 {
3730 let axis_dist = delta.dot(cross).abs() / cross_len;
3731 if axis_dist > r1 + r2 + Tolerance::new().linear {
3732 return Ok(Some(vec![])); }
3734 }
3735
3736 let roots = |sweep: &CylindricalSurface, other: &CylindricalSurface| {
3742 let (o, a, radius) = (other.origin(), other.axis(), other.radius());
3743 let alpha = sweep.axis().dot(a);
3744 let quad = 1.0 - alpha * alpha;
3745 let (axis, sweep) = (sweep.axis(), sweep.clone());
3746 move |u: f64| {
3747 let q = sweep.evaluate(u, 0.0) - o;
3748 let (q_a1, q_a2) = (q.dot(axis), q.dot(a));
3749 let b = 2.0 * (q_a1 - alpha * q_a2);
3750 let c = q.dot(q) - q_a2 * q_a2 - radius * radius;
3751 ruling_quadratic(quad, b, c)
3752 }
3753 };
3754 let (roots1, roots2) = (roots(c1, c2), roots(c2, c1));
3755 let samples1 = ruling_samples(c1, &roots1);
3756 let loops = if samples1.iter().all(Option::is_some) {
3757 closed_ruling_loops(c1, &roots1, &samples1)
3758 } else {
3759 let samples2 = ruling_samples(c2, &roots2);
3760 if samples2.iter().all(Option::is_some) {
3761 closed_ruling_loops(c2, &roots2, &samples2)
3762 } else if samples1.iter().any(Option::is_some) {
3763 partial_ruling_loops(c1, &roots1, &samples1)
3764 } else {
3765 partial_ruling_loops(c2, &roots2, &samples2)
3766 }
3767 };
3768 if loops.is_empty() {
3769 return Ok(None);
3770 }
3771 Ok(Some(fit_ruling_loops(&loops, |p| {
3772 (c1.project_point(p), c2.project_point(p))
3773 })))
3774}
3775
3776fn ruling_cone_cylinder(
3783 cone: &ConicalSurface,
3784 cyl: &CylindricalSurface,
3785 cone_first: bool,
3786) -> Option<Vec<IntersectionCurve>> {
3787 let (sin_t, cos_t) = cone.half_angle().sin_cos();
3788 if sin_t < 1e-12 || cos_t < 1e-12 {
3789 return None;
3790 }
3791 let (apex, d, w) = (cone.apex(), cone.axis(), cyl.axis());
3792 let s = 1.0 / (sin_t * sin_t);
3793 let alpha = w.dot(d);
3794 let quad = 1.0 - s * alpha * alpha;
3795 if quad.abs() < 1e-9 {
3796 return None;
3797 }
3798 let roots = |u: f64| {
3799 let delta = cyl.evaluate(u, 0.0) - apex;
3800 let (dd, dw) = (delta.dot(d), delta.dot(w));
3801 let b = 2.0 * (dw - s * dd * alpha);
3802 let c = delta.dot(delta) - s * dd * dd;
3803 ruling_quadratic(quad, b, c)
3804 };
3805 let lin_tol = Tolerance::new().linear;
3806 let far_nappe = (0..WINDOW_SCAN * RULING_SAMPLES).any(|k| {
3807 #[allow(clippy::cast_precision_loss)]
3808 let u = TAU * (k as f64 + 0.5) / (WINDOW_SCAN * RULING_SAMPLES) as f64;
3809 let (disc, vp, vm) = roots(u);
3810 disc >= -lin_tol
3811 && [vp, vm]
3812 .iter()
3813 .any(|&t| (cyl.evaluate(u, t) - apex).dot(d) < -lin_tol)
3814 });
3815 if far_nappe {
3816 return None;
3817 }
3818 let samples = ruling_samples(cyl, &roots);
3819 let scan = WINDOW_SCAN * RULING_SAMPLES;
3824 #[allow(clippy::cast_precision_loss)]
3827 let meets = |k: usize| roots(TAU * ((k % scan) as f64 + 0.5) / scan as f64).0 >= -lin_tol;
3828 if let Some(start) = (0..scan).find(|&k| !meets(k)) {
3829 let mut k = start;
3830 while k < start + scan {
3831 if !meets(k) {
3832 k += 1;
3833 continue;
3834 }
3835 let first = k;
3836 while k < start + scan && meets(k) {
3837 k += 1;
3838 }
3839 let covered = (first..k)
3840 .filter(|&j| j % WINDOW_SCAN == WINDOW_SCAN / 2 - 1 && meets(j + 1))
3841 .count();
3842 if covered < WINDOW_MIN_SAMPLES {
3843 return None;
3844 }
3845 }
3846 }
3847 let loops = if samples.iter().all(Option::is_some) {
3848 closed_ruling_loops(cyl, &roots, &samples)
3849 } else {
3850 partial_ruling_loops(cyl, &roots, &samples)
3851 };
3852 if loops.is_empty() {
3853 return None;
3854 }
3855 Some(fit_ruling_loops(&loops, |p| {
3856 in_order(cone.project_point(p), cyl.project_point(p), cone_first)
3857 }))
3858}
3859
3860fn ruling_torus_cylinder(
3870 torus: &ToroidalSurface,
3871 cyl: &CylindricalSurface,
3872 torus_first: bool,
3873) -> Option<Vec<IntersectionCurve>> {
3874 if cyl.axis().dot(torus.z_axis()).abs() > 1.0 - 1e-9
3875 || torus.minor_radius() >= torus.major_radius()
3876 {
3877 return None;
3878 }
3879 let roots = |u: f64| intersect_line_torus(torus, cyl.evaluate(u, 0.0), cyl.axis());
3880 let rows: Vec<Vec<f64>> = (0..RULING_SAMPLES).map(|i| roots(ruling_u(i))).collect();
3881 let count = rows[0].len();
3882 let scan = WINDOW_SCAN * RULING_SAMPLES;
3883 #[allow(clippy::cast_precision_loss)]
3884 if count == 0
3885 || count % 2 == 1
3886 || (0..scan).any(|k| roots(TAU * (k as f64 + 0.5) / scan as f64).len() != count)
3887 {
3888 return None;
3889 }
3890 let loops: Vec<Vec<Point3>> = (0..count)
3891 .map(|j| {
3892 let mut pts: Vec<Point3> = rows
3893 .iter()
3894 .enumerate()
3895 .map(|(i, r)| cyl.evaluate(ruling_u(i), r[j]))
3896 .collect();
3897 pts.push(pts[0]);
3898 pts
3899 })
3900 .collect();
3901 Some(fit_ruling_loops(&loops, |p| {
3902 in_order(torus.project_point(p), cyl.project_point(p), torus_first)
3903 }))
3904}
3905
3906fn ruling_cone_sphere(
3915 cone: &ConicalSurface,
3916 sphere: &SphericalSurface,
3917 cone_first: bool,
3918) -> Option<Vec<IntersectionCurve>> {
3919 let (apex, centre, radius) = (cone.apex(), sphere.center(), sphere.radius());
3920 let offset = apex - centre;
3921 let lin_tol = Tolerance::new().linear;
3922 let along = offset.dot(cone.axis());
3923 let across = (offset - cone.axis() * along).length();
3924 if across < lin_tol {
3925 return None;
3926 }
3927 let k = offset.dot(offset) - radius * radius;
3933 if radius - offset.length() > lin_tol {
3934 let exit = |u: f64| {
3935 let h = (cone.evaluate(u, 1.0) - apex).dot(offset);
3936 let root = h.madd(h, -k).sqrt();
3937 cone.evaluate(u, if h > 0.0 { -k / (h + root) } else { root - h })
3938 };
3939 let mut samples: Vec<(f64, Point3)> = (0..=RULING_SAMPLES)
3944 .map(|i| (ruling_u(i), exit(ruling_u(i))))
3945 .collect();
3946 for _ in 0..10 {
3947 let mut refined = Vec::with_capacity(2 * samples.len());
3948 for pair in samples.windows(2) {
3949 let ((u0, p0), (u1, p1)) = (pair[0], pair[1]);
3950 refined.push(pair[0]);
3951 let um = 0.5 * (u0 + u1);
3952 let pm = exit(um);
3953 let chord = (p1 - p0).length();
3954 if chord > lin_tol && (pm - (p0 + (p1 - p0) * 0.5)).length() > 0.01 * chord {
3955 refined.push((um, pm));
3956 }
3957 }
3958 refined.extend(samples.last().copied());
3959 if refined.len() == samples.len() {
3960 break;
3961 }
3962 samples = refined;
3963 }
3964 let mut pts: Vec<Point3> = samples.iter().map(|&(_, p)| p).collect();
3965 if let Some(last) = pts.last_mut() {
3966 *last = samples[0].1;
3967 }
3968 return Some(fit_ruling_loops(&[pts], |p| {
3969 in_order(cone.project_point(p), sphere.project_point(p), cone_first)
3970 }));
3971 }
3972 let crossing = |h: f64| {
3976 let (disc, vp, vm) = ruling_quadratic(1.0, 2.0 * h, k);
3977 (disc > lin_tol && vm >= lin_tol).then_some((vm, vp))
3978 };
3979 let (sin_a, cos_a) = cone.half_angle().sin_cos();
3984 if crossing(sin_a.madd(along, cos_a * across)).is_none()
3985 || crossing(sin_a.madd(along, -cos_a * across)).is_none()
3986 {
3987 return window_cone_sphere(cone, sphere, cone_first);
3988 }
3989 let rows: Vec<(f64, f64)> = (0..RULING_SAMPLES)
3990 .map(|i| crossing((cone.evaluate(ruling_u(i), 1.0) - apex).dot(offset)))
3991 .collect::<Option<_>>()?;
3992 let loops: Vec<Vec<Point3>> = [0, 1]
3993 .iter()
3994 .map(|&j| {
3995 let mut pts: Vec<Point3> = rows
3996 .iter()
3997 .enumerate()
3998 .map(|(i, &(near, far))| {
3999 cone.evaluate(ruling_u(i), if j == 0 { near } else { far })
4000 })
4001 .collect();
4002 pts.push(pts[0]);
4003 pts
4004 })
4005 .collect();
4006 Some(fit_ruling_loops(&loops, |p| {
4007 in_order(cone.project_point(p), sphere.project_point(p), cone_first)
4008 }))
4009}
4010
4011fn window_cone_sphere(
4026 cone: &ConicalSurface,
4027 sphere: &SphericalSurface,
4028 cone_first: bool,
4029) -> Option<Vec<IntersectionCurve>> {
4030 let offset = cone.apex() - sphere.center();
4031 let lin_tol = Tolerance::new().linear;
4032 if offset.length() - sphere.radius() <= lin_tol {
4033 return None;
4034 }
4035 let k = offset.dot(offset) - sphere.radius() * sphere.radius();
4036 let (sin_a, cos_a) = cone.half_angle().sin_cos();
4037 let (ox, oy) = (offset.dot(cone.x_axis()), offset.dot(cone.y_axis()));
4038 let (c, a) = (sin_a * offset.dot(cone.axis()), cos_a * ox.hypot(oy));
4039 if a < lin_tol {
4040 return None;
4041 }
4042 let reach = (-k.sqrt() - c) / a;
4043 if reach <= -1.0 {
4044 return Some(Vec::new());
4045 }
4046 if reach >= 1.0 {
4047 return None;
4048 }
4049 let (mid, half) = (oy.atan2(ox) + std::f64::consts::PI, reach.acos());
4050 let half = std::f64::consts::PI - half;
4051 let n = RULING_SAMPLES;
4052 let mut pts: Vec<Point3> = (0..n)
4053 .map(|i| {
4054 #[allow(clippy::cast_precision_loss)]
4055 let theta = TAU * i as f64 / n as f64;
4056 let u = half.madd(-theta.cos(), mid);
4057 let h = a.madd((u - mid + std::f64::consts::PI).cos(), c);
4058 let split = h.madd(h, -k).max(0.0).sqrt();
4059 cone.evaluate(u, -h - split.copysign(theta.sin()))
4060 })
4061 .collect();
4062 pts.push(pts[0]);
4063 Some(fit_ruling_loops(&[pts], |p| {
4064 in_order(cone.project_point(p), sphere.project_point(p), cone_first)
4065 }))
4066}
4067
4068const WINDOW_SCAN: usize = 16;
4071const WINDOW_MIN_SAMPLES: usize = 8;
4072
4073const RULING_SAMPLES: usize = 128;
4077
4078#[allow(clippy::cast_precision_loss)]
4079fn ruling_u(i: usize) -> f64 {
4080 TAU * (i as f64 + 0.5) / RULING_SAMPLES as f64
4081}
4082
4083fn ruling_quadratic(quad: f64, b: f64, c: f64) -> (f64, f64, f64) {
4085 let disc = b * b - 4.0 * quad * c;
4086 let root = disc.max(0.0).sqrt();
4087 (disc, (-b + root) / (2.0 * quad), (-b - root) / (2.0 * quad))
4088}
4089
4090fn ruling_samples(
4094 sweep: &CylindricalSurface,
4095 roots: &impl Fn(f64) -> (f64, f64, f64),
4096) -> Vec<Option<(Point3, Point3)>> {
4097 let lin_tol = Tolerance::new().linear;
4098 (0..RULING_SAMPLES)
4099 .map(|i| {
4100 let u = ruling_u(i);
4101 let (disc, vp, vm) = roots(u);
4102 (disc >= -lin_tol).then(|| (sweep.evaluate(u, vp), sweep.evaluate(u, vm)))
4103 })
4104 .collect()
4105}
4106
4107fn closed_ruling_loops(
4114 sweep: &CylindricalSurface,
4115 roots: &impl Fn(f64) -> (f64, f64, f64),
4116 samples: &[Option<(Point3, Point3)>],
4117) -> Vec<Vec<Point3>> {
4118 let (mut plus, mut minus): (Vec<Point3>, Vec<Point3>) =
4119 if let Some((neck, touching)) = narrowest_ruling(roots) {
4120 let count = 2 * RULING_SAMPLES;
4121 #[allow(clippy::cast_precision_loss)]
4122 (0..count)
4123 .map(|i| {
4124 let t = i as f64 / count as f64;
4125 let u = TAU.madd(t - 0.9 * (TAU * t).sin() / TAU, neck);
4126 let (_, vp, vm) = roots(u);
4127 if i == 0 && touching {
4128 let at = sweep.evaluate(u, 0.5 * (vp + vm));
4129 (at, at)
4130 } else {
4131 (sweep.evaluate(u, vp), sweep.evaluate(u, vm))
4132 }
4133 })
4134 .unzip()
4135 } else {
4136 samples.iter().flatten().copied().unzip()
4137 };
4138 plus.push(plus[0]);
4139 minus.push(minus[0]);
4140 vec![plus, minus]
4141}
4142
4143fn narrowest_ruling(roots: &impl Fn(f64) -> (f64, f64, f64)) -> Option<(f64, bool)> {
4151 let scan = WINDOW_SCAN * RULING_SAMPLES;
4152 #[allow(clippy::cast_precision_loss)]
4153 let step = TAU / scan as f64;
4154 let gap = |u: f64| {
4155 let (_, vp, vm) = roots(u);
4156 (vp - vm).abs()
4157 };
4158 #[allow(clippy::cast_precision_loss)]
4159 let gaps: Vec<f64> = (0..scan).map(|k| gap(step * k as f64)).collect();
4160 let widest = gaps.iter().copied().fold(0.0, f64::max);
4161 let tol = Tolerance::new().linear * (1.0 + widest);
4162 let mut necks = Vec::new();
4163 for k in 0..scan {
4164 let (before, here, after) = (gaps[(k + scan - 1) % scan], gaps[k], gaps[(k + 1) % scan]);
4165 if here > before || here >= after || here >= 0.25 * widest {
4166 continue;
4167 }
4168 #[allow(clippy::cast_precision_loss)]
4169 let (mut lo, mut hi) = (step * (k as f64 - 1.0), step * (k as f64 + 1.0));
4170 for _ in 0..100 {
4171 let (a, b) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
4172 if gap(a) < gap(b) {
4173 hi = b;
4174 } else {
4175 lo = a;
4176 }
4177 }
4178 let u = 0.5 * (lo + hi);
4179 necks.push((u, gap(u) <= tol));
4180 }
4181 match necks[..] {
4182 [neck] => Some(neck),
4183 _ => None,
4184 }
4185}
4186
4187fn partial_ruling_loops(
4192 sweep: &CylindricalSurface,
4193 roots: &impl Fn(f64) -> (f64, f64, f64),
4194 samples: &[Option<(Point3, Point3)>],
4195) -> Vec<Vec<Point3>> {
4196 let branch_point = |inside: usize, outside: usize| -> Point3 {
4197 let (mut lo, mut hi) = (ruling_u(inside), ruling_u(outside));
4198 if (hi - lo).abs() > std::f64::consts::PI {
4199 hi += if hi < lo { TAU } else { -TAU };
4200 }
4201 for _ in 0..60 {
4202 let mid = 0.5 * (lo + hi);
4203 if roots(mid).0 >= 0.0 {
4204 lo = mid;
4205 } else {
4206 hi = mid;
4207 }
4208 }
4209 let (_, vp, vm) = roots(lo);
4210 sweep.evaluate(lo, 0.5 * (vp + vm))
4211 };
4212 let Some(first_gap) = samples.iter().position(Option::is_none) else {
4213 return Vec::new();
4214 };
4215 let mut loops = Vec::new();
4216 let mut k = 0;
4217 while k < RULING_SAMPLES {
4218 let i = (first_gap + k) % RULING_SAMPLES;
4219 if samples[i].is_none() {
4220 k += 1;
4221 continue;
4222 }
4223 let start = i;
4224 let mut run = Vec::new();
4225 while k < RULING_SAMPLES {
4226 let j = (first_gap + k) % RULING_SAMPLES;
4227 let Some(pair) = samples[j] else { break };
4228 run.push(pair);
4229 k += 1;
4230 }
4231 let end = (start + run.len() - 1) % RULING_SAMPLES;
4232 let head = branch_point(start, (start + RULING_SAMPLES - 1) % RULING_SAMPLES);
4233 let tail = branch_point(end, (end + 1) % RULING_SAMPLES);
4234 let mut pts = vec![head];
4235 pts.extend(run.iter().map(|p| p.0));
4236 pts.push(tail);
4237 pts.extend(run.iter().rev().map(|p| p.1));
4238 pts.push(head);
4239 loops.push(pts);
4240 }
4241 loops
4242}
4243
4244fn fit_ruling_loops(
4247 loops: &[Vec<Point3>],
4248 params: impl Fn(Point3) -> ((f64, f64), (f64, f64)),
4249) -> Vec<IntersectionCurve> {
4250 let mut curves = Vec::new();
4251 for pts in loops {
4252 if pts.len() < 4 {
4253 continue;
4254 }
4255 let ipts: Vec<IntersectionPoint> = pts
4256 .iter()
4257 .map(|&p| {
4258 let (param1, param2) = params(p);
4259 IntersectionPoint {
4260 point: p,
4261 param1,
4262 param2,
4263 }
4264 })
4265 .collect();
4266 let degree = 3.min(pts.len() - 1);
4267 if let Ok(curve) = interpolate(pts, degree) {
4268 curves.push(IntersectionCurve {
4269 curve,
4270 points: ipts,
4271 });
4272 }
4273 }
4274 curves
4275}
4276
4277#[allow(clippy::unnecessary_wraps)]
4303fn algebraic_parallel_cone_cylinder(
4304 cone: &ConicalSurface,
4305 cyl: &CylindricalSurface,
4306 v_range_cone: Option<(f64, f64)>,
4307 v_range_cyl: Option<(f64, f64)>,
4308) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
4309 let axis = cone.axis();
4310 if axis.dot(cyl.axis()).abs() < 1.0 - 1e-10 {
4311 return Ok(None); }
4313
4314 let apex = cone.apex();
4315 let delta = cyl.origin() - apex;
4316 let along = delta.dot(axis);
4317 let perp = delta - axis * along;
4318 let d = perp.length();
4319 if d < 1e-9 {
4320 return Ok(None); }
4322
4323 let (e1, e2) = (cone.x_axis(), cone.y_axis());
4324 let phi0 = perp.dot(e2).atan2(perp.dot(e1));
4325
4326 let (sin_t, cos_t) = cone.half_angle().sin_cos();
4327 if cos_t < 1e-12 || sin_t < 1e-12 {
4328 return Ok(None);
4329 }
4330 let r = cyl.radius();
4331
4332 let mut v_min = (d - r).abs() / cos_t;
4334 let mut v_max = (d + r) / cos_t;
4335 if v_max <= v_min {
4336 return Ok(Some(vec![]));
4337 }
4338
4339 let mut lo = v_min;
4345 let mut hi = v_max;
4346 if let Some((a, b)) = v_range_cone {
4351 let (a, b) = if a <= b { (a, b) } else { (b, a) };
4352 lo = lo.max(a);
4353 hi = hi.min(b);
4354 }
4355 if let Some((a, b)) = v_range_cyl {
4356 let flip = cyl.axis().dot(axis);
4359 let to_cone_v = |cv: f64| (along + cv * flip) / sin_t;
4360 let (a, b) = (to_cone_v(a), to_cone_v(b));
4361 let (a, b) = if a <= b { (a, b) } else { (b, a) };
4362 lo = lo.max(a);
4363 hi = hi.min(b);
4364 }
4365 let (turn_lo, turn_hi) = (v_min, v_max);
4366 v_min = lo.max(v_min);
4367 v_max = hi.min(v_max);
4368 if v_max - v_min <= 1e-12 {
4369 return Ok(Some(vec![]));
4370 }
4371 let slack = Tolerance::new().linear;
4379 #[allow(clippy::cast_precision_loss)]
4380 let resolved = d - r > 3.0 * (d * r).sqrt() * TAU / RULING_SAMPLES as f64;
4381 if v_min <= turn_lo + slack && v_max >= turn_hi - slack && resolved {
4382 let mut pts: Vec<Point3> = (0..RULING_SAMPLES)
4383 .map(|i| {
4384 let (sin_u, cos_u) = ruling_u(i).sin_cos();
4385 let foot = cyl.origin() + (cyl.x_axis() * cos_u + cyl.y_axis() * sin_u) * r;
4386 let off = foot - apex;
4387 let across = off - axis * off.dot(axis);
4388 apex + across + axis * (across.length() * sin_t / cos_t)
4389 })
4390 .collect();
4391 pts.push(pts[0]);
4392 return Ok(Some(fit_ruling_loops(&[pts], |p| {
4393 (cone.project_point(p), cyl.project_point(p))
4394 })));
4395 }
4396
4397 let n_samples = 128;
4398 let mut plus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
4399 let mut minus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
4400 #[allow(clippy::cast_precision_loss)]
4401 for i in 0..=n_samples {
4402 let v = v_min + (v_max - v_min) * (i as f64) / (n_samples as f64);
4403 let rho = v * cos_t;
4404 if rho < 1e-12 {
4405 if (d - r).abs() < 1e-12 {
4413 let apex = cone.evaluate(phi0, v);
4414 plus.push(apex);
4415 minus.push(apex);
4416 }
4417 continue;
4418 }
4419 let cos_alpha = ((d * d + rho * rho - r * r) / (2.0 * d * rho)).clamp(-1.0, 1.0);
4420 let alpha = cos_alpha.acos();
4421 plus.push(cone.evaluate(phi0 + alpha, v));
4422 minus.push(cone.evaluate(phi0 - alpha, v));
4423 }
4424
4425 let mut curves = Vec::new();
4426 for pts in [&plus, &minus] {
4427 if pts.len() < 4 {
4430 continue;
4431 }
4432 let ipts: Vec<IntersectionPoint> = pts
4433 .iter()
4434 .map(|&p| IntersectionPoint {
4435 point: p,
4436 param1: cone.project_point(p),
4437 param2: cyl.project_point(p),
4438 })
4439 .collect();
4440 let degree = 3.min(pts.len() - 1);
4441 match interpolate(pts, degree) {
4442 Ok(curve) => curves.push(IntersectionCurve {
4443 curve,
4444 points: ipts,
4445 }),
4446 Err(_) => return Ok(None),
4451 }
4452 }
4453
4454 Ok(Some(curves))
4455}
4456
4457fn algebraic_sphere_sphere(
4465 s1: &SphericalSurface,
4466 s2: &SphericalSurface,
4467) -> Result<Vec<IntersectionCurve>, MathError> {
4468 let c1 = s1.center();
4469 let c2 = s2.center();
4470 let r1 = s1.radius();
4471 let r2 = s2.radius();
4472
4473 let delta = c2 - c1;
4474 let d_sq = delta.x() * delta.x() + delta.y() * delta.y() + delta.z() * delta.z();
4475 let d = d_sq.sqrt();
4476
4477 if d < 1e-12 {
4478 return Ok(vec![]);
4480 }
4481
4482 if d > r1 + r2 + 1e-10 {
4484 return Ok(vec![]); }
4486 if d + r2.min(r1) + 1e-10 < r1.max(r2) {
4487 return Ok(vec![]); }
4489
4490 let d1 = (d_sq + r1 * r1 - r2 * r2) / (2.0 * d);
4492
4493 let r_circle_sq = r1 * r1 - d1 * d1;
4495 if r_circle_sq < 0.0 {
4496 if r_circle_sq > -1e-10 {
4498 let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
4500 let tangent_pt = Point3::new(
4501 c1.x() + axis.x() * d1,
4502 c1.y() + axis.y() * d1,
4503 c1.z() + axis.z() * d1,
4504 );
4505 let ipt = IntersectionPoint {
4506 point: tangent_pt,
4507 param1: (0.0, 0.0),
4508 param2: (0.0, 0.0),
4509 };
4510 return Ok(vec![IntersectionCurve {
4512 curve: interpolate(&[tangent_pt, tangent_pt], 1)?,
4513 points: vec![ipt],
4514 }]);
4515 }
4516 return Ok(vec![]);
4517 }
4518
4519 let r_circle = r_circle_sq.sqrt();
4520 let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
4521 let center = Point3::new(
4522 c1.x() + axis.x() * d1,
4523 c1.y() + axis.y() * d1,
4524 c1.z() + axis.z() * d1,
4525 );
4526
4527 let basis = Frame3::from_normal(center, axis)?;
4529 let u_dir = basis.x;
4530 let v_dir = basis.y;
4531
4532 let n_samples = 33; let mut points = Vec::with_capacity(n_samples);
4535 #[allow(clippy::cast_precision_loss)]
4536 for i in 0..n_samples {
4537 let theta = TAU * i as f64 / (n_samples - 1) as f64;
4538 let (sin_t, cos_t) = theta.sin_cos();
4539 let pt = Point3::new(
4540 center.x() + (u_dir.x() * cos_t + v_dir.x() * sin_t) * r_circle,
4541 center.y() + (u_dir.y() * cos_t + v_dir.y() * sin_t) * r_circle,
4542 center.z() + (u_dir.z() * cos_t + v_dir.z() * sin_t) * r_circle,
4543 );
4544 points.push(IntersectionPoint {
4545 point: pt,
4546 param1: (0.0, 0.0),
4547 param2: (0.0, 0.0),
4548 });
4549 }
4550
4551 let curve = conic_loop(center, u_dir, v_dir, r_circle, r_circle)?;
4552
4553 Ok(vec![IntersectionCurve { curve, points }])
4554}
4555
4556#[allow(clippy::too_many_arguments)]
4562fn correct_to_intersection(
4563 a: &AnalyticSurface<'_>,
4564 b: &AnalyticSurface<'_>,
4565 surf_a: &dyn Fn(f64, f64) -> Point3,
4566 norm_a: &dyn Fn(f64, f64) -> Vec3,
4567 surf_b: &dyn Fn(f64, f64) -> Point3,
4568 norm_b: &dyn Fn(f64, f64) -> Vec3,
4569 point: Point3,
4570 u_range_a: (f64, f64),
4571 v_range_a: (f64, f64),
4572 u_range_b: (f64, f64),
4573 v_range_b: (f64, f64),
4574 max_iters: usize,
4575) -> Point3 {
4576 let mut p = point;
4577 for _ in 0..max_iters {
4578 let (ua, va) = project_analytic(a, p, u_range_a, v_range_a);
4579 let (ub, vb) = project_analytic(b, p, u_range_b, v_range_b);
4580 let pa = surf_a(ua, va);
4581 let pb = surf_b(ub, vb);
4582 let na = norm_a(ua, va);
4583 let nb = norm_b(ub, vb);
4584 let pv = Vec3::new(p.x(), p.y(), p.z());
4585
4586 let da = (pv - Vec3::new(pa.x(), pa.y(), pa.z())).dot(na);
4587 let db = (pv - Vec3::new(pb.x(), pb.y(), pb.z())).dot(nb);
4588
4589 if da.abs() < 1e-7 && db.abs() < 1e-7 {
4590 break;
4591 }
4592
4593 let t = na.cross(nb);
4594 let t_len = t.length();
4595 if t_len < 1e-10 {
4596 return Point3::new(
4598 (pa.x() + pb.x()) * 0.5,
4599 (pa.y() + pb.y()) * 0.5,
4600 (pa.z() + pb.z()) * 0.5,
4601 );
4602 }
4603 let t_hat = t * (1.0 / t_len);
4604
4605 let det = na.x() * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
4607 - na.y() * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
4608 + na.z() * (nb.x() * t_hat.y() - nb.y() * t_hat.x());
4609 if det.abs() < 1e-15 {
4610 return Point3::new(
4611 (pa.x() + pb.x()) * 0.5,
4612 (pa.y() + pb.y()) * 0.5,
4613 (pa.z() + pb.z()) * 0.5,
4614 );
4615 }
4616 let inv = 1.0 / det;
4617 let dx = inv
4619 * (-da * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
4620 + db * (na.y() * t_hat.z() - na.z() * t_hat.y()));
4621 let dy = inv
4622 * (da * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
4623 - db * (na.x() * t_hat.z() - na.z() * t_hat.x()));
4624 let dz = inv
4625 * (-da * (nb.x() * t_hat.y() - nb.y() * t_hat.x())
4626 + db * (na.x() * t_hat.y() - na.y() * t_hat.x()));
4627 let candidate = Point3::new(p.x() + dx, p.y() + dy, p.z() + dz);
4628
4629 let (uc, vc) = project_analytic(a, candidate, u_range_a, v_range_a);
4632 let (ud, vd) = project_analytic(b, candidate, u_range_b, v_range_b);
4633 let pc_a = surf_a(uc, vc);
4634 let pc_b = surf_b(ud, vd);
4635 let cv = Vec3::new(candidate.x(), candidate.y(), candidate.z());
4636 let da_new = (cv - Vec3::new(pc_a.x(), pc_a.y(), pc_a.z()))
4637 .dot(norm_a(uc, vc))
4638 .abs();
4639 let db_new = (cv - Vec3::new(pc_b.x(), pc_b.y(), pc_b.z()))
4640 .dot(norm_b(ud, vd))
4641 .abs();
4642 if da_new > da.abs() && db_new > db.abs() {
4643 return p;
4644 }
4645
4646 p = candidate;
4647 }
4648 p
4649}
4650
4651#[allow(clippy::too_many_arguments)]
4657fn march_analytic_intersection(
4658 a: &AnalyticSurface<'_>,
4659 b: &AnalyticSurface<'_>,
4660 surf_a: &dyn Fn(f64, f64) -> Point3,
4661 norm_a: &dyn Fn(f64, f64) -> Vec3,
4662 surf_b: &dyn Fn(f64, f64) -> Point3,
4663 norm_b: &dyn Fn(f64, f64) -> Vec3,
4664 seed: Point3,
4665 u_range_a: (f64, f64),
4666 v_range_a: (f64, f64),
4667 u_range_b: (f64, f64),
4668 v_range_b: (f64, f64),
4669 initial_step: f64,
4670 u_periodic_a: bool,
4671 u_periodic_b: bool,
4672 region: Option<Aabb3>,
4673) -> Vec<Point3> {
4674 let max_steps = 500;
4675 let h_min = 1e-6;
4676 let h_max = initial_step * 4.0;
4677 let closure_dist = initial_step * 5.0;
4681 let max_angle = 10.0_f64.to_radians();
4683 let min_angle = 2.0_f64.to_radians();
4684
4685 let mut forward = Vec::new();
4687 let mut backward = Vec::new();
4689
4690 for (direction, points) in [(1.0_f64, &mut forward), (-1.0_f64, &mut backward)] {
4691 let mut current = seed;
4692 let mut h = initial_step;
4693 let mut prev_tangent: Option<Vec3> = None;
4694
4695 for _ in 0..max_steps {
4696 let (ua, va) = project_analytic(a, current, u_range_a, v_range_a);
4697 let (ub, vb) = project_analytic(b, current, u_range_b, v_range_b);
4698
4699 let na = norm_a(ua, va);
4700 let nb = norm_b(ub, vb);
4701
4702 let tangent = na.cross(nb);
4703 let t_len = tangent.length();
4704 if t_len < 1e-10 {
4705 break;
4706 }
4707 let t_dir = tangent * (direction / t_len);
4708
4709 if let Some(prev_t) = prev_tangent {
4711 let cos_angle = prev_t.dot(t_dir).clamp(-1.0, 1.0);
4712 let angle = cos_angle.acos();
4713 if angle > max_angle && h > h_min {
4714 h = (h * 0.5).max(h_min);
4715 } else if angle < min_angle {
4716 h = (h * 2.0).min(h_max);
4717 }
4718 }
4719 prev_tangent = Some(t_dir);
4720
4721 let next = Point3::new(
4722 h.madd(t_dir.x(), current.x()),
4723 h.madd(t_dir.y(), current.y()),
4724 h.madd(t_dir.z(), current.z()),
4725 );
4726
4727 let (ua2, va2) = project_analytic(a, next, u_range_a, v_range_a);
4728 let (ub2, vb2) = project_analytic(b, next, u_range_b, v_range_b);
4729
4730 let pa = surf_a(ua2, va2);
4731 let pb = surf_b(ub2, vb2);
4732 let mid = Point3::new(
4733 (pa.x() + pb.x()) * 0.5,
4734 (pa.y() + pb.y()) * 0.5,
4735 (pa.z() + pb.z()) * 0.5,
4736 );
4737 let out_a = (!u_periodic_a && (ua2 <= u_range_a.0 || ua2 >= u_range_a.1))
4738 || va2 <= v_range_a.0
4739 || va2 >= v_range_a.1;
4740 let out_b = (!u_periodic_b && (ub2 <= u_range_b.0 || ub2 >= u_range_b.1))
4741 || vb2 <= v_range_b.0
4742 || vb2 >= v_range_b.1;
4743
4744 if out_a || out_b {
4745 break;
4746 }
4747 if region.is_some_and(|r| !r.contains_point(mid)) {
4748 points.push(mid);
4749 break;
4750 }
4751
4752 let dist_to_seed = (mid - seed).length();
4756 if points.len() > 10 && dist_to_seed < closure_dist {
4757 points.push(seed);
4758 break;
4759 }
4760
4761 points.push(mid);
4762 current = mid;
4763 }
4764 }
4765
4766 backward.reverse();
4768 let mut result = backward;
4769 result.push(seed);
4770 result.append(&mut forward);
4771
4772 for pt in &mut result {
4774 *pt = correct_to_intersection(
4775 a, b, surf_a, norm_a, surf_b, norm_b, *pt, u_range_a, v_range_a, u_range_b, v_range_b,
4776 5,
4777 );
4778 }
4779
4780 result
4781}
4782
4783fn project_analytic(
4787 surface: &AnalyticSurface<'_>,
4788 point: Point3,
4789 u_range: (f64, f64),
4790 v_range: (f64, f64),
4791) -> (f64, f64) {
4792 match surface {
4793 AnalyticSurface::Cylinder(cyl) => {
4794 let (u, v) = cyl.project_point(point);
4795 (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
4796 }
4797 AnalyticSurface::Sphere(sphere) => {
4798 let (u, v) = sphere.project_point(point);
4799 (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
4800 }
4801 AnalyticSurface::Cone(cone) => {
4802 let (u, v) = cone.project_point(point);
4803 (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
4804 }
4805 AnalyticSurface::Torus(torus) => {
4806 let (u, v) = torus.project_point(point);
4807 (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
4808 }
4809 }
4810}
4811
4812fn is_u_periodic(surface: &AnalyticSurface<'_>) -> bool {
4816 matches!(
4817 surface,
4818 AnalyticSurface::Cylinder(_)
4819 | AnalyticSurface::Cone(_)
4820 | AnalyticSurface::Sphere(_)
4821 | AnalyticSurface::Torus(_)
4822 )
4823}
4824
4825#[allow(clippy::type_complexity)]
4827fn surface_closures<'a>(
4828 surface: &'a AnalyticSurface<'a>,
4829) -> (
4830 Box<dyn Fn(f64, f64) -> Point3 + 'a>,
4831 Box<dyn Fn(f64, f64) -> Vec3 + 'a>,
4832 (f64, f64),
4833 (f64, f64),
4834) {
4835 match surface {
4836 AnalyticSurface::Cylinder(cyl) => (
4837 Box::new(|u, v| cyl.evaluate(u, v)),
4838 Box::new(|u, v| cyl.normal(u, v)),
4839 (0.0, TAU),
4840 (-1.0, 1.0),
4841 ),
4842 AnalyticSurface::Cone(cone) => (
4843 Box::new(|u, v| cone.evaluate(u, v)),
4844 Box::new(|u, v| cone.normal(u, v)),
4845 (0.0, TAU),
4846 (0.01, 2.0),
4847 ),
4848 AnalyticSurface::Sphere(sphere) => (
4849 Box::new(|u, v| sphere.evaluate(u, v)),
4850 Box::new(|u, v| sphere.normal(u, v)),
4851 (0.0, TAU),
4852 (-FRAC_PI_2, FRAC_PI_2),
4853 ),
4854 AnalyticSurface::Torus(torus) => (
4855 Box::new(|u, v| torus.evaluate(u, v)),
4856 Box::new(|u, v| torus.normal(u, v)),
4857 (0.0, TAU),
4858 (0.0, TAU),
4859 ),
4860 }
4861}
4862
4863#[cfg(test)]
4864#[allow(clippy::unwrap_used, clippy::expect_used)]
4865mod tests {
4866 use super::*;
4867 use crate::tolerance::Tolerance;
4868
4869 #[test]
4873 fn plane_cone_conic_arcs_lie_on_both_surfaces() {
4874 let half_angle = 1.1_f64;
4875 let cone = ConicalSurface::new(
4876 Point3::new(0.0, 0.0, 0.0),
4877 Vec3::new(0.0, 0.0, 1.0),
4878 half_angle,
4879 )
4880 .unwrap();
4881 let ruling = Vec3::new(half_angle.sin(), 0.0, half_angle.cos());
4882 for (normal, d) in [(Vec3::new(1.0, 0.0, 0.0), 0.5), (ruling, 1.0)] {
4883 let chains =
4884 exact_plane_analytic_reaching(AnalyticSurface::Cone(&cone), normal, d, 10.0)
4885 .unwrap();
4886 let chain = chains
4887 .iter()
4888 .find_map(|c| match c {
4889 ExactIntersectionCurve::Points(chain) => Some(chain),
4890 _ => None,
4891 })
4892 .expect("a parabola or hyperbola section is sampled");
4893 let (from, to) = (chain[2], chain[chain.len() - 3]);
4894 let arc = plane_cone_conic_arc(&cone, normal, d, from, to)
4895 .unwrap()
4896 .expect("an exact arc");
4897 let (t0, t1) = arc.domain();
4898 assert!((arc.evaluate(t0) - from).length() < 1e-12);
4899 assert!((arc.evaluate(t1) - to).length() < 1e-12);
4900 for i in 0..=200 {
4901 let q = arc.evaluate(t0 + (t1 - t0) * f64::from(i) / 200.0);
4902 let w = q - Point3::new(0.0, 0.0, 0.0);
4903 let off_plane = (normal.dot(w) - d).abs();
4904 let off_cone = (w.z() - w.length() * half_angle.sin()).abs();
4905 assert!(off_plane < 1e-9, "off the plane by {off_plane}");
4906 assert!(off_cone < 1e-9, "off the cone by {off_cone}");
4907 }
4908 }
4909 }
4910
4911 #[test]
4915 fn plane_cone_conic_arc_declines_a_near_parabolic_ellipse() {
4916 let half_angle = 1.1_f64;
4917 let cone = ConicalSurface::new(
4918 Point3::new(0.0, 0.0, 0.0),
4919 Vec3::new(0.0, 0.0, 1.0),
4920 half_angle,
4921 )
4922 .unwrap();
4923 for shortfall in [1e-10, 3e-10, 8e-10] {
4924 let tilt = half_angle - shortfall / (2.0 * half_angle).sin();
4925 let normal = Vec3::new(tilt.sin(), 0.0, tilt.cos());
4926 let chains =
4927 exact_plane_analytic_reaching(AnalyticSurface::Cone(&cone), normal, 1.0, 10.0)
4928 .unwrap();
4929 let Some(chain) = chains.iter().find_map(|c| match c {
4930 ExactIntersectionCurve::Points(chain) => Some(chain),
4931 _ => None,
4932 }) else {
4933 continue;
4934 };
4935 let (from, to) = (chain[2], chain[chain.len() - 3]);
4936 assert!(
4937 plane_cone_conic_arc(&cone, normal, 1.0, from, from)
4938 .unwrap()
4939 .is_none(),
4940 "coincident ends"
4941 );
4942 let Some(arc) = plane_cone_conic_arc(&cone, normal, 1.0, from, to).unwrap() else {
4943 continue;
4944 };
4945 let (t0, t1) = arc.domain();
4946 for i in 0..=200 {
4947 let w = arc.evaluate(t0 + (t1 - t0) * f64::from(i) / 200.0)
4948 - Point3::new(0.0, 0.0, 0.0);
4949 let off_cone = (w.z() - w.length() * half_angle.sin()).abs();
4950 assert!(off_cone < 1e-8, "{shortfall}: off the cone by {off_cone}");
4951 }
4952 }
4953 }
4954
4955 #[test]
4956 fn plane_cylinder_perpendicular() {
4957 let cyl =
4958 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
4959 .unwrap();
4960
4961 let curves = intersect_plane_cylinder(&cyl, Vec3::new(0.0, 0.0, 1.0), 3.0).unwrap();
4963 assert!(!curves.is_empty(), "should find intersection curve");
4964 assert!(
4965 curves[0].points.len() > 10,
4966 "should have many sample points"
4967 );
4968
4969 let tol = Tolerance::loose();
4970 for pt in &curves[0].points {
4971 assert!(
4972 tol.approx_eq(pt.point.z(), 3.0),
4973 "z should be ~3.0, got {}",
4974 pt.point.z()
4975 );
4976 let r = pt.point.x().hypot(pt.point.y());
4977 assert!(tol.approx_eq(r, 2.0), "radius should be ~2.0, got {r}");
4978 }
4979 }
4980
4981 #[test]
4982 fn plane_sphere_equator() {
4983 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 3.0).unwrap();
4984
4985 let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
4986 assert!(!curves.is_empty());
4987
4988 let tol = Tolerance::loose();
4989 for pt in &curves[0].points {
4990 assert!(
4991 tol.approx_eq(pt.point.z(), 0.0),
4992 "z should be ~0, got {}",
4993 pt.point.z()
4994 );
4995 let r = pt.point.x().hypot(pt.point.y());
4996 assert!(tol.approx_eq(r, 3.0), "radius should be ~3.0, got {r}");
4997 }
4998 }
4999
5000 #[test]
5001 fn plane_sphere_no_intersection() {
5002 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
5003
5004 let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 5.0).unwrap();
5005 assert!(curves.is_empty());
5006 }
5007
5008 #[test]
5009 fn plane_cone_cross_section() {
5010 let cone = ConicalSurface::new(
5011 Point3::new(0.0, 0.0, 0.0),
5012 Vec3::new(0.0, 0.0, 1.0),
5013 std::f64::consts::FRAC_PI_4,
5014 )
5015 .unwrap();
5016
5017 let curves = intersect_plane_cone(&cone, Vec3::new(0.0, 0.0, 1.0), 1.0).unwrap();
5018 assert!(!curves.is_empty(), "should find intersection with cone");
5019 }
5020
5021 #[test]
5028 fn offset_parallel_equal_angle_cones_give_one_exact_ellipse() {
5029 let c1 = ConicalSurface::new(
5030 Point3::new(
5031 -16.999_999_999_999_975,
5032 -16.999_999_999_999_975,
5033 5.849_999_999_999_951,
5034 ),
5035 Vec3::new(0.0, 0.0, -1.0),
5036 0.785_398_163_397_433_5,
5037 )
5038 .unwrap();
5039 let c2 = ConicalSurface::new(
5040 Point3::new(
5041 -16.750_000_000_000_036,
5042 -16.750_000_000_000_018,
5043 0.749_999_999_999_881,
5044 ),
5045 Vec3::new(0.0, 0.0, 1.0),
5046 0.785_398_163_397_467_6,
5047 )
5048 .unwrap();
5049
5050 let curves = exact_cone_cone(&c1, &c2)
5051 .unwrap()
5052 .expect("offset parallel equal-angle cones must take the radical-plane path");
5053 assert_eq!(curves.len(), 1, "expected exactly one section conic");
5054 assert!(
5055 matches!(curves[0], ExactIntersectionCurve::Ellipse(_)),
5056 "expected an ellipse section, got {:?}",
5057 curves[0]
5058 );
5059 let ExactIntersectionCurve::Ellipse(ellipse) = &curves[0] else {
5060 return;
5061 };
5062
5063 for i in 0..16 {
5067 let p = crate::traits::ParametricCurve::evaluate(ellipse, TAU * f64::from(i) / 16.0);
5068 for (cone, label) in [(&c1, "c1"), (&c2, "c2")] {
5069 let rel = p - cone.apex();
5070 let rel_v = Vec3::new(rel.x(), rel.y(), rel.z());
5071 let axial = rel_v.dot(cone.axis());
5072 let radial = (rel_v - cone.axis() * axial).length();
5073 assert!(
5074 axial > 0.0,
5075 "{label}: sample on phantom nappe (axial {axial})"
5076 );
5077 let expect = cone.half_angle().tan() * axial;
5078 assert!(
5079 (radial - expect).abs() < 1e-9,
5080 "{label}: sample off surface by {}",
5081 (radial - expect).abs()
5082 );
5083 }
5084 }
5085 }
5086
5087 #[test]
5091 fn offset_parallel_cones_opening_apart_have_no_real_intersection() {
5092 let c1 = ConicalSurface::new(
5093 Point3::new(0.0, 0.0, 5.0),
5094 Vec3::new(0.0, 0.0, -1.0),
5095 std::f64::consts::FRAC_PI_4,
5096 )
5097 .unwrap();
5098 let c2 = ConicalSurface::new(
5099 Point3::new(0.25, 0.25, 20.0),
5100 Vec3::new(0.0, 0.0, 1.0),
5101 std::f64::consts::FRAC_PI_4,
5102 )
5103 .unwrap();
5104 let curves = exact_cone_cone(&c1, &c2)
5105 .unwrap()
5106 .expect("radical-plane path");
5107 assert!(curves.is_empty(), "disjoint nappes must yield no curves");
5108 }
5109
5110 #[test]
5113 fn offset_parallel_cones_with_unequal_angles_defer() {
5114 let c1 = ConicalSurface::new(
5115 Point3::new(0.0, 0.0, 5.0),
5116 Vec3::new(0.0, 0.0, -1.0),
5117 std::f64::consts::FRAC_PI_4,
5118 )
5119 .unwrap();
5120 let c2 = ConicalSurface::new(Point3::new(0.25, 0.25, 0.5), Vec3::new(0.0, 0.0, 1.0), 0.6)
5121 .unwrap();
5122 assert!(exact_cone_cone(&c1, &c2).unwrap().is_none());
5123 }
5124
5125 fn cone_and_tilted_tube() -> (ConicalSurface, CylindricalSurface) {
5129 let cone = ConicalSurface::new(
5130 Point3::new(0.0, 0.0, 0.0),
5131 Vec3::new(0.0, 0.0, 1.0),
5132 std::f64::consts::FRAC_PI_4,
5133 )
5134 .unwrap();
5135 let (s, c) = 40.0_f64.to_radians().sin_cos();
5136 let tube =
5137 CylindricalSurface::new(Point3::new(0.1, 0.0, 3.0), Vec3::new(0.0, s, c), 0.1).unwrap();
5138 (cone, tube)
5139 }
5140
5141 #[test]
5142 fn marcher_keeps_to_its_region() {
5143 let (cone, tube) = cone_and_tilted_tube();
5144 let run = |region: Option<Aabb3>| {
5145 let (a, b) = (
5146 AnalyticSurface::Cone(&cone),
5147 AnalyticSurface::Cylinder(&tube),
5148 );
5149 let (va, vb) = (Some((0.5, 4.0)), Some((-5.0, 5.0)));
5150 match region {
5151 Some(r) => intersect_analytic_analytic_in_region(a, b, 32, va, vb, r),
5152 None => intersect_analytic_analytic_bounded(a, b, 32, va, vb),
5153 }
5154 .unwrap()
5155 };
5156 assert!(!run(None).is_empty());
5157 let near = Aabb3 {
5158 min: Point3::new(-0.5, -2.0, 0.8),
5159 max: Point3::new(0.7, -0.7, 2.0),
5160 };
5161 let curves = run(Some(near));
5162 assert!(!curves.is_empty(), "the loop through the region is kept");
5163 let reach = near.expanded(0.6);
5165 for curve in &curves {
5166 assert!(curve.points.iter().all(|p| reach.contains_point(p.point)));
5167 }
5168 let away = Aabb3 {
5169 min: Point3::new(5.0, 5.0, 5.0),
5170 max: Point3::new(6.0, 6.0, 6.0),
5171 };
5172 assert!(run(Some(away)).is_empty(), "nothing is marched outside it");
5173 }
5174
5175 #[test]
5176 fn coaxial_cones_cross_at_single_circle() {
5177 let outer = ConicalSurface::new(
5182 Point3::new(0.0, 0.0, 50.0),
5183 Vec3::new(0.0, 0.0, -1.0),
5184 5.0_f64.atan(),
5185 )
5186 .unwrap();
5187 let inner = ConicalSurface::new(
5188 Point3::new(0.0, 0.0, 90.0),
5189 Vec3::new(0.0, 0.0, -1.0),
5190 10.0_f64.atan(),
5191 )
5192 .unwrap();
5193
5194 let curves = intersect_analytic_analytic_bounded(
5195 AnalyticSurface::Cone(&outer),
5196 AnalyticSurface::Cone(&inner),
5197 32,
5198 None,
5199 None,
5200 )
5201 .unwrap();
5202
5203 assert_eq!(
5204 curves.len(),
5205 1,
5206 "coaxial cones crossing at one circle must yield exactly one curve, got {}",
5207 curves.len()
5208 );
5209 for p in &curves[0].points {
5210 let r = p.point.x().hypot(p.point.y());
5211 assert!(
5212 (p.point.z() - 10.0).abs() < 1e-6 && (r - 8.0).abs() < 1e-6,
5213 "intersection point off the expected z=10,r=8 circle: {:?}",
5214 p.point
5215 );
5216 }
5217 }
5218
5219 #[test]
5220 fn plane_torus_cross_section() {
5221 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 5.0, 1.0).unwrap();
5222
5223 let curves = intersect_plane_torus(&torus, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
5224 assert!(
5225 !curves.is_empty(),
5226 "should find intersection curves with torus"
5227 );
5228 }
5229
5230 #[test]
5233 fn plane_tangent_to_a_tube_touches_it_along_one_circle() {
5234 for (major, minor) in [(5.0, 1.0), (0.1, 2.45)] {
5235 let torus = ToroidalSurface::new(Point3::new(1.0, 2.0, 3.0), major, minor).unwrap();
5236 for z in [3.0 - minor, 3.0 + minor] {
5237 let exact = exact_plane_analytic(
5238 AnalyticSurface::Torus(&torus),
5239 Vec3::new(0.0, 0.0, 1.0),
5240 z,
5241 )
5242 .unwrap();
5243 assert_eq!(exact.len(), 1, "R={major} r={minor} z={z}");
5244 let circle = match &exact[0] {
5245 ExactIntersectionCurve::Circle(c) => Some(c),
5246 _ => None,
5247 };
5248 let c = circle.expect("a circle");
5249 assert!((c.radius() - major).abs() < 1e-12);
5250 assert!((c.center() - Point3::new(1.0, 2.0, z)).length() < 1e-12);
5251
5252 let sampled = intersect_plane_torus(&torus, Vec3::new(0.0, 0.0, 1.0), z).unwrap();
5253 assert_eq!(sampled.len(), 1, "R={major} r={minor} z={z}");
5254 }
5255 let single = |normal: Vec3, d: f64| {
5257 matches!(
5258 exact_plane_analytic(AnalyticSurface::Torus(&torus), normal, d)
5259 .unwrap()
5260 .as_slice(),
5261 [ExactIntersectionCurve::Circle(_)]
5262 )
5263 };
5264 assert!(!single(Vec3::new(1e-6, 0.0, 1.0), 3.0 + minor));
5265 }
5266 }
5267
5268 #[test]
5272 fn plane_tangent_to_a_large_tube_is_read_through_rounding() {
5273 let torus = ToroidalSurface::new(Point3::new(0.3, -0.7, 3.0), 200.0, 100.1).unwrap();
5274 let level = Vec3::new(0.0, 0.0, 1.0);
5275 let curves =
5276 |d: f64| exact_plane_analytic(AnalyticSurface::Torus(&torus), level, d).unwrap();
5277 assert!(matches!(
5278 curves(3.0 + 100.1).as_slice(),
5279 [ExactIntersectionCurve::Circle(_)]
5280 ));
5281 let inside = curves(3.0 + 100.1 - 4e-7);
5282 assert!(!matches!(
5283 inside.as_slice(),
5284 [ExactIntersectionCurve::Circle(_)]
5285 ));
5286 }
5287
5288 fn torus_implicit(p: Point3, major: f64, minor: f64) -> f64 {
5291 let rho = p.x().hypot(p.y());
5292 ((rho - major).hypot(p.z())) - minor
5293 }
5294
5295 #[test]
5301 fn oblique_cone_cylinder_traces_curves_on_both() {
5302 use crate::traits::ParametricCurve;
5303 let cone = ConicalSurface::new(
5307 Point3::new(0.0, 0.0, 3.0),
5308 Vec3::new(0.0, 0.0, -1.0),
5309 2.0_f64.atan(),
5310 )
5311 .unwrap();
5312 for (x0, loops) in [(0.5, 1), (0.0, 2)] {
5313 let cyl =
5314 CylindricalSurface::new(Point3::new(x0, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
5315 .unwrap();
5316 for cone_first in [true, false] {
5317 let (a, b) = if cone_first {
5318 (
5319 AnalyticSurface::Cone(&cone),
5320 AnalyticSurface::Cylinder(&cyl),
5321 )
5322 } else {
5323 (
5324 AnalyticSurface::Cylinder(&cyl),
5325 AnalyticSurface::Cone(&cone),
5326 )
5327 };
5328 let curves = intersect_analytic_analytic(a, b, 32).unwrap();
5329 assert_eq!(curves.len(), loops, "x0 {x0}: loops");
5330 for c in &curves {
5331 let (t0, t1) = c.curve.domain();
5332 for k in 0..=64 {
5333 let t = (t1 - t0).madd(f64::from(k) / 64.0, t0);
5334 let p = ParametricCurve::evaluate(&c.curve, t);
5335 let rod = (p.x() - x0).hypot(p.z() - 1.0);
5338 assert!(
5339 (rod - 0.6).abs() < 1e-4,
5340 "x0 {x0}: off the rod by {}",
5341 rod - 0.6
5342 );
5343 let cone_r = p.x().hypot(p.y());
5344 assert!(
5345 (cone_r - 0.5 * (3.0 - p.z())).abs() < 1e-4,
5346 "x0 {x0}: off the cone at {p:?}"
5347 );
5348 }
5349 }
5350 }
5351 }
5352 }
5353
5354 #[test]
5355 fn a_rod_through_a_rings_tube_traces_four_loops() {
5356 use crate::traits::ParametricCurve;
5357 let ring = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
5358 let rod =
5361 CylindricalSurface::new(Point3::new(0.5, 0.0, 0.3), Vec3::new(0.0, 1.0, 0.0), 0.6)
5362 .unwrap();
5363 let curves = ruling_torus_cylinder(&ring, &rod, true).unwrap();
5364 assert_eq!(curves.len(), 4);
5365 for c in &curves {
5366 let (t0, t1) = c.curve.domain();
5367 for k in 0..=64 {
5368 let p =
5369 ParametricCurve::evaluate(&c.curve, (t1 - t0).madd(f64::from(k) / 64.0, t0));
5370 let on_rod = (p.x() - 0.5).hypot(p.z() - 0.3) - 0.6;
5371 let on_ring = (p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5;
5372 assert!(
5373 on_rod.abs() < 1e-4 && on_ring.abs() < 1e-4,
5374 "off by {on_rod}, {on_ring}"
5375 );
5376 }
5377 }
5378 let high =
5380 CylindricalSurface::new(Point3::new(0.5, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
5381 .unwrap();
5382 assert!(ruling_torus_cylinder(&ring, &high, true).is_none());
5383 let grazing =
5385 CylindricalSurface::new(Point3::new(0.5, 0.0, 0.9001), Vec3::new(0.0, 1.0, 0.0), 0.6)
5386 .unwrap();
5387 assert!(ruling_torus_cylinder(&ring, &grazing, true).is_none());
5388 let spindle = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0, 2.0).unwrap();
5390 let thin =
5391 CylindricalSurface::new(Point3::new(0.3, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), 0.2)
5392 .unwrap();
5393 assert!(ruling_torus_cylinder(&spindle, &thin, true).is_none());
5394 }
5395
5396 #[test]
5397 fn a_pin_through_a_ball_traces_two_loops() {
5398 use crate::traits::ParametricCurve;
5399 let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 3.0).unwrap();
5400 let half = 0.08_f64.atan();
5403 let apex = Point3::new(1.0, 0.5, -5.0 + 1.2 / 0.08);
5404 let pin = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, -1.0), FRAC_PI_2 - half).unwrap();
5405 for cone_first in [true, false] {
5406 let (a, b) = if cone_first {
5407 (AnalyticSurface::Cone(&pin), AnalyticSurface::Sphere(&ball))
5408 } else {
5409 (AnalyticSurface::Sphere(&ball), AnalyticSurface::Cone(&pin))
5410 };
5411 let curves = intersect_analytic_analytic(a, b, 32).unwrap();
5412 assert_eq!(curves.len(), 2, "entry and exit loops");
5413 for c in &curves {
5414 let (t0, t1) = c.curve.domain();
5415 for k in 0..=64 {
5416 let p = ParametricCurve::evaluate(
5417 &c.curve,
5418 (t1 - t0).madd(f64::from(k) / 64.0, t0),
5419 );
5420 let on_ball = (p - Point3::new(0.0, 0.0, 0.0)).length() - 3.0;
5421 let axial = apex.z() - p.z();
5422 let on_pin = (p.x() - 1.0).hypot(p.y() - 0.5) - axial * half.tan();
5423 assert!(
5424 on_ball.abs() < 1e-4 && on_pin.abs() < 1e-4,
5425 "off by {on_ball}, {on_pin}"
5426 );
5427 }
5428 }
5429 }
5430 let coaxial =
5435 ConicalSurface::new(Point3::new(0.0, 0.0, 10.0), Vec3::new(0.0, 0.0, -1.0), 1.4)
5436 .unwrap();
5437 assert!(ruling_cone_sphere(&coaxial, &ball, true).is_none());
5438 let aside = ConicalSurface::new(
5439 Point3::new(2.8, 0.0, 10.0),
5440 Vec3::new(0.0, 0.0, -1.0),
5441 FRAC_PI_2 - half,
5442 )
5443 .unwrap();
5444 assert_eq!(ruling_cone_sphere(&aside, &ball, true).unwrap().len(), 1);
5445 let holding = ConicalSurface::new(
5446 Point3::new(1.0, 0.5, 1.0),
5447 Vec3::new(0.0, 0.0, -1.0),
5448 FRAC_PI_2 - half,
5449 )
5450 .unwrap();
5451 assert_eq!(ruling_cone_sphere(&holding, &ball, true).unwrap().len(), 1);
5452 let away = ConicalSurface::new(
5453 Point3::new(1.0, 0.5, 10.0),
5454 Vec3::new(0.0, 0.0, 1.0),
5455 FRAC_PI_2 - half,
5456 )
5457 .unwrap();
5458 assert!(ruling_cone_sphere(&away, &ball, true).unwrap().is_empty());
5459 let step = TAU / 2048.0;
5463 let grazed =
5464 SphericalSurface::new(Point3::new(step.cos(), step.sin(), 10.0), 9.255_250_971_8)
5465 .unwrap();
5466 let wide =
5467 ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5).unwrap();
5468 assert_eq!(ruling_cone_sphere(&wide, &grazed, true).unwrap().len(), 1);
5469 }
5470
5471 #[test]
5472 fn a_ball_beside_a_cone_meets_it_in_one_loop() {
5473 use crate::traits::ParametricCurve;
5474 let cone = ConicalSurface::new(
5476 Point3::new(0.0, 0.0, 3.0),
5477 Vec3::new(0.0, 0.0, -1.0),
5478 2.0_f64.atan(),
5479 )
5480 .unwrap();
5481 for (centre, radius) in [
5482 (Point3::new(1.0, 0.8, 1.2), 1.1),
5483 (Point3::new(1.5, 0.0, 0.0), 0.8),
5484 ] {
5485 let ball = SphericalSurface::new(centre, radius).unwrap();
5486 let curves = ruling_cone_sphere(&cone, &ball, true).unwrap();
5487 assert_eq!(curves.len(), 1, "one loop for the ball at {centre:?}");
5488 let (t0, t1) = curves[0].curve.domain();
5489 for k in 0..=64 {
5490 let p = ParametricCurve::evaluate(
5491 &curves[0].curve,
5492 (t1 - t0).madd(f64::from(k) / 64.0, t0),
5493 );
5494 let on_ball = (p - centre).length() - radius;
5495 let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
5496 assert!(
5497 on_ball.abs() < 1e-5 && on_cone.abs() < 1e-5,
5498 "ball at {centre:?}: off by {on_ball}, {on_cone}"
5499 );
5500 }
5501 }
5502 let clear = SphericalSurface::new(Point3::new(4.0, 0.0, 0.0), 0.5).unwrap();
5504 assert!(ruling_cone_sphere(&cone, &clear, true).unwrap().is_empty());
5505 let on_apex = SphericalSurface::new(Point3::new(0.6, 0.0, 3.8), 1.0).unwrap();
5506 assert!(ruling_cone_sphere(&cone, &on_apex, true).is_none());
5507 }
5508
5509 #[test]
5510 fn a_ball_holding_a_cones_apex_meets_it_in_one_loop() {
5511 use crate::traits::ParametricCurve;
5512 let cone = ConicalSurface::new(
5513 Point3::new(0.0, 0.0, 3.0),
5514 Vec3::new(0.0, 0.0, -1.0),
5515 2.0_f64.atan(),
5516 )
5517 .unwrap();
5518 for (centre, radius) in [
5521 (Point3::new(0.5, 0.0, 2.5), 2.0),
5522 (Point3::new(-0.4, 0.3, 2.0), 1.5),
5523 (Point3::new(0.0, 0.8, 3.0), 0.8001),
5524 (Point3::new(0.0, 0.8, 3.0), 0.800_001),
5525 ] {
5526 let ball = SphericalSurface::new(centre, radius).unwrap();
5527 let curves = ruling_cone_sphere(&cone, &ball, true).unwrap();
5528 assert_eq!(curves.len(), 1, "one loop for the ball at {centre:?}");
5529 let (t0, t1) = curves[0].curve.domain();
5530 for k in 0..=4096 {
5531 let p = ParametricCurve::evaluate(
5532 &curves[0].curve,
5533 (t1 - t0).madd(f64::from(k) / 4096.0, t0),
5534 );
5535 let on_ball = (p - centre).length() - radius;
5536 let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
5537 assert!(
5538 on_ball.abs() < 1e-5 && on_cone.abs() < 1e-5 && p.z() < 3.0,
5539 "ball at {centre:?}: off by {on_ball}, {on_cone} at {p:?}"
5540 );
5541 }
5542 }
5543 }
5544
5545 #[test]
5546 fn oblique_cone_cylinder_defers_where_rulings_cannot_trace_it() {
5547 let t = 2.0_f64.atan();
5548 let cone =
5549 ConicalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(0.0, 0.0, -1.0), t).unwrap();
5550 let through_apex =
5552 CylindricalSurface::new(Point3::new(0.0, 0.0, 3.0), Vec3::new(0.0, 1.0, 0.0), 0.6)
5553 .unwrap();
5554 assert!(ruling_cone_cylinder(&cone, &through_apex, true).is_none());
5555 let generator = Vec3::new(t.cos(), 0.0, -t.sin());
5557 let along = CylindricalSurface::new(Point3::new(0.0, 0.3, 0.0), generator, 0.2).unwrap();
5558 assert!(ruling_cone_cylinder(&cone, &along, true).is_none());
5559 let pin =
5562 ConicalSurface::new(Point3::new(20.5, 0.0, 0.0), Vec3::new(-1.0, 0.0, 0.0), t).unwrap();
5563 let tube =
5564 CylindricalSurface::new(Point3::new(0.0, 0.0, -10.0), Vec3::new(0.0, 0.0, 1.0), 20.0)
5565 .unwrap();
5566 assert!(ruling_cone_cylinder(&pin, &tube, true).is_none());
5567 }
5568
5569 #[test]
5570 fn parallel_cone_cylinder_gives_two_exact_branches() {
5571 use crate::traits::ParametricCurve;
5572 let cone = ConicalSurface::new(
5573 Point3::new(-5.45, -36.55, -4.85),
5574 Vec3::new(0.0, 0.0, 1.0),
5575 std::f64::consts::FRAC_PI_4,
5576 )
5577 .unwrap();
5578 let cyl = CylindricalSurface::new(
5579 Point3::new(-8.0, -34.0, -5.0),
5580 Vec3::new(0.0, 0.0, 1.0),
5581 4.45,
5582 )
5583 .unwrap();
5584 let v_hint = (1.484_924_240_492_058, 2.616_295_090_390_43);
5586 let curves = intersect_analytic_analytic_bounded(
5587 AnalyticSurface::Cone(&cone),
5588 AnalyticSurface::Cylinder(&cyl),
5589 32,
5590 Some(v_hint),
5591 Some((0.0, 2.5)),
5592 )
5593 .unwrap();
5594
5595 assert_eq!(curves.len(), 2, "expected exactly the two branches");
5596 for c in &curves {
5597 let (t0, t1) = c.curve.domain();
5598 for k in 0..=32 {
5599 let t = (t1 - t0).madd(f64::from(k) / 32.0, t0);
5600 let p = ParametricCurve::evaluate(&c.curve, t);
5601 let radial = ((p.x() + 8.0).powi(2) + (p.y() + 34.0).powi(2)).sqrt();
5603 assert!((radial - 4.45).abs() < 1e-6, "off cylinder: {radial}");
5604 let cone_r = ((p.x() + 5.45).powi(2) + (p.y() + 36.55).powi(2)).sqrt();
5606 assert!((cone_r - (p.z() + 4.85)).abs() < 1e-6, "off cone at {p:?}");
5607 assert!(p.z() >= -3.8 - 1e-9 && p.z() <= -3.0 + 1e-9, "z={}", p.z());
5609 }
5610 }
5611 }
5612
5613 #[test]
5614 fn parallel_rod_through_a_cones_wall_closes_one_loop() {
5615 use crate::traits::ParametricCurve;
5616 let cone = ConicalSurface::new(
5618 Point3::new(0.0, 0.0, 3.0),
5619 Vec3::new(0.0, 0.0, -1.0),
5620 2.0_f64.atan(),
5621 )
5622 .unwrap();
5623 for (x, y) in [(0.0, 1.3), (1.2, 0.5)] {
5625 let rod =
5626 CylindricalSurface::new(Point3::new(x, y, -10.0), Vec3::new(0.0, 0.0, 1.0), 0.6)
5627 .unwrap();
5628 let curves = algebraic_parallel_cone_cylinder(&cone, &rod, None, None)
5629 .unwrap()
5630 .unwrap();
5631 assert_eq!(curves.len(), 1, "one closed loop at ({x}, {y})");
5632 let (t0, t1) = curves[0].curve.domain();
5633 let (first, last) = (
5634 ParametricCurve::evaluate(&curves[0].curve, t0),
5635 ParametricCurve::evaluate(&curves[0].curve, t1),
5636 );
5637 assert!((first - last).length() < 1e-9, "open at ({x}, {y})");
5638 for k in 0..=64 {
5639 let p = ParametricCurve::evaluate(
5640 &curves[0].curve,
5641 (t1 - t0).madd(f64::from(k) / 64.0, t0),
5642 );
5643 let on_rod = (p.x() - x).hypot(p.y() - y) - 0.6;
5644 let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
5645 assert!(
5646 on_rod.abs() < 1e-5 && on_cone.abs() < 1e-5,
5647 "({x}, {y}): off by {on_rod}, {on_cone}"
5648 );
5649 }
5650 }
5651 for (x, y) in [(0.3, 0.2), (0.65, 0.0)] {
5654 let rod =
5655 CylindricalSurface::new(Point3::new(x, y, -10.0), Vec3::new(0.0, 0.0, 1.0), 0.6)
5656 .unwrap();
5657 let curves = algebraic_parallel_cone_cylinder(&cone, &rod, None, None)
5658 .unwrap()
5659 .unwrap();
5660 assert_eq!(curves.len(), 2, "two branches at ({x}, {y})");
5661 }
5662 }
5663
5664 #[test]
5667 fn coaxial_cone_cylinder_defers_to_other_paths() {
5668 let cone = ConicalSurface::new(
5669 Point3::new(0.0, 0.0, 0.0),
5670 Vec3::new(0.0, 0.0, 1.0),
5671 std::f64::consts::FRAC_PI_4,
5672 )
5673 .unwrap();
5674 let cyl =
5675 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
5676 .unwrap();
5677 assert!(
5678 algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
5679 .unwrap()
5680 .is_none()
5681 );
5682 }
5683
5684 #[test]
5685 fn oblique_cone_cylinder_defers_to_other_paths() {
5686 let cone = ConicalSurface::new(
5687 Point3::new(0.0, 0.0, 0.0),
5688 Vec3::new(0.0, 0.0, 1.0),
5689 std::f64::consts::FRAC_PI_4,
5690 )
5691 .unwrap();
5692 let cyl =
5693 CylindricalSurface::new(Point3::new(3.0, 0.0, 1.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
5694 .unwrap();
5695 assert!(
5696 algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
5697 .unwrap()
5698 .is_none()
5699 );
5700 }
5701
5702 #[test]
5703 fn plane_torus_lobe_closes_and_stays_on_surface() {
5704 use crate::traits::ParametricCurve;
5705 let (major, minor) = (10.0, 3.0);
5706 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5707
5708 for (n, d) in [
5712 (Vec3::new(0.0, -1.0, 0.0), 4.0), (Vec3::new(-1.0, 0.0, 0.0), -6.0), (Vec3::new(0.0, 0.0, 1.0), 0.0), ] {
5716 let curves = intersect_plane_torus(&torus, n, d).unwrap();
5717 assert!(!curves.is_empty(), "plane n={n:?} d={d} found no curves");
5718 for c in &curves {
5719 let p0 = ParametricCurve::evaluate(&c.curve, 0.0);
5720 let p1 = ParametricCurve::evaluate(&c.curve, 1.0);
5721 assert!(
5722 (p0 - p1).length() < 1e-7,
5723 "lobe not closed: gap={} (n={n:?} d={d})",
5724 (p0 - p1).length()
5725 );
5726 for k in 0..=64 {
5728 let t = f64::from(k) / 64.0;
5729 let p = ParametricCurve::evaluate(&c.curve, t);
5730 assert!(
5731 torus_implicit(p, major, minor).abs() < 1e-2,
5732 "off-surface point {p:?} implicit={}",
5733 torus_implicit(p, major, minor)
5734 );
5735 }
5736 }
5737 }
5738 }
5739
5740 #[test]
5745 fn plane_torus_inner_tangent_figure_eight_is_two_loops_through_its_node() {
5746 let (major, minor) = (10.0, 3.0);
5747 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5748 let curves =
5749 intersect_plane_torus(&torus, Vec3::new(-1.0, 0.0, 0.0), -(major - minor)).unwrap();
5750 assert_eq!(curves.len(), 2, "one loop per lobe");
5751 let node = Point3::new(major - minor, 0.0, 0.0);
5752 let mut sides = Vec::new();
5753 for c in &curves {
5754 let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
5755 assert!((first - node).length() < 1e-6, "starts at {first:?}");
5756 assert_eq!(first, last, "closes on the node");
5757 for p in c.points.iter().map(|p| p.point) {
5758 assert!((p.x() - node.x()).abs() < 1e-9, "off the plane at {p:?}");
5759 assert!(
5760 torus_implicit(p, major, minor).abs() < 1e-6,
5761 "off the torus at {p:?}"
5762 );
5763 }
5764 let y: f64 = c.points.iter().map(|p| p.point.y()).sum();
5765 sides.push(y > 0.0);
5766 assert!(
5767 c.points.iter().all(|p| p.point.y() * y >= -1e-9),
5768 "a lobe crosses y = 0"
5769 );
5770 }
5771 assert_ne!(sides[0], sides[1], "the lobes lie either side of y = 0");
5772 }
5773
5774 #[test]
5780 fn a_wall_just_off_the_inner_tangent_cuts_no_node() {
5781 let (major, minor) = (3.0, 1.0);
5782 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5783 for (x, loops) in [(2.0001, 1), (1.9999, 2)] {
5784 let curves = intersect_plane_torus(&torus, Vec3::new(1.0, 0.0, 0.0), x).unwrap();
5785 assert_eq!(curves.len(), loops, "x = {x}");
5786 for c in &curves {
5787 let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
5788 assert_eq!(first, last, "x = {x}: the loop closes");
5789 for p in c.points.iter().map(|p| p.point) {
5790 assert!((p.x() - x).abs() < 1e-9, "x = {x}: off the wall at {p:?}");
5791 assert!(
5792 torus_implicit(p, major, minor).abs() < 1e-6,
5793 "x = {x}: off the torus at {p:?}"
5794 );
5795 }
5796 }
5797 }
5798 let curves = intersect_plane_torus(&torus, Vec3::new(1.0, 0.0, 0.0), 2.0001).unwrap();
5800 let low = curves[0]
5801 .points
5802 .iter()
5803 .map(|p| p.point)
5804 .filter(|p| p.y().abs() < 1e-6)
5805 .map(Point3::z)
5806 .collect::<Vec<_>>();
5807 let gap = (2.0001_f64 - 2.0)
5808 .madd(2.0, -(2.0001_f64 - 2.0).powi(2))
5809 .sqrt();
5810 assert!(
5811 low.iter().any(|z| (z - gap).abs() < 1e-6)
5812 && low.iter().any(|z| (z + gap).abs() < 1e-6),
5813 "turns at {low:?}, not at z = ±{gap}"
5814 );
5815 }
5816
5817 #[test]
5821 fn a_tilted_plane_tangent_inside_the_tube_cuts_two_loops_through_its_node() {
5822 let (major, minor) = (3.0, 1.0);
5823 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5824 for v0 in [1.7_f64, 2.0, 2.5, 4.0] {
5825 let normal = Vec3::new(v0.cos(), 0.0, v0.sin());
5826 let node = torus.evaluate(0.0, v0);
5827 let d = normal.dot(Vec3::new(node.x(), node.y(), node.z()));
5828 let curves = intersect_plane_torus(&torus, normal, d).unwrap();
5829 assert_eq!(curves.len(), 2, "v0 {v0}: one loop per lobe");
5830 for c in &curves {
5831 let (first, last) = (c.points[0].point, c.points[c.points.len() - 1].point);
5832 assert!(
5833 (first - node).length() < 1e-6,
5834 "v0 {v0}: starts at {first:?}, not {node:?}"
5835 );
5836 assert_eq!(first, last, "v0 {v0}: closes on the node");
5837 for p in c.points.iter().map(|p| p.point) {
5838 let off = normal.dot(Vec3::new(p.x(), p.y(), p.z())) - d;
5839 assert!(off.abs() < 1e-9, "v0 {v0}: off the plane at {p:?}");
5840 assert!(
5841 torus_implicit(p, major, minor).abs() < 1e-6,
5842 "v0 {v0}: off the torus at {p:?}"
5843 );
5844 }
5845 }
5846 }
5847 }
5848
5849 #[test]
5854 fn plane_torus_wall_sections_close_into_their_loops() {
5855 for (major, minor) in [(4.0, 1.5), (100.0, 30.0), (0.05, 0.01)] {
5856 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5857 for k in 1..200 {
5858 let (d, want) = match k.cmp(&100) {
5859 std::cmp::Ordering::Less => ((major - minor) * f64::from(k) / 100.0, 2),
5861 std::cmp::Ordering::Greater => (
5863 2.0f64.madd(minor * f64::from(k - 100) / 100.0, major - minor),
5864 1,
5865 ),
5866 std::cmp::Ordering::Equal => continue,
5867 };
5868 let loops = plane_torus_loops(&torus, Vec3::new(1.0, 0.0, 0.0), d, 128);
5869 let closed = loops
5870 .iter()
5871 .filter(|l| (l[0].point - l[l.len() - 1].point).length() < 1e-12)
5872 .count();
5873 assert_eq!(
5874 (loops.len(), closed),
5875 (want, want),
5876 "R {major} r {minor}, wall at {d}"
5877 );
5878 }
5879 }
5880 }
5881
5882 #[test]
5886 fn plane_torus_sections_round_the_axis_stay_on_the_torus() {
5887 let (major, minor) = (4.0, 1.5);
5888 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
5889 for tilt in [0.03_f64, 0.08, 0.2] {
5890 let normal = Vec3::new(tilt.sin(), 0.0, tilt.cos());
5891 let curves = intersect_plane_torus(&torus, normal, 0.0).unwrap();
5892 assert_eq!(curves.len(), 2, "tilt {tilt}");
5893 for c in &curves {
5894 let (t0, t1) = c.curve.domain();
5895 let off = (0..=400)
5896 .map(|k| {
5897 let p = c.curve.evaluate((t1 - t0).madd(f64::from(k) / 400.0, t0));
5898 (p.x().hypot(p.y()) - major).hypot(p.z()) - minor
5899 })
5900 .fold(0.0_f64, |m, e| m.max(e.abs()));
5901 assert!(
5902 off < 1e-6,
5903 "tilt {tilt}: fitted section {off} off the torus"
5904 );
5905 }
5906 }
5907 }
5908
5909 #[test]
5910 fn line_torus_box_edge_crossing_is_exact() {
5911 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
5914 let ts = intersect_line_torus(
5915 &torus,
5916 Point3::new(6.0, -4.0, -5.0),
5917 Vec3::new(0.0, 0.0, 1.0),
5918 );
5919 assert_eq!(ts.len(), 2, "expected 2 crossings, got {ts:?}");
5921 let zs: Vec<f64> = ts.iter().map(|t| -5.0 + t).collect();
5922 let rho = 6.0_f64.hypot(4.0);
5923 let z_exp = (9.0 - (rho - 10.0).powi(2)).sqrt();
5924 assert!(
5925 (zs[0] - (-z_exp)).abs() < 1e-9,
5926 "z0={} exp={}",
5927 zs[0],
5928 -z_exp
5929 );
5930 assert!((zs[1] - z_exp).abs() < 1e-9, "z1={} exp={}", zs[1], z_exp);
5931 for &t in &ts {
5933 let p = Point3::new(6.0, -4.0, -5.0 + t);
5934 let rho = p.x().hypot(p.y());
5935 let impl_v = (rho - 10.0).hypot(p.z()) - 3.0;
5936 assert!(impl_v.abs() < 1e-9, "off-torus impl={impl_v}");
5937 }
5938 }
5939
5940 #[test]
5945 fn line_spindle_torus_roots_lie_on_their_tubes() {
5946 let torus = ToroidalSurface::new(Point3::new(41.0, 17.0, 4.7), 0.1, 2.45).unwrap();
5947 let origin = Point3::new(42.36, 18.31, 3.4);
5948 let dir = Vec3::new(
5949 0.573_576_436_351_046,
5950 0.740_535_693_464_567_5,
5951 0.350_889_803_483_932_2,
5952 );
5953 let ts = intersect_line_torus(&torus, origin, dir);
5954 let tube = |t: f64, across: f64| {
5955 let q = origin + dir * t;
5956 ((q.x() - 41.0).hypot(q.y() - 17.0) - across * 0.1).hypot(q.z() - 4.7) - 2.45
5957 };
5958 for &t in &ts {
5959 assert!(
5960 tube(t, 1.0).abs().min(tube(t, -1.0).abs()) < 1e-9,
5961 "root {t} off both tubes in {ts:?}"
5962 );
5963 }
5964 for want in [0.124, 0.398] {
5965 assert!(
5966 ts.iter().any(|&t| (t - want).abs() < 1e-3),
5967 "no root near {want} in {ts:?}"
5968 );
5969 }
5970 }
5971
5972 #[test]
5973 fn line_torus_miss_and_tangent() {
5974 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
5975 let miss = intersect_line_torus(
5977 &torus,
5978 Point3::new(20.0, 0.0, 0.0),
5979 Vec3::new(0.0, 0.0, 1.0),
5980 );
5981 assert!(miss.is_empty(), "expected no crossings, got {miss:?}");
5982 let axis =
5984 intersect_line_torus(&torus, Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0));
5985 assert!(axis.is_empty(), "z-axis should miss the tube, got {axis:?}");
5986 }
5987
5988 #[test]
5989 fn dispatch_via_analytic_surface() {
5990 let cyl =
5991 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
5992 .unwrap();
5993 let curves = intersect_plane_analytic(
5994 AnalyticSurface::Cylinder(&cyl),
5995 Vec3::new(0.0, 0.0, 1.0),
5996 0.0,
5997 )
5998 .unwrap();
5999 assert!(!curves.is_empty());
6000 }
6001
6002 #[test]
6003 fn perpendicular_cylinders_intersect() {
6004 let cyl_z =
6005 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
6006 .unwrap();
6007 let cyl_x =
6008 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
6009 .unwrap();
6010
6011 let curves = intersect_analytic_analytic(
6012 AnalyticSurface::Cylinder(&cyl_z),
6013 AnalyticSurface::Cylinder(&cyl_x),
6014 16,
6015 )
6016 .unwrap();
6017
6018 assert!(
6019 !curves.is_empty(),
6020 "perpendicular cylinders should intersect"
6021 );
6022
6023 for c in &curves {
6024 assert!(
6025 c.points.len() >= 2,
6026 "intersection curve should have >= 2 points, got {}",
6027 c.points.len()
6028 );
6029 }
6030 }
6031
6032 #[test]
6035 fn partially_overlapping_cylinders_meet_in_one_closed_loop() {
6036 let cyl_z =
6037 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
6038 .unwrap();
6039 let cyl_x =
6040 CylindricalSurface::new(Point3::new(0.0, 1.2, 0.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
6041 .unwrap();
6042 let curves = algebraic_cylinder_cylinder(&cyl_z, &cyl_x)
6043 .unwrap()
6044 .unwrap();
6045 assert_eq!(curves.len(), 1);
6046 let curve = &curves[0].curve;
6047 let (t0, t1) = curve.domain();
6048 assert!((curve.evaluate(t0) - curve.evaluate(t1)).length() < 1e-9);
6049 let off = |p: Point3| {
6050 let on_z = (p.x().hypot(p.y()) - 1.0).abs();
6051 let on_x = ((p.y() - 1.2).hypot(p.z()) - 1.0).abs();
6052 on_z.max(on_x)
6053 };
6054 let worst = (0..=400)
6055 .map(|k| off(curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0)))
6056 .fold(0.0, f64::max);
6057 assert!(worst < 2e-4, "curve leaves the cylinders by {worst}");
6058 }
6059
6060 #[test]
6064 fn near_tangent_cylinders_find_their_loop_on_the_thinner_sweep() {
6065 let cyl_z =
6066 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
6067 .unwrap();
6068 let cyl_x =
6069 CylindricalSurface::new(Point3::new(0.0, 1.1998, 0.0), Vec3::new(1.0, 0.0, 0.0), 0.2)
6070 .unwrap();
6071 let curves = algebraic_cylinder_cylinder(&cyl_z, &cyl_x)
6072 .unwrap()
6073 .expect("the thin cylinder's sweep finds the loop");
6074 assert_eq!(curves.len(), 1);
6075 }
6076
6077 #[test]
6082 fn equal_cylinders_with_crossing_axes_meet_in_two_cornered_loops() {
6083 let crossing = Point3::new(1.0, 2.0, 3.0);
6084 let (s, c) = 60.0_f64.to_radians().sin_cos();
6085 let (d1, d2) = (Vec3::new(0.0, 0.0, 1.0), Vec3::new(s, 0.0, c));
6086 let c1 = CylindricalSurface::new(crossing - d1 * 2.0, d1, 1.5).unwrap();
6087 let c2 = CylindricalSurface::new(crossing + d2 * 0.7, d2, 1.5).unwrap();
6088 let curves = algebraic_cylinder_cylinder(&c1, &c2).unwrap().unwrap();
6089 assert_eq!(curves.len(), 2);
6090 let off = |p: Point3, cyl: &CylindricalSurface| {
6091 let q = p - cyl.origin();
6092 ((q - cyl.axis() * q.dot(cyl.axis())).length() - 1.5).abs()
6093 };
6094 let ends = [
6095 crossing + Vec3::new(0.0, 1.5, 0.0),
6096 crossing - Vec3::new(0.0, 1.5, 0.0),
6097 ];
6098 let mut vertices: Vec<Point3> = Vec::new();
6099 for (ic, (end, side)) in curves.iter().zip([(ends[0], 1.0), (ends[1], -1.0)]) {
6100 let (t0, t1) = ic.curve.domain();
6101 for k in 0..=400 {
6102 let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
6103 assert!(off(p, &c1).max(off(p, &c2)) < 1e-13);
6104 assert!(side * (p - crossing).dot(d1) > -1e-13);
6105 }
6106 assert!((ic.curve.evaluate(t0) - end).length() < 1e-14);
6107 assert!((ic.curve.evaluate(t1) - end).length() < 1e-14);
6108 let other = ends[usize::from(side > 0.0)];
6109 assert!((ic.curve.evaluate(0.5) - other).length() < 1e-14);
6110 for t in [0.25, 0.75] {
6111 let vertex = ic.curve.evaluate(t);
6112 assert!(vertices.iter().all(|&v| (v - vertex).length() > 1.0));
6113 vertices.push(vertex);
6114 }
6115 }
6116 }
6117
6118 #[test]
6123 fn nearly_crossing_equal_cylinders_are_not_ellipses() {
6124 let z = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
6125 .unwrap();
6126 let x = |(x0, y): (f64, f64), r: f64| {
6127 CylindricalSurface::new(Point3::new(x0, y, 0.0), Vec3::new(1.0, 0.0, 0.0), r).unwrap()
6128 };
6129 let taken = |c: &CylindricalSurface| crossing_equal_cylinders(&z, c).unwrap().is_some();
6130 assert!(taken(&x((-2.0, 0.0), 1.0)));
6131 assert!(!taken(&x((-2.0, 1e-9), 1.0)));
6132 assert!(!taken(&x((-2.0, 0.0), 1.0 + 1e-9)));
6133 assert!(!taken(&x((-1e8, 1e-6), 1.0)));
6134 }
6135
6136 #[test]
6140 fn nearly_parallel_equal_cylinders_are_not_ellipses() {
6141 let z = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 10.0)
6142 .unwrap();
6143 for slope in [1e-8, 1.5e-5] {
6144 let tilted = CylindricalSurface::new(
6145 Point3::new(0.0, 0.0, 0.0),
6146 Vec3::new(slope, 0.0, 1.0),
6147 10.0,
6148 )
6149 .unwrap();
6150 assert!(crossing_equal_cylinders(&z, &tilted).unwrap().is_none());
6151 }
6152 }
6153
6154 #[test]
6155 fn sphere_cylinder_intersect() {
6156 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
6157 let cyl =
6158 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
6159 .unwrap();
6160
6161 let curves = intersect_analytic_analytic(
6162 AnalyticSurface::Sphere(&sphere),
6163 AnalyticSurface::Cylinder(&cyl),
6164 16,
6165 )
6166 .unwrap();
6167
6168 assert!(!curves.is_empty(), "sphere and cylinder should intersect");
6172 }
6173
6174 #[test]
6175 fn exact_sphere_cylinder_coaxial_two_circles() {
6176 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
6179 let cyl =
6180 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
6181 .unwrap();
6182 let circles = exact_sphere_cylinder(&sphere, &cyl)
6183 .unwrap()
6184 .expect("coaxial case returns Some");
6185 assert_eq!(circles.len(), 2, "through-bore meets the sphere twice");
6186 let mut zs: Vec<f64> = circles
6187 .iter()
6188 .filter_map(|c| match c {
6189 ExactIntersectionCurve::Circle(circle) => {
6190 assert!(
6191 (circle.radius() - 3.0).abs() < 1e-9,
6192 "rim radius == cyl radius"
6193 );
6194 Some(circle.center().z())
6195 }
6196 _ => None,
6197 })
6198 .collect();
6199 assert_eq!(zs.len(), 2, "both sections must be exact circles");
6200 zs.sort_by(f64::total_cmp);
6201 let z = 27.0_f64.sqrt();
6202 assert!((zs[0] + z).abs() < 1e-9 && (zs[1] - z).abs() < 1e-9);
6203 }
6204
6205 #[test]
6206 fn exact_sphere_cylinder_non_coaxial_defers() {
6207 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
6209 let cyl =
6210 CylindricalSurface::new(Point3::new(2.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
6211 .unwrap();
6212 assert!(
6213 exact_sphere_cylinder(&sphere, &cyl).unwrap().is_none(),
6214 "non-coaxial sphere/cylinder defers to the marcher"
6215 );
6216 }
6217
6218 #[test]
6219 fn a_ball_on_a_cones_axis_meets_it_in_circles() {
6220 let cone = ConicalSurface::new(
6222 Point3::new(0.0, 0.0, 3.0),
6223 Vec3::new(0.0, 0.0, -1.0),
6224 2.0_f64.atan(),
6225 )
6226 .unwrap();
6227 for (height, radius, count) in [
6228 (0.0, 2.0, 2), (2.5, 1.3, 1), (2.5, 0.5, 1), (0.0, 1.0, 0), (5.0, 1.0, 0), ] {
6234 let centre = Point3::new(0.0, 0.0, height);
6235 let ball = SphericalSurface::new(centre, radius).unwrap();
6236 let curves = exact_cone_sphere(&cone, &ball).unwrap().unwrap();
6237 let circles = circles_of(&curves);
6238 assert_eq!(circles.len(), count, "ball at {height}, radius {radius}");
6239 for circle in circles {
6240 for k in 0..16 {
6241 let p = circle.evaluate(TAU * f64::from(k) / 16.0);
6242 let on_ball = (p - centre).length() - radius;
6243 let on_cone = p.x().hypot(p.y()) - (3.0 - p.z()) / 2.0;
6244 assert!(
6245 on_ball.abs() < 1e-9 && on_cone.abs() < 1e-9,
6246 "ball at {height}: off by {on_ball}, {on_cone}"
6247 );
6248 }
6249 }
6250 }
6251 let aside = SphericalSurface::new(Point3::new(0.5, 0.0, 0.0), 2.0).unwrap();
6252 assert!(exact_cone_sphere(&cone, &aside).unwrap().is_none());
6253 let wide =
6256 ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.3).unwrap();
6257 let far = SphericalSurface::new(Point3::new(0.0, 0.0, 1e6), 1e6 * 0.3_f64.cos()).unwrap();
6258 let curves = exact_cone_sphere(&wide, &far).unwrap().unwrap();
6259 let circles = circles_of(&curves);
6260 assert_eq!(circles.len(), 1, "the touch");
6261 let touch = 1e6 * 0.3_f64.sin() * 0.3_f64.cos();
6262 assert!(
6263 (circles[0].radius() - touch).abs() < 1e-3,
6264 "{}",
6265 circles[0].radius()
6266 );
6267 }
6268
6269 fn circles_of(curves: &[ExactIntersectionCurve]) -> Vec<&Circle3D> {
6271 curves
6272 .iter()
6273 .filter_map(|c| match c {
6274 ExactIntersectionCurve::Circle(circle) => Some(circle),
6275 _ => None,
6276 })
6277 .collect()
6278 }
6279
6280 fn worst_off(
6283 circles: &[&Circle3D],
6284 torus: &ToroidalSurface,
6285 other: impl Fn(Point3) -> f64,
6286 ) -> f64 {
6287 let mut worst = 0.0_f64;
6288 for circle in circles {
6289 for k in 0..16 {
6290 let p = circle.evaluate(TAU * f64::from(k) / 16.0);
6291 let q = p - torus.center();
6292 let along = q.dot(torus.z_axis());
6293 let rho = (q - torus.z_axis() * along).length();
6294 let off = ((rho - torus.major_radius()).hypot(along) - torus.minor_radius()).abs();
6295 worst = worst.max(off).max(other(p).abs());
6296 }
6297 }
6298 worst
6299 }
6300
6301 #[test]
6302 fn exact_sphere_torus_meets_a_ball_on_the_axis_in_circles() {
6303 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
6304 for height in [0.0, 1.0] {
6305 let centre = Point3::new(0.0, 0.0, height);
6306 let sphere = SphericalSurface::new(centre, 3.0).unwrap();
6307 let curves = exact_sphere_torus(&sphere, &torus).unwrap().unwrap();
6308 let circles = circles_of(&curves);
6309 assert_eq!((curves.len(), circles.len()), (2, 2), "height {height}");
6310 let worst = worst_off(&circles, &torus, |p| (p - centre).length() - 3.0);
6311 assert!(worst < 1e-9, "height {height}: {worst}");
6312 }
6313 }
6314
6315 #[test]
6321 fn a_ball_off_a_torus_axis_meets_it_in_its_closed_form_loops() {
6322 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
6323 let on_torus = |p: Point3| (p.x().hypot(p.y()) - 4.0).hypot(p.z()) - 1.5;
6324 for (centre, radius, loops) in [
6325 (Point3::new(4.0, 0.0, 1.0), 1.0, 1),
6326 (Point3::new(4.0, 0.0, 0.0), 2.0, 2),
6327 (Point3::new(2.0, 1.0, 0.5), 1.2, 1),
6328 (Point3::new(6.4999, 0.0, 0.0), 1.0, 1),
6329 ] {
6330 let ball = SphericalSurface::new(centre, radius).unwrap();
6331 let on_ball = |p: Point3| (p - centre).length() - radius;
6332 for ball_first in [true, false] {
6333 let (a, b) = if ball_first {
6334 (
6335 AnalyticSurface::Sphere(&ball),
6336 AnalyticSurface::Torus(&torus),
6337 )
6338 } else {
6339 (
6340 AnalyticSurface::Torus(&torus),
6341 AnalyticSurface::Sphere(&ball),
6342 )
6343 };
6344 let curves = intersect_analytic_analytic(a, b, 32).unwrap();
6345 let case = format!("ball {radius} at {centre:?}, ball first {ball_first}");
6346 assert_eq!(curves.len(), loops, "{case}");
6347 for ic in &curves {
6348 for q in &ic.points {
6349 let off = on_ball(q.point).abs().max(on_torus(q.point).abs());
6350 assert!(off < 1e-9, "{case}: a point lies {off:.2e} off");
6351 let (on_ball_at, on_torus_at) = if ball_first {
6352 (q.param1, q.param2)
6353 } else {
6354 (q.param2, q.param1)
6355 };
6356 let (pb, pt) = (
6357 ball.evaluate(on_ball_at.0, on_ball_at.1),
6358 torus.evaluate(on_torus_at.0, on_torus_at.1),
6359 );
6360 assert!(
6361 (pb - q.point).length() < 1e-9 && (pt - q.point).length() < 1e-9,
6362 "{case}: a point's parameters miss it"
6363 );
6364 }
6365 let (t0, t1) = ic.curve.domain();
6366 for k in 0..=400 {
6367 let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
6368 let off = on_ball(p).abs().max(on_torus(p).abs());
6369 assert!(off < 1e-7, "{case}: the curve strays {off:.2e}");
6370 }
6371 }
6372 }
6373 }
6374 }
6375
6376 #[test]
6383 fn balls_meet_tori_in_loops_a_scan_would_miss() {
6384 for (big, small, centre, radius, loops) in [
6385 (4000.0, 1500.0, Point3::new(5500.0, 0.0, 0.0), 0.001, 1),
6386 (4.0, 1.5, Point3::new(1e-6, 0.0, 0.0), 2.500_002, 2),
6387 (1000.0, 1.0, Point3::new(1000.0, 0.0, 0.0), 1.000_000_5, 2),
6388 (4.0, 1.5, Point3::new(1.500_001, 0.0, 0.0), 4.0, 2),
6389 ] {
6390 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), big, small).unwrap();
6391 let ball = SphericalSurface::new(centre, radius).unwrap();
6392 let on_torus = |p: Point3| (p.x().hypot(p.y()) - big).hypot(p.z()) - small;
6393 let on_ball = |p: Point3| (p - centre).length() - radius;
6394 for ball_first in [true, false] {
6395 let (a, b) = if ball_first {
6396 (
6397 AnalyticSurface::Sphere(&ball),
6398 AnalyticSurface::Torus(&torus),
6399 )
6400 } else {
6401 (
6402 AnalyticSurface::Torus(&torus),
6403 AnalyticSurface::Sphere(&ball),
6404 )
6405 };
6406 let curves = intersect_analytic_analytic(a, b, 32).unwrap();
6407 let case = format!("ball {radius} at {centre:?} on torus ({big}, {small})");
6408 assert_eq!(curves.len(), loops, "{case}");
6409 for ic in &curves {
6410 for q in &ic.points {
6411 let off = on_ball(q.point).abs().max(on_torus(q.point).abs());
6412 assert!(off < 1e-9, "{case}: a point lies {off:.2e} off");
6413 }
6414 let (t0, t1) = ic.curve.domain();
6415 for k in 0..=2000 {
6416 let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 2000.0);
6417 let off = on_ball(p).abs().max(on_torus(p).abs());
6418 assert!(off < 1e-7, "{case}: the curve strays {off:.2e}");
6419 }
6420 }
6421 }
6422 }
6423 }
6424
6425 #[test]
6431 fn scaled_and_ill_conditioned_sections_are_kept_or_deferred() {
6432 let origin = Point3::new(0.0, 0.0, 0.0);
6433 let torus = ToroidalSurface::new(origin, 4.0, 1.5).unwrap();
6434 let unit = plane_torus_loops(&torus, Vec3::new(1.0, 0.0, 0.0), 4.0, 128).len();
6435 let scaled = plane_torus_loops(&torus, Vec3::new(1e14, 0.0, 0.0), 4e14, 128).len();
6436 assert_eq!((unit, scaled), (1, 1));
6437
6438 let large = ToroidalSurface::new(origin, 4000.0, 1500.0).unwrap();
6439 let speck = SphericalSurface::new(Point3::new(5_500.000_001, 0.0, 0.0), 1e-5).unwrap();
6440 assert!(sphere_torus_curves(&speck, &large, true).is_none());
6441
6442 let ring = ToroidalSurface::new(origin, 1e8, 1.0).unwrap();
6443 let ball = SphericalSurface::new(Point3::new(1e8, 0.0, 0.0), 1.000_001).unwrap();
6444 assert!(exact_sphere_torus(&ball, &ring).unwrap().is_none());
6445 assert!(sphere_torus_curves(&ball, &ring, true).is_none());
6446 }
6447
6448 #[test]
6452 fn a_ball_filling_a_torus_tube_meets_it_in_one_meridian_circle() {
6453 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
6454 let centre = Point3::new(4.0, 0.0, 0.0);
6455 let ball = SphericalSurface::new(centre, 1.5).unwrap();
6456 for (a, b) in [
6457 (
6458 AnalyticSurface::Sphere(&ball),
6459 AnalyticSurface::Torus(&torus),
6460 ),
6461 (
6462 AnalyticSurface::Torus(&torus),
6463 AnalyticSurface::Sphere(&ball),
6464 ),
6465 ] {
6466 let curves = intersect_analytic_analytic(a, b, 32).unwrap();
6467 assert_eq!(curves.len(), 1);
6468 let (t0, t1) = curves[0].curve.domain();
6469 for k in 0..=100 {
6470 let p = curves[0]
6471 .curve
6472 .evaluate(t0 + (t1 - t0) * f64::from(k) / 100.0);
6473 let off = ((p - centre).length() - 1.5).abs().max(p.y().abs());
6474 assert!(off < 1e-9, "the circle strays {off:.2e}");
6475 }
6476 }
6477 }
6478
6479 #[test]
6480 fn exact_sphere_torus_misses_touches_and_defers() {
6481 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
6482 let ball = |x: f64, r: f64| SphericalSurface::new(Point3::new(x, 0.0, 0.0), r).unwrap();
6483 assert!(
6484 exact_sphere_torus(&ball(0.0, 1.0), &torus)
6485 .unwrap()
6486 .unwrap()
6487 .is_empty(),
6488 "a small ball in the hole misses"
6489 );
6490 let touching = exact_sphere_torus(&ball(0.0, 2.5), &torus)
6491 .unwrap()
6492 .unwrap();
6493 let circles = circles_of(&touching);
6494 assert_eq!(
6495 circles.len(),
6496 1,
6497 "a ball in the hole touches the inner equator"
6498 );
6499 assert!((circles[0].radius() - 2.5).abs() < 1e-12);
6500 assert!(circles[0].center().z().abs() < 1e-12);
6501 assert!(
6502 exact_sphere_torus(&ball(1.0, 3.0), &torus)
6503 .unwrap()
6504 .is_none(),
6505 "a ball off the axis defers"
6506 );
6507 let spindle = ToroidalSurface::with_axis_and_ref_dir(
6508 Point3::new(0.0, 0.0, 0.0),
6509 1.0,
6510 2.0,
6511 Vec3::new(0.0, 0.0, 1.0),
6512 Vec3::new(1.0, 0.0, 0.0),
6513 )
6514 .unwrap();
6515 assert!(
6516 exact_sphere_torus(&ball(0.0, 2.5), &spindle)
6517 .unwrap()
6518 .is_none()
6519 );
6520 }
6521
6522 #[test]
6523 fn exact_cylinder_torus_meets_a_coaxial_rod_in_circles() {
6524 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 4.0, 1.5).unwrap();
6525 let z = Vec3::new(0.0, 0.0, 1.0);
6526 let rod = |r: f64| CylindricalSurface::new(Point3::new(0.0, 0.0, -5.0), z, r).unwrap();
6527 let curves = exact_cylinder_torus(&rod(4.2), &torus).unwrap().unwrap();
6528 let circles = circles_of(&curves);
6529 assert_eq!((curves.len(), circles.len()), (2, 2));
6530 let worst = worst_off(&circles, &torus, |p| p.x().hypot(p.y()) - 4.2);
6531 assert!(worst < 1e-9, "{worst}");
6532 assert!(
6533 exact_cylinder_torus(&rod(2.0), &torus)
6534 .unwrap()
6535 .unwrap()
6536 .is_empty(),
6537 "a rod clear in the hole misses"
6538 );
6539 for (wall, label) in [(5.5, "outer"), (2.5, "inner")] {
6540 let curves = exact_cylinder_torus(&rod(wall), &torus).unwrap().unwrap();
6541 let circles = circles_of(&curves);
6542 assert_eq!(circles.len(), 1, "a wall touching the {label} equator");
6543 assert!(circles[0].center().z().abs() < 1e-12, "{label}");
6544 let worst = worst_off(&circles, &torus, |p| p.x().hypot(p.y()) - wall);
6545 assert!(worst < 1e-9, "{label}: {worst}");
6546 }
6547 assert!(
6548 exact_cylinder_torus(&rod(5.5 + 1e-6), &torus)
6549 .unwrap()
6550 .unwrap()
6551 .is_empty(),
6552 "a wall clear of the tube by more than the tolerance misses it"
6553 );
6554 assert_eq!(
6555 exact_cylinder_torus(&rod(5.5 - 1e-6), &torus)
6556 .unwrap()
6557 .unwrap()
6558 .len(),
6559 2,
6560 "a wall into the tube by more than the tolerance crosses it twice"
6561 );
6562 for wall in [5.5 - 5e-8, 5.5 + 5e-8] {
6566 let curves = exact_cylinder_torus(&rod(wall), &torus).unwrap().unwrap();
6567 assert_eq!(circles_of(&curves).len(), 1, "a wall at {wall}");
6568 }
6569 let tilted =
6570 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.1, 1.0), 4.2)
6571 .unwrap();
6572 let offset = CylindricalSurface::new(Point3::new(0.5, 0.0, 0.0), z, 4.2).unwrap();
6573 assert!(exact_cylinder_torus(&tilted, &torus).unwrap().is_none());
6574 assert!(exact_cylinder_torus(&offset, &torus).unwrap().is_none());
6575 let spindle = ToroidalSurface::with_axis_and_ref_dir(
6576 Point3::new(0.0, 0.0, 0.0),
6577 1.0,
6578 2.0,
6579 z,
6580 Vec3::new(1.0, 0.0, 0.0),
6581 )
6582 .unwrap();
6583 assert!(
6584 exact_cylinder_torus(&rod(0.5), &spindle).unwrap().is_none(),
6585 "a spindle torus's inner lemon also meets the rod"
6586 );
6587 let spindle = ToroidalSurface::with_axis_and_ref_dir(
6590 Point3::new(0.0, 0.0, 4.7),
6591 0.1,
6592 2.45,
6593 z,
6594 Vec3::new(1.0, 0.0, 0.0),
6595 )
6596 .unwrap();
6597 let curves = exact_cylinder_torus(&rod(2.55), &spindle).unwrap().unwrap();
6598 let circles = circles_of(&curves);
6599 assert_eq!(circles.len(), 1);
6600 assert!((circles[0].center().z() - 4.7).abs() < 1e-12);
6601 let worst = worst_off(&circles, &spindle, |p| p.x().hypot(p.y()) - 2.55);
6602 assert!(worst < 1e-9, "{worst}");
6603 let curves = exact_cylinder_torus(&rod(2.4), &spindle).unwrap().unwrap();
6604 let circles = circles_of(&curves);
6605 assert_eq!(circles.len(), 2, "a wall into the spindle's outer tube");
6606 let worst = worst_off(&circles, &spindle, |p| p.x().hypot(p.y()) - 2.4);
6607 assert!(worst < 1e-9, "{worst}");
6608 }
6609
6610 fn off_axis_loops(cylinder_origin: Point3, cylinder_radius: f64) -> (usize, f64) {
6613 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
6614 let cyl =
6615 CylindricalSurface::new(cylinder_origin, Vec3::new(0.0, 0.0, 1.0), cylinder_radius)
6616 .unwrap();
6617 let curves = algebraic_sphere_cylinder(&sphere, &cyl, true)
6618 .unwrap()
6619 .unwrap();
6620 let mut worst: f64 = 0.0;
6621 for c in &curves {
6622 for ip in &c.points {
6623 let on_sphere = sphere.evaluate(ip.param1.0, ip.param1.1);
6624 let on_cylinder = cyl.evaluate(ip.param2.0, ip.param2.1);
6625 worst = worst
6626 .max((on_sphere - ip.point).length())
6627 .max((on_cylinder - ip.point).length());
6628 }
6629 let (t0, t1) = c.curve.domain();
6630 assert!((c.curve.evaluate(t0) - c.curve.evaluate(t1)).length() < 1e-9);
6631 for k in 0..=400 {
6632 let p = c.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 400.0);
6633 let on_sphere = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 2.0).abs();
6634 let on_cylinder = ((p.x() - cylinder_origin.x())
6635 .hypot(p.y() - cylinder_origin.y())
6636 - cylinder_radius)
6637 .abs();
6638 worst = worst.max(on_sphere).max(on_cylinder);
6639 }
6640 }
6641 (curves.len(), worst)
6642 }
6643
6644 #[test]
6647 fn off_axis_drill_through_a_sphere_meets_it_in_two_loops() {
6648 let (count, worst) = off_axis_loops(Point3::new(0.5, 0.0, 0.0), 0.2);
6649 assert_eq!(count, 2);
6650 assert!(worst < 1e-5, "loops leave the surfaces by {worst}");
6651 }
6652
6653 #[test]
6655 fn cylinder_over_a_spheres_side_meets_it_in_one_loop() {
6656 let (count, worst) = off_axis_loops(Point3::new(1.8, 0.0, 0.0), 0.5);
6657 assert_eq!(count, 1);
6658 assert!(worst < 5e-4, "loop leaves the surfaces by {worst}");
6659 }
6660
6661 #[test]
6662 fn disjoint_cylinders_no_intersection() {
6663 let cyl_a =
6664 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
6665 .unwrap();
6666 let cyl_b =
6667 CylindricalSurface::new(Point3::new(5.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
6668 .unwrap();
6669
6670 let curves = intersect_analytic_analytic(
6671 AnalyticSurface::Cylinder(&cyl_a),
6672 AnalyticSurface::Cylinder(&cyl_b),
6673 16,
6674 )
6675 .unwrap();
6676
6677 assert!(curves.is_empty(), "disjoint cylinders should not intersect");
6678 }
6679
6680 fn collect_points(curve: &ExactIntersectionCurve) -> Vec<Point3> {
6684 use crate::traits::ParametricCurve;
6685 match curve {
6686 ExactIntersectionCurve::Circle(c) => (0..=64)
6687 .map(|i| ParametricCurve::evaluate(c, TAU * f64::from(i) / 64.0))
6688 .collect(),
6689 ExactIntersectionCurve::Ellipse(e) => (0..=64)
6690 .map(|i| ParametricCurve::evaluate(e, TAU * f64::from(i) / 64.0))
6691 .collect(),
6692 ExactIntersectionCurve::Points(pts) => pts.clone(),
6693 }
6694 }
6695
6696 fn assert_on_plane_and_cone(
6699 curves: &[ExactIntersectionCurve],
6700 cone: &ConicalSurface,
6701 n: Vec3,
6702 d: f64,
6703 z_bound: (f64, f64),
6704 ) {
6705 assert!(!curves.is_empty(), "expected at least one section curve");
6706 let mut total = 0;
6707 for curve in curves {
6708 for p in collect_points(curve) {
6709 total += 1;
6710 let plane_err = (n.x() * p.x() + n.y() * p.y() + n.z() * p.z() - d).abs();
6711 assert!(
6712 plane_err < 1e-9,
6713 "point off plane by {plane_err:.2e}: {p:?}"
6714 );
6715 let (u, v) = cone.project_point(p);
6716 let q = cone.evaluate(u, v);
6717 let cone_err =
6718 ((p.x() - q.x()).powi(2) + (p.y() - q.y()).powi(2) + (p.z() - q.z()).powi(2))
6719 .sqrt();
6720 assert!(cone_err < 1e-7, "point off cone by {cone_err:.2e}: {p:?}");
6721 assert!(v >= -1e-9, "point on phantom nappe (v={v:.4}): {p:?}");
6722 assert!(
6723 p.z() >= z_bound.0 - 1e-6 && p.z() <= z_bound.1 + 1e-6,
6724 "point z={:.4} outside sane bound {z_bound:?}: {p:?}",
6725 p.z()
6726 );
6727 }
6728 }
6729 assert!(total >= 8, "too few section points ({total})");
6730 }
6731
6732 #[test]
6733 fn oblique_plane_cone_ellipse_is_exact_and_on_both() {
6734 let cone = ConicalSurface::new(
6738 Point3::new(0.0, 0.0, 0.0),
6739 Vec3::new(0.0, 0.0, 1.0),
6740 std::f64::consts::FRAC_PI_4,
6741 )
6742 .unwrap();
6743 let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
6744 let d = n.z() * 5.0;
6746 let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
6747 assert!(
6748 curves
6749 .iter()
6750 .any(|c| matches!(c, ExactIntersectionCurve::Ellipse(_))),
6751 "oblique steep plane × cone must yield an exact Ellipse"
6752 );
6753 assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 12.0));
6755 }
6756
6757 #[test]
6758 fn oblique_plane_cone_wrong_nappe_is_empty() {
6759 let cone = ConicalSurface::new(
6763 Point3::new(0.0, 0.0, 0.0),
6764 Vec3::new(0.0, 0.0, 1.0),
6765 std::f64::consts::FRAC_PI_4,
6766 )
6767 .unwrap();
6768 let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
6769 let d = n.z() * -5.0;
6770 let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
6771 assert!(
6772 curves.is_empty(),
6773 "plane on the phantom-nappe side must yield no real curve, got {}",
6774 curves.len()
6775 );
6776 }
6777
6778 #[test]
6779 fn oblique_plane_cone_parabola_on_both_single_branch() {
6780 let cone = ConicalSurface::new(
6783 Point3::new(0.0, 0.0, 0.0),
6784 Vec3::new(0.0, 0.0, 1.0),
6785 std::f64::consts::FRAC_PI_4,
6786 )
6787 .unwrap();
6788 let n = Vec3::new(1.0, 0.0, 1.0).normalize().unwrap();
6789 let d = n.x() * 3.0 + n.z() * 3.0; let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
6791 assert_eq!(
6792 curves.len(),
6793 1,
6794 "a parabola is a single branch, got {}",
6795 curves.len()
6796 );
6797 assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 400.0));
6799 }
6800
6801 #[test]
6802 fn oblique_plane_cone_hyperbola_real_nappe_only() {
6803 let cone = ConicalSurface::new(
6811 Point3::new(-59.0, -59.0, 15.85),
6812 Vec3::new(0.0, 0.0, -1.0),
6813 std::f64::consts::FRAC_PI_4,
6814 )
6815 .unwrap();
6816 let n = Vec3::new(0.0, 0.995_18, 0.098_02).normalize().unwrap();
6817 let d = -58.360_56;
6818 let cos_theta = n.dot(cone.axis()).abs();
6819 assert!(cos_theta < 0.2, "expected a shallow (hyperbola) plane");
6820 let curves = exact_plane_cone(&cone, n, d, 0.0).unwrap();
6821 assert_on_plane_and_cone(&curves, &cone, n, d, (5.0, 15.85));
6824 for c in &curves {
6826 assert!(
6827 matches!(c, ExactIntersectionCurve::Points(_)),
6828 "hyperbola must be sampled Points, not a closed conic"
6829 );
6830 }
6831 }
6832
6833 #[test]
6837 fn sphere_sphere_meets_in_a_circle_on_both() {
6838 let ball = |x: f64, y: f64, z: f64, r: f64| {
6839 SphericalSurface::new(Point3::new(x, y, z), r).unwrap()
6840 };
6841 let (a, b) = (ball(0.0, 0.0, 0.0, 2.0), ball(1.6, 0.3, 0.2, 1.5));
6842 let curves = exact_sphere_sphere(&a, &b).unwrap().unwrap();
6843 assert_eq!(curves.len(), 1);
6844 let circle = match &curves[0] {
6845 ExactIntersectionCurve::Circle(circle) => circle,
6846 other => unreachable!("expected a circle, got {other:?}"),
6847 };
6848 for k in 0..16 {
6849 let p = circle.evaluate(std::f64::consts::TAU * f64::from(k) / 16.0);
6850 assert!(((p - a.center()).length() - 2.0).abs() < 1e-12);
6851 assert!(((p - b.center()).length() - 1.5).abs() < 1e-12);
6852 }
6853 assert!(
6854 exact_sphere_sphere(&a, &ball(4.0, 0.0, 0.0, 1.5))
6855 .unwrap()
6856 .unwrap()
6857 .is_empty()
6858 );
6859 assert!(
6860 exact_sphere_sphere(&a, &ball(0.2, 0.0, 0.0, 1.0))
6861 .unwrap()
6862 .unwrap()
6863 .is_empty()
6864 );
6865 assert!(
6866 exact_sphere_sphere(&a, &ball(0.0, 0.0, 0.0, 1.0))
6867 .unwrap()
6868 .unwrap()
6869 .is_empty()
6870 );
6871 assert!(
6872 exact_sphere_sphere(&a, &ball(0.0, 0.0, 0.0, 2.0))
6873 .unwrap()
6874 .is_none()
6875 );
6876
6877 let radius = |p: &SphericalSurface, q: &SphericalSurface| -> f64 {
6880 match exact_sphere_sphere(p, q).unwrap().unwrap().as_slice() {
6881 [ExactIntersectionCurve::Circle(c)] => c.radius(),
6882 other => unreachable!("expected one circle, got {other:?}"),
6883 }
6884 };
6885 let tiny = ball(2.0, 0.0, 0.0, 1e-5);
6886 assert!((radius(&a, &tiny) - 1e-5).abs() < 1e-9);
6887 assert!((radius(&tiny, &a) - 1e-5).abs() < 1e-9);
6888 let near = radius(&ball(0.0, 0.0, 0.0, 2.0), &ball(3.5, 0.0, 0.0, 1.500_001));
6889 let far = radius(
6890 &ball(1e10, 0.0, 0.0, 2.0),
6891 &ball(1e10 + 3.5, 0.0, 0.0, 1.500_001),
6892 );
6893 assert!(near > 1e-3);
6894 assert!((far - near).abs() < 1e-9 * near.max(1.0));
6895 }
6896
6897 #[allow(clippy::panic)]
6900 fn lines_of(sections: &[PlaneSection]) -> Vec<(Line3D, bool)> {
6901 sections
6902 .iter()
6903 .map(|s| match s {
6904 PlaneSection::Line { line, ray } => (line.clone(), *ray),
6905 other => panic!("expected a line, got {other:?}"),
6906 })
6907 .collect()
6908 }
6909
6910 #[test]
6915 fn a_plane_along_a_cylinder_cuts_its_rulings() {
6916 let cyl =
6917 CylindricalSurface::new(Point3::new(0.0, 0.0, -2.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
6918 .unwrap();
6919 let y = Vec3::new(0.0, 1.0, 0.0);
6920 let surface = AnalyticSurface::Cylinder(&cyl);
6921 let on_both = |p: Point3, d: f64| {
6922 assert!((p.y() - d).abs() < 1e-12, "{p:?} off the plane y = {d}");
6923 assert!(
6924 (p.x().hypot(p.y()) - 1.0).abs() < 1e-12,
6925 "{p:?} off the cylinder"
6926 );
6927 };
6928 for (d, count) in [(0.0, 2), (1e-6_f64.cos(), 2), (1.0, 1), (1.5, 0)] {
6929 assert!(exact_plane_analytic(surface, y, d).unwrap().is_empty());
6930 let lines = lines_of(&exact_plane_section(surface, y, d).unwrap());
6931 assert_eq!(lines.len(), count, "plane y = {d}");
6932 let mut xs = Vec::new();
6933 for (line, ray) in lines {
6934 assert!(!ray);
6935 assert!(line.direction().cross(cyl.axis()).length() < 1e-12);
6936 for t in [-3.0, 0.0, 3.0] {
6937 on_both(line.evaluate(t), d);
6938 }
6939 xs.push(line.evaluate(0.0).x());
6940 }
6941 if count == 2 {
6942 let apart = (xs[0] - xs[1]).abs();
6943 let want = 2.0 * (1.0 - d * d).sqrt();
6944 assert!(
6945 (apart - want).abs() < 1e-9 * want.max(1e-6),
6946 "{apart} apart"
6947 );
6948 }
6949 }
6950 }
6951
6952 #[test]
6957 #[allow(clippy::panic)]
6958 fn a_plane_through_a_cone_apex_cuts_its_rulings() {
6959 use std::f64::consts::FRAC_PI_4;
6960
6961 let cone = ConicalSurface::new(
6962 Point3::new(1.0, 2.0, 3.0),
6963 Vec3::new(0.0, 0.0, 1.0),
6964 FRAC_PI_4,
6965 )
6966 .unwrap();
6967 let surface = AnalyticSurface::Cone(&cone);
6968 let apex = cone.apex();
6969 let through = |n: Vec3| {
6970 let n = n.normalize().unwrap();
6971 let d = n.dot(apex - Point3::new(0.0, 0.0, 0.0));
6972 assert!(exact_plane_analytic(surface, n, d).unwrap().is_empty());
6973 (n, d, exact_plane_section(surface, n, d).unwrap())
6974 };
6975 for (n, count) in [
6976 (Vec3::new(1.0, 0.0, 0.0), 2),
6977 (Vec3::new(1.0, 0.0, -1.0), 1),
6978 ] {
6979 let (n, d, sections) = through(n);
6980 let rays = lines_of(§ions);
6981 assert_eq!(rays.len(), count, "plane normal {n:?}");
6982 for (line, ray) in rays {
6983 assert!(ray);
6984 assert!((line.evaluate(0.0) - apex).length() < 1e-12);
6985 let p = line.evaluate(2.0);
6986 assert!((n.dot(p - Point3::new(0.0, 0.0, 0.0)) - d).abs() < 1e-12);
6987 let rel = p - apex;
6988 assert!(rel.z() > 0.0, "{p:?} on the phantom nappe");
6989 assert!(
6990 (rel.x().hypot(rel.y()) - rel.z()).abs() < 1e-12,
6991 "{p:?} off the cone"
6992 );
6993 }
6994 }
6995 for n in [Vec3::new(0.1, 0.0, 1.0), Vec3::new(0.0, 0.0, 1.0)] {
6996 let (_, _, sections) = through(n);
6997 assert!(
6998 matches!(sections[..], [PlaneSection::Point(p)] if (p - apex).length() < 1e-12),
6999 "{sections:?}"
7000 );
7001 }
7002
7003 let upright = ConicalSurface::new(
7004 Point3::new(0.0, 0.0, 0.0),
7005 Vec3::new(0.0, 0.0, 1.0),
7006 FRAC_PI_4,
7007 )
7008 .unwrap();
7009 let n = Vec3::new((0.5 - 1e-8_f64).sqrt(), 0.0, (0.5 + 1e-8_f64).sqrt());
7010 let sections = exact_plane_section(AnalyticSurface::Cone(&upright), n, 5e-8).unwrap();
7011 let [PlaneSection::Ellipse(ellipse)] = §ions[..] else {
7012 panic!("{sections:?}");
7013 };
7014 assert!(
7015 ellipse.semi_major() > 1.0,
7016 "semi-major {}",
7017 ellipse.semi_major()
7018 );
7019 }
7020
7021 #[test]
7024 #[allow(clippy::panic)]
7025 fn a_plane_touching_a_sphere_meets_it_at_a_point() {
7026 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 1.0), 1.0).unwrap();
7027 let surface = AnalyticSurface::Sphere(&sphere);
7028 let z = Vec3::new(0.0, 0.0, 1.0);
7029 assert!(exact_plane_analytic(surface, z, 0.0).unwrap().is_empty());
7030 let sections = exact_plane_section(surface, z, 0.0).unwrap();
7031 assert!(
7032 matches!(sections[..], [PlaneSection::Point(p)] if p.z().abs() < 1e-15 && p.x() == 0.0),
7033 "{sections:?}"
7034 );
7035 assert!(exact_plane_section(surface, z, -1e-9).unwrap().is_empty());
7036 for height in [5e-15, 1e-12, 1e-8] {
7037 let sections = exact_plane_section(surface, z, height).unwrap();
7038 let [PlaneSection::Circle(circle)] = §ions[..] else {
7039 panic!("{sections:?}");
7040 };
7041 let want = (height * (2.0 - height)).sqrt();
7042 assert!(
7043 (circle.radius() - want).abs() < 1e-3 * want,
7044 "circle at z = {height}: radius {}, want {want}",
7045 circle.radius()
7046 );
7047 assert!((circle.center().z() - height).abs() < 1e-15);
7048 }
7049 }
7050
7051 fn farthest(curves: &[IntersectionCurve], off: impl Fn(Point3) -> f64) -> f64 {
7053 let mut far = 0.0_f64;
7054 for ic in curves {
7055 let (t0, t1) = ic.curve.domain();
7056 for i in 0..=2000 {
7057 let t = t0 + (t1 - t0) * f64::from(i) / 2000.0;
7058 far = far.max(off(ic.curve.evaluate(t)));
7059 }
7060 }
7061 far
7062 }
7063
7064 #[test]
7067 fn a_ball_in_its_bore_meets_it_on_an_exact_circle() {
7068 let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
7069 let bore =
7070 CylindricalSurface::new(Point3::new(0.0, 0.0, -2.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7071 .unwrap();
7072 let curves = intersect_analytic_analytic_bounded(
7073 AnalyticSurface::Sphere(&ball),
7074 AnalyticSurface::Cylinder(&bore),
7075 64,
7076 None,
7077 Some((0.0, 4.0)),
7078 )
7079 .unwrap();
7080 assert_eq!(curves.len(), 1);
7081 let far = farthest(&curves, |p| {
7082 let on_ball = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 1.0).abs();
7083 on_ball
7084 .max((p.x().hypot(p.y()) - 1.0).abs())
7085 .max(p.z().abs())
7086 });
7087 assert!(far < 1e-14, "circle strays {far:.2e}");
7088 }
7089
7090 #[test]
7093 fn overlapping_balls_meet_on_an_exact_circle() {
7094 let a = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
7095 let b = SphericalSurface::new(Point3::new(1.0, 0.0, 0.0), 1.0).unwrap();
7096 let curves = intersect_analytic_analytic_bounded(
7097 AnalyticSurface::Sphere(&a),
7098 AnalyticSurface::Sphere(&b),
7099 64,
7100 None,
7101 None,
7102 )
7103 .unwrap();
7104 assert_eq!(curves.len(), 1);
7105 let far = farthest(&curves, |p| {
7106 let on_a = ((p - Point3::new(0.0, 0.0, 0.0)).length() - 1.0).abs();
7107 on_a.max(((p - Point3::new(1.0, 0.0, 0.0)).length() - 1.0).abs())
7108 });
7109 assert!(far < 1e-14, "circle strays {far:.2e}");
7110 }
7111
7112 #[test]
7115 fn a_conic_loop_is_its_ellipse() {
7116 let centre = Point3::new(1.0, -2.0, 0.5);
7117 let frame = Frame3::from_normal(centre, Vec3::new(0.3, -0.4, 1.0)).unwrap();
7118 let curve = conic_loop(centre, frame.x, frame.y, 3.0, 1.5).unwrap();
7119 let (t0, t1) = curve.domain();
7120 assert!((curve.evaluate(t0) - (centre + frame.x * 3.0)).length() < 1e-15);
7121 for i in 0..=2000 {
7122 let p = curve.evaluate(t0 + (t1 - t0) * f64::from(i) / 2000.0) - centre;
7123 let (x, y) = (p.dot(frame.x) / 3.0, p.dot(frame.y) / 1.5);
7124 assert!(
7125 (x.hypot(y) - 1.0).abs() < 1e-14,
7126 "off its ellipse by {}",
7127 x.hypot(y) - 1.0
7128 );
7129 assert!(p.dot(frame.z).abs() < 1e-14);
7130 }
7131 }
7132
7133 #[test]
7137 fn touching_coaxial_rings_meet_along_one_circle() {
7138 let z = Vec3::new(0.0, 0.0, 1.0);
7139 let x = Vec3::new(1.0, 0.0, 0.0);
7140 let ring =
7141 ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 0.0), 3.0, 1.0, z, x)
7142 .unwrap();
7143 let ball = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
7144 let curves = intersect_analytic_analytic_bounded(
7145 AnalyticSurface::Sphere(&ball),
7146 AnalyticSurface::Torus(&ring),
7147 64,
7148 None,
7149 None,
7150 )
7151 .unwrap();
7152 assert_eq!(curves.len(), 1);
7153 let far = farthest(&curves, |p| {
7154 let q = p - Point3::new(0.0, 0.0, 0.0);
7155 let rho = q.x().hypot(q.y());
7156 let on_ring = ((rho - 3.0).hypot(q.z()) - 1.0).abs();
7157 on_ring.max((q.length() - 2.0).abs())
7158 });
7159 assert!(far < 1e-14, "circle strays {far:.2e}");
7160
7161 let wider =
7165 ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 1.2), 3.9, 0.5, z, x)
7166 .unwrap();
7167 let touching = exact_torus_torus(&ring, &wider).unwrap().unwrap();
7168 let circles = circles_of(&touching);
7169 assert_eq!(circles.len(), 1);
7170 assert!(
7171 (circles[0].radius() - 3.6).abs() < 1e-12,
7172 "{}",
7173 circles[0].radius()
7174 );
7175 assert!((circles[0].center().z() - 0.8).abs() < 1e-12);
7176 }
7177
7178 #[test]
7183 fn huge_coaxial_rings_cross_or_miss_rather_than_touch() {
7184 let z = Vec3::new(0.0, 0.0, 1.0);
7185 let x = Vec3::new(1.0, 0.0, 0.0);
7186 let ring = |big: f64| {
7187 ToroidalSurface::with_axis_and_ref_dir(Point3::new(0.0, 0.0, 0.0), big, 1.0, z, x)
7188 .unwrap()
7189 };
7190 let crossing = exact_torus_torus(&ring(1e6), &ring(1_000_001.999))
7191 .unwrap()
7192 .unwrap();
7193 let circles = circles_of(&crossing);
7194 assert_eq!(circles.len(), 2);
7195 for circle in circles {
7196 let height = (1.0 - 0.9995_f64 * 0.9995).sqrt();
7197 assert!(
7198 (circle.center().z().abs() - height).abs() < 1e-9,
7199 "{}",
7200 circle.center().z()
7201 );
7202 }
7203 let apart = exact_torus_torus(&ring(1e6), &ring(1_000_002.001))
7204 .unwrap()
7205 .unwrap();
7206 assert!(apart.is_empty());
7207 }
7208
7209 #[test]
7213 fn a_plane_cuts_a_cones_open_conics() {
7214 let up = Vec3::new(0.0, 0.0, 1.0);
7215 let on_cone = |p: Point3, slope: f64| (p.z() - slope * p.x().hypot(p.y())).abs();
7216 let steep =
7217 ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, 60_f64.to_radians()).unwrap();
7218 let slope = 60_f64.to_radians().tan();
7219 let along =
7220 exact_plane_section(AnalyticSurface::Cone(&steep), Vec3::new(1.0, 0.0, 0.0), 1.0)
7221 .unwrap();
7222 let [PlaneSection::Hyperbola(h)] = along.as_slice() else {
7223 unreachable!("{along:?}")
7224 };
7225 for i in -20..=20 {
7226 let p = h.evaluate(f64::from(i) / 5.0);
7227 assert!((p.x() - 1.0).abs() < 1e-12 && p.z() > 0.0, "{p:?}");
7228 assert!(on_cone(p, slope) < 1e-12 * p.z().max(1.0), "{p:?}");
7229 }
7230 let even =
7231 ConicalSurface::new(Point3::new(0.0, 0.0, 0.0), up, 45_f64.to_radians()).unwrap();
7232 let tilt = Vec3::new(-1.0, 0.0, 1.0) * std::f64::consts::FRAC_1_SQRT_2;
7233 let above = exact_plane_section(AnalyticSurface::Cone(&even), tilt, 1.0).unwrap();
7234 let [PlaneSection::Parabola(parabola)] = above.as_slice() else {
7235 unreachable!("{above:?}")
7236 };
7237 for i in -20..=20 {
7238 let p = parabola.evaluate(f64::from(i) / 2.0);
7239 assert!(
7240 (tilt.dot(p - Point3::new(0.0, 0.0, 0.0)) - 1.0).abs() < 1e-12,
7241 "{p:?}"
7242 );
7243 assert!(
7244 p.z() > 0.0 && on_cone(p, 1.0) < 1e-12 * p.z().max(1.0),
7245 "{p:?}"
7246 );
7247 }
7248 let below = exact_plane_section(AnalyticSurface::Cone(&even), tilt, -1.0).unwrap();
7249 assert!(below.is_empty(), "{below:?}");
7250 }
7251
7252 #[test]
7258 fn extreme_cones_give_sections_on_the_cone() {
7259 let up = Vec3::new(0.0, 0.0, 1.0);
7260 let apex = Point3::new(0.0, 0.0, 0.0);
7261 let holds = |cone: &ConicalSurface, q: Point3| {
7262 let w = q - apex;
7263 (w.dot(up) - cone.half_angle().sin() * w.length()).abs() <= 1e-6 * (1.0 + w.length())
7264 };
7265 let flat = ConicalSurface::new(apex, up, 1e-7).unwrap();
7266 let tilt = Vec3::new(5e-13_f64.sqrt(), 0.0, (1.0 - 5e-13_f64).sqrt());
7267 let needle = ConicalSurface::new(apex, up, FRAC_PI_2 - 5e-7).unwrap();
7268 for (cone, normal, d) in [(&flat, tilt, 1.0), (&needle, Vec3::new(1.0, 0.0, 0.0), 1.0)] {
7269 let sections = exact_plane_section(AnalyticSurface::Cone(cone), normal, d).unwrap();
7270 assert!(!sections.is_empty());
7271 for section in §ions {
7272 let points: Vec<Point3> = match section {
7273 PlaneSection::Hyperbola(h) => {
7274 (-4..=4).map(|i| h.evaluate(f64::from(i) / 4.0)).collect()
7275 }
7276 PlaneSection::Parabola(q) => {
7277 (-4..=4).map(|i| q.evaluate(f64::from(i))).collect()
7278 }
7279 PlaneSection::Points(points) => points.clone(),
7280 other => unreachable!("{other:?}"),
7281 };
7282 for q in points {
7283 assert!(holds(cone, q), "{q:?} off the cone");
7284 }
7285 }
7286 }
7287 let flat_section = exact_plane_section(AnalyticSurface::Cone(&flat), tilt, 1.0).unwrap();
7288 assert!(matches!(
7289 flat_section.as_slice(),
7290 [PlaneSection::Hyperbola(_)]
7291 ));
7292 }
7293
7294 fn parallel_rulings(
7297 (c1, r1, v1): (Point3, f64, (f64, f64)),
7298 (c2, r2, axis2, v2): (Point3, f64, Vec3, (f64, f64)),
7299 ) -> Vec<(Point3, Point3)> {
7300 rulings_within((c1, r1, v1), (c2, r2, axis2, v2), 1e-12)
7301 }
7302
7303 fn rulings_within(
7306 (c1, r1, v1): (Point3, f64, (f64, f64)),
7307 (c2, r2, axis2, v2): (Point3, f64, Vec3, (f64, f64)),
7308 tolerance: f64,
7309 ) -> Vec<(Point3, Point3)> {
7310 let a = CylindricalSurface::new(c1, Vec3::new(0.0, 0.0, 1.0), r1).unwrap();
7311 let b = CylindricalSurface::new(c2, axis2, r2).unwrap();
7312 let curves = intersect_analytic_analytic_bounded(
7313 AnalyticSurface::Cylinder(&a),
7314 AnalyticSurface::Cylinder(&b),
7315 32,
7316 Some(v1),
7317 Some(v2),
7318 )
7319 .unwrap();
7320 curves
7321 .iter()
7322 .map(|ic| {
7323 let (t0, t1) = ic.curve.domain();
7324 let (p, q) = (ic.curve.evaluate(t0), ic.curve.evaluate(t1));
7325 for i in 0..=100 {
7326 let x = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(i) / 100.0);
7327 let on_a = ((x - c1) - Vec3::new(0.0, 0.0, (x - c1).z())).length() - r1;
7328 let w = x - c2;
7329 let on_b = (w - axis2 * w.dot(axis2)).length() - r2;
7330 assert!(
7331 on_a.abs() < tolerance && on_b.abs() < tolerance,
7332 "{x:?} off a cylinder by {on_a:.1e}, {on_b:.1e}"
7333 );
7334 }
7335 if p.z() <= q.z() { (p, q) } else { (q, p) }
7336 })
7337 .collect()
7338 }
7339
7340 #[test]
7344 fn overlapping_parallel_rods_meet_along_two_rulings() {
7345 let mut rulings = parallel_rulings(
7346 (Point3::new(0.0, 0.0, 0.0), 1.0, (0.0, 4.0)),
7347 (
7348 Point3::new(1.2, 0.0, 3.0),
7349 1.0,
7350 Vec3::new(0.0, 0.0, -1.0),
7351 (0.0, 2.0),
7352 ),
7353 );
7354 rulings.sort_by(|a, b| a.0.y().total_cmp(&b.0.y()));
7355 assert_eq!(rulings.len(), 2);
7356 for ((lo, hi), y) in rulings.into_iter().zip([-0.8, 0.8]) {
7357 assert!((lo - Point3::new(0.6, y, 1.0)).length() < 1e-12, "{lo:?}");
7358 assert!((hi - Point3::new(0.6, y, 3.0)).length() < 1e-12, "{hi:?}");
7359 }
7360 }
7361
7362 #[test]
7365 fn touching_parallel_rods_meet_along_one_ruling() {
7366 let up = Vec3::new(0.0, 0.0, 1.0);
7367 let beside = parallel_rulings(
7368 (Point3::new(0.0, 0.0, 0.0), 1.0, (-2.0, 2.0)),
7369 (Point3::new(2.0, 0.0, -2.0), 1.0, up, (0.0, 4.0)),
7370 );
7371 assert_eq!(beside.len(), 1);
7372 assert!((beside[0].0 - Point3::new(1.0, 0.0, -2.0)).length() < 1e-12);
7373 assert!((beside[0].1 - Point3::new(1.0, 0.0, 2.0)).length() < 1e-12);
7374 let inside = parallel_rulings(
7375 (Point3::new(0.0, 0.0, 0.0), 2.0, (0.0, 1.0)),
7376 (Point3::new(-1.0, 0.0, 0.0), 1.0, up, (0.0, 1.0)),
7377 );
7378 assert_eq!(inside.len(), 1);
7379 assert!((inside[0].0 - Point3::new(-2.0, 0.0, 0.0)).length() < 1e-12);
7380 let apart = parallel_rulings(
7381 (Point3::new(0.0, 0.0, 0.0), 1.0, (0.0, 1.0)),
7382 (Point3::new(2.5, 0.0, 0.0), 1.0, up, (0.0, 1.0)),
7383 );
7384 assert!(apart.is_empty());
7385 }
7386
7387 #[test]
7391 fn rods_leaning_apart_keep_rulings_only_over_a_short_span() {
7392 let up = CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
7393 .unwrap();
7394 let lean = Vec3::new(1e-5_f64.sin(), 0.0, 1e-5_f64.cos());
7395 let leaning = CylindricalSurface::new(Point3::new(1.2, 0.0, 0.0), lean, 1.0).unwrap();
7396 let span = |h: f64| parallel_cylinders(&up, &leaning, Some((0.0, h)), Some((0.0, h)));
7397 assert!(span(100.0).unwrap().is_none());
7398 assert_eq!(span(0.001).unwrap().map(|r| r.len()), Some(2));
7399 }
7400
7401 #[test]
7405 fn parallel_rods_keep_short_and_close_rulings() {
7406 let up = Vec3::new(0.0, 0.0, 1.0);
7407 let huge = rulings_within(
7408 (Point3::new(0.0, 0.0, 0.0), 1e6, (0.0, 0.001)),
7409 (Point3::new(1.2e6, 0.0, 0.0), 1e6, up, (0.0, 0.001)),
7410 1e-9,
7411 );
7412 assert_eq!(huge.len(), 2);
7413 assert!(
7414 huge.iter()
7415 .all(|(lo, hi)| ((*hi - *lo).length() - 0.001).abs() < 1e-12)
7416 );
7417 let mut close = rulings_within(
7418 (Point3::new(0.0, 0.0, 0.0), 100.0, (0.0, 1.0)),
7419 (Point3::new(199.999_999_7, 0.0, 0.0), 100.0, up, (0.0, 1.0)),
7420 1e-9,
7421 );
7422 assert_eq!(close.len(), 2);
7423 close.sort_by(|a, b| a.0.y().total_cmp(&b.0.y()));
7424 let apart = close[1].0.y() - close[0].0.y();
7425 assert!((apart - 0.010_954).abs() < 1e-5, "{apart}");
7426 }
7427
7428 fn off_cone(cone: &ConicalSurface, p: Point3) -> (f64, f64) {
7430 let q = p - cone.apex();
7431 let (along, s) = (q.dot(cone.axis()), cone.half_angle().sin());
7432 ((along.abs() - s * q.length()).abs(), along / s)
7433 }
7434
7435 #[test]
7439 fn cones_sharing_an_apex_touch_along_one_ruling() {
7440 let apex = Point3::new(1.0, 2.0, 3.0);
7441 let a = 20.0_f64.to_radians();
7442 let half = std::f64::consts::FRAC_PI_2 - a;
7443 let c1 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, a.sin()), half).unwrap();
7444 let c2 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, -a.sin()), half).unwrap();
7445 let curves = intersect_analytic_analytic_bounded(
7446 AnalyticSurface::Cone(&c1),
7447 AnalyticSurface::Cone(&c2),
7448 64,
7449 Some((0.2, 3.0)),
7450 Some((0.5, 4.0)),
7451 )
7452 .unwrap();
7453 assert_eq!(curves.len(), 1);
7454 let curve = &curves[0].curve;
7455 let (t0, t1) = curve.domain();
7456 let x = Vec3::new(1.0, 0.0, 0.0);
7457 assert!((curve.evaluate(t0) - (apex + x * 0.5)).length() < 1e-12);
7458 assert!((curve.evaluate(t1) - (apex + x * 3.0)).length() < 1e-12);
7459 }
7460
7461 #[test]
7465 fn cones_sharing_an_apex_cross_along_two_rulings() {
7466 let apex = Point3::new(-1.0, 0.5, 2.0);
7467 let b = 20.0_f64.to_radians();
7468 let half = 60.0_f64.to_radians();
7469 let c1 = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, 1.0), half).unwrap();
7470 let c2 = ConicalSurface::new(apex, Vec3::new(b.sin(), 0.0, b.cos()), half).unwrap();
7471 for (range, pieces) in [((0.5, 2.0), 2), ((-2.0, 2.0), 4)] {
7472 let curves = intersect_analytic_analytic_bounded(
7473 AnalyticSurface::Cone(&c1),
7474 AnalyticSurface::Cone(&c2),
7475 64,
7476 Some(range),
7477 Some(range),
7478 )
7479 .unwrap();
7480 assert_eq!(curves.len(), pieces, "{range:?}");
7481 for ic in &curves {
7482 let (t0, t1) = ic.curve.domain();
7483 for k in 0..=20 {
7484 let p = ic.curve.evaluate(t0 + (t1 - t0) * f64::from(k) / 20.0);
7485 for cone in [&c1, &c2] {
7486 let (off, v) = off_cone(cone, p);
7487 assert!(off < 1e-12, "{range:?}: off a cone by {off:.2e}");
7488 assert!(v > range.0 - 1e-12 && v < range.1 + 1e-12);
7489 }
7490 }
7491 if pieces == 4 {
7492 let ends = [ic.curve.evaluate(t0), ic.curve.evaluate(t1)];
7493 assert!(ends.iter().any(|&e| (e - apex).length() < 1e-12));
7494 }
7495 for point in &ic.points {
7496 let (on1, on2) = (point.param1, point.param2);
7497 assert!((c1.evaluate(on1.0, on1.1) - point.point).length() < 1e-9);
7498 assert!((c2.evaluate(on2.0, on2.1) - point.point).length() < 1e-9);
7499 }
7500 }
7501 }
7502 }
7503
7504 #[test]
7509 fn cones_sharing_an_apex_defer_what_rounding_cannot_settle() {
7510 let apex = Point3::new(0.0, 0.0, 0.0);
7511 let half = 60.0_f64.to_radians();
7512 let c1 = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, 1.0), half).unwrap();
7513 let c2 = ConicalSurface::new(apex, Vec3::new(1e-8_f64.sin(), 0.0, 1e-8_f64.cos()), half)
7514 .unwrap();
7515 let near = Some((0.5, 2.0));
7516 assert!(shared_apex_cones(&c1, &c2, near, near).unwrap().is_none());
7517 let a = 20.0_f64.to_radians();
7518 let half = std::f64::consts::FRAC_PI_2 - a;
7519 let c1 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, a.sin()), half).unwrap();
7520 let c2 = ConicalSurface::new(apex, Vec3::new(a.cos(), 0.0, -a.sin()), half).unwrap();
7521 let far = Some((0.5, 1e6));
7522 assert!(shared_apex_cones(&c1, &c2, far, far).unwrap().is_none());
7523 }
7524
7525 #[test]
7528 fn cones_sharing_an_apex_just_short_of_touching_cross_in_two_rulings() {
7529 let apex = Point3::new(0.0, 0.0, 0.0);
7530 let half = std::f64::consts::FRAC_PI_4 - 1e-15;
7531 let c1 = ConicalSurface::new(apex, Vec3::new(0.0, 0.0, 1.0), half).unwrap();
7532 let c2 = ConicalSurface::new(apex, Vec3::new(1.0, 0.0, 0.0), half).unwrap();
7533 let range = Some((0.5, 1e6));
7534 let curves = shared_apex_cones(&c1, &c2, range, range).unwrap().unwrap();
7535 assert_eq!(curves.len(), 2);
7536 let ends: Vec<Point3> = curves
7537 .iter()
7538 .map(|ic| ic.curve.evaluate(ic.curve.domain().1))
7539 .collect();
7540 assert!((ends[0] - ends[1]).length() > 0.05);
7541 }
7542
7543 #[test]
7550 fn a_ball_off_a_rings_axis_touches_it_at_one_point() {
7551 let o = Point3::new(1.0, 2.0, 3.0);
7552 let ring = ToroidalSurface::new(o, 3.0, 1.0).unwrap();
7553 let (s, c) = 30.0_f64.to_radians().sin_cos();
7554 let (out, up) = (Vec3::new(c, s, 0.0), Vec3::new(0.0, 0.0, 1.0));
7555 let on_ring = |p: Point3| {
7556 let q = p - o;
7557 ((q.x().hypot(q.y()) - 3.0).hypot(q.z()) - 1.0).abs()
7558 };
7559 let balls = [
7560 (o + out * 5.0, 1.0),
7561 (o + out * 3.2 + up * 0.1, 1.0 - 0.05_f64.sqrt()),
7562 (o + out + up * 0.5, 1.0 + 16.25_f64.sqrt()),
7563 ];
7564 let mut touches = Vec::new();
7565 for (centre, radius) in balls {
7566 let ball = SphericalSurface::new(centre, radius).unwrap();
7567 let exacts = exact_sphere_torus(&ball, &ring).unwrap().unwrap();
7568 let p = match exacts.as_slice() {
7569 [ExactIntersectionCurve::Points(points)] => points[0],
7570 _ => unreachable!("one touching point"),
7571 };
7572 assert!(on_ring(p) < 1e-12 && ((p - centre).length() - radius).abs() < 1e-12);
7573 let curves = intersect_analytic_analytic(
7574 AnalyticSurface::Sphere(&ball),
7575 AnalyticSurface::Torus(&ring),
7576 16,
7577 )
7578 .unwrap();
7579 assert_eq!(curves.len(), 1);
7580 let (t0, t1) = curves[0].curve.domain();
7581 assert!((curves[0].curve.evaluate(t0) - p).length() < 1e-15);
7582 assert!((curves[0].curve.evaluate(t1) - p).length() < 1e-15);
7583 touches.push(p);
7584 }
7585 assert!((touches[0] - (o + out * 4.0)).length() < 1e-12);
7586 let past = SphericalSurface::new(o + out * 5.0, 1.0 + 1e-6).unwrap();
7587 assert!(exact_sphere_torus(&past, &ring).unwrap().is_none());
7588 let on_core = SphericalSurface::new(o + out * 3.0, 1.0).unwrap();
7589 let meridian = exact_sphere_torus(&on_core, &ring).unwrap().unwrap();
7590 let [ExactIntersectionCurve::Circle(circle)] = meridian.as_slice() else {
7591 unreachable!("one meridian circle");
7592 };
7593 assert!((circle.center() - (o + out * 3.0)).length() < 1e-12);
7594 assert!((circle.radius() - 1.0).abs() < 1e-12);
7595 }
7596}