1use super::*;
2pub use super::recognition::{generatrix_is_meridional_half_ray, surface_scale};
3use super::revolution::{intersect_coaxial_revolutions, intersect_cylinder_radius_invariant, rotate_curve_about_axis};
4
5struct PlaneData {
7 origin: Vec3,
8 normal: Vec3,
9}
10
11fn plane_data(analytic: &AnalyticSurface) -> Option<PlaneData> {
12 match analytic {
13 AnalyticSurface::Plane {
14 origin,
15 u_dir,
16 v_dir,
17 ..
18 } => Some(PlaneData {
19 origin: *origin,
20 normal: u_dir.cross(*v_dir).normalized().ok()?,
21 }),
22 _ => None,
23 }
24}
25
26fn map_rational_curve(
31 curve: &NurbsCurve,
32 map: impl Fn(crate::Vec4) -> crate::Vec4,
33) -> Option<NurbsCurve> {
34 let mut controls = Vec::with_capacity(curve.control_points.len());
35 let mut sign = 0.0f64;
36 for point in &curve.control_points {
37 let image = map(*point);
38 if image.w == 0.0 || !image.w.is_finite() {
39 return None;
40 }
41 if sign == 0.0 {
42 sign = image.w.signum();
43 } else if image.w.signum() != sign {
44 return None;
45 }
46 controls.push(image);
47 }
48 if sign < 0.0 {
49 for point in &mut controls {
50 point.x = -point.x;
51 point.y = -point.y;
52 point.z = -point.z;
53 point.w = -point.w;
54 }
55 }
56 NurbsCurve::new(curve.degree, curve.knots.clone(), controls).ok()
57}
58
59fn cone_plane_open_section_enabled() -> bool {
64 crate::switch!(live "BREP_CONE_PLANE_OPEN_SECTION", false)
65}
66
67#[allow(clippy::too_many_arguments)]
78fn cone_plane_open_section(
79 frame: &RevolutionFrame,
80 height: f64,
81 apex: Vec3,
82 reference_rho: f64,
83 reference_z: f64,
84 k: f64,
85 normal: Vec3,
86 tolerance: f64,
87 project: &dyn Fn(crate::Vec4) -> crate::Vec4,
88) -> Option<Vec<NurbsCurve>> {
89 let center = frame.origin.add(frame.axis.scale(reference_z));
90 let a = center.sub(apex).dot(normal);
91 let b = reference_rho * frame.x_axis.dot(normal);
92 let c = reference_rho * frame.y_axis.dot(normal);
93 let r = (b * b + c * c).sqrt();
94 let z_apex = apex.sub(frame.origin).dot(frame.axis);
95 let big_k = k * (reference_z - z_apex);
97 let (band_low, band_high) = (0.0_f64.min(height), 0.0_f64.max(height));
98 let margin = tolerance.max(1e-12);
99 let axial = |theta: f64| -> Option<f64> {
100 let w = a + b * theta.cos() + c * theta.sin();
101 (w.abs() > 1e-300).then(|| z_apex + big_k / w)
102 };
103 let mut roots: Vec<f64> = Vec::new();
104 let mut solve = |target: f64| {
105 if r <= 0.0 {
107 return;
108 }
109 let ratio = (target - a) / r;
110 if ratio.abs() > 1.0 {
111 return;
112 }
113 let phi = c.atan2(b);
114 let spread = ratio.acos();
115 for theta in [phi + spread, phi - spread] {
116 roots.push(theta.rem_euclid(std::f64::consts::TAU));
117 }
118 };
119 solve(0.0);
120 for end in [band_low, band_high] {
121 let offset = end - z_apex;
122 if offset.abs() > 1e-300 {
123 solve(big_k / offset);
124 }
125 }
126 roots.sort_by(f64::total_cmp);
127 roots.dedup();
128 if roots.is_empty() {
129 roots.push(0.0);
130 }
131 let mut arcs = Vec::new();
132 for index in 0..roots.len() {
133 let start = roots[index];
134 let mut end = if index + 1 < roots.len() { roots[index + 1] } else { roots[0] + std::f64::consts::TAU };
135 if roots.len() == 1 {
136 end = start + std::f64::consts::TAU;
137 }
138 if !(end > start) {
142 continue;
143 }
144 let middle = 0.5 * (start + end);
145 let Some(z) = axial(middle) else { continue };
146 if z < band_low - margin || z > band_high + margin {
147 continue;
148 }
149 let arc = make_arc(center, frame.x_axis, frame.y_axis, reference_rho, start, end).ok()?;
150 arcs.push(map_rational_curve(&arc, project)?);
152 }
153 Some(arcs)
154}
155
156fn frame_circle(frame: &RevolutionFrame, rho: f64, z: f64) -> Option<NurbsCurve> {
159 make_arc(
160 frame.origin.add(frame.axis.scale(z)),
161 frame.x_axis,
162 frame.y_axis,
163 rho,
164 0.0,
165 std::f64::consts::TAU,
166 )
167 .ok()
168}
169
170pub fn intersect_analytic_pair(
174 first: &NurbsSurface,
175 second: &NurbsSurface,
176 tolerance: f64,
177) -> Option<Vec<NurbsCurve>> {
178 intersect_analytic_pair_with(first, second, tolerance, ruled_gate())
179}
180
181#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184pub enum RuledGate {
185 Count,
187 Geometry,
191}
192
193pub fn ruled_gate() -> RuledGate {
199 if std::env::var("BREP_RULED_GATE_GEOMETRY").as_deref() == Ok("0") {
200 RuledGate::Count
201 } else {
202 RuledGate::Geometry
203 }
204}
205
206pub fn intersect_analytic_pair_with(
209 first: &NurbsSurface,
210 second: &NurbsSurface,
211 tolerance: f64,
212 gate: RuledGate,
213) -> Option<Vec<NurbsCurve>> {
214 if let Some(curves) = intersect_recognized_pair(first, second, tolerance, gate) {
215 return Some(curves);
216 }
217 if crate::switch!("BREP_EXTRUSION_SECTIONS", true) {
218 for (plane, swept) in [(first,second),(second,first)] {
219 if matches!(swept.analytic(),Some(AnalyticSurface::Plane { .. })) { continue; }
220 if let (Some(plane),Some(extrusion)) = (plane.analytic().and_then(plane_data),swept.linear_extrusion()) {
221 if let Some(curves) = super::plane_extrusion_section(extrusion,plane.origin,plane.normal,tolerance) { return Some(curves); }
222 }
223 }
224 if !matches!(first.analytic(),Some(AnalyticSurface::Plane { .. })) && !matches!(second.analytic(),Some(AnalyticSurface::Plane { .. })) {
225 if let (Some(a),Some(b)) = (first.linear_extrusion(),second.linear_extrusion()) {
226 if let Some(curves) = super::parallel_extrusion_sections(a,b,tolerance) { return Some(curves); }
227 }
228 }
229 }
230 if let Some(curves) = intersect_plane_affine_sphere(first, second, tolerance) {
231 return Some(curves);
232 }
233 if let Some(curves) = intersect_coaxial_revolutions(first, second, tolerance) {
234 return Some(curves);
235 }
236 if coaxial_iso_section_enabled() {
237 if let Some(curves) = intersect_cylinder_radius_invariant(first, second, tolerance) {
238 return Some(curves);
239 }
240 if let Some(curves) = intersect_cylinder_radius_invariant(second, first, tolerance) {
241 return Some(curves);
242 }
243 }
244 if gate == RuledGate::Geometry && plane_revolution_section_enabled() {
248 if let Some(curves) = intersect_perpendicular_plane_revolution(first, second, tolerance) {
249 return Some(curves);
250 }
251 if let Some(curves) = intersect_perpendicular_plane_revolution(second, first, tolerance) {
252 return Some(curves);
253 }
254 }
255 if let Some(curves) = intersect_axial_plane_revolution(first, second, tolerance) {
256 return Some(curves);
257 }
258 intersect_axial_plane_revolution(second, first, tolerance)
259}
260
261fn coaxial_iso_section_enabled() -> bool {
266 crate::switch!("BREP_COAXIAL_ISO_SECTION", true)
267}
268
269fn plane_revolution_section_enabled() -> bool {
287 crate::switch!("BREP_PLANE_REVOLUTION_SECTION", true)
288}
289
290fn intersect_perpendicular_plane_revolution(
291 plane_surface: &NurbsSurface,
292 revolution: &NurbsSurface,
293 tolerance: f64,
294) -> Option<Vec<NurbsCurve>> {
295 let plane = plane_data(plane_surface.analytic()?)?;
296 if matches!(revolution.analytic(), Some(AnalyticSurface::Plane { .. })) {
297 return None;
298 }
299 let structure = super::revolution::revolution_structure(revolution)?;
300 let frame = &structure.frame;
301 if plane.normal.dot(frame.axis).abs() < 1.0 - 1e-12 {
302 return None;
303 }
304 let generatrix = &structure.generatrix;
305 let [start, end] = generatrix.domain().ok()?;
306 let height = |t: f64| -> Option<f64> { Some(generatrix.evaluate(t).ok()?.sub(plane.origin).dot(plane.normal)) };
307 let scale = surface_scale(revolution).max(1.0);
308 let band = tolerance.max(1e-9 * scale);
309 let spans = generatrix.knots.windows(2).filter(|pair| pair[1] > pair[0]).count().max(1);
310 let stations = 64 * spans;
311 let mut previous_t = start;
312 let mut previous = height(start)?;
313 if previous.abs() <= band || height(end)?.abs() <= band {
315 return None;
316 }
317 let mut roots = Vec::new();
318 for index in 1..=stations {
319 let t = start + (end - start) * index as f64 / stations as f64;
320 let value = height(t)?;
321 if value.abs() <= band && index < stations {
322 return None;
325 }
326 if (previous < 0.0) != (value < 0.0) {
327 let (mut lo, mut hi, mut lo_value) = (previous_t, t, previous);
328 for _ in 0..200 {
329 let middle = 0.5 * (lo + hi);
330 if middle <= lo || middle >= hi {
331 break;
332 }
333 let middle_value = height(middle)?;
334 if (middle_value < 0.0) == (lo_value < 0.0) {
335 lo = middle;
336 lo_value = middle_value;
337 } else {
338 hi = middle;
339 }
340 }
341 roots.push(0.5 * (lo + hi));
342 }
343 previous_t = t;
344 previous = value;
345 }
346 if roots.is_empty() {
347 return None;
348 }
349 let mut coefficient_signs = Vec::new();
354 for control in &generatrix.control_points {
355 if control.w <= 0.0 {
356 return None;
357 }
358 let value = control.point().ok()?.sub(plane.origin).dot(plane.normal);
359 if value.abs() <= band {
360 return None;
361 }
362 coefficient_signs.push(value > 0.0);
363 }
364 let sign_changes = coefficient_signs.windows(2).filter(|pair| pair[0] != pair[1]).count();
365 if sign_changes != roots.len() {
366 return None;
367 }
368 let radius_floor = (tolerance * 10.0).max(1e-9 * scale);
369 let mut curves = Vec::new();
370 for root in roots {
371 let derivatives = generatrix.derivatives(root, 1).ok()?;
372 let tangent = derivatives.get(1)?.normalized().ok()?;
373 if tangent.dot(plane.normal).abs() <= 1e-9 {
374 return None;
375 }
376 let point = generatrix.evaluate(root).ok()?;
377 let (_, radius, axial) = frame.cylindrical(point);
378 if radius <= radius_floor {
379 return None;
380 }
381 let center = frame.origin.add(frame.axis.scale(axial));
382 let phase = if generatrix_is_meridional_half_ray(generatrix, frame) {
385 0.0
386 } else {
387 let radial = point.sub(center);
388 radial.dot(frame.y_axis).atan2(radial.dot(frame.x_axis))
389 };
390 curves.push(make_arc(center, frame.x_axis, frame.y_axis, radius, phase, phase + structure.sweep).ok()?);
391 }
392 Some(curves)
393}
394
395fn intersect_axial_plane_revolution(
401 plane_surface: &NurbsSurface,
402 revolved: &NurbsSurface,
403 _tolerance: f64,
404) -> Option<Vec<NurbsCurve>> {
405 let plane = match plane_surface.analytic()? {
406 AnalyticSurface::Plane {
407 origin,
408 u_dir,
409 v_dir,
410 ..
411 } => (*origin, u_dir.cross(*v_dir).normalized().ok()?),
412 _ => return None,
413 };
414 let structure = revolution_structure(revolved)?;
415 if !generatrix_is_meridional_half_ray(&structure.generatrix, &structure.frame) {
416 return None;
417 }
418 let scale = surface_scale(plane_surface)
419 .max(surface_scale(revolved))
420 .max(1.0);
421 let (plane_origin, plane_normal) = plane;
422 if structure.frame.axis.dot(plane_normal).abs() > 1e-9 {
423 return None;
424 }
425 if structure
426 .frame
427 .origin
428 .sub(plane_origin)
429 .dot(plane_normal)
430 .abs()
431 > 1e-9 * scale
432 {
433 return None;
434 }
435 let radial = structure.frame.axis.cross(plane_normal).normalized().ok()?;
436 let tau = std::f64::consts::TAU;
437 let mut curves = Vec::new();
438 for direction in [radial, radial.scale(-1.0)] {
439 let mut angle = direction
440 .dot(structure.frame.y_axis)
441 .atan2(direction.dot(structure.frame.x_axis));
442 if angle < -1e-9 {
443 angle += tau;
444 }
445 if angle <= structure.sweep + 1e-9 {
446 curves.push(rotate_curve_about_axis(
447 &structure.generatrix,
448 structure.frame.origin,
449 structure.frame.axis,
450 angle.clamp(0.0, structure.sweep),
451 )?);
452 }
453 }
454 Some(curves)
455}
456
457fn intersect_plane_affine_sphere(
462 first: &NurbsSurface,
463 second: &NurbsSurface,
464 tolerance: f64,
465) -> Option<Vec<NurbsCurve>> {
466 for (plane_surface, other) in [(first, second), (second, first)] {
467 let Some(ellipsoid) = other.affine_sphere() else { continue };
468 let Some(plane) = plane_surface.analytic().and_then(plane_data) else { continue };
469 return ellipsoid.plane_section(plane.origin, plane.normal, tolerance);
470 }
471 None
472}
473
474fn intersect_recognized_pair(
475 first: &NurbsSurface,
476 second: &NurbsSurface,
477 tolerance: f64,
478 gate: RuledGate,
479) -> Option<Vec<NurbsCurve>> {
480 let a = first.analytic()?;
481 let b = second.analytic()?;
482 if !matches!(b, AnalyticSurface::Plane { .. }) {
483 if let Some(plane) = plane_data(a) {
484 return intersect_plane_quadric(&plane, b, tolerance, gate);
485 }
486 }
487 if !matches!(a, AnalyticSurface::Plane { .. }) {
488 if let Some(plane) = plane_data(b) {
489 return intersect_plane_quadric(&plane, a, tolerance, gate);
490 }
491 }
492 if let (Some((center_a, radius_a)), Some((center_b, radius_b))) =
495 (a.sphere_geometry(), b.sphere_geometry())
496 {
497 return intersect_sphere_sphere(center_a, radius_a, center_b, radius_b, tolerance);
498 }
499 if let Some(curves) = intersect_sphere_coaxial_ruled(a, b, tolerance, gate)
500 .or_else(|| intersect_sphere_coaxial_ruled(b, a, tolerance, gate))
501 {
502 return Some(curves);
503 }
504 if let Some(curves) = intersect_equal_cylinders_meeting_axes(first, second, a, b, tolerance, gate) {
505 return Some(curves);
506 }
507 if let Some(curves) = intersect_cones_sharing_a_ruling(a, b, tolerance, gate)
511 .or_else(|| intersect_cones_sharing_a_ruling(b, a, tolerance, gate))
512 {
513 return Some(curves);
514 }
515 None
522}
523
524fn sphere_cone_coaxial_enabled() -> bool {
528 crate::switch!(live "BREP_SPHERE_CONE_COAXIAL", false)
529}
530
531fn intersect_sphere_coaxial_ruled(
539 sphere: &AnalyticSurface,
540 ruled: &AnalyticSurface,
541 tolerance: f64,
542 gate: RuledGate,
543) -> Option<Vec<NurbsCurve>> {
544 if !sphere_cone_coaxial_enabled() {
545 return None;
546 }
547 let (center, radius) = sphere.sphere_geometry()?;
548 let (frame, rho0, rho1, height) = ruled_revolution_data(ruled, tolerance, gate)?;
549 let offset = center.sub(frame.origin);
550 let center_z = offset.dot(frame.axis);
551 let off_axis = offset.sub(frame.axis.scale(center_z)).length();
552 if off_axis > tolerance.max(1e-12) * (1.0 + radius) {
557 return None;
558 }
559 let margin = tolerance.max(1e-12);
560 let slope = (rho1 - rho0) / height;
561 let rho_center = rho0 + slope * center_z;
565 let a = 1.0 + slope * slope;
566 let b = 2.0 * slope * rho_center;
567 let c = rho_center * rho_center - radius * radius;
568 let discriminant = b * b - 4.0 * a * c;
569 let mut heights = Vec::new();
570 if discriminant > 0.0 {
571 let root = discriminant.sqrt();
572 let q = -0.5 * (b + if b >= 0.0 { root } else { -root });
573 if q != 0.0 {
574 heights.push(center_z + q / a);
575 heights.push(center_z + c / q);
576 } else {
577 heights.push(center_z);
578 }
579 }
580 let separation_bar = 2e-6 * radius * a;
588 if discriminant.abs() <= 1e-9 * (b * b + (4.0 * a * c).abs()).max(radius * radius * 1e-24)
589 || (discriminant > 0.0 && discriminant <= separation_bar * separation_bar)
590 {
591 return None;
592 }
593 let (band_low, band_high) = (0.0_f64.min(height), 0.0_f64.max(height));
594 let mut circles = Vec::new();
595 for z in heights {
596 let rho = rho0 + slope * z;
597 if rho < -margin || z < band_low - margin || z > band_high + margin || rho <= margin {
598 continue;
599 }
600 circles.push(frame_circle(&frame, rho, z)?);
601 }
602 Some(circles)
603}
604
605fn cone_shared_ruling_enabled() -> bool {
608 crate::switch!(live "BREP_CONE_SHARED_RULING", false)
609}
610
611struct ConeData {
614 apex: Vec3,
615 axis: Vec3,
616 cos2: f64,
617 frame: RevolutionFrame,
618 height: f64,
619 sweep: f64,
621 size: f64,
623}
624
625fn cone_data(quadric: &AnalyticSurface, tolerance: f64, gate: RuledGate) -> Option<ConeData> {
626 let (frame, rho0, rho1, height) = ruled_revolution_data(quadric, tolerance, gate)?;
627 let slope = (rho1 - rho0) / height;
628 if !(slope.is_finite() && slope.abs() > 1e-9) {
629 return None;
630 }
631 let apex = frame.origin.add(frame.axis.scale(-rho0 / slope));
632 let sweep = match quadric {
633 AnalyticSurface::Revolution { sweep, .. } => *sweep,
634 _ => std::f64::consts::TAU,
635 };
636 let size = height.abs().max(rho0.abs()).max(rho1.abs());
637 Some(ConeData { apex, axis: frame.axis, cos2: 1.0 / (1.0 + slope * slope), frame, height, sweep, size })
638}
639
640impl ConeData {
641 fn value(&self, point: Vec3) -> f64 {
643 let d = point.sub(self.apex);
644 let along = d.dot(self.axis);
645 along * along - self.cos2 * d.dot(d)
646 }
647
648 fn distance(&self, point: Vec3) -> f64 {
650 let d = point.sub(self.apex);
651 let gradient = self.axis.scale(2.0 * d.dot(self.axis)).sub(d.scale(2.0 * self.cos2));
652 let norm = gradient.length();
653 if norm > 0.0 { self.value(point).abs() / norm } else { d.length() }
654 }
655
656 fn matrix(&self) -> [[f64; 4]; 4] {
658 let d = [self.axis.x, self.axis.y, self.axis.z];
659 let a = [self.apex.x, self.apex.y, self.apex.z];
660 let mut m = [[0.0; 4]; 4];
661 let mut da = [0.0; 3];
662 for i in 0..3 {
663 for j in 0..3 {
664 m[i][j] = d[i] * d[j] - if i == j { self.cos2 } else { 0.0 };
665 }
666 }
667 for i in 0..3 {
668 da[i] = (0..3).map(|j| m[i][j] * a[j]).sum();
669 }
670 for i in 0..3 {
671 m[i][3] = -da[i];
672 m[3][i] = -da[i];
673 }
674 m[3][3] = (0..3).map(|i| a[i] * da[i]).sum();
675 m
676 }
677
678 fn within_sweep(&self, point: Vec3, slack: f64) -> bool {
681 if self.sweep >= std::f64::consts::TAU - 1e-12 {
682 return true;
683 }
684 match self.frame.cylindrical(point).0 {
685 None => true,
686 Some(theta) => theta <= self.sweep + slack || theta >= std::f64::consts::TAU - slack,
687 }
688 }
689
690 fn within_extent(&self, point: Vec3, slack: f64) -> bool {
693 let axial = point.sub(self.frame.origin).dot(self.frame.axis);
694 axial >= 0.0_f64.min(self.height) - slack && axial <= 0.0_f64.max(self.height) + slack
695 }
696
697 fn extent_along(&self, origin: Vec3, direction: Vec3) -> Option<[f64; 2]> {
700 let rate = direction.dot(self.frame.axis);
701 if rate.abs() <= 1e-12 {
702 return None;
703 }
704 let at = origin.sub(self.frame.origin).dot(self.frame.axis);
705 let (low, high) = (0.0_f64.min(self.height), 0.0_f64.max(self.height));
706 let (s0, s1) = ((low - at) / rate, (high - at) / rate);
707 Some([s0.min(s1), s0.max(s1)])
708 }
709}
710
711fn pieces_within_extent(curve: &NurbsCurve, cone: &ConeData, slack: f64) -> Option<Vec<NurbsCurve>> {
719 if curve.degree > 2 {
720 return None;
721 }
722 let (low, high) = (0.0_f64.min(cone.height) - slack, 0.0_f64.max(cone.height) + slack);
723 let axial_times_weight = |t: f64, bound: f64| -> Option<f64> {
724 let h = curve.evaluate_homogeneous(t).ok()?;
725 let along = Vec3::new(h.x, h.y, h.z).sub(cone.frame.origin.scale(h.w)).dot(cone.frame.axis);
726 Some(along - bound * h.w)
727 };
728 let mut breaks: Vec<f64> = curve.knots.iter().copied().collect();
729 breaks.sort_by(f64::total_cmp);
730 breaks.dedup();
731 let mut cuts = Vec::new();
732 for pair in breaks.windows(2) {
733 let (t0, t1) = (pair[0], pair[1]);
734 if !(t1 > t0) {
735 continue;
736 }
737 for bound in [low, high] {
738 let (f0, fm, f1) = (axial_times_weight(t0, bound)?, axial_times_weight(0.5 * (t0 + t1), bound)?, axial_times_weight(t1, bound)?);
740 let a = 2.0 * f1 - 4.0 * fm + 2.0 * f0;
741 let b = 4.0 * fm - f1 - 3.0 * f0;
742 let c = f0;
743 let mut roots = Vec::new();
744 if a.abs() <= 1e-14 * (b.abs() + c.abs()).max(1e-300) {
745 if b != 0.0 {
746 roots.push(-c / b);
747 }
748 } else {
749 let discriminant = b * b - 4.0 * a * c;
750 if discriminant >= 0.0 {
751 let root = discriminant.sqrt();
752 let q = -0.5 * (b + b.signum() * root);
753 if q != 0.0 {
754 roots.push(q / a);
755 roots.push(c / q);
756 }
757 }
758 }
759 for s in roots {
762 if s >= -1e-12 && s <= 1.0 + 1e-12 {
763 cuts.push(t0 + s.clamp(0.0, 1.0) * (t1 - t0));
764 }
765 }
766 }
767 }
768 cuts.sort_by(f64::total_cmp);
769 cuts.dedup();
770 let inside = |point: Vec3| cone.within_extent(point, slack);
771 let mut pieces = Vec::new();
772 let mut rest = curve.clone();
773 for cut in cuts {
774 let [r0, r1] = rest.domain().ok()?;
775 if cut <= r0 + 1e-12 * (r1 - r0).abs().max(1.0) || cut >= r1 - 1e-12 * (r1 - r0).abs().max(1.0) {
776 continue;
777 }
778 let (left, right) = rest.split(cut).ok()?;
779 pieces.push(left);
780 rest = right;
781 }
782 pieces.push(rest);
783 let mut kept = Vec::new();
784 for piece in pieces {
785 let [p0, p1] = piece.domain().ok()?;
786 if inside(piece.evaluate(0.5 * (p0 + p1)).ok()?) {
787 kept.push(piece);
788 }
789 }
790 Some(kept)
791}
792
793fn intersect_cones_sharing_a_ruling(
812 a: &AnalyticSurface,
813 b: &AnalyticSurface,
814 tolerance: f64,
815 gate: RuledGate,
816) -> Option<Vec<NurbsCurve>> {
817 if !cone_shared_ruling_enabled() {
818 return None;
819 }
820 let (first, second) = (cone_data(a, tolerance, gate)?, cone_data(b, tolerance, gate)?);
821 let between = second.apex.sub(first.apex);
822 let length = between.length();
823 let scale = 1.0 + first.size.max(second.size);
825 if !(length > 1e-9 * scale) {
826 return None;
827 }
828 let line = between.scale(1.0 / length);
829 for cone in [&first, &second] {
831 let along = line.dot(cone.axis);
832 if (along * along - cone.cos2).abs() > 1e-9 {
833 return None;
834 }
835 }
836 let normal_first = first.axis.cross(line).cross(line).normalized().ok()?;
838 let normal_second = second.axis.cross(line).cross(line).normalized().ok()?;
839 if normal_first.cross(normal_second).length() > 1e-9 {
840 return None;
841 }
842 let off = first.apex.add(normal_first.cross(line).scale(length.max(1.0)));
844 let (value_first, value_second) = (first.value(off), second.value(off));
845 if !(value_second.abs() > 1e-12 * (1.0 + value_first.abs())) {
846 return None;
847 }
848 let lambda = value_first / value_second;
849 let (m_first, m_second) = (first.matrix(), second.matrix());
850 let mut pencil = [[0.0; 4]; 4];
851 for i in 0..4 {
852 for j in 0..4 {
853 pencil[i][j] = m_first[i][j] - lambda * m_second[i][j];
854 }
855 }
856 let t = [normal_first.x, normal_first.y, normal_first.z, -normal_first.dot(first.apex)];
857 let homogeneous = |point: Vec3| [point.x, point.y, point.z, 1.0];
858 let apply = |m: &[[f64; 4]; 4], x: [f64; 4]| -> [f64; 4] {
859 let mut out = [0.0; 4];
860 for i in 0..4 {
861 out[i] = (0..4).map(|j| m[i][j] * x[j]).sum();
862 }
863 out
864 };
865 let dot4 = |p: [f64; 4], q: [f64; 4]| p[0] * q[0] + p[1] * q[1] + p[2] * q[2] + p[3] * q[3];
866 let y = homogeneous(first.apex.add(normal_first.scale(length.max(1.0))));
868 let s = dot4(t, y);
869 if !(s.abs() > 1e-12) {
870 return None;
871 }
872 let py = apply(&pencil, y);
873 let pi_y = dot4(y, py) / s;
874 let mut pi = [0.0; 4];
875 for i in 0..4 {
876 pi[i] = (2.0 * py[i] - t[i] * pi_y) / s;
877 }
878 for probe in [second.apex.add(Vec3::new(0.37, -0.21, 0.53).scale(length)), first.apex.add(Vec3::new(-0.44, 0.61, 0.17).scale(length)), off.add(line.scale(0.3 * length))] {
880 let x = homogeneous(probe);
881 let member = dot4(x, apply(&pencil, x));
882 let pair = dot4(t, x) * dot4(pi, x);
883 if (member - pair).abs() > 1e-8 * (1.0 + member.abs().max(pair.abs())) {
884 return None;
885 }
886 }
887 let mut curves = Vec::new();
888 if let (Some([a0, a1]), Some([b0, b1])) = (first.extent_along(first.apex, line), second.extent_along(first.apex, line)) {
890 let (s0, s1) = (a0.max(b0), a1.min(b1));
891 let (start, end) = (first.apex.add(line.scale(s0)), first.apex.add(line.scale(s1)));
892 let middle = start.add(end).scale(0.5);
893 if std::env::var_os("BREP_DEBUG_CONE_RULING").is_some() {
894 eprintln!(
895 "cone ruling: s [{s0:.6}, {s1:.6}] from {start:?} to {end:?}; middle theta first {:?} (sweep {:.6}) second {:?} (sweep {:.6})",
896 first.frame.cylindrical(middle).0, first.sweep, second.frame.cylindrical(middle).0, second.sweep
897 );
898 }
899 if s1 - s0 > tolerance.max(1e-12) && first.within_sweep(middle, 1e-9) && second.within_sweep(middle, 1e-9) {
902 curves.push(crate::make_line(start, end).ok()?);
903 }
904 }
905 let pi_normal = Vec3::new(pi[0], pi[1], pi[2]);
907 let pi_length = pi_normal.length();
908 if pi_length > 1e-12 * (1.0 + pi[3].abs()) {
909 let unit = pi_normal.scale(1.0 / pi_length);
910 let origin = pi_normal.scale(-pi[3] / (pi_length * pi_length));
911 let same_as_t = unit.cross(normal_first).length() <= 1e-9 && (unit.dot(first.apex) + pi[3] / pi_length).abs() <= tolerance;
912 if !same_as_t {
913 let plane = PlaneData { origin, normal: unit };
914 let conics = intersect_plane_quadric(&plane, a, tolerance, gate)?;
915 for conic in conics {
916 let [c0, c1] = conic.domain().ok()?;
917 let (mut inside, mut outside) = (0, 0);
918 for k in 0..=32 {
919 let point = conic.evaluate(c0 + (c1 - c0) * k as f64 / 32.0).ok()?;
920 if second.distance(point) > 1e3 * tolerance.max(1e-12) * scale {
921 return None;
922 }
923 if first.within_sweep(point, 1e-9) && second.within_sweep(point, 1e-9) {
924 inside += 1;
925 } else {
926 outside += 1;
927 }
928 }
929 if std::env::var_os("BREP_DEBUG_CONE_RULING").is_some() {
930 let ends = (conic.evaluate(c0).ok(), conic.evaluate(c1).ok());
931 eprintln!("cone ruling conic: inside {inside} outside {outside}; ends {ends:?}; sweeps {:.6} {:.6}", first.sweep, second.sweep);
932 }
933 let slack = tolerance.max(1e-12) * scale;
943 curves.extend(pieces_within_extent(&conic, &second, slack)?);
944 }
945 }
946 }
947 Some(curves)
948}
949
950fn equal_cylinder_sections_enabled() -> bool {
953 crate::switch!(live "BREP_EQUAL_CYLINDER_SECTIONS", true)
954}
955
956fn intersect_equal_cylinders_meeting_axes(
968 surface_a: &NurbsSurface,
969 surface_b: &NurbsSurface,
970 a: &AnalyticSurface,
971 b: &AnalyticSurface,
972 tolerance: f64,
973 gate: RuledGate,
974) -> Option<Vec<NurbsCurve>> {
975 if !equal_cylinder_sections_enabled() {
976 return None;
977 }
978 let (frame_a, rho0_a, rho1_a, _) = ruled_revolution_data(a, tolerance, gate)?;
979 let (frame_b, rho0_b, rho1_b, _) = ruled_revolution_data(b, tolerance, gate)?;
980 let band = tolerance.max(4.0 * f64::EPSILON * 1.0f64.max(rho0_a.abs()).max(rho0_b.abs()));
985 let same_radius = 16.0 * f64::EPSILON * 1.0f64.max(rho0_a.abs()).max(rho0_b.abs());
990 if (rho0_a - rho1_a).abs() > band || (rho0_b - rho1_b).abs() > band || (rho0_a - rho0_b).abs() > same_radius || rho0_a <= band {
991 return None;
992 }
993 let (radius, radius_b) = (rho0_a, rho0_b);
994 let (da, mut db) = (frame_a.axis.normalized().ok()?, frame_b.axis.normalized().ok()?);
995 if da.dot(db) < 0.0 {
996 db = db.scale(-1.0);
997 }
998 let cross = da.cross(db);
999 let sine = cross.length();
1000 if sine <= 1e-6 {
1003 return None;
1004 }
1005 let offset = frame_b.origin.sub(frame_a.origin);
1009 let skew = offset.dot(cross.scale(1.0 / sine)).abs();
1010 let meet = 16.0 * f64::EPSILON * 1.0f64.max(rho0_a.abs()).max(frame_a.origin.length()).max(frame_b.origin.length());
1011 if std::env::var_os("BREP_DEBUG_EQUAL_CYLINDERS").is_some() {
1012 eprintln!("equal cylinders: skew {skew:.3e} (round-off bar {meet:.3e}), radii {rho0_a} / {rho0_b}");
1013 }
1014 if skew > meet {
1015 return None;
1016 }
1017 let s = offset.cross(db).dot(cross) / (sine * sine);
1019 let centre = frame_a.origin.add(da.scale(s));
1020 let off_axis = |point: Vec3, origin: Vec3, axis: Vec3, rho: f64| {
1021 let delta = point.sub(origin);
1022 (delta.sub(axis.scale(delta.dot(axis))).length() - rho).abs()
1023 };
1024 for (surface, origin, axis, rho) in [(surface_a, frame_a.origin, da, radius), (surface_b, frame_b.origin, db, radius_b)] {
1028 let ([u0, u1], [v0, v1]) = (surface.domain_u().ok()?, surface.domain_v().ok()?);
1029 for i in 0..=6 {
1030 for j in 0..=6 {
1031 let point = surface.evaluate(u0 + (u1 - u0) * i as f64 / 6.0, v0 + (v1 - v0) * j as f64 / 6.0).ok()?;
1032 if off_axis(point, origin, axis, rho) > band {
1033 return None;
1034 }
1035 }
1036 }
1037 }
1038 let on_b = |point: Vec3| off_axis(point, frame_b.origin, db, radius_b);
1039 let mut curves = Vec::new();
1040 for normal in [da.sub(db), da.add(db)] {
1041 let normal = normal.normalized().ok()?;
1042 let plane = PlaneData { origin: centre, normal };
1043 for curve in intersect_plane_quadric(&plane, a, tolerance, gate)? {
1044 let [t0, t1] = curve.domain().ok()?;
1045 for index in 0..=16 {
1046 let point = curve.evaluate(t0 + (t1 - t0) * index as f64 / 16.0).ok()?;
1047 if on_b(point) > band * 10.0 {
1048 return None;
1049 }
1050 }
1051 curves.push(curve);
1052 }
1053 }
1054 Some(curves)
1055}
1056
1057fn ruled_revolution_data(
1064 quadric: &AnalyticSurface,
1065 tolerance: f64,
1066 gate: RuledGate,
1067) -> Option<(RevolutionFrame, f64, f64, f64)> {
1068 match quadric {
1069 AnalyticSurface::RuledRevolution {
1070 frame,
1071 rho0,
1072 rho1,
1073 height,
1074 } => Some((frame.clone(), *rho0, *rho1, *height)),
1075 AnalyticSurface::Revolution {
1076 frame, generatrix, ..
1077 } => {
1078 if !generatrix_is_meridional_half_ray(generatrix, frame) {
1081 return None;
1082 }
1083 let (start, end) = match gate {
1084 RuledGate::Count => {
1085 let controls = &generatrix.control_points;
1086 if generatrix.degree != 1
1087 || controls.len() != 2
1088 || (controls[0].w - 1.0).abs() > RECOGNITION_TOLERANCE
1089 || (controls[1].w - 1.0).abs() > RECOGNITION_TOLERANCE
1090 {
1091 return None;
1092 }
1093 (controls[0].point().ok()?, controls[1].point().ok()?)
1094 }
1095 RuledGate::Geometry => generatrix.straight_segment(tolerance)?,
1096 };
1097 let (_, rho0, z0) = frame.cylindrical(start);
1098 let (_, rho1, z1) = frame.cylindrical(end);
1099 let height = z1 - z0;
1100 if height.abs() <= 1e-12 * (1.0 + rho0.abs().max(rho1.abs())) {
1101 return None;
1102 }
1103 let origin = frame.origin.add(frame.axis.scale(z0));
1104 Some((
1105 RevolutionFrame {
1106 origin,
1107 ..frame.clone()
1108 },
1109 rho0,
1110 rho1,
1111 height,
1112 ))
1113 }
1114 _ => None,
1115 }
1116}
1117
1118pub fn ruled_gate_census(surface: &NurbsSurface, tolerance: f64) -> Option<String> {
1122 let quadric = surface.analytic()?;
1123 let AnalyticSurface::Revolution { generatrix, .. } = quadric else {
1124 return None;
1125 };
1126 let count = ruled_revolution_data(quadric, tolerance, RuledGate::Count).is_some();
1127 let geometry = ruled_revolution_data(quadric, tolerance, RuledGate::Geometry).is_some();
1128 if count == geometry {
1129 return None;
1130 }
1131 let controls = &generatrix.control_points;
1132 let points: Vec<Vec3> = controls
1133 .iter()
1134 .map(|control| control.point().unwrap_or_default())
1135 .collect();
1136 let (first, last) = (points[0], points[points.len() - 1]);
1137 let direction = last.sub(first);
1138 let length_squared = direction.length_squared();
1139 let mut collinearity = 0.0_f64;
1140 for point in &points {
1141 collinearity = collinearity.max(if length_squared <= 0.0 {
1142 point.sub(first).length()
1143 } else {
1144 let fraction = (point.sub(first).dot(direction) / length_squared).clamp(0.0, 1.0);
1145 point.sub(first.add(direction.scale(fraction))).length()
1146 });
1147 }
1148 let unit_weights = controls
1149 .iter()
1150 .all(|control| (control.w - 1.0).abs() <= RECOGNITION_TOLERANCE);
1151 Some(format!(
1152 "degree={} controls={} collinearity={collinearity:.3e} unit_weights={unit_weights} \
1153 count_gate={count} geometry_gate={geometry}",
1154 generatrix.degree,
1155 controls.len()
1156 ))
1157}
1158
1159fn degenerate_apex_frustum(rho0: f64, rho1: f64, height: f64) -> bool {
1180 if std::env::var("BREP_CONE_APEX_GUARD").as_deref() == Ok("0") {
1181 return false;
1182 }
1183 let delta = rho1 - rho0;
1184 delta * delta <= 64.0 * f64::EPSILON * height.abs() * rho0.abs().max(rho1.abs())
1185}
1186
1187pub fn plane_ruled_section_arc(
1223 plane_origin: Vec3,
1224 plane_normal: Vec3,
1225 frame: &RevolutionFrame,
1226 rho0: f64,
1227 rho1: f64,
1228 height: f64,
1229 start_azimuth: f64,
1230 sweep: f64,
1231 tolerance: f64,
1232) -> Result<NurbsCurve, String> {
1233 let tau = std::f64::consts::TAU;
1234 if !(start_azimuth.is_finite() && sweep.is_finite()) {
1235 return Err("plane_ruled_section_arc: non-finite azimuth range".into());
1236 }
1237 if sweep <= 1e-12 || sweep > tau + 1e-9 {
1238 return Err(format!(
1239 "plane_ruled_section_arc: the section arc sweeps {sweep:.6e} rad, which is not a \
1240 positive arc of at most one turn — refusing"
1241 ));
1242 }
1243 let normal = plane_normal.normalized()?;
1244 let radius_scale = rho0.abs().max(rho1.abs()).max(1.0);
1245 let axis = frame.axis;
1246 let is_cylinder = (rho1 - rho0).abs() <= 1e-9 * radius_scale
1247 || degenerate_apex_frustum(rho0, rho1, height);
1248 let curve = if is_cylinder {
1249 let alignment = normal.dot(axis);
1250 if alignment.abs() <= 1e-12 {
1251 return Err(
1252 "plane_ruled_section_arc: the plane is parallel to the cylinder axis, so the \
1253 section is a generatrix pair rather than a conic — refusing"
1254 .into(),
1255 );
1256 }
1257 if rho0.abs() <= tolerance {
1258 return Err("plane_ruled_section_arc: the cylinder carrier has no radius".into());
1259 }
1260 let base = make_arc(
1261 frame.origin,
1262 frame.x_axis,
1263 frame.y_axis,
1264 rho0.abs(),
1265 start_azimuth,
1266 start_azimuth + sweep,
1267 )?;
1268 let origin_dot = plane_origin.dot(normal);
1269 map_rational_curve(&base, |p| {
1270 let t = (origin_dot * p.w - Vec3::new(p.x, p.y, p.z).dot(normal)) / alignment;
1271 crate::Vec4 {
1272 x: p.x + axis.x * t,
1273 y: p.y + axis.y * t,
1274 z: p.z + axis.z * t,
1275 w: p.w,
1276 }
1277 })
1278 .ok_or_else(|| {
1279 "plane_ruled_section_arc: the cylinder section's weights are not one-signed \
1280 — refusing"
1281 .to_string()
1282 })?
1283 } else {
1284 let apex = frame.origin.add(axis.scale(height * rho0 / (rho0 - rho1)));
1285 let k = plane_origin.sub(apex).dot(normal);
1286 if k.abs() <= tolerance {
1287 return Err(
1288 "plane_ruled_section_arc: the plane passes through the cone apex, so the \
1289 section is a line pair rather than a conic — refusing"
1290 .into(),
1291 );
1292 }
1293 let (reference_rho, reference_z) = if rho0.abs() > rho1.abs() {
1294 (rho0.abs(), 0.0)
1295 } else {
1296 (rho1.abs(), height)
1297 };
1298 if reference_rho <= tolerance {
1299 return Err("plane_ruled_section_arc: the cone carrier degenerates to its apex".into());
1300 }
1301 let base = make_arc(
1302 frame.origin.add(axis.scale(reference_z)),
1303 frame.x_axis,
1304 frame.y_axis,
1305 reference_rho,
1306 start_azimuth,
1307 start_azimuth + sweep,
1308 )?;
1309 map_rational_curve(&base, |p| {
1310 let relative = Vec3::new(p.x - p.w * apex.x, p.y - p.w * apex.y, p.z - p.w * apex.z);
1311 let w_new = relative.dot(normal);
1312 let scaled = relative.scale(k);
1313 crate::Vec4 {
1314 x: apex.x * w_new + scaled.x,
1315 y: apex.y * w_new + scaled.y,
1316 z: apex.z * w_new + scaled.z,
1317 w: w_new,
1318 }
1319 })
1320 .ok_or_else(|| {
1321 "plane_ruled_section_arc: the section crosses the cone's apex plane (a parabolic \
1322 or hyperbolic branch, whose weights change sign) — refusing"
1323 .to_string()
1324 })?
1325 };
1326 let [d0, d1] = curve.domain()?;
1330 let slope = if height == 0.0 {
1331 0.0
1332 } else {
1333 (rho1 - rho0) / height
1334 };
1335 for step in 0..=8 {
1336 let point = curve.evaluate(d0 + (d1 - d0) * (step as f64 / 8.0))?;
1337 let delta = point.sub(frame.origin);
1338 let axial = delta.dot(axis);
1339 let radial = delta.sub(axis.scale(axial)).length();
1340 let off_ruled = (radial - (rho0 + slope * axial)).abs();
1341 let off_plane = point.sub(plane_origin).dot(normal).abs();
1342 if off_ruled > 10.0 * tolerance || off_plane > 10.0 * tolerance {
1343 return Err(format!(
1344 "plane_ruled_section_arc: the section does not lie on both carriers (off ruled \
1345 {off_ruled:.3e}, off plane {off_plane:.3e}) — refusing"
1346 ));
1347 }
1348 }
1349 Ok(curve)
1350}
1351
1352fn intersect_plane_quadric(
1353 plane: &PlaneData,
1354 quadric: &AnalyticSurface,
1355 tolerance: f64,
1356 gate: RuledGate,
1357) -> Option<Vec<NurbsCurve>> {
1358 match quadric {
1359 AnalyticSurface::RuledRevolution { .. } | AnalyticSurface::Revolution { .. }
1360 if ruled_revolution_data(quadric, tolerance, gate).is_some() =>
1361 {
1362 let (frame, rho0, rho1, height) = ruled_revolution_data(quadric, tolerance, gate)?;
1363 let (frame, rho0, rho1, height) = (&frame, &rho0, &rho1, &height);
1364 let alignment = plane.normal.dot(frame.axis);
1365 if alignment.abs() >= 1.0 - 1e-12 {
1366 let z = plane.origin.sub(frame.origin).dot(frame.axis);
1368 let t = z / height;
1369 if !(-1e-9..=1.0 + 1e-9).contains(&t) {
1370 return Some(Vec::new());
1371 }
1372 let rho = rho0 + (rho1 - rho0) * t.clamp(0.0, 1.0);
1373 if rho <= tolerance {
1374 return Some(Vec::new());
1375 }
1376 return Some(vec![frame_circle(frame, rho, z)?]);
1377 }
1378 if (rho1 - rho0).abs() <= 1e-12 || degenerate_apex_frustum(*rho0, *rho1, *height) {
1379 if alignment.abs() <= 1e-12 {
1381 return cylinder_parallel_plane_lines(plane, frame, *rho0, *height, tolerance);
1384 }
1385 let circle = frame_circle(frame, *rho0, 0.0)?;
1388 let denominator = alignment;
1389 let origin_dot = plane.origin.dot(plane.normal);
1390 let normal = plane.normal;
1391 let axis = frame.axis;
1392 let ellipse = map_rational_curve(&circle, |p| {
1393 let t = (origin_dot * p.w - Vec3::new(p.x, p.y, p.z).dot(normal)) / denominator;
1394 crate::Vec4 {
1395 x: p.x + axis.x * t,
1396 y: p.y + axis.y * t,
1397 z: p.z + axis.z * t,
1398 w: p.w,
1399 }
1400 })?;
1401 if !section_within_band(&ellipse, frame, *height, tolerance) {
1402 return Some(Vec::new());
1403 }
1404 return Some(vec![ellipse]);
1405 }
1406 let apex_t = rho0 / (rho0 - rho1);
1410 let apex = frame.origin.add(frame.axis.scale(height * apex_t));
1411 let reference_rho = if rho0.abs() > rho1.abs() {
1412 *rho0
1413 } else {
1414 *rho1
1415 };
1416 let reference_z = if rho0.abs() > rho1.abs() {
1417 0.0
1418 } else {
1419 *height
1420 };
1421 let circle = frame_circle(frame, reference_rho, reference_z)?;
1422 let k = plane.origin.sub(apex).dot(plane.normal);
1423 if k.abs() <= tolerance {
1424 return None;
1426 }
1427 let normal = plane.normal;
1428 let project = |p: crate::Vec4| {
1429 let relative =
1430 Vec3::new(p.x - p.w * apex.x, p.y - p.w * apex.y, p.z - p.w * apex.z);
1431 let w_new = relative.dot(normal);
1432 let scaled = relative.scale(k);
1433 crate::Vec4 {
1434 x: apex.x * w_new + scaled.x,
1435 y: apex.y * w_new + scaled.y,
1436 z: apex.z * w_new + scaled.z,
1437 w: w_new,
1438 }
1439 };
1440 let Some(conic) = map_rational_curve(&circle, project) else {
1441 if cone_plane_open_section_enabled() {
1443 return cone_plane_open_section(frame, *height, apex, reference_rho, reference_z, k, normal, tolerance, &project);
1444 }
1445 return None;
1446 };
1447 if !section_within_band(&conic, frame, *height, tolerance) {
1448 return Some(Vec::new());
1449 }
1450 Some(vec![conic])
1451 }
1452 AnalyticSurface::Sphere { frame, radius } => {
1453 plane_sphere_section(plane, frame.origin, *radius, tolerance)
1454 }
1455 AnalyticSurface::Torus {
1456 frame,
1457 major_radius,
1458 minor_radius,
1459 } => plane_torus_section(plane, frame, *major_radius, *minor_radius, tolerance),
1460 AnalyticSurface::Plane { .. } => None,
1461 AnalyticSurface::RuledRevolution { .. } => None,
1462 AnalyticSurface::Revolution { .. } => {
1468 if let Some((center, radius)) = quadric.sphere_geometry() {
1469 return plane_sphere_section(plane, center, radius, tolerance);
1470 }
1471 if let Some((frame, major_radius, minor_radius)) = quadric.torus_geometry() {
1472 return plane_torus_section(plane, &frame, major_radius, minor_radius, tolerance);
1473 }
1474 None
1475 }
1476 }
1477}
1478
1479fn plane_sphere_section(
1482 plane: &PlaneData,
1483 center: Vec3,
1484 radius: f64,
1485 tolerance: f64,
1486) -> Option<Vec<NurbsCurve>> {
1487 let distance = center.sub(plane.origin).dot(plane.normal);
1488 if distance.abs() >= radius - tolerance {
1489 return Some(Vec::new());
1490 }
1491 let circle_center = center.sub(plane.normal.scale(distance));
1492 let circle_radius = (radius * radius - distance * distance).sqrt();
1493 let x_axis = plane.normal.perpendicular().ok()?;
1494 let y_axis = plane.normal.cross(x_axis);
1495 Some(vec![make_arc(
1496 circle_center,
1497 x_axis,
1498 y_axis,
1499 circle_radius,
1500 0.0,
1501 std::f64::consts::TAU,
1502 )
1503 .ok()?])
1504}
1505
1506fn plane_torus_section(
1511 plane: &PlaneData,
1512 frame: &RevolutionFrame,
1513 major_radius: f64,
1514 minor_radius: f64,
1515 tolerance: f64,
1516) -> Option<Vec<NurbsCurve>> {
1517 let alignment = plane.normal.dot(frame.axis);
1518 if alignment.abs() < 1.0 - 1e-12 {
1519 return None;
1520 }
1521 let z = plane.origin.sub(frame.origin).dot(frame.axis);
1522 if z.abs() >= minor_radius - tolerance {
1523 return Some(Vec::new());
1524 }
1525 let offset = (minor_radius * minor_radius - z * z).sqrt();
1526 let mut circles = Vec::new();
1527 for rho in [major_radius - offset, major_radius + offset] {
1528 if rho > tolerance {
1529 circles.push(frame_circle(frame, rho, z)?);
1530 }
1531 }
1532 Some(circles)
1533}
1534
1535fn section_within_band(
1552 curve: &NurbsCurve,
1553 frame: &RevolutionFrame,
1554 height: f64,
1555 tolerance: f64,
1556) -> bool {
1557 let (band_low, band_high) = if height >= 0.0 {
1558 (0.0, height)
1559 } else {
1560 (height, 0.0)
1561 };
1562 let margin = tolerance.max(1e-9) + 1e-9;
1563 let mut min_z = f64::INFINITY;
1564 let mut max_z = f64::NEG_INFINITY;
1565 for p in &curve.control_points {
1566 let z = Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w)
1567 .sub(frame.origin)
1568 .dot(frame.axis);
1569 min_z = min_z.min(z);
1570 max_z = max_z.max(z);
1571 }
1572 max_z >= band_low - margin && min_z <= band_high + margin
1574}
1575
1576fn cylinder_parallel_plane_lines(
1577 plane: &PlaneData,
1578 frame: &RevolutionFrame,
1579 radius: f64,
1580 height: f64,
1581 tolerance: f64,
1582) -> Option<Vec<NurbsCurve>> {
1583 let axis_to_plane = plane.origin.sub(frame.origin).dot(plane.normal);
1585 if axis_to_plane.abs() >= radius - tolerance {
1586 return Some(Vec::new());
1587 }
1588 let chord_half = (radius * radius - axis_to_plane * axis_to_plane).sqrt();
1590 let chord_direction = frame.axis.cross(plane.normal).normalized().ok()?;
1591 let foot = frame.origin.add(plane.normal.scale(axis_to_plane));
1592 let mut lines = Vec::new();
1593 for sign in [-1.0, 1.0] {
1594 let base = foot.add(chord_direction.scale(sign * chord_half));
1595 let top = base.add(frame.axis.scale(height));
1596 lines.push(crate::make_line(base, top).ok()?);
1597 }
1598 Some(lines)
1599}
1600
1601fn intersect_sphere_sphere(
1602 center_a: Vec3,
1603 radius_a: f64,
1604 center_b: Vec3,
1605 radius_b: f64,
1606 tolerance: f64,
1607) -> Option<Vec<NurbsCurve>> {
1608 let offset = center_b.sub(center_a);
1609 let distance = offset.length();
1610 if distance <= tolerance {
1611 return if (radius_a - radius_b).abs() <= tolerance {
1614 None
1615 } else {
1616 Some(Vec::new())
1617 };
1618 }
1619 if distance >= radius_a + radius_b - tolerance
1620 || distance <= (radius_a - radius_b).abs() + tolerance
1621 {
1622 return Some(Vec::new());
1623 }
1624 let normal = offset.scale(1.0 / distance);
1625 let along =
1626 (distance * distance + radius_a * radius_a - radius_b * radius_b) / (2.0 * distance);
1627 let circle_radius_squared = radius_a * radius_a - along * along;
1628 if circle_radius_squared <= tolerance * tolerance {
1629 return Some(Vec::new());
1630 }
1631 let center = center_a.add(normal.scale(along));
1632 let x_axis = normal.perpendicular().ok()?;
1633 let y_axis = normal.cross(x_axis);
1634 Some(vec![make_arc(
1635 center,
1636 x_axis,
1637 y_axis,
1638 circle_radius_squared.sqrt(),
1639 0.0,
1640 std::f64::consts::TAU,
1641 )
1642 .ok()?])
1643}
1644
1645
1646
1647