1use std::f64::consts::{FRAC_PI_2, TAU};
8
9use crate::MathError;
10use crate::curves::{Circle3D, Ellipse3D};
11use crate::frame::Frame3;
12use crate::nurbs::fitting::interpolate;
13use crate::nurbs::intersection::{IntersectionCurve, IntersectionPoint};
14use crate::surfaces::{ConicalSurface, CylindricalSurface, SphericalSurface, ToroidalSurface};
15use crate::tolerance::Tolerance;
16use crate::vec::{Point3, Vec3};
17
18#[derive(Debug, Clone)]
20pub enum ExactIntersectionCurve {
21 Circle(Circle3D),
23 Ellipse(Ellipse3D),
25 Points(Vec<Point3>),
27}
28
29pub fn exact_plane_analytic(
40 surface: AnalyticSurface<'_>,
41 plane_normal: Vec3,
42 plane_d: f64,
43) -> Result<Vec<ExactIntersectionCurve>, MathError> {
44 match surface {
45 AnalyticSurface::Cylinder(cyl) => exact_plane_cylinder(cyl, plane_normal, plane_d),
46 AnalyticSurface::Sphere(sphere) => exact_plane_sphere(sphere, plane_normal, plane_d),
47 AnalyticSurface::Cone(cone) => exact_plane_cone(cone, plane_normal, plane_d),
48 AnalyticSurface::Torus(torus) => {
49 let chains = sample_plane_torus(torus, plane_normal, plane_d)?;
51 Ok(chains
52 .into_iter()
53 .map(ExactIntersectionCurve::Points)
54 .collect())
55 }
56 }
57}
58
59fn exact_plane_cylinder(
65 cyl: &CylindricalSurface,
66 normal: Vec3,
67 d: f64,
68) -> Result<Vec<ExactIntersectionCurve>, MathError> {
69 let axis = cyl.axis();
70 let cos_theta = normal.dot(axis).abs();
71 let r = cyl.radius();
72
73 if cos_theta < 1e-10 {
74 let chains = sample_plane_cylinder(cyl, normal, d)?;
77 return Ok(chains
78 .into_iter()
79 .map(ExactIntersectionCurve::Points)
80 .collect());
81 }
82
83 let n_dot_axis = normal.dot(axis);
86 let n_dot_origin = dot_np(normal, cyl.origin());
87 let t = (d - n_dot_origin) / n_dot_axis;
88 let center_on_axis = Point3::new(
89 cyl.origin().x() + t * axis.x(),
90 cyl.origin().y() + t * axis.y(),
91 cyl.origin().z() + t * axis.z(),
92 );
93
94 if cos_theta > 1.0 - 1e-10 {
95 let circle = Circle3D::new(center_on_axis, normal, r)?;
97 Ok(vec![ExactIntersectionCurve::Circle(circle)])
98 } else {
99 let semi_minor = r;
103 let semi_major = r / cos_theta;
104
105 let axis_proj = Vec3::new(
109 axis.x() - n_dot_axis * normal.x(),
110 axis.y() - n_dot_axis * normal.y(),
111 axis.z() - n_dot_axis * normal.z(),
112 );
113 let u_axis = axis_proj.normalize()?;
114 let v_axis = normal.cross(u_axis);
115
116 let ellipse = Ellipse3D::with_axes(
117 center_on_axis,
118 normal,
119 semi_major,
120 semi_minor,
121 u_axis,
122 v_axis,
123 )?;
124 Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)])
125 }
126}
127
128fn exact_plane_sphere(
132 sphere: &SphericalSurface,
133 normal: Vec3,
134 d: f64,
135) -> Result<Vec<ExactIntersectionCurve>, MathError> {
136 let h = dot_np(normal, sphere.center()) - d;
137 let r = sphere.radius();
138
139 if h.abs() > r - 1e-10 {
140 return Ok(vec![]);
141 }
142
143 let circle_r = (r.mul_add(r, -(h * h))).sqrt();
144 let circle_center = Point3::new(
145 h.mul_add(-normal.x(), sphere.center().x()),
146 h.mul_add(-normal.y(), sphere.center().y()),
147 h.mul_add(-normal.z(), sphere.center().z()),
148 );
149
150 let circle = Circle3D::new(circle_center, normal, circle_r)?;
151 Ok(vec![ExactIntersectionCurve::Circle(circle)])
152}
153
154fn exact_plane_cone(
163 cone: &ConicalSurface,
164 normal: Vec3,
165 d: f64,
166) -> Result<Vec<ExactIntersectionCurve>, MathError> {
167 let axis = cone.axis();
168 let cos_theta = normal.dot(axis).abs();
169 let half_angle = cone.half_angle();
170
171 if cos_theta > 1.0 - 1e-10 {
172 let n_dot_axis = normal.dot(axis);
175 let n_dot_apex = dot_np(normal, cone.apex());
176 let t = (d - n_dot_apex) / n_dot_axis;
177
178 if t.abs() < 1e-10 {
183 return Ok(vec![]);
184 }
185
186 let center = Point3::new(
187 cone.apex().x() + t * axis.x(),
188 cone.apex().y() + t * axis.y(),
189 cone.apex().z() + t * axis.z(),
190 );
191 let circle_r = t.abs() * half_angle.cos() / half_angle.sin();
195 if circle_r < 1e-15 {
196 return Ok(vec![]);
197 }
198
199 let circle = Circle3D::new(center, normal, circle_r)?;
200 return Ok(vec![ExactIntersectionCurve::Circle(circle)]);
201 }
202
203 let c = normal.dot(axis);
215 let p2 = (1.0 - c * c).max(0.0);
216 let p = p2.sqrt();
217 let k = half_angle.sin().powi(2);
218 let a_coeff = p2 - k;
219
220 let m = Vec3::new(
222 axis.x() - c * normal.x(),
223 axis.y() - c * normal.y(),
224 axis.z() - c * normal.z(),
225 );
226 let m_len = m.length();
227 if m_len < 1e-12 {
228 let chains = sample_plane_cone(cone, normal, d)?;
231 return Ok(chains
232 .into_iter()
233 .map(ExactIntersectionCurve::Points)
234 .collect());
235 }
236 let e1 = m * (1.0 / m_len);
237 let e2 = normal.cross(e1);
238 let apex = cone.apex();
239 let e = d - dot_np(normal, apex);
240
241 if a_coeff < -1e-9 {
244 let abs_a = -a_coeff; if e * c < 0.0 {
251 return Ok(vec![]);
252 }
253 let s_c = e * c * p / abs_a;
256 let rhs = e * e * k * (1.0 - k) / abs_a;
257 if rhs <= 0.0 {
258 return Ok(vec![]);
259 }
260 let semi_s = (rhs / abs_a).sqrt(); let semi_t = (rhs / k).sqrt(); if semi_s < 1e-12 || semi_t < 1e-12 {
263 return Ok(vec![]);
264 }
265 let center = apex + normal * e + e1 * s_c;
266 let (semi_major, semi_minor, u_axis, v_axis) = if semi_s >= semi_t {
267 (semi_s, semi_t, e1, e2)
268 } else {
269 (semi_t, semi_s, e2, e1)
270 };
271 let ellipse = Ellipse3D::with_axes(center, normal, semi_major, semi_minor, u_axis, v_axis)?;
272 return Ok(vec![ExactIntersectionCurve::Ellipse(ellipse)]);
273 }
274
275 let chains = sample_plane_cone(cone, normal, d)?;
278 Ok(chains
279 .into_iter()
280 .map(ExactIntersectionCurve::Points)
281 .collect())
282}
283
284#[derive(Clone, Copy)]
286pub enum AnalyticSurface<'a> {
287 Cylinder(&'a CylindricalSurface),
289 Cone(&'a ConicalSurface),
291 Sphere(&'a SphericalSurface),
293 Torus(&'a ToroidalSurface),
295}
296
297fn dot_np(n: Vec3, p: Point3) -> f64 {
299 n.dot(Vec3::new(p.x(), p.y(), p.z()))
300}
301
302pub fn intersect_plane_analytic(
310 surface: AnalyticSurface<'_>,
311 normal: Vec3,
312 d: f64,
313) -> Result<Vec<IntersectionCurve>, MathError> {
314 match surface {
315 AnalyticSurface::Cylinder(cyl) => intersect_plane_cylinder(cyl, normal, d),
316 AnalyticSurface::Cone(cone) => intersect_plane_cone(cone, normal, d),
317 AnalyticSurface::Sphere(sphere) => intersect_plane_sphere(sphere, normal, d),
318 AnalyticSurface::Torus(torus) => intersect_plane_torus(torus, normal, d),
319 }
320}
321
322pub fn sample_plane_analytic(
333 surface: AnalyticSurface<'_>,
334 normal: Vec3,
335 d: f64,
336) -> Result<Vec<Vec<Point3>>, MathError> {
337 match surface {
338 AnalyticSurface::Cylinder(cyl) => sample_plane_cylinder(cyl, normal, d),
339 AnalyticSurface::Cone(cone) => sample_plane_cone(cone, normal, d),
340 AnalyticSurface::Sphere(sphere) => sample_plane_sphere(sphere, normal, d),
341 AnalyticSurface::Torus(torus) => sample_plane_torus(torus, normal, d),
342 }
343}
344
345#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
347fn sample_plane_cylinder(
348 cyl: &CylindricalSurface,
349 normal: Vec3,
350 d: f64,
351) -> Result<Vec<Vec<Point3>>, MathError> {
352 let n_samples = 64_usize;
353 let mut points = Vec::with_capacity(n_samples + 1);
354
355 for i in 0..=n_samples {
356 let u = TAU * (i as f64) / (n_samples as f64);
357 let base = cyl.evaluate(u, 0.0);
358 let n_dot_axis = normal.dot(cyl.axis());
359 let n_dot_base = dot_np(normal, base);
360
361 if n_dot_axis.abs() < 1e-12 {
362 if (n_dot_base - d).abs() < 1e-6 {
363 points.push(base);
364 }
365 } else {
366 let v = (d - n_dot_base) / n_dot_axis;
367 if v.abs() <= 100.0 {
368 points.push(cyl.evaluate(u, v));
369 }
370 }
371 }
372
373 if points.len() < 2 {
374 Ok(vec![])
375 } else {
376 Ok(vec![points])
377 }
378}
379
380#[allow(clippy::cast_precision_loss)]
382fn sample_plane_sphere(
383 sphere: &SphericalSurface,
384 normal: Vec3,
385 d: f64,
386) -> Result<Vec<Vec<Point3>>, MathError> {
387 let h = dot_np(normal, sphere.center()) - d;
388 let r = sphere.radius();
389
390 if h.abs() > r - 1e-10 {
391 return Ok(vec![]);
392 }
393
394 let circle_r = (r.mul_add(r, -(h * h))).sqrt();
395 let circle_center = Point3::new(
396 h.mul_add(-normal.x(), sphere.center().x()),
397 h.mul_add(-normal.y(), sphere.center().y()),
398 h.mul_add(-normal.z(), sphere.center().z()),
399 );
400
401 let basis = Frame3::from_normal(circle_center, normal)?;
402 let u_dir = basis.x;
403 let v_dir = basis.y;
404
405 let n_samples = 64_usize;
406 let mut points = Vec::with_capacity(n_samples + 1);
407
408 for i in 0..=n_samples {
409 let theta = TAU * (i as f64) / (n_samples as f64);
410 let (sin_t, cos_t) = theta.sin_cos();
411 points.push(circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t));
412 }
413
414 Ok(vec![points])
415}
416
417#[allow(clippy::cast_precision_loss, clippy::unnecessary_wraps)]
429fn sample_plane_cone(
430 cone: &ConicalSurface,
431 normal: Vec3,
432 d: f64,
433) -> Result<Vec<Vec<Point3>>, MathError> {
434 let apex = cone.apex();
435 let n_dot_apex = dot_np(normal, apex);
436 let e = d - n_dot_apex;
437
438 let n_samples = 512_usize;
442 let mut vs: Vec<Option<f64>> = Vec::with_capacity(n_samples);
443 let mut v_min = f64::INFINITY;
444 for i in 0..n_samples {
445 let u = TAU * (i as f64) / (n_samples as f64);
446 let g = cone.evaluate(u, 1.0) - apex;
447 let n_dot_g = normal.dot(Vec3::new(g.x(), g.y(), g.z()));
448 if n_dot_g.abs() < 1e-12 {
449 vs.push(None);
450 continue;
451 }
452 let v = e / n_dot_g;
453 if v >= -1e-12 {
454 let v = v.max(0.0);
455 v_min = v_min.min(v);
456 vs.push(Some(v));
457 } else {
458 vs.push(None);
459 }
460 }
461
462 if !v_min.is_finite() {
463 return Ok(Vec::new());
464 }
465
466 let v_max = (8.0 * v_min).max(v_min + 4.0);
473
474 let kept: Vec<Option<f64>> = vs.iter().map(|v| v.filter(|&v| v <= v_max)).collect();
477
478 let point_at = |u: f64, v: f64| -> Point3 {
479 let g = cone.evaluate(u, 1.0) - apex;
480 apex + g * v
481 };
482 #[allow(clippy::cast_precision_loss)]
483 let u_of = |i: usize| TAU * (i as f64) / (n_samples as f64);
484 let n_dot_g_at = |u: f64| -> f64 {
485 let g = cone.evaluate(u, 1.0) - apex;
486 normal.dot(Vec3::new(g.x(), g.y(), g.z()))
487 };
488
489 if kept.iter().all(Option::is_some) {
490 let mut pts: Vec<Point3> = kept
492 .iter()
493 .enumerate()
494 .filter_map(|(i, v)| v.map(|v| point_at(u_of(i), v)))
495 .collect();
496 if let Some(&first) = pts.first() {
497 pts.push(first);
498 }
499 return Ok(vec![pts]);
500 }
501
502 let tail = |i_end: usize, forward: bool, kept: &[Option<f64>]| -> Vec<Point3> {
511 let Some(v_end) = kept[i_end] else {
512 return Vec::new();
513 };
514 let u_end = u_of(i_end);
515 #[allow(clippy::cast_precision_loss)]
516 let pitch = TAU / (n_samples as f64);
517 let u_next = if forward {
518 u_end + pitch
519 } else {
520 u_end - pitch
521 };
522 let target = e / v_max;
523 let h_end = n_dot_g_at(u_end) - target;
524 let h_next = n_dot_g_at(u_next) - target;
525 if v_end >= v_max || h_end == 0.0 || h_end.signum() == h_next.signum() {
526 return Vec::new();
527 }
528 let (mut lo, mut hi) = (u_end, u_next);
529 for _ in 0..60 {
530 let mid = f64::midpoint(lo, hi);
531 if (n_dot_g_at(mid) - target).signum() == h_end.signum() {
532 lo = mid;
533 } else {
534 hi = mid;
535 }
536 }
537 let u_star = f64::midpoint(lo, hi);
538 let tail_n = 8_usize;
539 (1..=tail_n)
540 .filter_map(|k| {
541 #[allow(clippy::cast_precision_loss)]
542 let u = u_end + (u_star - u_end) * (k as f64) / (tail_n as f64);
543 let ng = n_dot_g_at(u);
544 if ng.abs() < 1e-12 {
545 return None;
546 }
547 let v = e / ng;
548 (v >= -1e-12 && v <= v_max * (1.0 + 1e-9)).then(|| point_at(u, v.max(0.0)))
549 })
550 .collect()
551 };
552
553 let gap = kept.iter().position(Option::is_none).unwrap_or(0);
556 let mut chains: Vec<Vec<Point3>> = Vec::new();
557 let mut run: Vec<usize> = Vec::new();
558 let flush = |run: &mut Vec<usize>, chains: &mut Vec<Vec<Point3>>| {
559 if run.len() >= 2 {
560 let first = run[0];
561 let last = run[run.len() - 1];
562 let mut pts: Vec<Point3> = tail(first, false, &kept);
563 pts.reverse();
564 pts.extend(
565 run.iter()
566 .filter_map(|&i| kept[i].map(|v| point_at(u_of(i), v))),
567 );
568 pts.extend(tail(last, true, &kept));
569 chains.push(pts);
570 }
571 run.clear();
572 };
573 for k in 0..n_samples {
574 let idx = (gap + k) % n_samples;
575 if kept[idx].is_some() {
576 run.push(idx);
577 } else {
578 flush(&mut run, &mut chains);
579 }
580 }
581 flush(&mut run, &mut chains);
582 Ok(chains.into_iter().filter(|c| c.len() >= 2).collect())
583}
584
585#[allow(clippy::unnecessary_wraps)] fn sample_plane_torus(
591 torus: &ToroidalSurface,
592 normal: Vec3,
593 d: f64,
594) -> Result<Vec<Vec<Point3>>, MathError> {
595 let crossing_pts = plane_torus_crossings(torus, normal, d, 128);
596 Ok(chain_torus_crossings(&crossing_pts)
597 .into_iter()
598 .map(|run| run.into_iter().map(|p| p.point).collect())
599 .collect())
600}
601
602#[allow(clippy::cast_precision_loss)]
612pub fn intersect_plane_cylinder(
613 cyl: &CylindricalSurface,
614 normal: Vec3,
615 d: f64,
616) -> Result<Vec<IntersectionCurve>, MathError> {
617 let n_samples = 64_usize;
618 let mut points_3d = Vec::new();
619 let mut ipoints = Vec::new();
620
621 for i in 0..=n_samples {
622 let u = TAU * (i as f64) / (n_samples as f64);
623 let base = cyl.evaluate(u, 0.0);
626 let n_dot_axis = normal.dot(cyl.axis());
627 let n_dot_base = dot_np(normal, base);
628
629 if n_dot_axis.abs() < 1e-12 {
630 if (n_dot_base - d).abs() < 1e-6 {
632 let pt = base;
633 points_3d.push(pt);
634 ipoints.push(IntersectionPoint {
635 point: pt,
636 param1: (u, 0.0),
637 param2: (0.0, 0.0),
638 });
639 }
640 } else {
641 let v = (d - n_dot_base) / n_dot_axis;
642 if v.abs() <= 100.0 {
644 let pt = cyl.evaluate(u, v);
645 points_3d.push(pt);
646 ipoints.push(IntersectionPoint {
647 point: pt,
648 param1: (u, v),
649 param2: (0.0, 0.0),
650 });
651 }
652 }
653 }
654
655 build_curves_from_points(&points_3d, ipoints)
656}
657
658#[allow(clippy::cast_precision_loss)]
667pub fn intersect_plane_sphere(
668 sphere: &SphericalSurface,
669 normal: Vec3,
670 d: f64,
671) -> Result<Vec<IntersectionCurve>, MathError> {
672 let h = dot_np(normal, sphere.center()) - d;
673 let r = sphere.radius();
674
675 if h.abs() > r - 1e-10 {
677 return Ok(vec![]);
678 }
679
680 let circle_r = (r.mul_add(r, -(h * h))).sqrt();
681 let circle_center = Point3::new(
682 h.mul_add(-normal.x(), sphere.center().x()),
683 h.mul_add(-normal.y(), sphere.center().y()),
684 h.mul_add(-normal.z(), sphere.center().z()),
685 );
686
687 let basis = Frame3::from_normal(circle_center, normal)?;
689 let u_dir = basis.x;
690 let v_dir = basis.y;
691
692 let n_samples = 64_usize;
693 let mut points_3d = Vec::new();
694 let mut ipoints = Vec::new();
695
696 for i in 0..=n_samples {
697 let theta = TAU * (i as f64) / (n_samples as f64);
698 let (sin_t, cos_t) = theta.sin_cos();
699 let pt = circle_center + u_dir * (circle_r * cos_t) + v_dir * (circle_r * sin_t);
700 points_3d.push(pt);
701 ipoints.push(IntersectionPoint {
702 point: pt,
703 param1: (theta, 0.0),
704 param2: (0.0, 0.0),
705 });
706 }
707
708 build_curves_from_points(&points_3d, ipoints)
709}
710
711#[allow(clippy::cast_precision_loss)]
720pub fn intersect_plane_cone(
721 cone: &ConicalSurface,
722 normal: Vec3,
723 d: f64,
724) -> Result<Vec<IntersectionCurve>, MathError> {
725 let n_samples = 64_usize;
726 let mut points_3d = Vec::new();
727 let mut ipoints = Vec::new();
728
729 for i in 0..n_samples {
730 let u = TAU * (i as f64) / (n_samples as f64);
731 let apex = cone.apex();
734 let n_dot_apex = dot_np(normal, apex);
735 let p1 = cone.evaluate(u, 1.0);
737 let dir = p1 - apex;
738 let n_dot_dir = normal.dot(dir);
739
740 if n_dot_dir.abs() < 1e-12 {
741 continue;
742 }
743
744 let v = (d - n_dot_apex) / n_dot_dir;
745 if v.abs() > 1e-10 && v.abs() < 100.0 {
747 let pt = cone.evaluate(u, v);
748 points_3d.push(pt);
749 ipoints.push(IntersectionPoint {
750 point: pt,
751 param1: (u, v),
752 param2: (0.0, 0.0),
753 });
754 }
755 }
756
757 build_curves_from_points(&points_3d, ipoints)
758}
759
760#[allow(clippy::unnecessary_wraps)]
772pub fn intersect_plane_torus(
773 torus: &ToroidalSurface,
774 normal: Vec3,
775 d: f64,
776) -> Result<Vec<IntersectionCurve>, MathError> {
777 let crossing_pts = plane_torus_crossings(torus, normal, d, 128);
781
782 let mut curves = Vec::new();
783 for ipts in chain_torus_crossings(&crossing_pts) {
784 let pts: Vec<Point3> = ipts.iter().map(|p| p.point).collect();
785 if let Ok(curve) = interpolate(&pts, 3.min(pts.len() - 1)) {
786 curves.push(IntersectionCurve {
787 curve,
788 points: ipts,
789 });
790 }
791 }
792
793 Ok(curves)
794}
795
796fn chain_torus_crossings(crossing_pts: &[(f64, f64, Point3)]) -> Vec<Vec<IntersectionPoint>> {
808 let mut used = vec![false; crossing_pts.len()];
809 let mut runs = Vec::new();
810
811 for start in 0..crossing_pts.len() {
812 if used[start] {
813 continue;
814 }
815 used[start] = true;
816 let mut chain = vec![start];
817
818 loop {
819 let last = chain[chain.len() - 1];
820 let last_pt = crossing_pts[last].2;
821 let mut best_idx = None;
822 let mut best_dist = 1.0_f64;
823
824 for (j, &is_used) in used.iter().enumerate() {
825 if is_used {
826 continue;
827 }
828 let dist = (crossing_pts[j].2 - last_pt).length();
829 if dist < best_dist {
830 best_dist = dist;
831 best_idx = Some(j);
832 }
833 }
834
835 if let Some(j) = best_idx {
836 used[j] = true;
837 chain.push(j);
838 } else {
839 break;
840 }
841 }
842
843 if chain.len() < 4 {
844 continue;
845 }
846 let mut ipts: Vec<IntersectionPoint> = chain
847 .iter()
848 .map(|&i| IntersectionPoint {
849 point: crossing_pts[i].2,
850 param1: (crossing_pts[i].0, crossing_pts[i].1),
851 param2: (0.0, 0.0),
852 })
853 .collect();
854
855 let closing_gap = (ipts[ipts.len() - 1].point - ipts[0].point).length();
856 let median_spacing = {
857 let mut spac: Vec<f64> = ipts
858 .windows(2)
859 .map(|w| (w[1].point - w[0].point).length())
860 .collect();
861 spac.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
862 spac.get(spac.len() / 2).copied().unwrap_or(0.0)
863 };
864 if closing_gap > 1e-9
871 && median_spacing > 1e-12
872 && closing_gap <= 2.0 * median_spacing
873 && !chain_self_touches(&ipts, median_spacing)
874 {
875 ipts.push(ipts[0]);
876 }
877 runs.push(ipts);
878 }
879
880 runs
881}
882
883fn chain_self_touches(ipts: &[IntersectionPoint], median_spacing: f64) -> bool {
893 let m = ipts.len();
894 let k = (m / 4).clamp(1, 6);
895 if m < 3 * k || median_spacing <= 0.0 {
896 return false;
897 }
898 let thresh = median_spacing * 1.5;
899 for i in k..(m - k) {
900 for j in (i + k)..(m - k) {
901 if (ipts[i].point - ipts[j].point).length() < thresh {
902 return true;
903 }
904 }
905 }
906 false
907}
908
909#[allow(clippy::cast_precision_loss)]
926fn plane_torus_crossings(
927 torus: &ToroidalSurface,
928 normal: Vec3,
929 d: f64,
930 n_v: usize,
931) -> Vec<(f64, f64, Point3)> {
932 let big_r = torus.major_radius();
933 let small_r = torus.minor_radius();
934 let a = normal.dot(torus.x_axis());
935 let b = normal.dot(torus.y_axis());
936 let c = normal.dot(torus.z_axis());
937 let s = a.hypot(b);
938 let phi = b.atan2(a);
939 let d_local = d - dot_np(normal, torus.center());
940
941 let mut pts: Vec<(f64, f64, Point3)> = Vec::new();
942
943 if s < 1e-12 {
945 if c.abs() < 1e-12 {
946 return pts;
947 }
948 let sin_v = d_local / (small_r * c);
949 if sin_v.abs() > 1.0 + 1e-9 {
950 return pts;
951 }
952 let v0 = sin_v.clamp(-1.0, 1.0).asin();
953 let v1 = std::f64::consts::PI - v0;
954 let mut vs = vec![v0];
955 if (v1 - v0).abs() > 1e-9 {
957 vs.push(v1);
958 }
959 for v in vs {
960 for i in 0..n_v {
961 let u = TAU * (i as f64) / (n_v as f64);
962 pts.push((u, v, torus.evaluate(u, v)));
963 }
964 }
965 return pts;
966 }
967
968 let v_off = TAU / (n_v as f64) * 0.5;
974 for i in 0..n_v {
975 let v = (i as f64).mul_add(TAU / (n_v as f64), v_off);
976 let tube_r = small_r.mul_add(v.cos(), big_r); let rhs = (d_local - small_r * c * v.sin()) / (s * tube_r);
978 if rhs.abs() > 1.0 {
979 continue;
980 }
981 let delta = rhs.clamp(-1.0, 1.0).acos();
982 for u in [phi + delta, phi - delta] {
983 pts.push((u, v, torus.evaluate(u, v)));
984 }
985 }
986 pts
987}
988
989#[must_use]
1002pub fn intersect_line_torus(torus: &ToroidalSurface, origin: Point3, dir: Vec3) -> Vec<f64> {
1003 let c = torus.center();
1004 let (xa, ya, za) = (torus.x_axis(), torus.y_axis(), torus.z_axis());
1005 let big_r = torus.major_radius();
1006 let small_r = torus.minor_radius();
1007
1008 let o = Vec3::new(origin.x() - c.x(), origin.y() - c.y(), origin.z() - c.z());
1010 let (a0, a1) = (xa.dot(o), xa.dot(dir));
1011 let (b0, b1) = (ya.dot(o), ya.dot(dir));
1012 let (c0, c1) = (za.dot(o), za.dot(dir));
1013
1014 let g2 = a1.mul_add(a1, b1.mul_add(b1, c1 * c1));
1016 let g1 = 2.0 * a1.mul_add(a0, b1.mul_add(b0, c1 * c0));
1017 let g0 = a0.mul_add(
1018 a0,
1019 b0.mul_add(b0, c0.mul_add(c0, big_r.mul_add(big_r, -small_r * small_r))),
1020 );
1021
1022 let four_rr = 4.0 * big_r * big_r;
1024 let h2 = four_rr * a1.mul_add(a1, b1 * b1);
1025 let h1 = four_rr * (2.0 * a1.mul_add(a0, b1 * b0));
1026 let h0 = four_rr * a0.mul_add(a0, b0 * b0);
1027
1028 let e4 = g2 * g2;
1030 let e3 = 2.0 * g2 * g1;
1031 let e2 = g1.mul_add(g1, 2.0 * g2 * g0) - h2;
1032 let e1 = 2.0f64.mul_add(g1 * g0, -h1);
1033 let e0 = g0.mul_add(g0, -h0);
1034
1035 let mut roots = real_roots_quartic(e4, e3, e2, e1, e0);
1036 let impl_f = |t: f64| -> f64 {
1038 let p = origin + dir * t;
1039 let q = Vec3::new(p.x() - c.x(), p.y() - c.y(), p.z() - c.z());
1040 let (a, b, cc) = (xa.dot(q), ya.dot(q), za.dot(q));
1041 (a.hypot(b) - big_r).hypot(cc) - small_r
1042 };
1043 for t in &mut roots {
1044 let eps = 1e-7;
1045 let f = impl_f(*t);
1046 let df = (impl_f(*t + eps) - impl_f(*t - eps)) / (2.0 * eps);
1047 if df.abs() > 1e-12 {
1048 *t -= f / df;
1049 }
1050 }
1051 roots.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
1052 roots
1053}
1054
1055fn real_roots_quartic(c4: f64, c3: f64, c2: f64, c1: f64, c0: f64) -> Vec<f64> {
1058 if c4.abs() < 1e-14 {
1060 return real_roots_cubic(c3, c2, c1, c0);
1061 }
1062 let (a, b, c, d) = (c3 / c4, c2 / c4, c1 / c4, c0 / c4);
1064 let eval = |z: Complex| -> Complex {
1065 let mut acc = Complex::new(1.0, 0.0);
1067 acc = acc * z + Complex::new(a, 0.0);
1068 acc = acc * z + Complex::new(b, 0.0);
1069 acc = acc * z + Complex::new(c, 0.0);
1070 acc * z + Complex::new(d, 0.0)
1071 };
1072 let seed = Complex::new(0.4, 0.9);
1074 let mut r = [
1075 Complex::new(1.0, 0.0),
1076 seed,
1077 seed * seed,
1078 seed * seed * seed,
1079 ];
1080 for _ in 0..100 {
1081 let mut max_step = 0.0_f64;
1082 for i in 0..4 {
1083 let mut denom = Complex::new(1.0, 0.0);
1084 for j in 0..4 {
1085 if i != j {
1086 denom = denom * (r[i] - r[j]);
1087 }
1088 }
1089 if denom.norm() < 1e-300 {
1090 continue;
1091 }
1092 let step = eval(r[i]) / denom;
1093 r[i] = r[i] - step;
1094 max_step = max_step.max(step.norm());
1095 }
1096 if max_step < 1e-14 {
1097 break;
1098 }
1099 }
1100 let p_real = |x: f64| -> f64 { (((x + a) * x + b) * x + c) * x + d };
1107 let mut out: Vec<f64> = Vec::new();
1108 for z in r {
1109 if z.im.abs() >= 1e-7 {
1110 continue;
1111 }
1112 let x = z.re;
1113 let scale = 1.0 + a.abs() + b.abs() + c.abs() + d.abs() + x.abs().powi(4);
1116 if p_real(x).abs() > 1e-6 * scale {
1117 continue;
1118 }
1119 if out.iter().any(|&y| (y - x).abs() < 1e-9 * (1.0 + x.abs())) {
1120 continue;
1121 }
1122 out.push(x);
1123 }
1124 out
1125}
1126
1127fn real_roots_cubic(a: f64, b: f64, c: f64, d: f64) -> Vec<f64> {
1129 if a.abs() < 1e-14 {
1130 return real_roots_quadratic(b, c, d);
1131 }
1132 let (b, c, d) = (b / a, c / a, d / a);
1134 let p = c - b * b / 3.0;
1135 let q = 2.0 * b * b * b / 27.0 - b * c / 3.0 + d;
1136 let shift = -b / 3.0;
1137 let disc = q * q / 4.0 + p * p * p / 27.0;
1138 if disc > 1e-14 {
1139 let sq = disc.sqrt();
1140 let u = (-q / 2.0 + sq).cbrt();
1141 let v = (-q / 2.0 - sq).cbrt();
1142 vec![u + v + shift]
1143 } else if disc < -1e-14 {
1144 let m = 2.0 * (-p / 3.0).sqrt();
1146 let theta = (3.0 * q / (p * m)).clamp(-1.0, 1.0).acos() / 3.0;
1147 (0..3)
1148 .map(|k| {
1149 m.mul_add(
1150 (theta - 2.0 * std::f64::consts::PI * f64::from(k) / 3.0).cos(),
1151 shift,
1152 )
1153 })
1154 .collect()
1155 } else {
1156 let u = (-q / 2.0).cbrt();
1158 vec![2.0 * u + shift, -u + shift]
1159 }
1160}
1161
1162fn real_roots_quadratic(a: f64, b: f64, c: f64) -> Vec<f64> {
1164 if a.abs() < 1e-14 {
1165 if b.abs() < 1e-14 {
1166 return Vec::new();
1167 }
1168 return vec![-c / b];
1169 }
1170 let disc = b * b - 4.0 * a * c;
1171 if disc < 0.0 {
1172 Vec::new()
1173 } else {
1174 let sq = disc.sqrt();
1175 vec![(-b - sq) / (2.0 * a), (-b + sq) / (2.0 * a)]
1176 }
1177}
1178
1179#[derive(Clone, Copy)]
1181struct Complex {
1182 re: f64,
1183 im: f64,
1184}
1185
1186impl Complex {
1187 const fn new(re: f64, im: f64) -> Self {
1188 Self { re, im }
1189 }
1190 fn norm(self) -> f64 {
1191 self.re.hypot(self.im)
1192 }
1193}
1194
1195impl std::ops::Add for Complex {
1196 type Output = Self;
1197 fn add(self, o: Self) -> Self {
1198 Self::new(self.re + o.re, self.im + o.im)
1199 }
1200}
1201
1202impl std::ops::Sub for Complex {
1203 type Output = Self;
1204 fn sub(self, o: Self) -> Self {
1205 Self::new(self.re - o.re, self.im - o.im)
1206 }
1207}
1208
1209impl std::ops::Mul for Complex {
1210 type Output = Self;
1211 fn mul(self, o: Self) -> Self {
1212 Self::new(
1213 self.re.mul_add(o.re, -(self.im * o.im)),
1214 self.re.mul_add(o.im, self.im * o.re),
1215 )
1216 }
1217}
1218
1219impl std::ops::Div for Complex {
1220 type Output = Self;
1221 fn div(self, o: Self) -> Self {
1222 let den = o.re.mul_add(o.re, o.im * o.im);
1223 Self::new(
1224 self.re.mul_add(o.re, self.im * o.im) / den,
1225 self.im.mul_add(o.re, -(self.re * o.im)) / den,
1226 )
1227 }
1228}
1229
1230fn build_curves_from_points(
1234 points_3d: &[Point3],
1235 ipoints: Vec<IntersectionPoint>,
1236) -> Result<Vec<IntersectionCurve>, MathError> {
1237 if points_3d.len() < 2 {
1238 return Ok(vec![]);
1239 }
1240
1241 let degree = 3.min(points_3d.len() - 1);
1242 let curve = interpolate(points_3d, degree)?;
1243 Ok(vec![IntersectionCurve {
1244 curve,
1245 points: ipoints,
1246 }])
1247}
1248
1249#[allow(
1261 clippy::cast_precision_loss,
1262 clippy::too_many_lines,
1263 clippy::similar_names,
1264 clippy::unnecessary_wraps,
1265 clippy::type_complexity
1266)]
1267pub fn intersect_analytic_analytic(
1268 a: AnalyticSurface<'_>,
1269 b: AnalyticSurface<'_>,
1270 grid_res: usize,
1271) -> Result<Vec<IntersectionCurve>, MathError> {
1272 intersect_analytic_analytic_bounded(a, b, grid_res, None, None)
1273}
1274
1275pub fn intersect_analytic_analytic_bounded(
1286 a: AnalyticSurface<'_>,
1287 b: AnalyticSurface<'_>,
1288 grid_res: usize,
1289 v_range_hint_a: Option<(f64, f64)>,
1290 v_range_hint_b: Option<(f64, f64)>,
1291) -> Result<Vec<IntersectionCurve>, MathError> {
1292 if let Some(result) = try_algebraic_intersection(&a, &b, v_range_hint_a, v_range_hint_b)? {
1295 return Ok(result);
1296 }
1297
1298 let (surf_a, norm_a, u_range_a, default_v_a) = surface_closures(&a);
1299 let (surf_b, norm_b, u_range_b, default_v_b) = surface_closures(&b);
1300 let v_range_a = v_range_hint_a.unwrap_or(default_v_a);
1301 let v_range_b = v_range_hint_b.unwrap_or(default_v_b);
1302
1303 let diag_a = {
1305 let p00 = surf_a(u_range_a.0, v_range_a.0);
1306 let p11 = surf_a(u_range_a.1, v_range_a.1);
1307 (p00 - p11).length()
1308 };
1309 let diag_b = {
1310 let p00 = surf_b(u_range_b.0, v_range_b.0);
1311 let p11 = surf_b(u_range_b.1, v_range_b.1);
1312 (p00 - p11).length()
1313 };
1314 let char_size = diag_a.min(diag_b).max(0.1);
1315
1316 #[allow(clippy::type_complexity)]
1320 let mut seeds: Vec<(Point3, (f64, f64), (f64, f64))> = Vec::new();
1321 let seed_threshold = diag_a.max(diag_b).max(1.0) * 0.5;
1325 let mut min_dist = f64::INFINITY;
1326
1327 #[allow(clippy::cast_precision_loss)]
1328 for ia in 0..grid_res {
1329 for ja in 0..grid_res {
1330 let ua =
1331 u_range_a.0 + (u_range_a.1 - u_range_a.0) * (ia as f64 + 0.5) / (grid_res as f64);
1332 let va =
1333 v_range_a.0 + (v_range_a.1 - v_range_a.0) * (ja as f64 + 0.5) / (grid_res as f64);
1334
1335 let pa = surf_a(ua, va);
1336
1337 let (ub, vb) = project_analytic(&b, pa, u_range_b, v_range_b);
1339 let pb = surf_b(ub, vb);
1340 let dist = (pa - pb).length();
1341 min_dist = min_dist.min(dist);
1342
1343 if dist < seed_threshold {
1344 let mid = Point3::new(
1349 (pa.x() + pb.x()) * 0.5,
1350 (pa.y() + pb.y()) * 0.5,
1351 (pa.z() + pb.z()) * 0.5,
1352 );
1353 seeds.push((mid, (ua, va), (ub, vb)));
1354 }
1355 }
1356 }
1357
1358 let reject_dist = (char_size / grid_res as f64) * 3.0;
1367 if min_dist > reject_dist {
1368 return Ok(vec![]);
1369 }
1370
1371 if seeds.is_empty() {
1372 return Ok(vec![]);
1373 }
1374
1375 let march_step = (char_size * 0.02).clamp(0.005, 0.5);
1379 let dedup_radius = march_step * 10.0;
1380 let mut unique_seeds = Vec::new();
1381 for seed in &seeds {
1382 let dominated = unique_seeds
1383 .iter()
1384 .any(|s: &(Point3, (f64, f64), (f64, f64))| (s.0 - seed.0).length() < dedup_radius);
1385 if !dominated {
1386 unique_seeds.push(*seed);
1387 }
1388 }
1389
1390 let mut curves = Vec::new();
1392 let mut used_seeds = vec![false; unique_seeds.len()];
1393
1394 for si in 0..unique_seeds.len() {
1395 if used_seeds[si] {
1396 continue;
1397 }
1398 used_seeds[si] = true;
1399
1400 let march_result = march_analytic_intersection(
1401 &a,
1402 &b,
1403 surf_a.as_ref(),
1404 norm_a.as_ref(),
1405 surf_b.as_ref(),
1406 norm_b.as_ref(),
1407 unique_seeds[si].0,
1408 u_range_a,
1409 v_range_a,
1410 u_range_b,
1411 v_range_b,
1412 march_step,
1413 is_u_periodic(&a),
1414 is_u_periodic(&b),
1415 );
1416
1417 if march_result.len() >= 2 {
1418 for (sj, other) in unique_seeds.iter().enumerate() {
1419 if !used_seeds[sj]
1420 && march_result
1421 .iter()
1422 .any(|p| (*p - other.0).length() < dedup_radius)
1423 {
1424 used_seeds[sj] = true;
1425 }
1426 }
1427
1428 let ipts: Vec<IntersectionPoint> = march_result
1429 .iter()
1430 .map(|&pt| IntersectionPoint {
1431 point: pt,
1432 param1: (0.0, 0.0),
1433 param2: (0.0, 0.0),
1434 })
1435 .collect();
1436
1437 let degree = 3.min(march_result.len() - 1);
1438 if let Ok(curve) = interpolate(&march_result, degree) {
1439 curves.push(IntersectionCurve {
1440 curve,
1441 points: ipts,
1442 });
1443 }
1444 }
1445 }
1446
1447 Ok(curves)
1448}
1449
1450#[allow(clippy::too_many_lines)]
1460fn try_algebraic_intersection(
1461 a: &AnalyticSurface<'_>,
1462 b: &AnalyticSurface<'_>,
1463 v_range_a: Option<(f64, f64)>,
1464 v_range_b: Option<(f64, f64)>,
1465) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
1466 match (a, b) {
1467 (AnalyticSurface::Cone(cone), AnalyticSurface::Cylinder(cyl)) => {
1468 algebraic_parallel_cone_cylinder(cone, cyl, v_range_a, v_range_b)
1469 }
1470 (AnalyticSurface::Cylinder(cyl), AnalyticSurface::Cone(cone)) => {
1471 algebraic_parallel_cone_cylinder(cone, cyl, v_range_b, v_range_a)
1472 }
1473 (AnalyticSurface::Sphere(s1), AnalyticSurface::Sphere(s2)) => {
1474 algebraic_sphere_sphere(s1, s2).map(Some)
1475 }
1476 (AnalyticSurface::Cylinder(c1), AnalyticSurface::Cylinder(c2)) => {
1477 let axis_dot = c1.axis().dot(c2.axis()).abs();
1478 if axis_dot > 1.0 - 1e-10 {
1479 let delta = c2.origin() - c1.origin();
1481 let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
1482 let along = delta_vec.dot(c1.axis());
1483 let perp = (delta_vec - c1.axis() * along).length();
1484 if perp < 1e-8 {
1485 if (c1.radius() - c2.radius()).abs() < 1e-8 {
1488 return Ok(None); }
1490 return Ok(Some(vec![])); }
1492 }
1493 algebraic_cylinder_cylinder(c1, c2)
1495 }
1496 (AnalyticSurface::Sphere(s), AnalyticSurface::Cylinder(c))
1498 | (AnalyticSurface::Cylinder(c), AnalyticSurface::Sphere(s)) => {
1499 algebraic_sphere_cylinder(s, c)
1500 }
1501 (AnalyticSurface::Cone(c1), AnalyticSurface::Cone(c2)) => algebraic_cone_cone(c1, c2),
1502 _ => Ok(None),
1503 }
1504}
1505
1506pub fn exact_cone_cone(
1531 c1: &ConicalSurface,
1532 c2: &ConicalSurface,
1533) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
1534 let axis = c1.axis();
1535 let axis2 = c2.axis();
1536
1537 if axis.dot(axis2).abs() < 1.0 - 1e-10 {
1539 return Ok(None); }
1541 let apex1 = c1.apex();
1542 let apex2 = c2.apex();
1543 let delta = apex2 - apex1;
1544 let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
1545 let along = delta_v.dot(axis);
1546 if (delta_v - axis * along).length() > 1e-8 {
1547 return offset_parallel_cone_cone(c1, c2);
1548 }
1549
1550 let (s1, s2) = (c1.half_angle().sin(), c2.half_angle().sin());
1551 if s1.abs() < 1e-12 || s2.abs() < 1e-12 {
1552 return Ok(None); }
1554 let m1 = c1.half_angle().cos() / s1;
1555 let m2 = c2.half_angle().cos() / s2;
1556 let sigma = if axis.dot(axis2) >= 0.0 { 1.0 } else { -1.0 };
1557 let d2 = along; let denom = m1 - m2 * sigma;
1560 if denom.abs() < 1e-12 {
1561 if sigma > 0.0 && d2.abs() < 1e-9 {
1564 return Ok(None);
1565 }
1566 return Ok(Some(vec![]));
1567 }
1568
1569 let t_star = (-m2 * sigma * d2) / denom;
1570 let radius = m1 * t_star;
1571 if radius < 1e-12 {
1572 return Ok(Some(vec![])); }
1574
1575 let center = Point3::new(
1576 apex1.x() + axis.x() * t_star,
1577 apex1.y() + axis.y() * t_star,
1578 apex1.z() + axis.z() * t_star,
1579 );
1580 let circle = Circle3D::new(center, axis, radius)?;
1581 Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
1582}
1583
1584fn offset_parallel_cone_cone(
1595 c1: &ConicalSurface,
1596 c2: &ConicalSurface,
1597) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
1598 if c1.half_angle().sin().abs() < 1e-12 || c2.half_angle().sin().abs() < 1e-12 {
1599 return Ok(None); }
1601 let t1 = c1.half_angle().tan();
1602 let t2 = c2.half_angle().tan();
1603 if !t1.is_finite() || !t2.is_finite() {
1604 return Ok(None);
1605 }
1606 if (t1 - t2).abs() > 1e-9 * (1.0 + t1.abs().max(t2.abs())) {
1607 return Ok(None);
1608 }
1609
1610 let w = c1.axis();
1611 let apex1 = c1.apex();
1612 let apex2 = c2.apex();
1613 let delta = apex2 - apex1;
1614 let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
1615 let s = delta_v.dot(w);
1616 let tm = 0.5 * (t1 + t2);
1617 let k = 1.0 + tm * tm;
1618
1619 let n = (delta_v - w * (k * s)) * 2.0;
1623 let n_len = n.length();
1624 if n_len < 1e-12 {
1625 return Ok(None);
1626 }
1627 let n_hat = n * (1.0 / n_len);
1628 let d = (dot_np(n, apex1) + delta_v.dot(delta_v) - k * s * s) / n_len;
1629
1630 let axis2 = c2.axis();
1636 let scale = 1.0 + delta_v.length();
1637 let mut out = Vec::new();
1638 for curve in exact_plane_cone(c1, n_hat, d)? {
1639 let samples: Vec<Point3> = match &curve {
1640 ExactIntersectionCurve::Circle(c) => (0..4)
1641 .map(|i| crate::traits::ParametricCurve::evaluate(c, TAU * f64::from(i) / 4.0))
1642 .collect(),
1643 ExactIntersectionCurve::Ellipse(e) => (0..4)
1644 .map(|i| crate::traits::ParametricCurve::evaluate(e, TAU * f64::from(i) / 4.0))
1645 .collect(),
1646 ExactIntersectionCurve::Points(_) => return Ok(None),
1647 };
1648 let on_real_nappe = |p: &Point3| {
1649 let rel = *p - apex2;
1650 Vec3::new(rel.x(), rel.y(), rel.z()).dot(axis2) >= -1e-9 * scale
1651 };
1652 let hits = samples.iter().filter(|p| on_real_nappe(p)).count();
1653 match hits {
1654 0 => {}
1655 4 => out.push(curve),
1656 _ => return Ok(None),
1657 }
1658 }
1659 Ok(Some(out))
1660}
1661
1662pub fn exact_cone_cylinder(
1682 cone: &ConicalSurface,
1683 cyl: &CylindricalSurface,
1684) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
1685 let axis = cone.axis();
1686 let cyl_axis = cyl.axis();
1687
1688 if axis.dot(cyl_axis).abs() < 1.0 - 1e-10 {
1690 return Ok(None);
1691 }
1692 let apex = cone.apex();
1693 let delta = apex - cyl.origin();
1694 let delta_v = Vec3::new(delta.x(), delta.y(), delta.z());
1695 let along = delta_v.dot(cyl_axis);
1696 if (delta_v - cyl_axis * along).length() > 1e-8 {
1697 return Ok(None);
1698 }
1699
1700 let s = cone.half_angle().sin();
1701 if s.abs() < 1e-12 {
1702 return Ok(None); }
1704 let m = cone.half_angle().cos() / s; if m.abs() < 1e-12 {
1706 return Ok(None); }
1708
1709 let t_star = cyl.radius() / m; if t_star.abs() < 1e-12 {
1711 return Ok(Some(vec![])); }
1713 let center = Point3::new(
1714 apex.x() + axis.x() * t_star,
1715 apex.y() + axis.y() * t_star,
1716 apex.z() + axis.z() * t_star,
1717 );
1718 let circle = Circle3D::new(center, axis, cyl.radius())?;
1719 Ok(Some(vec![ExactIntersectionCurve::Circle(circle)]))
1720}
1721
1722fn algebraic_cone_cone(
1731 c1: &ConicalSurface,
1732 c2: &ConicalSurface,
1733) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
1734 let Some(exacts) = exact_cone_cone(c1, c2)? else {
1735 return Ok(None);
1736 };
1737 let mut curves = Vec::new();
1738 for exact in exacts {
1739 let n_samples = 33;
1740 let mut positions = Vec::with_capacity(n_samples);
1741 let mut points = Vec::with_capacity(n_samples);
1742 #[allow(clippy::cast_precision_loss)]
1743 for i in 0..n_samples {
1744 let theta = TAU * i as f64 / (n_samples - 1) as f64;
1745 let pt = match &exact {
1746 ExactIntersectionCurve::Circle(circle) => {
1747 crate::traits::ParametricCurve::evaluate(circle, theta)
1748 }
1749 ExactIntersectionCurve::Ellipse(ellipse) => {
1750 crate::traits::ParametricCurve::evaluate(ellipse, theta)
1751 }
1752 ExactIntersectionCurve::Points(_) => break,
1753 };
1754 positions.push(pt);
1755 points.push(IntersectionPoint {
1756 point: pt,
1757 param1: (0.0, 0.0),
1758 param2: (0.0, 0.0),
1759 });
1760 }
1761 if positions.is_empty() {
1762 continue;
1763 }
1764 let degree = 3.min(positions.len() - 1);
1765 let curve = interpolate(&positions, degree)?;
1766 curves.push(IntersectionCurve { curve, points });
1767 }
1768 Ok(Some(curves))
1769}
1770
1771pub fn exact_sphere_cylinder(
1791 sphere: &SphericalSurface,
1792 cyl: &CylindricalSurface,
1793) -> Result<Option<Vec<ExactIntersectionCurve>>, MathError> {
1794 let sc = sphere.center();
1795 let r_sphere = sphere.radius();
1796 let co = cyl.origin();
1797 let axis = cyl.axis();
1798 let r_cyl = cyl.radius();
1799
1800 let delta = sc - co;
1802 let delta_vec = Vec3::new(delta.x(), delta.y(), delta.z());
1803 let along = delta_vec.dot(axis);
1804 let perp_vec = delta_vec - axis * along;
1805 let d_perp = perp_vec.length();
1806
1807 if d_perp > 1e-7 {
1810 return Ok(None);
1811 }
1812
1813 if r_cyl > r_sphere + 1e-10 {
1816 return Ok(Some(vec![]));
1817 }
1818 let z_sq = r_sphere * r_sphere - r_cyl * r_cyl;
1819 if z_sq < 0.0 {
1820 return Ok(Some(vec![]));
1821 }
1822 let z = z_sq.sqrt();
1823
1824 let center_axis_pt = Point3::new(
1827 co.x() + axis.x() * along,
1828 co.y() + axis.y() * along,
1829 co.z() + axis.z() * along,
1830 );
1831
1832 let mut circles = Vec::new();
1833 let offsets: &[f64] = if z < 1e-10 { &[0.0] } else { &[z, -z] };
1834 for &z_offset in offsets {
1835 let center = Point3::new(
1836 center_axis_pt.x() + axis.x() * z_offset,
1837 center_axis_pt.y() + axis.y() * z_offset,
1838 center_axis_pt.z() + axis.z() * z_offset,
1839 );
1840 let circle = Circle3D::new(center, axis, r_cyl)?;
1841 circles.push(ExactIntersectionCurve::Circle(circle));
1842 }
1843 Ok(Some(circles))
1844}
1845
1846fn algebraic_sphere_cylinder(
1854 sphere: &SphericalSurface,
1855 cyl: &CylindricalSurface,
1856) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
1857 let Some(exacts) = exact_sphere_cylinder(sphere, cyl)? else {
1858 return Ok(None);
1859 };
1860
1861 let mut curves = Vec::new();
1862 for exact in exacts {
1863 let ExactIntersectionCurve::Circle(circle) = exact else {
1864 continue;
1865 };
1866 let n_samples = 33;
1867 let mut points = Vec::with_capacity(n_samples);
1868 let mut positions = Vec::with_capacity(n_samples);
1869 #[allow(clippy::cast_precision_loss)]
1870 for i in 0..n_samples {
1871 let theta = TAU * i as f64 / (n_samples - 1) as f64;
1872 let pt = crate::traits::ParametricCurve::evaluate(&circle, theta);
1873 positions.push(pt);
1874 points.push(IntersectionPoint {
1875 point: pt,
1876 param1: (0.0, 0.0),
1877 param2: (0.0, 0.0),
1878 });
1879 }
1880 let degree = 3.min(positions.len() - 1);
1881 let curve = interpolate(&positions, degree)?;
1882 curves.push(IntersectionCurve { curve, points });
1883 }
1884
1885 Ok(Some(curves))
1886}
1887
1888#[allow(clippy::too_many_lines, clippy::unnecessary_wraps)]
1902fn algebraic_cylinder_cylinder(
1903 c1: &CylindricalSurface,
1904 c2: &CylindricalSurface,
1905) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
1906 let alpha = c1.axis().dot(c2.axis());
1907 let a_coeff = 1.0 - alpha * alpha;
1908
1909 if a_coeff.abs() < 1e-12 {
1911 return Ok(None);
1912 }
1913
1914 let r1 = c1.radius();
1915 let r2 = c2.radius();
1916 let o1 = c1.origin();
1917 let o2 = c2.origin();
1918 let a1 = c1.axis();
1919 let a2 = c2.axis();
1920 let x1 = c1.x_axis();
1921 let y1 = c1.y_axis();
1922
1923 let delta = Vec3::new(o1.x() - o2.x(), o1.y() - o2.y(), o1.z() - o2.z());
1926 let cross = a1.cross(a2);
1927 let cross_len = cross.length();
1928 if cross_len > 1e-12 {
1929 let axis_dist = delta.dot(cross).abs() / cross_len;
1930 if axis_dist > r1 + r2 + Tolerance::new().linear {
1931 return Ok(Some(vec![])); }
1933 }
1934
1935 let n_samples = 128;
1940 let mut curve_plus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
1941 let mut curve_minus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
1942 let u_offset = TAU / (n_samples as f64 * 2.0); #[allow(clippy::cast_precision_loss)]
1947 for i in 0..n_samples {
1948 let u = u_offset + TAU * i as f64 / n_samples as f64;
1949 let (sin_u, cos_u) = u.sin_cos();
1950
1951 let qx = o1.x() + r1 * (cos_u * x1.x() + sin_u * y1.x()) - o2.x();
1954 let qy = o1.y() + r1 * (cos_u * x1.y() + sin_u * y1.y()) - o2.y();
1955 let qz = o1.z() + r1 * (cos_u * x1.z() + sin_u * y1.z()) - o2.z();
1956
1957 let q_dot_a1 = qx * a1.x() + qy * a1.y() + qz * a1.z();
1958 let q_dot_a2 = qx * a2.x() + qy * a2.y() + qz * a2.z();
1959 let q_sq = qx * qx + qy * qy + qz * qz;
1960
1961 let b_coeff = 2.0 * (q_dot_a1 - alpha * q_dot_a2);
1962 let c_coeff = q_sq - q_dot_a2 * q_dot_a2 - r2 * r2;
1963
1964 let disc = b_coeff * b_coeff - 4.0 * a_coeff * c_coeff;
1965 if disc < -Tolerance::new().linear {
1968 continue;
1969 }
1970
1971 let sqrt_disc = disc.max(0.0).sqrt();
1972 let v_plus = (-b_coeff + sqrt_disc) / (2.0 * a_coeff);
1973 let v_minus = (-b_coeff - sqrt_disc) / (2.0 * a_coeff);
1974
1975 curve_plus.push(c1.evaluate(u, v_plus));
1976 curve_minus.push(c1.evaluate(u, v_minus));
1977 }
1978
1979 if !curve_plus.is_empty() {
1982 curve_plus.push(curve_plus[0]);
1983 }
1984 if !curve_minus.is_empty() {
1985 curve_minus.push(curve_minus[0]);
1986 }
1987
1988 let mut curves = Vec::new();
1989
1990 for pts in [&curve_plus, &curve_minus] {
1991 if pts.len() < 4 {
1992 continue;
1993 }
1994
1995 let ipts: Vec<IntersectionPoint> = pts
1996 .iter()
1997 .map(|&p| {
1998 let (u1, v1) = c1.project_point(p);
1999 let (u2, v2) = c2.project_point(p);
2000 IntersectionPoint {
2001 point: p,
2002 param1: (u1, v1),
2003 param2: (u2, v2),
2004 }
2005 })
2006 .collect();
2007
2008 let degree = 3.min(pts.len() - 1);
2009 if let Ok(curve) = interpolate(pts, degree) {
2010 curves.push(IntersectionCurve {
2011 curve,
2012 points: ipts,
2013 });
2014 }
2015 }
2016
2017 Ok(Some(curves))
2018}
2019
2020#[allow(clippy::unnecessary_wraps)]
2046fn algebraic_parallel_cone_cylinder(
2047 cone: &ConicalSurface,
2048 cyl: &CylindricalSurface,
2049 v_range_cone: Option<(f64, f64)>,
2050 v_range_cyl: Option<(f64, f64)>,
2051) -> Result<Option<Vec<IntersectionCurve>>, MathError> {
2052 let axis = cone.axis();
2053 if axis.dot(cyl.axis()).abs() < 1.0 - 1e-10 {
2054 return Ok(None); }
2056
2057 let apex = cone.apex();
2058 let delta = cyl.origin() - apex;
2059 let along = delta.dot(axis);
2060 let perp = delta - axis * along;
2061 let d = perp.length();
2062 if d < 1e-9 {
2063 return Ok(None); }
2065
2066 let (e1, e2) = (cone.x_axis(), cone.y_axis());
2067 let phi0 = perp.dot(e2).atan2(perp.dot(e1));
2068
2069 let (sin_t, cos_t) = cone.half_angle().sin_cos();
2070 if cos_t < 1e-12 || sin_t < 1e-12 {
2071 return Ok(None);
2072 }
2073 let r = cyl.radius();
2074
2075 let mut v_min = (d - r).abs() / cos_t;
2077 let mut v_max = (d + r) / cos_t;
2078 if v_max <= v_min {
2079 return Ok(Some(vec![]));
2080 }
2081
2082 let mut lo = v_min;
2088 let mut hi = v_max;
2089 if let Some((a, b)) = v_range_cone {
2094 let (a, b) = if a <= b { (a, b) } else { (b, a) };
2095 lo = lo.max(a);
2096 hi = hi.min(b);
2097 }
2098 if let Some((a, b)) = v_range_cyl {
2099 let flip = cyl.axis().dot(axis);
2102 let to_cone_v = |cv: f64| (along + cv * flip) / sin_t;
2103 let (a, b) = (to_cone_v(a), to_cone_v(b));
2104 let (a, b) = if a <= b { (a, b) } else { (b, a) };
2105 lo = lo.max(a);
2106 hi = hi.min(b);
2107 }
2108 v_min = lo.max(v_min);
2109 v_max = hi.min(v_max);
2110 if v_max - v_min <= 1e-12 {
2111 return Ok(Some(vec![]));
2112 }
2113
2114 let n_samples = 128;
2115 let mut plus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
2116 let mut minus: Vec<Point3> = Vec::with_capacity(n_samples + 1);
2117 #[allow(clippy::cast_precision_loss)]
2118 for i in 0..=n_samples {
2119 let v = v_min + (v_max - v_min) * (i as f64) / (n_samples as f64);
2120 let rho = v * cos_t;
2121 if rho < 1e-12 {
2122 if (d - r).abs() < 1e-12 {
2130 let apex = cone.evaluate(phi0, v);
2131 plus.push(apex);
2132 minus.push(apex);
2133 }
2134 continue;
2135 }
2136 let cos_alpha = ((d * d + rho * rho - r * r) / (2.0 * d * rho)).clamp(-1.0, 1.0);
2137 let alpha = cos_alpha.acos();
2138 plus.push(cone.evaluate(phi0 + alpha, v));
2139 minus.push(cone.evaluate(phi0 - alpha, v));
2140 }
2141
2142 let mut curves = Vec::new();
2143 for pts in [&plus, &minus] {
2144 if pts.len() < 4 {
2147 continue;
2148 }
2149 let ipts: Vec<IntersectionPoint> = pts
2150 .iter()
2151 .map(|&p| IntersectionPoint {
2152 point: p,
2153 param1: cone.project_point(p),
2154 param2: cyl.project_point(p),
2155 })
2156 .collect();
2157 let degree = 3.min(pts.len() - 1);
2158 match interpolate(pts, degree) {
2159 Ok(curve) => curves.push(IntersectionCurve {
2160 curve,
2161 points: ipts,
2162 }),
2163 Err(_) => return Ok(None),
2168 }
2169 }
2170
2171 Ok(Some(curves))
2172}
2173
2174fn algebraic_sphere_sphere(
2182 s1: &SphericalSurface,
2183 s2: &SphericalSurface,
2184) -> Result<Vec<IntersectionCurve>, MathError> {
2185 let c1 = s1.center();
2186 let c2 = s2.center();
2187 let r1 = s1.radius();
2188 let r2 = s2.radius();
2189
2190 let delta = c2 - c1;
2191 let d_sq = delta.x() * delta.x() + delta.y() * delta.y() + delta.z() * delta.z();
2192 let d = d_sq.sqrt();
2193
2194 if d < 1e-12 {
2195 return Ok(vec![]);
2197 }
2198
2199 if d > r1 + r2 + 1e-10 {
2201 return Ok(vec![]); }
2203 if d + r2.min(r1) + 1e-10 < r1.max(r2) {
2204 return Ok(vec![]); }
2206
2207 let d1 = (d_sq + r1 * r1 - r2 * r2) / (2.0 * d);
2209
2210 let r_circle_sq = r1 * r1 - d1 * d1;
2212 if r_circle_sq < 0.0 {
2213 if r_circle_sq > -1e-10 {
2215 let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
2217 let tangent_pt = Point3::new(
2218 c1.x() + axis.x() * d1,
2219 c1.y() + axis.y() * d1,
2220 c1.z() + axis.z() * d1,
2221 );
2222 let ipt = IntersectionPoint {
2223 point: tangent_pt,
2224 param1: (0.0, 0.0),
2225 param2: (0.0, 0.0),
2226 };
2227 return Ok(vec![IntersectionCurve {
2229 curve: interpolate(&[tangent_pt, tangent_pt], 1)?,
2230 points: vec![ipt],
2231 }]);
2232 }
2233 return Ok(vec![]);
2234 }
2235
2236 let r_circle = r_circle_sq.sqrt();
2237 let axis = Vec3::new(delta.x() / d, delta.y() / d, delta.z() / d);
2238 let center = Point3::new(
2239 c1.x() + axis.x() * d1,
2240 c1.y() + axis.y() * d1,
2241 c1.z() + axis.z() * d1,
2242 );
2243
2244 let basis = Frame3::from_normal(center, axis)?;
2246 let u_dir = basis.x;
2247 let v_dir = basis.y;
2248
2249 let n_samples = 33; let mut points = Vec::with_capacity(n_samples);
2252 let mut positions = Vec::with_capacity(n_samples);
2253 #[allow(clippy::cast_precision_loss)]
2254 for i in 0..n_samples {
2255 let theta = TAU * i as f64 / (n_samples - 1) as f64;
2256 let (sin_t, cos_t) = theta.sin_cos();
2257 let pt = Point3::new(
2258 center.x() + (u_dir.x() * cos_t + v_dir.x() * sin_t) * r_circle,
2259 center.y() + (u_dir.y() * cos_t + v_dir.y() * sin_t) * r_circle,
2260 center.z() + (u_dir.z() * cos_t + v_dir.z() * sin_t) * r_circle,
2261 );
2262 positions.push(pt);
2263 points.push(IntersectionPoint {
2264 point: pt,
2265 param1: (0.0, 0.0),
2266 param2: (0.0, 0.0),
2267 });
2268 }
2269
2270 let degree = 3.min(positions.len() - 1);
2271 let curve = interpolate(&positions, degree)?;
2272
2273 Ok(vec![IntersectionCurve { curve, points }])
2274}
2275
2276#[allow(clippy::too_many_arguments)]
2282fn correct_to_intersection(
2283 a: &AnalyticSurface<'_>,
2284 b: &AnalyticSurface<'_>,
2285 surf_a: &dyn Fn(f64, f64) -> Point3,
2286 norm_a: &dyn Fn(f64, f64) -> Vec3,
2287 surf_b: &dyn Fn(f64, f64) -> Point3,
2288 norm_b: &dyn Fn(f64, f64) -> Vec3,
2289 point: Point3,
2290 u_range_a: (f64, f64),
2291 v_range_a: (f64, f64),
2292 u_range_b: (f64, f64),
2293 v_range_b: (f64, f64),
2294 max_iters: usize,
2295) -> Point3 {
2296 let mut p = point;
2297 for _ in 0..max_iters {
2298 let (ua, va) = project_analytic(a, p, u_range_a, v_range_a);
2299 let (ub, vb) = project_analytic(b, p, u_range_b, v_range_b);
2300 let pa = surf_a(ua, va);
2301 let pb = surf_b(ub, vb);
2302 let na = norm_a(ua, va);
2303 let nb = norm_b(ub, vb);
2304 let pv = Vec3::new(p.x(), p.y(), p.z());
2305
2306 let da = (pv - Vec3::new(pa.x(), pa.y(), pa.z())).dot(na);
2307 let db = (pv - Vec3::new(pb.x(), pb.y(), pb.z())).dot(nb);
2308
2309 if da.abs() < 1e-7 && db.abs() < 1e-7 {
2310 break;
2311 }
2312
2313 let t = na.cross(nb);
2314 let t_len = t.length();
2315 if t_len < 1e-10 {
2316 return Point3::new(
2318 (pa.x() + pb.x()) * 0.5,
2319 (pa.y() + pb.y()) * 0.5,
2320 (pa.z() + pb.z()) * 0.5,
2321 );
2322 }
2323 let t_hat = t * (1.0 / t_len);
2324
2325 let det = na.x() * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
2327 - na.y() * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
2328 + na.z() * (nb.x() * t_hat.y() - nb.y() * t_hat.x());
2329 if det.abs() < 1e-15 {
2330 return Point3::new(
2331 (pa.x() + pb.x()) * 0.5,
2332 (pa.y() + pb.y()) * 0.5,
2333 (pa.z() + pb.z()) * 0.5,
2334 );
2335 }
2336 let inv = 1.0 / det;
2337 let dx = inv
2339 * (-da * (nb.y() * t_hat.z() - nb.z() * t_hat.y())
2340 + db * (na.y() * t_hat.z() - na.z() * t_hat.y()));
2341 let dy = inv
2342 * (da * (nb.x() * t_hat.z() - nb.z() * t_hat.x())
2343 - db * (na.x() * t_hat.z() - na.z() * t_hat.x()));
2344 let dz = inv
2345 * (-da * (nb.x() * t_hat.y() - nb.y() * t_hat.x())
2346 + db * (na.x() * t_hat.y() - na.y() * t_hat.x()));
2347 let candidate = Point3::new(p.x() + dx, p.y() + dy, p.z() + dz);
2348
2349 let (uc, vc) = project_analytic(a, candidate, u_range_a, v_range_a);
2352 let (ud, vd) = project_analytic(b, candidate, u_range_b, v_range_b);
2353 let pc_a = surf_a(uc, vc);
2354 let pc_b = surf_b(ud, vd);
2355 let cv = Vec3::new(candidate.x(), candidate.y(), candidate.z());
2356 let da_new = (cv - Vec3::new(pc_a.x(), pc_a.y(), pc_a.z()))
2357 .dot(norm_a(uc, vc))
2358 .abs();
2359 let db_new = (cv - Vec3::new(pc_b.x(), pc_b.y(), pc_b.z()))
2360 .dot(norm_b(ud, vd))
2361 .abs();
2362 if da_new > da.abs() && db_new > db.abs() {
2363 return p;
2364 }
2365
2366 p = candidate;
2367 }
2368 p
2369}
2370
2371#[allow(clippy::too_many_arguments)]
2377fn march_analytic_intersection(
2378 a: &AnalyticSurface<'_>,
2379 b: &AnalyticSurface<'_>,
2380 surf_a: &dyn Fn(f64, f64) -> Point3,
2381 norm_a: &dyn Fn(f64, f64) -> Vec3,
2382 surf_b: &dyn Fn(f64, f64) -> Point3,
2383 norm_b: &dyn Fn(f64, f64) -> Vec3,
2384 seed: Point3,
2385 u_range_a: (f64, f64),
2386 v_range_a: (f64, f64),
2387 u_range_b: (f64, f64),
2388 v_range_b: (f64, f64),
2389 initial_step: f64,
2390 u_periodic_a: bool,
2391 u_periodic_b: bool,
2392) -> Vec<Point3> {
2393 let max_steps = 500;
2394 let h_min = 1e-6;
2395 let h_max = initial_step * 4.0;
2396 let closure_dist = initial_step * 5.0;
2400 let max_angle = 10.0_f64.to_radians();
2402 let min_angle = 2.0_f64.to_radians();
2403
2404 let mut forward = Vec::new();
2406 let mut backward = Vec::new();
2408
2409 for (direction, points) in [(1.0_f64, &mut forward), (-1.0_f64, &mut backward)] {
2410 let mut current = seed;
2411 let mut h = initial_step;
2412 let mut prev_tangent: Option<Vec3> = None;
2413
2414 for _ in 0..max_steps {
2415 let (ua, va) = project_analytic(a, current, u_range_a, v_range_a);
2416 let (ub, vb) = project_analytic(b, current, u_range_b, v_range_b);
2417
2418 let na = norm_a(ua, va);
2419 let nb = norm_b(ub, vb);
2420
2421 let tangent = na.cross(nb);
2422 let t_len = tangent.length();
2423 if t_len < 1e-10 {
2424 break;
2425 }
2426 let t_dir = tangent * (direction / t_len);
2427
2428 if let Some(prev_t) = prev_tangent {
2430 let cos_angle = prev_t.dot(t_dir).clamp(-1.0, 1.0);
2431 let angle = cos_angle.acos();
2432 if angle > max_angle && h > h_min {
2433 h = (h * 0.5).max(h_min);
2434 } else if angle < min_angle {
2435 h = (h * 2.0).min(h_max);
2436 }
2437 }
2438 prev_tangent = Some(t_dir);
2439
2440 let next = Point3::new(
2441 h.mul_add(t_dir.x(), current.x()),
2442 h.mul_add(t_dir.y(), current.y()),
2443 h.mul_add(t_dir.z(), current.z()),
2444 );
2445
2446 let (ua2, va2) = project_analytic(a, next, u_range_a, v_range_a);
2447 let (ub2, vb2) = project_analytic(b, next, u_range_b, v_range_b);
2448
2449 let pa = surf_a(ua2, va2);
2450 let pb = surf_b(ub2, vb2);
2451 let mid = Point3::new(
2452 (pa.x() + pb.x()) * 0.5,
2453 (pa.y() + pb.y()) * 0.5,
2454 (pa.z() + pb.z()) * 0.5,
2455 );
2456 let out_a = (!u_periodic_a && (ua2 <= u_range_a.0 || ua2 >= u_range_a.1))
2457 || va2 <= v_range_a.0
2458 || va2 >= v_range_a.1;
2459 let out_b = (!u_periodic_b && (ub2 <= u_range_b.0 || ub2 >= u_range_b.1))
2460 || vb2 <= v_range_b.0
2461 || vb2 >= v_range_b.1;
2462
2463 if out_a || out_b {
2464 break;
2465 }
2466
2467 let dist_to_seed = (mid - seed).length();
2471 if points.len() > 10 && dist_to_seed < closure_dist {
2472 points.push(seed);
2473 break;
2474 }
2475
2476 points.push(mid);
2477 current = mid;
2478 }
2479 }
2480
2481 backward.reverse();
2483 let mut result = backward;
2484 result.push(seed);
2485 result.append(&mut forward);
2486
2487 for pt in &mut result {
2489 *pt = correct_to_intersection(
2490 a, b, surf_a, norm_a, surf_b, norm_b, *pt, u_range_a, v_range_a, u_range_b, v_range_b,
2491 5,
2492 );
2493 }
2494
2495 result
2496}
2497
2498fn project_analytic(
2502 surface: &AnalyticSurface<'_>,
2503 point: Point3,
2504 u_range: (f64, f64),
2505 v_range: (f64, f64),
2506) -> (f64, f64) {
2507 match surface {
2508 AnalyticSurface::Cylinder(cyl) => {
2509 let (u, v) = cyl.project_point(point);
2510 (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
2511 }
2512 AnalyticSurface::Sphere(sphere) => {
2513 let (u, v) = sphere.project_point(point);
2514 (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
2515 }
2516 AnalyticSurface::Cone(cone) => {
2517 let (u, v) = cone.project_point(point);
2518 (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
2519 }
2520 AnalyticSurface::Torus(torus) => {
2521 let (u, v) = torus.project_point(point);
2522 (u.clamp(u_range.0, u_range.1), v.clamp(v_range.0, v_range.1))
2523 }
2524 }
2525}
2526
2527fn is_u_periodic(surface: &AnalyticSurface<'_>) -> bool {
2531 matches!(
2532 surface,
2533 AnalyticSurface::Cylinder(_)
2534 | AnalyticSurface::Cone(_)
2535 | AnalyticSurface::Sphere(_)
2536 | AnalyticSurface::Torus(_)
2537 )
2538}
2539
2540#[allow(clippy::type_complexity)]
2542fn surface_closures<'a>(
2543 surface: &'a AnalyticSurface<'a>,
2544) -> (
2545 Box<dyn Fn(f64, f64) -> Point3 + 'a>,
2546 Box<dyn Fn(f64, f64) -> Vec3 + 'a>,
2547 (f64, f64),
2548 (f64, f64),
2549) {
2550 match surface {
2551 AnalyticSurface::Cylinder(cyl) => (
2552 Box::new(|u, v| cyl.evaluate(u, v)),
2553 Box::new(|u, v| cyl.normal(u, v)),
2554 (0.0, TAU),
2555 (-1.0, 1.0),
2556 ),
2557 AnalyticSurface::Cone(cone) => (
2558 Box::new(|u, v| cone.evaluate(u, v)),
2559 Box::new(|u, v| cone.normal(u, v)),
2560 (0.0, TAU),
2561 (0.01, 2.0),
2562 ),
2563 AnalyticSurface::Sphere(sphere) => (
2564 Box::new(|u, v| sphere.evaluate(u, v)),
2565 Box::new(|u, v| sphere.normal(u, v)),
2566 (0.0, TAU),
2567 (-FRAC_PI_2, FRAC_PI_2),
2568 ),
2569 AnalyticSurface::Torus(torus) => (
2570 Box::new(|u, v| torus.evaluate(u, v)),
2571 Box::new(|u, v| torus.normal(u, v)),
2572 (0.0, TAU),
2573 (0.0, TAU),
2574 ),
2575 }
2576}
2577
2578#[cfg(test)]
2579#[allow(clippy::unwrap_used, clippy::expect_used)]
2580mod tests {
2581 use super::*;
2582 use crate::tolerance::Tolerance;
2583
2584 #[test]
2585 fn plane_cylinder_perpendicular() {
2586 let cyl =
2587 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
2588 .unwrap();
2589
2590 let curves = intersect_plane_cylinder(&cyl, Vec3::new(0.0, 0.0, 1.0), 3.0).unwrap();
2592 assert!(!curves.is_empty(), "should find intersection curve");
2593 assert!(
2594 curves[0].points.len() > 10,
2595 "should have many sample points"
2596 );
2597
2598 let tol = Tolerance::loose();
2599 for pt in &curves[0].points {
2600 assert!(
2601 tol.approx_eq(pt.point.z(), 3.0),
2602 "z should be ~3.0, got {}",
2603 pt.point.z()
2604 );
2605 let r = pt.point.x().hypot(pt.point.y());
2606 assert!(tol.approx_eq(r, 2.0), "radius should be ~2.0, got {r}");
2607 }
2608 }
2609
2610 #[test]
2611 fn plane_sphere_equator() {
2612 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 3.0).unwrap();
2613
2614 let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
2615 assert!(!curves.is_empty());
2616
2617 let tol = Tolerance::loose();
2618 for pt in &curves[0].points {
2619 assert!(
2620 tol.approx_eq(pt.point.z(), 0.0),
2621 "z should be ~0, got {}",
2622 pt.point.z()
2623 );
2624 let r = pt.point.x().hypot(pt.point.y());
2625 assert!(tol.approx_eq(r, 3.0), "radius should be ~3.0, got {r}");
2626 }
2627 }
2628
2629 #[test]
2630 fn plane_sphere_no_intersection() {
2631 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 1.0).unwrap();
2632
2633 let curves = intersect_plane_sphere(&sphere, Vec3::new(0.0, 0.0, 1.0), 5.0).unwrap();
2634 assert!(curves.is_empty());
2635 }
2636
2637 #[test]
2638 fn plane_cone_cross_section() {
2639 let cone = ConicalSurface::new(
2640 Point3::new(0.0, 0.0, 0.0),
2641 Vec3::new(0.0, 0.0, 1.0),
2642 std::f64::consts::FRAC_PI_4,
2643 )
2644 .unwrap();
2645
2646 let curves = intersect_plane_cone(&cone, Vec3::new(0.0, 0.0, 1.0), 1.0).unwrap();
2647 assert!(!curves.is_empty(), "should find intersection with cone");
2648 }
2649
2650 #[test]
2657 fn offset_parallel_equal_angle_cones_give_one_exact_ellipse() {
2658 let c1 = ConicalSurface::new(
2659 Point3::new(
2660 -16.999_999_999_999_975,
2661 -16.999_999_999_999_975,
2662 5.849_999_999_999_951,
2663 ),
2664 Vec3::new(0.0, 0.0, -1.0),
2665 0.785_398_163_397_433_5,
2666 )
2667 .unwrap();
2668 let c2 = ConicalSurface::new(
2669 Point3::new(
2670 -16.750_000_000_000_036,
2671 -16.750_000_000_000_018,
2672 0.749_999_999_999_881,
2673 ),
2674 Vec3::new(0.0, 0.0, 1.0),
2675 0.785_398_163_397_467_6,
2676 )
2677 .unwrap();
2678
2679 let curves = exact_cone_cone(&c1, &c2)
2680 .unwrap()
2681 .expect("offset parallel equal-angle cones must take the radical-plane path");
2682 assert_eq!(curves.len(), 1, "expected exactly one section conic");
2683 assert!(
2684 matches!(curves[0], ExactIntersectionCurve::Ellipse(_)),
2685 "expected an ellipse section, got {:?}",
2686 curves[0]
2687 );
2688 let ExactIntersectionCurve::Ellipse(ellipse) = &curves[0] else {
2689 return;
2690 };
2691
2692 for i in 0..16 {
2696 let p = crate::traits::ParametricCurve::evaluate(ellipse, TAU * f64::from(i) / 16.0);
2697 for (cone, label) in [(&c1, "c1"), (&c2, "c2")] {
2698 let rel = p - cone.apex();
2699 let rel_v = Vec3::new(rel.x(), rel.y(), rel.z());
2700 let axial = rel_v.dot(cone.axis());
2701 let radial = (rel_v - cone.axis() * axial).length();
2702 assert!(
2703 axial > 0.0,
2704 "{label}: sample on phantom nappe (axial {axial})"
2705 );
2706 let expect = cone.half_angle().tan() * axial;
2707 assert!(
2708 (radial - expect).abs() < 1e-9,
2709 "{label}: sample off surface by {}",
2710 (radial - expect).abs()
2711 );
2712 }
2713 }
2714 }
2715
2716 #[test]
2720 fn offset_parallel_cones_opening_apart_have_no_real_intersection() {
2721 let c1 = ConicalSurface::new(
2722 Point3::new(0.0, 0.0, 5.0),
2723 Vec3::new(0.0, 0.0, -1.0),
2724 std::f64::consts::FRAC_PI_4,
2725 )
2726 .unwrap();
2727 let c2 = ConicalSurface::new(
2728 Point3::new(0.25, 0.25, 20.0),
2729 Vec3::new(0.0, 0.0, 1.0),
2730 std::f64::consts::FRAC_PI_4,
2731 )
2732 .unwrap();
2733 let curves = exact_cone_cone(&c1, &c2)
2734 .unwrap()
2735 .expect("radical-plane path");
2736 assert!(curves.is_empty(), "disjoint nappes must yield no curves");
2737 }
2738
2739 #[test]
2742 fn offset_parallel_cones_with_unequal_angles_defer() {
2743 let c1 = ConicalSurface::new(
2744 Point3::new(0.0, 0.0, 5.0),
2745 Vec3::new(0.0, 0.0, -1.0),
2746 std::f64::consts::FRAC_PI_4,
2747 )
2748 .unwrap();
2749 let c2 = ConicalSurface::new(Point3::new(0.25, 0.25, 0.5), Vec3::new(0.0, 0.0, 1.0), 0.6)
2750 .unwrap();
2751 assert!(exact_cone_cone(&c1, &c2).unwrap().is_none());
2752 }
2753
2754 #[test]
2755 fn coaxial_cones_cross_at_single_circle() {
2756 let outer = ConicalSurface::new(
2761 Point3::new(0.0, 0.0, 50.0),
2762 Vec3::new(0.0, 0.0, -1.0),
2763 5.0_f64.atan(),
2764 )
2765 .unwrap();
2766 let inner = ConicalSurface::new(
2767 Point3::new(0.0, 0.0, 90.0),
2768 Vec3::new(0.0, 0.0, -1.0),
2769 10.0_f64.atan(),
2770 )
2771 .unwrap();
2772
2773 let curves = intersect_analytic_analytic_bounded(
2774 AnalyticSurface::Cone(&outer),
2775 AnalyticSurface::Cone(&inner),
2776 32,
2777 None,
2778 None,
2779 )
2780 .unwrap();
2781
2782 assert_eq!(
2783 curves.len(),
2784 1,
2785 "coaxial cones crossing at one circle must yield exactly one curve, got {}",
2786 curves.len()
2787 );
2788 for p in &curves[0].points {
2789 let r = p.point.x().hypot(p.point.y());
2790 assert!(
2791 (p.point.z() - 10.0).abs() < 1e-6 && (r - 8.0).abs() < 1e-6,
2792 "intersection point off the expected z=10,r=8 circle: {:?}",
2793 p.point
2794 );
2795 }
2796 }
2797
2798 #[test]
2799 fn plane_torus_cross_section() {
2800 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 5.0, 1.0).unwrap();
2801
2802 let curves = intersect_plane_torus(&torus, Vec3::new(0.0, 0.0, 1.0), 0.0).unwrap();
2803 assert!(
2804 !curves.is_empty(),
2805 "should find intersection curves with torus"
2806 );
2807 }
2808
2809 fn torus_implicit(p: Point3, major: f64, minor: f64) -> f64 {
2812 let rho = p.x().hypot(p.y());
2813 ((rho - major).hypot(p.z())) - minor
2814 }
2815
2816 #[test]
2822 fn parallel_cone_cylinder_gives_two_exact_branches() {
2823 use crate::traits::ParametricCurve;
2824 let cone = ConicalSurface::new(
2825 Point3::new(-5.45, -36.55, -4.85),
2826 Vec3::new(0.0, 0.0, 1.0),
2827 std::f64::consts::FRAC_PI_4,
2828 )
2829 .unwrap();
2830 let cyl = CylindricalSurface::new(
2831 Point3::new(-8.0, -34.0, -5.0),
2832 Vec3::new(0.0, 0.0, 1.0),
2833 4.45,
2834 )
2835 .unwrap();
2836 let v_hint = (1.484_924_240_492_058, 2.616_295_090_390_43);
2838 let curves = intersect_analytic_analytic_bounded(
2839 AnalyticSurface::Cone(&cone),
2840 AnalyticSurface::Cylinder(&cyl),
2841 32,
2842 Some(v_hint),
2843 Some((0.0, 2.5)),
2844 )
2845 .unwrap();
2846
2847 assert_eq!(curves.len(), 2, "expected exactly the two branches");
2848 for c in &curves {
2849 let (t0, t1) = c.curve.domain();
2850 for k in 0..=32 {
2851 let t = (t1 - t0).mul_add(f64::from(k) / 32.0, t0);
2852 let p = ParametricCurve::evaluate(&c.curve, t);
2853 let radial = ((p.x() + 8.0).powi(2) + (p.y() + 34.0).powi(2)).sqrt();
2855 assert!((radial - 4.45).abs() < 1e-6, "off cylinder: {radial}");
2856 let cone_r = ((p.x() + 5.45).powi(2) + (p.y() + 36.55).powi(2)).sqrt();
2858 assert!((cone_r - (p.z() + 4.85)).abs() < 1e-6, "off cone at {p:?}");
2859 assert!(p.z() >= -3.8 - 1e-9 && p.z() <= -3.0 + 1e-9, "z={}", p.z());
2861 }
2862 }
2863 }
2864
2865 #[test]
2868 fn coaxial_cone_cylinder_defers_to_other_paths() {
2869 let cone = ConicalSurface::new(
2870 Point3::new(0.0, 0.0, 0.0),
2871 Vec3::new(0.0, 0.0, 1.0),
2872 std::f64::consts::FRAC_PI_4,
2873 )
2874 .unwrap();
2875 let cyl =
2876 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 2.0)
2877 .unwrap();
2878 assert!(
2879 algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
2880 .unwrap()
2881 .is_none()
2882 );
2883 }
2884
2885 #[test]
2886 fn oblique_cone_cylinder_defers_to_other_paths() {
2887 let cone = ConicalSurface::new(
2888 Point3::new(0.0, 0.0, 0.0),
2889 Vec3::new(0.0, 0.0, 1.0),
2890 std::f64::consts::FRAC_PI_4,
2891 )
2892 .unwrap();
2893 let cyl =
2894 CylindricalSurface::new(Point3::new(3.0, 0.0, 1.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
2895 .unwrap();
2896 assert!(
2897 algebraic_parallel_cone_cylinder(&cone, &cyl, None, None)
2898 .unwrap()
2899 .is_none()
2900 );
2901 }
2902
2903 #[test]
2904 fn plane_torus_lobe_closes_and_stays_on_surface() {
2905 use crate::traits::ParametricCurve;
2906 let (major, minor) = (10.0, 3.0);
2907 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
2908
2909 for (n, d) in [
2913 (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), ] {
2917 let curves = intersect_plane_torus(&torus, n, d).unwrap();
2918 assert!(!curves.is_empty(), "plane n={n:?} d={d} found no curves");
2919 for c in &curves {
2920 let p0 = ParametricCurve::evaluate(&c.curve, 0.0);
2921 let p1 = ParametricCurve::evaluate(&c.curve, 1.0);
2922 assert!(
2923 (p0 - p1).length() < 1e-7,
2924 "lobe not closed: gap={} (n={n:?} d={d})",
2925 (p0 - p1).length()
2926 );
2927 for k in 0..=64 {
2929 let t = f64::from(k) / 64.0;
2930 let p = ParametricCurve::evaluate(&c.curve, t);
2931 assert!(
2932 torus_implicit(p, major, minor).abs() < 1e-2,
2933 "off-surface point {p:?} implicit={}",
2934 torus_implicit(p, major, minor)
2935 );
2936 }
2937 }
2938 }
2939 }
2940
2941 #[test]
2942 fn plane_torus_inner_tangent_figure_eight_stays_open() {
2943 use crate::traits::ParametricCurve;
2944 let (major, minor) = (10.0, 3.0);
2945 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), major, minor).unwrap();
2946
2947 let curves =
2953 intersect_plane_torus(&torus, Vec3::new(-1.0, 0.0, 0.0), -(major - minor)).unwrap();
2954 assert!(!curves.is_empty(), "inner-tangent plane found no curves");
2955 let max_gap = curves
2956 .iter()
2957 .map(|c| {
2958 let p0 = ParametricCurve::evaluate(&c.curve, 0.0);
2959 let p1 = ParametricCurve::evaluate(&c.curve, 1.0);
2960 (p0 - p1).length()
2961 })
2962 .fold(0.0_f64, f64::max);
2963 assert!(
2964 max_gap > 1e-2,
2965 "figure-eight chain was wrongly force-closed (max end-gap={max_gap})"
2966 );
2967 }
2968
2969 #[test]
2970 fn line_torus_box_edge_crossing_is_exact() {
2971 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
2974 let ts = intersect_line_torus(
2975 &torus,
2976 Point3::new(6.0, -4.0, -5.0),
2977 Vec3::new(0.0, 0.0, 1.0),
2978 );
2979 assert_eq!(ts.len(), 2, "expected 2 crossings, got {ts:?}");
2981 let zs: Vec<f64> = ts.iter().map(|t| -5.0 + t).collect();
2982 let rho = 6.0_f64.hypot(4.0);
2983 let z_exp = (9.0 - (rho - 10.0).powi(2)).sqrt();
2984 assert!(
2985 (zs[0] - (-z_exp)).abs() < 1e-9,
2986 "z0={} exp={}",
2987 zs[0],
2988 -z_exp
2989 );
2990 assert!((zs[1] - z_exp).abs() < 1e-9, "z1={} exp={}", zs[1], z_exp);
2991 for &t in &ts {
2993 let p = Point3::new(6.0, -4.0, -5.0 + t);
2994 let rho = p.x().hypot(p.y());
2995 let impl_v = (rho - 10.0).hypot(p.z()) - 3.0;
2996 assert!(impl_v.abs() < 1e-9, "off-torus impl={impl_v}");
2997 }
2998 }
2999
3000 #[test]
3001 fn line_torus_miss_and_tangent() {
3002 let torus = ToroidalSurface::new(Point3::new(0.0, 0.0, 0.0), 10.0, 3.0).unwrap();
3003 let miss = intersect_line_torus(
3005 &torus,
3006 Point3::new(20.0, 0.0, 0.0),
3007 Vec3::new(0.0, 0.0, 1.0),
3008 );
3009 assert!(miss.is_empty(), "expected no crossings, got {miss:?}");
3010 let axis =
3012 intersect_line_torus(&torus, Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0));
3013 assert!(axis.is_empty(), "z-axis should miss the tube, got {axis:?}");
3014 }
3015
3016 #[test]
3017 fn dispatch_via_analytic_surface() {
3018 let cyl =
3019 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
3020 .unwrap();
3021 let curves = intersect_plane_analytic(
3022 AnalyticSurface::Cylinder(&cyl),
3023 Vec3::new(0.0, 0.0, 1.0),
3024 0.0,
3025 )
3026 .unwrap();
3027 assert!(!curves.is_empty());
3028 }
3029
3030 #[test]
3031 fn perpendicular_cylinders_intersect() {
3032 let cyl_z =
3033 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
3034 .unwrap();
3035 let cyl_x =
3036 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), 1.0)
3037 .unwrap();
3038
3039 let curves = intersect_analytic_analytic(
3040 AnalyticSurface::Cylinder(&cyl_z),
3041 AnalyticSurface::Cylinder(&cyl_x),
3042 16,
3043 )
3044 .unwrap();
3045
3046 assert!(
3047 !curves.is_empty(),
3048 "perpendicular cylinders should intersect"
3049 );
3050
3051 for c in &curves {
3052 assert!(
3053 c.points.len() >= 2,
3054 "intersection curve should have >= 2 points, got {}",
3055 c.points.len()
3056 );
3057 }
3058 }
3059
3060 #[test]
3061 fn sphere_cylinder_intersect() {
3062 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 2.0).unwrap();
3063 let cyl =
3064 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 1.0)
3065 .unwrap();
3066
3067 let curves = intersect_analytic_analytic(
3068 AnalyticSurface::Sphere(&sphere),
3069 AnalyticSurface::Cylinder(&cyl),
3070 16,
3071 )
3072 .unwrap();
3073
3074 assert!(!curves.is_empty(), "sphere and cylinder should intersect");
3078 }
3079
3080 #[test]
3081 fn exact_sphere_cylinder_coaxial_two_circles() {
3082 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
3085 let cyl =
3086 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
3087 .unwrap();
3088 let circles = exact_sphere_cylinder(&sphere, &cyl)
3089 .unwrap()
3090 .expect("coaxial case returns Some");
3091 assert_eq!(circles.len(), 2, "through-bore meets the sphere twice");
3092 let mut zs: Vec<f64> = circles
3093 .iter()
3094 .filter_map(|c| match c {
3095 ExactIntersectionCurve::Circle(circle) => {
3096 assert!(
3097 (circle.radius() - 3.0).abs() < 1e-9,
3098 "rim radius == cyl radius"
3099 );
3100 Some(circle.center().z())
3101 }
3102 _ => None,
3103 })
3104 .collect();
3105 assert_eq!(zs.len(), 2, "both sections must be exact circles");
3106 zs.sort_by(f64::total_cmp);
3107 let z = 27.0_f64.sqrt();
3108 assert!((zs[0] + z).abs() < 1e-9 && (zs[1] - z).abs() < 1e-9);
3109 }
3110
3111 #[test]
3112 fn exact_sphere_cylinder_non_coaxial_defers() {
3113 let sphere = SphericalSurface::new(Point3::new(0.0, 0.0, 0.0), 6.0).unwrap();
3115 let cyl =
3116 CylindricalSurface::new(Point3::new(2.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 3.0)
3117 .unwrap();
3118 assert!(
3119 exact_sphere_cylinder(&sphere, &cyl).unwrap().is_none(),
3120 "non-coaxial sphere/cylinder defers to the marcher"
3121 );
3122 }
3123
3124 #[test]
3125 fn disjoint_cylinders_no_intersection() {
3126 let cyl_a =
3127 CylindricalSurface::new(Point3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
3128 .unwrap();
3129 let cyl_b =
3130 CylindricalSurface::new(Point3::new(5.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 0.5)
3131 .unwrap();
3132
3133 let curves = intersect_analytic_analytic(
3134 AnalyticSurface::Cylinder(&cyl_a),
3135 AnalyticSurface::Cylinder(&cyl_b),
3136 16,
3137 )
3138 .unwrap();
3139
3140 assert!(curves.is_empty(), "disjoint cylinders should not intersect");
3141 }
3142
3143 fn collect_points(curve: &ExactIntersectionCurve) -> Vec<Point3> {
3147 use crate::traits::ParametricCurve;
3148 match curve {
3149 ExactIntersectionCurve::Circle(c) => (0..=64)
3150 .map(|i| ParametricCurve::evaluate(c, TAU * f64::from(i) / 64.0))
3151 .collect(),
3152 ExactIntersectionCurve::Ellipse(e) => (0..=64)
3153 .map(|i| ParametricCurve::evaluate(e, TAU * f64::from(i) / 64.0))
3154 .collect(),
3155 ExactIntersectionCurve::Points(pts) => pts.clone(),
3156 }
3157 }
3158
3159 fn assert_on_plane_and_cone(
3162 curves: &[ExactIntersectionCurve],
3163 cone: &ConicalSurface,
3164 n: Vec3,
3165 d: f64,
3166 z_bound: (f64, f64),
3167 ) {
3168 assert!(!curves.is_empty(), "expected at least one section curve");
3169 let mut total = 0;
3170 for curve in curves {
3171 for p in collect_points(curve) {
3172 total += 1;
3173 let plane_err = (n.x() * p.x() + n.y() * p.y() + n.z() * p.z() - d).abs();
3174 assert!(
3175 plane_err < 1e-9,
3176 "point off plane by {plane_err:.2e}: {p:?}"
3177 );
3178 let (u, v) = cone.project_point(p);
3179 let q = cone.evaluate(u, v);
3180 let cone_err =
3181 ((p.x() - q.x()).powi(2) + (p.y() - q.y()).powi(2) + (p.z() - q.z()).powi(2))
3182 .sqrt();
3183 assert!(cone_err < 1e-7, "point off cone by {cone_err:.2e}: {p:?}");
3184 assert!(v >= -1e-9, "point on phantom nappe (v={v:.4}): {p:?}");
3185 assert!(
3186 p.z() >= z_bound.0 - 1e-6 && p.z() <= z_bound.1 + 1e-6,
3187 "point z={:.4} outside sane bound {z_bound:?}: {p:?}",
3188 p.z()
3189 );
3190 }
3191 }
3192 assert!(total >= 8, "too few section points ({total})");
3193 }
3194
3195 #[test]
3196 fn oblique_plane_cone_ellipse_is_exact_and_on_both() {
3197 let cone = ConicalSurface::new(
3201 Point3::new(0.0, 0.0, 0.0),
3202 Vec3::new(0.0, 0.0, 1.0),
3203 std::f64::consts::FRAC_PI_4,
3204 )
3205 .unwrap();
3206 let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
3207 let d = n.z() * 5.0;
3209 let curves = exact_plane_cone(&cone, n, d).unwrap();
3210 assert!(
3211 curves
3212 .iter()
3213 .any(|c| matches!(c, ExactIntersectionCurve::Ellipse(_))),
3214 "oblique steep plane × cone must yield an exact Ellipse"
3215 );
3216 assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 12.0));
3218 }
3219
3220 #[test]
3221 fn oblique_plane_cone_wrong_nappe_is_empty() {
3222 let cone = ConicalSurface::new(
3226 Point3::new(0.0, 0.0, 0.0),
3227 Vec3::new(0.0, 0.0, 1.0),
3228 std::f64::consts::FRAC_PI_4,
3229 )
3230 .unwrap();
3231 let n = Vec3::new(0.3, 0.0, 1.0).normalize().unwrap();
3232 let d = n.z() * -5.0;
3233 let curves = exact_plane_cone(&cone, n, d).unwrap();
3234 assert!(
3235 curves.is_empty(),
3236 "plane on the phantom-nappe side must yield no real curve, got {}",
3237 curves.len()
3238 );
3239 }
3240
3241 #[test]
3242 fn oblique_plane_cone_parabola_on_both_single_branch() {
3243 let cone = ConicalSurface::new(
3246 Point3::new(0.0, 0.0, 0.0),
3247 Vec3::new(0.0, 0.0, 1.0),
3248 std::f64::consts::FRAC_PI_4,
3249 )
3250 .unwrap();
3251 let n = Vec3::new(1.0, 0.0, 1.0).normalize().unwrap();
3252 let d = n.x() * 3.0 + n.z() * 3.0; let curves = exact_plane_cone(&cone, n, d).unwrap();
3254 assert_eq!(
3255 curves.len(),
3256 1,
3257 "a parabola is a single branch, got {}",
3258 curves.len()
3259 );
3260 assert_on_plane_and_cone(&curves, &cone, n, d, (0.0, 400.0));
3262 }
3263
3264 #[test]
3265 fn oblique_plane_cone_hyperbola_real_nappe_only() {
3266 let cone = ConicalSurface::new(
3274 Point3::new(-59.0, -59.0, 15.85),
3275 Vec3::new(0.0, 0.0, -1.0),
3276 std::f64::consts::FRAC_PI_4,
3277 )
3278 .unwrap();
3279 let n = Vec3::new(0.0, 0.995_18, 0.098_02).normalize().unwrap();
3280 let d = -58.360_56;
3281 let cos_theta = n.dot(cone.axis()).abs();
3282 assert!(cos_theta < 0.2, "expected a shallow (hyperbola) plane");
3283 let curves = exact_plane_cone(&cone, n, d).unwrap();
3284 assert_on_plane_and_cone(&curves, &cone, n, d, (5.0, 15.85));
3287 for c in &curves {
3289 assert!(
3290 matches!(c, ExactIntersectionCurve::Points(_)),
3291 "hyperbola must be sampled Points, not a closed conic"
3292 );
3293 }
3294 }
3295}