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 frame_circle(frame: &RevolutionFrame, rho: f64, z: f64) -> Option<NurbsCurve> {
62 make_arc(
63 frame.origin.add(frame.axis.scale(z)),
64 frame.x_axis,
65 frame.y_axis,
66 rho,
67 0.0,
68 std::f64::consts::TAU,
69 )
70 .ok()
71}
72
73pub fn intersect_analytic_pair(
77 first: &NurbsSurface,
78 second: &NurbsSurface,
79 tolerance: f64,
80) -> Option<Vec<NurbsCurve>> {
81 intersect_analytic_pair_with(first, second, tolerance, ruled_gate())
82}
83
84#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub enum RuledGate {
88 Count,
90 Geometry,
94}
95
96pub fn ruled_gate() -> RuledGate {
102 if std::env::var("BREP_RULED_GATE_GEOMETRY").as_deref() == Ok("0") {
103 RuledGate::Count
104 } else {
105 RuledGate::Geometry
106 }
107}
108
109pub fn intersect_analytic_pair_with(
112 first: &NurbsSurface,
113 second: &NurbsSurface,
114 tolerance: f64,
115 gate: RuledGate,
116) -> Option<Vec<NurbsCurve>> {
117 if let Some(curves) = intersect_recognized_pair(first, second, tolerance, gate) {
118 return Some(curves);
119 }
120 if let Some(curves) = intersect_plane_affine_sphere(first, second, tolerance) {
121 return Some(curves);
122 }
123 if let Some(curves) = intersect_coaxial_revolutions(first, second, tolerance) {
124 return Some(curves);
125 }
126 if coaxial_iso_section_enabled() {
127 if let Some(curves) = intersect_cylinder_radius_invariant(first, second, tolerance) {
128 return Some(curves);
129 }
130 if let Some(curves) = intersect_cylinder_radius_invariant(second, first, tolerance) {
131 return Some(curves);
132 }
133 }
134 if gate == RuledGate::Geometry && plane_revolution_section_enabled() {
138 if let Some(curves) = intersect_perpendicular_plane_revolution(first, second, tolerance) {
139 return Some(curves);
140 }
141 if let Some(curves) = intersect_perpendicular_plane_revolution(second, first, tolerance) {
142 return Some(curves);
143 }
144 }
145 if let Some(curves) = intersect_axial_plane_revolution(first, second, tolerance) {
146 return Some(curves);
147 }
148 intersect_axial_plane_revolution(second, first, tolerance)
149}
150
151fn coaxial_iso_section_enabled() -> bool {
156 crate::switch!("BREP_COAXIAL_ISO_SECTION", true)
157}
158
159fn plane_revolution_section_enabled() -> bool {
177 crate::switch!("BREP_PLANE_REVOLUTION_SECTION", true)
178}
179
180fn intersect_perpendicular_plane_revolution(
181 plane_surface: &NurbsSurface,
182 revolution: &NurbsSurface,
183 tolerance: f64,
184) -> Option<Vec<NurbsCurve>> {
185 let plane = plane_data(plane_surface.analytic()?)?;
186 if matches!(revolution.analytic(), Some(AnalyticSurface::Plane { .. })) {
187 return None;
188 }
189 let structure = super::revolution::revolution_structure(revolution)?;
190 let frame = &structure.frame;
191 if plane.normal.dot(frame.axis).abs() < 1.0 - 1e-12 {
192 return None;
193 }
194 let generatrix = &structure.generatrix;
195 let [start, end] = generatrix.domain().ok()?;
196 let height = |t: f64| -> Option<f64> { Some(generatrix.evaluate(t).ok()?.sub(plane.origin).dot(plane.normal)) };
197 let scale = surface_scale(revolution).max(1.0);
198 let band = tolerance.max(1e-9 * scale);
199 let spans = generatrix.knots.windows(2).filter(|pair| pair[1] > pair[0]).count().max(1);
200 let stations = 64 * spans;
201 let mut previous_t = start;
202 let mut previous = height(start)?;
203 if previous.abs() <= band || height(end)?.abs() <= band {
205 return None;
206 }
207 let mut roots = Vec::new();
208 for index in 1..=stations {
209 let t = start + (end - start) * index as f64 / stations as f64;
210 let value = height(t)?;
211 if value.abs() <= band && index < stations {
212 return None;
215 }
216 if (previous < 0.0) != (value < 0.0) {
217 let (mut lo, mut hi, mut lo_value) = (previous_t, t, previous);
218 for _ in 0..200 {
219 let middle = 0.5 * (lo + hi);
220 if middle <= lo || middle >= hi {
221 break;
222 }
223 let middle_value = height(middle)?;
224 if (middle_value < 0.0) == (lo_value < 0.0) {
225 lo = middle;
226 lo_value = middle_value;
227 } else {
228 hi = middle;
229 }
230 }
231 roots.push(0.5 * (lo + hi));
232 }
233 previous_t = t;
234 previous = value;
235 }
236 if roots.is_empty() {
237 return None;
238 }
239 let mut coefficient_signs = Vec::new();
244 for control in &generatrix.control_points {
245 if control.w <= 0.0 {
246 return None;
247 }
248 let value = control.point().ok()?.sub(plane.origin).dot(plane.normal);
249 if value.abs() <= band {
250 return None;
251 }
252 coefficient_signs.push(value > 0.0);
253 }
254 let sign_changes = coefficient_signs.windows(2).filter(|pair| pair[0] != pair[1]).count();
255 if sign_changes != roots.len() {
256 return None;
257 }
258 let radius_floor = (tolerance * 10.0).max(1e-9 * scale);
259 let mut curves = Vec::new();
260 for root in roots {
261 let derivatives = generatrix.derivatives(root, 1).ok()?;
262 let tangent = derivatives.get(1)?.normalized().ok()?;
263 if tangent.dot(plane.normal).abs() <= 1e-9 {
264 return None;
265 }
266 let point = generatrix.evaluate(root).ok()?;
267 let (_, radius, axial) = frame.cylindrical(point);
268 if radius <= radius_floor {
269 return None;
270 }
271 let center = frame.origin.add(frame.axis.scale(axial));
272 curves.push(make_arc(center, frame.x_axis, frame.y_axis, radius, 0.0, structure.sweep).ok()?);
273 }
274 Some(curves)
275}
276
277fn intersect_axial_plane_revolution(
283 plane_surface: &NurbsSurface,
284 revolved: &NurbsSurface,
285 _tolerance: f64,
286) -> Option<Vec<NurbsCurve>> {
287 let plane = match plane_surface.analytic()? {
288 AnalyticSurface::Plane {
289 origin,
290 u_dir,
291 v_dir,
292 ..
293 } => (*origin, u_dir.cross(*v_dir).normalized().ok()?),
294 _ => return None,
295 };
296 let structure = revolution_structure(revolved)?;
297 if !generatrix_is_meridional_half_ray(&structure.generatrix, &structure.frame) {
298 return None;
299 }
300 let scale = surface_scale(plane_surface)
301 .max(surface_scale(revolved))
302 .max(1.0);
303 let (plane_origin, plane_normal) = plane;
304 if structure.frame.axis.dot(plane_normal).abs() > 1e-9 {
305 return None;
306 }
307 if structure
308 .frame
309 .origin
310 .sub(plane_origin)
311 .dot(plane_normal)
312 .abs()
313 > 1e-9 * scale
314 {
315 return None;
316 }
317 let radial = structure.frame.axis.cross(plane_normal).normalized().ok()?;
318 let tau = std::f64::consts::TAU;
319 let mut curves = Vec::new();
320 for direction in [radial, radial.scale(-1.0)] {
321 let mut angle = direction
322 .dot(structure.frame.y_axis)
323 .atan2(direction.dot(structure.frame.x_axis));
324 if angle < -1e-9 {
325 angle += tau;
326 }
327 if angle <= structure.sweep + 1e-9 {
328 curves.push(rotate_curve_about_axis(
329 &structure.generatrix,
330 structure.frame.origin,
331 structure.frame.axis,
332 angle.clamp(0.0, structure.sweep),
333 )?);
334 }
335 }
336 Some(curves)
337}
338
339fn intersect_plane_affine_sphere(
344 first: &NurbsSurface,
345 second: &NurbsSurface,
346 tolerance: f64,
347) -> Option<Vec<NurbsCurve>> {
348 for (plane_surface, other) in [(first, second), (second, first)] {
349 let Some(ellipsoid) = other.affine_sphere() else { continue };
350 let Some(plane) = plane_surface.analytic().and_then(plane_data) else { continue };
351 return ellipsoid.plane_section(plane.origin, plane.normal, tolerance);
352 }
353 None
354}
355
356fn intersect_recognized_pair(
357 first: &NurbsSurface,
358 second: &NurbsSurface,
359 tolerance: f64,
360 gate: RuledGate,
361) -> Option<Vec<NurbsCurve>> {
362 let a = first.analytic()?;
363 let b = second.analytic()?;
364 if !matches!(b, AnalyticSurface::Plane { .. }) {
365 if let Some(plane) = plane_data(a) {
366 return intersect_plane_quadric(&plane, b, tolerance, gate);
367 }
368 }
369 if !matches!(a, AnalyticSurface::Plane { .. }) {
370 if let Some(plane) = plane_data(b) {
371 return intersect_plane_quadric(&plane, a, tolerance, gate);
372 }
373 }
374 if let (Some((center_a, radius_a)), Some((center_b, radius_b))) =
377 (a.sphere_geometry(), b.sphere_geometry())
378 {
379 return intersect_sphere_sphere(center_a, radius_a, center_b, radius_b, tolerance);
380 }
381 None
388}
389
390fn ruled_revolution_data(
397 quadric: &AnalyticSurface,
398 tolerance: f64,
399 gate: RuledGate,
400) -> Option<(RevolutionFrame, f64, f64, f64)> {
401 match quadric {
402 AnalyticSurface::RuledRevolution {
403 frame,
404 rho0,
405 rho1,
406 height,
407 } => Some((frame.clone(), *rho0, *rho1, *height)),
408 AnalyticSurface::Revolution {
409 frame, generatrix, ..
410 } => {
411 let (start, end) = match gate {
412 RuledGate::Count => {
413 let controls = &generatrix.control_points;
414 if generatrix.degree != 1
415 || controls.len() != 2
416 || (controls[0].w - 1.0).abs() > RECOGNITION_TOLERANCE
417 || (controls[1].w - 1.0).abs() > RECOGNITION_TOLERANCE
418 {
419 return None;
420 }
421 (controls[0].point().ok()?, controls[1].point().ok()?)
422 }
423 RuledGate::Geometry => generatrix.straight_segment(tolerance)?,
424 };
425 let (_, rho0, z0) = frame.cylindrical(start);
426 let (_, rho1, z1) = frame.cylindrical(end);
427 let height = z1 - z0;
428 if height.abs() <= 1e-12 * (1.0 + rho0.abs().max(rho1.abs())) {
429 return None;
430 }
431 let origin = frame.origin.add(frame.axis.scale(z0));
432 Some((
433 RevolutionFrame {
434 origin,
435 ..frame.clone()
436 },
437 rho0,
438 rho1,
439 height,
440 ))
441 }
442 _ => None,
443 }
444}
445
446pub fn ruled_gate_census(surface: &NurbsSurface, tolerance: f64) -> Option<String> {
450 let quadric = surface.analytic()?;
451 let AnalyticSurface::Revolution { generatrix, .. } = quadric else {
452 return None;
453 };
454 let count = ruled_revolution_data(quadric, tolerance, RuledGate::Count).is_some();
455 let geometry = ruled_revolution_data(quadric, tolerance, RuledGate::Geometry).is_some();
456 if count == geometry {
457 return None;
458 }
459 let controls = &generatrix.control_points;
460 let points: Vec<Vec3> = controls
461 .iter()
462 .map(|control| control.point().unwrap_or_default())
463 .collect();
464 let (first, last) = (points[0], points[points.len() - 1]);
465 let direction = last.sub(first);
466 let length_squared = direction.length_squared();
467 let mut collinearity = 0.0_f64;
468 for point in &points {
469 collinearity = collinearity.max(if length_squared <= 0.0 {
470 point.sub(first).length()
471 } else {
472 let fraction = (point.sub(first).dot(direction) / length_squared).clamp(0.0, 1.0);
473 point.sub(first.add(direction.scale(fraction))).length()
474 });
475 }
476 let unit_weights = controls
477 .iter()
478 .all(|control| (control.w - 1.0).abs() <= RECOGNITION_TOLERANCE);
479 Some(format!(
480 "degree={} controls={} collinearity={collinearity:.3e} unit_weights={unit_weights} \
481 count_gate={count} geometry_gate={geometry}",
482 generatrix.degree,
483 controls.len()
484 ))
485}
486
487fn degenerate_apex_frustum(rho0: f64, rho1: f64, height: f64) -> bool {
508 if std::env::var("BREP_CONE_APEX_GUARD").as_deref() == Ok("0") {
509 return false;
510 }
511 let delta = rho1 - rho0;
512 delta * delta <= 64.0 * f64::EPSILON * height.abs() * rho0.abs().max(rho1.abs())
513}
514
515pub fn plane_ruled_section_arc(
548 plane_origin: Vec3,
549 plane_normal: Vec3,
550 frame: &RevolutionFrame,
551 rho0: f64,
552 rho1: f64,
553 height: f64,
554 start_azimuth: f64,
555 sweep: f64,
556 tolerance: f64,
557) -> Result<NurbsCurve, String> {
558 let tau = std::f64::consts::TAU;
559 if !(start_azimuth.is_finite() && sweep.is_finite()) {
560 return Err("plane_ruled_section_arc: non-finite azimuth range".into());
561 }
562 if sweep <= 1e-12 || sweep > tau + 1e-9 {
563 return Err(format!(
564 "plane_ruled_section_arc: the section arc sweeps {sweep:.6e} rad, which is not a \
565 positive arc of at most one turn — refusing"
566 ));
567 }
568 let normal = plane_normal.normalized()?;
569 let radius_scale = rho0.abs().max(rho1.abs()).max(1.0);
570 let axis = frame.axis;
571 let is_cylinder = (rho1 - rho0).abs() <= 1e-9 * radius_scale
572 || degenerate_apex_frustum(rho0, rho1, height);
573 let curve = if is_cylinder {
574 let alignment = normal.dot(axis);
575 if alignment.abs() <= 1e-12 {
576 return Err(
577 "plane_ruled_section_arc: the plane is parallel to the cylinder axis, so the \
578 section is a generatrix pair rather than a conic — refusing"
579 .into(),
580 );
581 }
582 if rho0.abs() <= tolerance {
583 return Err("plane_ruled_section_arc: the cylinder carrier has no radius".into());
584 }
585 let base = make_arc(
586 frame.origin,
587 frame.x_axis,
588 frame.y_axis,
589 rho0.abs(),
590 start_azimuth,
591 start_azimuth + sweep,
592 )?;
593 let origin_dot = plane_origin.dot(normal);
594 map_rational_curve(&base, |p| {
595 let t = (origin_dot * p.w - Vec3::new(p.x, p.y, p.z).dot(normal)) / alignment;
596 crate::Vec4 {
597 x: p.x + axis.x * t,
598 y: p.y + axis.y * t,
599 z: p.z + axis.z * t,
600 w: p.w,
601 }
602 })
603 .ok_or_else(|| {
604 "plane_ruled_section_arc: the cylinder section's weights are not one-signed \
605 — refusing"
606 .to_string()
607 })?
608 } else {
609 let apex = frame.origin.add(axis.scale(height * rho0 / (rho0 - rho1)));
610 let k = plane_origin.sub(apex).dot(normal);
611 if k.abs() <= tolerance {
612 return Err(
613 "plane_ruled_section_arc: the plane passes through the cone apex, so the \
614 section is a line pair rather than a conic — refusing"
615 .into(),
616 );
617 }
618 let (reference_rho, reference_z) = if rho0.abs() > rho1.abs() {
619 (rho0.abs(), 0.0)
620 } else {
621 (rho1.abs(), height)
622 };
623 if reference_rho <= tolerance {
624 return Err("plane_ruled_section_arc: the cone carrier degenerates to its apex".into());
625 }
626 let base = make_arc(
627 frame.origin.add(axis.scale(reference_z)),
628 frame.x_axis,
629 frame.y_axis,
630 reference_rho,
631 start_azimuth,
632 start_azimuth + sweep,
633 )?;
634 map_rational_curve(&base, |p| {
635 let relative = Vec3::new(p.x - p.w * apex.x, p.y - p.w * apex.y, p.z - p.w * apex.z);
636 let w_new = relative.dot(normal);
637 let scaled = relative.scale(k);
638 crate::Vec4 {
639 x: apex.x * w_new + scaled.x,
640 y: apex.y * w_new + scaled.y,
641 z: apex.z * w_new + scaled.z,
642 w: w_new,
643 }
644 })
645 .ok_or_else(|| {
646 "plane_ruled_section_arc: the section crosses the cone's apex plane (a parabolic \
647 or hyperbolic branch, whose weights change sign) — refusing"
648 .to_string()
649 })?
650 };
651 let [d0, d1] = curve.domain()?;
655 let slope = if height == 0.0 {
656 0.0
657 } else {
658 (rho1 - rho0) / height
659 };
660 for step in 0..=8 {
661 let point = curve.evaluate(d0 + (d1 - d0) * (step as f64 / 8.0))?;
662 let delta = point.sub(frame.origin);
663 let axial = delta.dot(axis);
664 let radial = delta.sub(axis.scale(axial)).length();
665 let off_ruled = (radial - (rho0 + slope * axial)).abs();
666 let off_plane = point.sub(plane_origin).dot(normal).abs();
667 if off_ruled > 10.0 * tolerance || off_plane > 10.0 * tolerance {
668 return Err(format!(
669 "plane_ruled_section_arc: the section does not lie on both carriers (off ruled \
670 {off_ruled:.3e}, off plane {off_plane:.3e}) — refusing"
671 ));
672 }
673 }
674 Ok(curve)
675}
676
677fn intersect_plane_quadric(
678 plane: &PlaneData,
679 quadric: &AnalyticSurface,
680 tolerance: f64,
681 gate: RuledGate,
682) -> Option<Vec<NurbsCurve>> {
683 match quadric {
684 AnalyticSurface::RuledRevolution { .. } | AnalyticSurface::Revolution { .. }
685 if ruled_revolution_data(quadric, tolerance, gate).is_some() =>
686 {
687 let (frame, rho0, rho1, height) = ruled_revolution_data(quadric, tolerance, gate)?;
688 let (frame, rho0, rho1, height) = (&frame, &rho0, &rho1, &height);
689 let alignment = plane.normal.dot(frame.axis);
690 if alignment.abs() >= 1.0 - 1e-12 {
691 let z = plane.origin.sub(frame.origin).dot(frame.axis);
693 let t = z / height;
694 if !(-1e-9..=1.0 + 1e-9).contains(&t) {
695 return Some(Vec::new());
696 }
697 let rho = rho0 + (rho1 - rho0) * t.clamp(0.0, 1.0);
698 if rho <= tolerance {
699 return Some(Vec::new());
700 }
701 return Some(vec![frame_circle(frame, rho, z)?]);
702 }
703 if (rho1 - rho0).abs() <= 1e-12 || degenerate_apex_frustum(*rho0, *rho1, *height) {
704 if alignment.abs() <= 1e-12 {
706 return cylinder_parallel_plane_lines(plane, frame, *rho0, *height, tolerance);
709 }
710 let circle = frame_circle(frame, *rho0, 0.0)?;
713 let denominator = alignment;
714 let origin_dot = plane.origin.dot(plane.normal);
715 let normal = plane.normal;
716 let axis = frame.axis;
717 let ellipse = map_rational_curve(&circle, |p| {
718 let t = (origin_dot * p.w - Vec3::new(p.x, p.y, p.z).dot(normal)) / denominator;
719 crate::Vec4 {
720 x: p.x + axis.x * t,
721 y: p.y + axis.y * t,
722 z: p.z + axis.z * t,
723 w: p.w,
724 }
725 })?;
726 if !section_within_band(&ellipse, frame, *height, tolerance) {
727 return Some(Vec::new());
728 }
729 return Some(vec![ellipse]);
730 }
731 let apex_t = rho0 / (rho0 - rho1);
735 let apex = frame.origin.add(frame.axis.scale(height * apex_t));
736 let reference_rho = if rho0.abs() > rho1.abs() {
737 *rho0
738 } else {
739 *rho1
740 };
741 let reference_z = if rho0.abs() > rho1.abs() {
742 0.0
743 } else {
744 *height
745 };
746 let circle = frame_circle(frame, reference_rho, reference_z)?;
747 let k = plane.origin.sub(apex).dot(plane.normal);
748 if k.abs() <= tolerance {
749 return None;
751 }
752 let normal = plane.normal;
753 let conic = map_rational_curve(&circle, |p| {
754 let relative =
755 Vec3::new(p.x - p.w * apex.x, p.y - p.w * apex.y, p.z - p.w * apex.z);
756 let w_new = relative.dot(normal);
757 let scaled = relative.scale(k);
758 crate::Vec4 {
759 x: apex.x * w_new + scaled.x,
760 y: apex.y * w_new + scaled.y,
761 z: apex.z * w_new + scaled.z,
762 w: w_new,
763 }
764 })?;
765 if !section_within_band(&conic, frame, *height, tolerance) {
766 return Some(Vec::new());
767 }
768 Some(vec![conic])
769 }
770 AnalyticSurface::Sphere { frame, radius } => {
771 plane_sphere_section(plane, frame.origin, *radius, tolerance)
772 }
773 AnalyticSurface::Torus {
774 frame,
775 major_radius,
776 minor_radius,
777 } => plane_torus_section(plane, frame, *major_radius, *minor_radius, tolerance),
778 AnalyticSurface::Plane { .. } => None,
779 AnalyticSurface::RuledRevolution { .. } => None,
780 AnalyticSurface::Revolution { .. } => {
786 if let Some((center, radius)) = quadric.sphere_geometry() {
787 return plane_sphere_section(plane, center, radius, tolerance);
788 }
789 if let Some((frame, major_radius, minor_radius)) = quadric.torus_geometry() {
790 return plane_torus_section(plane, &frame, major_radius, minor_radius, tolerance);
791 }
792 None
793 }
794 }
795}
796
797fn plane_sphere_section(
800 plane: &PlaneData,
801 center: Vec3,
802 radius: f64,
803 tolerance: f64,
804) -> Option<Vec<NurbsCurve>> {
805 let distance = center.sub(plane.origin).dot(plane.normal);
806 if distance.abs() >= radius - tolerance {
807 return Some(Vec::new());
808 }
809 let circle_center = center.sub(plane.normal.scale(distance));
810 let circle_radius = (radius * radius - distance * distance).sqrt();
811 let x_axis = plane.normal.perpendicular().ok()?;
812 let y_axis = plane.normal.cross(x_axis);
813 Some(vec![make_arc(
814 circle_center,
815 x_axis,
816 y_axis,
817 circle_radius,
818 0.0,
819 std::f64::consts::TAU,
820 )
821 .ok()?])
822}
823
824fn plane_torus_section(
829 plane: &PlaneData,
830 frame: &RevolutionFrame,
831 major_radius: f64,
832 minor_radius: f64,
833 tolerance: f64,
834) -> Option<Vec<NurbsCurve>> {
835 let alignment = plane.normal.dot(frame.axis);
836 if alignment.abs() < 1.0 - 1e-12 {
837 return None;
838 }
839 let z = plane.origin.sub(frame.origin).dot(frame.axis);
840 if z.abs() >= minor_radius - tolerance {
841 return Some(Vec::new());
842 }
843 let offset = (minor_radius * minor_radius - z * z).sqrt();
844 let mut circles = Vec::new();
845 for rho in [major_radius - offset, major_radius + offset] {
846 if rho > tolerance {
847 circles.push(frame_circle(frame, rho, z)?);
848 }
849 }
850 Some(circles)
851}
852
853fn section_within_band(
870 curve: &NurbsCurve,
871 frame: &RevolutionFrame,
872 height: f64,
873 tolerance: f64,
874) -> bool {
875 let (band_low, band_high) = if height >= 0.0 {
876 (0.0, height)
877 } else {
878 (height, 0.0)
879 };
880 let margin = tolerance.max(1e-9) + 1e-9;
881 let mut min_z = f64::INFINITY;
882 let mut max_z = f64::NEG_INFINITY;
883 for p in &curve.control_points {
884 let z = Vec3::new(p.x / p.w, p.y / p.w, p.z / p.w)
885 .sub(frame.origin)
886 .dot(frame.axis);
887 min_z = min_z.min(z);
888 max_z = max_z.max(z);
889 }
890 max_z >= band_low - margin && min_z <= band_high + margin
892}
893
894fn cylinder_parallel_plane_lines(
895 plane: &PlaneData,
896 frame: &RevolutionFrame,
897 radius: f64,
898 height: f64,
899 tolerance: f64,
900) -> Option<Vec<NurbsCurve>> {
901 let axis_to_plane = plane.origin.sub(frame.origin).dot(plane.normal);
903 if axis_to_plane.abs() >= radius - tolerance {
904 return Some(Vec::new());
905 }
906 let chord_half = (radius * radius - axis_to_plane * axis_to_plane).sqrt();
908 let chord_direction = frame.axis.cross(plane.normal).normalized().ok()?;
909 let foot = frame.origin.add(plane.normal.scale(axis_to_plane));
910 let mut lines = Vec::new();
911 for sign in [-1.0, 1.0] {
912 let base = foot.add(chord_direction.scale(sign * chord_half));
913 let top = base.add(frame.axis.scale(height));
914 lines.push(crate::make_line(base, top).ok()?);
915 }
916 Some(lines)
917}
918
919fn intersect_sphere_sphere(
920 center_a: Vec3,
921 radius_a: f64,
922 center_b: Vec3,
923 radius_b: f64,
924 tolerance: f64,
925) -> Option<Vec<NurbsCurve>> {
926 let offset = center_b.sub(center_a);
927 let distance = offset.length();
928 if distance <= tolerance {
929 return if (radius_a - radius_b).abs() <= tolerance {
932 None
933 } else {
934 Some(Vec::new())
935 };
936 }
937 if distance >= radius_a + radius_b - tolerance
938 || distance <= (radius_a - radius_b).abs() + tolerance
939 {
940 return Some(Vec::new());
941 }
942 let normal = offset.scale(1.0 / distance);
943 let along =
944 (distance * distance + radius_a * radius_a - radius_b * radius_b) / (2.0 * distance);
945 let circle_radius_squared = radius_a * radius_a - along * along;
946 if circle_radius_squared <= tolerance * tolerance {
947 return Some(Vec::new());
948 }
949 let center = center_a.add(normal.scale(along));
950 let x_axis = normal.perpendicular().ok()?;
951 let y_axis = normal.cross(x_axis);
952 Some(vec![make_arc(
953 center,
954 x_axis,
955 y_axis,
956 circle_radius_squared.sqrt(),
957 0.0,
958 std::f64::consts::TAU,
959 )
960 .ok()?])
961}