1use crate::boolean::{boolean_operation, BooleanOperation, BooleanOptions};
10use crate::spatial::Aabb;
11use crate::topology::{make_box_brep, make_cylinder_brep, BrepSolid};
12use crate::transform_topology::{transform_brep, AffineTransform};
13use crate::{
14 make_cone_brep, make_sphere_brep, make_torus_brep, AnalyticSurface, NurbsSurface, Vec3,
15};
16use serde::Deserialize;
17
18fn solid_aabb(solid: &BrepSolid) -> Aabb {
27 let mut bounds = Aabb::empty();
28 for vertex in &solid.vertices {
29 bounds.include_point(vertex.point);
30 }
31 let surfaces = solid.shells.iter().flat_map(|shell| &shell.faces).flat_map(|face| face.surface.control_points.iter().flatten());
32 let curves = solid.edges.iter().flat_map(|edge| edge.curve.control_points.iter());
33 for control in surfaces.chain(curves) {
34 if let Ok(point) = control.point() {
35 bounds.include_point(point);
36 }
37 }
38 bounds
39}
40
41fn is_empty_piece(solid: &BrepSolid) -> bool {
44 solid.shells.is_empty() || solid.shells.iter().all(|shell| shell.faces.is_empty())
45}
46
47fn frame_transform(u: Vec3, v: Vec3, n: Vec3, center: Vec3) -> Result<AffineTransform, String> {
52 AffineTransform::new([
53 u.x, v.x, n.x, center.x, u.y, v.y, n.y, center.y, u.z, v.z, n.z, center.z, 0.0, 0.0, 0.0, 1.0,
57 ])
58}
59
60pub fn split_solid_by_plane(
71 solid: &BrepSolid,
72 plane_point: Vec3,
73 plane_normal: Vec3,
74) -> Result<(BrepSolid, BrepSolid), String> {
75 if plane_misses_box(solid, plane_point, plane_normal) {
76 return Err("split_solid_by_plane: plane does not intersect the solid".into());
77 }
78 let options = BooleanOptions::default();
79 let cut = |cover: f64| -> Result<_, String> {
80 let (tool_below, tool_above) = plane_tools(solid, plane_point, plane_normal, cover)?;
81 Ok((
82 boolean_operation(solid, &tool_below, BooleanOperation::Intersect, &options),
83 boolean_operation(solid, &tool_above, BooleanOperation::Intersect, &options),
84 ))
85 };
86 let (mut below, mut above) = cut(3.0)?;
93 if below.is_err() || above.is_err() {
94 (below, above) = cut(1.2)?;
95 }
96
97 match (below, above) {
98 (Ok(below), Ok(above)) => match (is_empty_piece(&below), is_empty_piece(&above)) {
99 (false, false) => Ok((below, above)),
100 (below_empty, above_empty) => Err(format!(
101 "split_solid_by_plane: the plane crosses the solid's box but the cut left the piece {} the plane empty",
102 match (below_empty, above_empty) {
103 (true, true) => "on each side of",
104 (true, false) => "below",
105 _ => "above",
106 },
107 )),
108 },
109 (Err(error), _) | (_, Err(error)) => Err(format!("split_solid_by_plane: the cut failed: {error}")),
110 }
111}
112
113fn plane_misses_box(solid: &BrepSolid, plane_point: Vec3, plane_normal: Vec3) -> bool {
116 let (bounds, Ok(n)) = (solid_aabb(solid), plane_normal.normalized()) else {
117 return false;
118 };
119 if !bounds.minimum.x.is_finite() {
120 return false;
121 }
122 let (lo, hi) = (bounds.minimum, bounds.maximum);
123 let reach = 1e-9 * bounds.diagonal().max(1.0);
124 let sides = (0..8).map(|corner| {
125 let point = Vec3::new(
126 if corner & 1 == 0 { lo.x } else { hi.x },
127 if corner & 2 == 0 { lo.y } else { hi.y },
128 if corner & 4 == 0 { lo.z } else { hi.z },
129 );
130 point.sub(plane_point).dot(n)
131 });
132 let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
133 for side in sides {
134 low = low.min(side);
135 high = high.max(side);
136 }
137 low > reach || high < -reach
138}
139
140pub fn solid_piece_by_plane(
150 solid: &BrepSolid,
151 plane_point: Vec3,
152 plane_normal: Vec3,
153 above: bool,
154 cover: f64,
155) -> Result<Option<BrepSolid>, String> {
156 if !(cover >= 1.0 && cover.is_finite()) {
157 return Err("solid_piece_by_plane: the cover must be at least 1".into());
158 }
159 let (tool_below, tool_above) = plane_tools(solid, plane_point, plane_normal, cover)?;
160 let tool = if above { tool_above } else { tool_below };
161 let piece = boolean_operation(solid, &tool, BooleanOperation::Intersect, &BooleanOptions::default())
162 .map_err(|error| format!("solid_piece_by_plane: {error}"))?;
163 Ok((!is_empty_piece(&piece)).then_some(piece))
164}
165
166fn plane_tools(
169 solid: &BrepSolid,
170 plane_point: Vec3,
171 plane_normal: Vec3,
172 cover: f64,
173) -> Result<(BrepSolid, BrepSolid), String> {
174 let n = plane_normal.normalized()?;
175 let u = n.perpendicular()?;
178 let v = n.cross(u);
179
180 let bounds = solid_aabb(solid);
181 if !bounds.minimum.x.is_finite() {
182 return Err("split_solid_by_plane: solid has no geometry".into());
183 }
184 let diagonal = bounds.diagonal();
185 if diagonal <= 0.0 {
186 return Err("split_solid_by_plane: solid is degenerate".into());
187 }
188 let length = cover * diagonal;
191 let half = 0.5 * length;
192
193 let center = bounds.minimum.add(bounds.maximum).scale(0.5);
198 let center_on_plane = center.sub(n.scale(center.sub(plane_point).dot(n)));
199
200 let cube = make_box_brep(Vec3::new(-half, -half, -half), length, length, length)?;
202
203 let below_center = center_on_plane.sub(n.scale(half));
206 let tool_below = transform_brep(&cube, frame_transform(u, v, n, below_center)?, false)?;
207
208 let above_center = center_on_plane.add(n.scale(half));
210 let tool_above = transform_brep(&cube, frame_transform(u, v, n, above_center)?, false)?;
211 Ok((tool_below, tool_above))
212}
213
214#[derive(Clone, Copy, Debug, Deserialize)]
232#[serde(tag = "type", rename_all = "lowercase")]
233pub enum SplitSurface {
234 Plane { point: Vec3, normal: Vec3 },
236 Cylinder {
239 axis_point: Vec3,
240 axis_dir: Vec3,
241 radius: f64,
242 },
243 Sphere { center: Vec3, radius: f64 },
245 Cone {
249 apex: Vec3,
250 axis_dir: Vec3,
251 half_angle: f64,
252 },
253 Torus {
255 center: Vec3,
256 axis_dir: Vec3,
257 major_radius: f64,
258 minor_radius: f64,
259 },
260}
261
262fn solid_extent(solid: &BrepSolid) -> Result<(Aabb, f64), String> {
265 let bounds = solid_aabb(solid);
266 if !bounds.minimum.x.is_finite() {
267 return Err("split_solid_by_surface: solid has no geometry".into());
268 }
269 let diagonal = bounds.diagonal();
270 if diagonal <= 0.0 {
271 return Err("split_solid_by_surface: solid is degenerate".into());
272 }
273 Ok((bounds, diagonal))
274}
275
276fn build_tool_solid(solid: &BrepSolid, tool: &SplitSurface) -> Result<BrepSolid, String> {
279 let (_, diagonal) = solid_extent(solid)?;
280 let margin = diagonal.max(1.0);
281 match *tool {
282 SplitSurface::Plane { .. } => {
283 Err("build_tool_solid: plane is handled by the plane path".into())
284 }
285 SplitSurface::Cylinder {
286 axis_point,
287 axis_dir,
288 radius,
289 } => {
290 if radius <= 0.0 {
291 return Err("split_solid_by_surface: cylinder radius must be positive".into());
292 }
293 let axis = axis_dir.normalized()?;
294 let (t_min, t_max) = axis_span(solid, axis_point, axis);
297 let base = axis_point.add(axis.scale(t_min - margin));
298 let height = (t_max - t_min) + 2.0 * margin;
299 make_cylinder_brep(base, axis, radius, height)
300 }
301 SplitSurface::Sphere { center, radius } => {
302 if radius <= 0.0 {
303 return Err("split_solid_by_surface: sphere radius must be positive".into());
304 }
305 make_sphere_brep(center, radius, Vec3::new(0.0, 0.0, 1.0))
307 }
308 SplitSurface::Cone {
309 apex,
310 axis_dir,
311 half_angle,
312 } => {
313 if !(half_angle > 0.0 && half_angle < std::f64::consts::FRAC_PI_2) {
314 return Err("split_solid_by_surface: cone half-angle must be in (0, pi/2)".into());
315 }
316 let axis = axis_dir.normalized()?;
317 let (_, d_max) = axis_span(solid, apex, axis);
319 if d_max <= 0.0 {
320 return Err(
321 "split_solid_by_surface: cone does not reach the solid (body is behind the apex)"
322 .into(),
323 );
324 }
325 let big_h = d_max + margin;
326 let base = apex.add(axis.scale(big_h));
330 let base_radius = big_h * half_angle.tan();
331 make_cone_brep(base, axis.scale(-1.0), base_radius, 0.0, big_h)
332 }
333 SplitSurface::Torus {
334 center,
335 axis_dir,
336 major_radius,
337 minor_radius,
338 } => {
339 if minor_radius <= 0.0 || major_radius <= 0.0 {
340 return Err("split_solid_by_surface: torus radii must be positive".into());
341 }
342 make_torus_brep(center, axis_dir, major_radius, minor_radius)
344 }
345 }
346}
347
348fn axis_span(solid: &BrepSolid, origin: Vec3, axis: Vec3) -> (f64, f64) {
351 let mut t_min = f64::INFINITY;
352 let mut t_max = f64::NEG_INFINITY;
353 for vertex in &solid.vertices {
354 let t = vertex.point.sub(origin).dot(axis);
355 t_min = t_min.min(t);
356 t_max = t_max.max(t);
357 }
358 (t_min, t_max)
359}
360
361pub fn split_solid_by_surface(
374 solid: &BrepSolid,
375 tool: &SplitSurface,
376) -> Result<Vec<BrepSolid>, String> {
377 if let SplitSurface::Plane { point, normal } = *tool {
378 let (below, above) = split_solid_by_plane(solid, point, normal)?;
379 return Ok(vec![below, above]);
380 }
381
382 let tool_solid = build_tool_solid(solid, tool)?;
383 let options = BooleanOptions::default();
384 let inside = boolean_operation(solid, &tool_solid, BooleanOperation::Intersect, &options);
385 let outside = boolean_operation(solid, &tool_solid, BooleanOperation::Subtract, &options);
386
387 match (inside, outside) {
388 (Ok(inside), Ok(outside))
389 if !is_empty_piece(&inside)
390 && !is_empty_piece(&outside)
391 && inside.validate().is_empty()
392 && outside.validate().is_empty() =>
393 {
394 Ok(vec![inside, outside])
395 }
396 _ => Err("split_solid_by_surface: tool surface does not divide the solid".into()),
397 }
398}
399
400fn recognized_split_surface(surface: &NurbsSurface) -> Result<SplitSurface, String> {
406 let analytic = surface
407 .analytic()
408 .ok_or("split_solid_by_face_surface: selected face is not an analytic surface")?;
409 match analytic {
410 AnalyticSurface::Plane {
411 origin,
412 u_dir,
413 v_dir,
414 ..
415 } => {
416 let normal = u_dir.cross(*v_dir).normalized()?;
417 Ok(SplitSurface::Plane {
418 point: *origin,
419 normal,
420 })
421 }
422 AnalyticSurface::RuledRevolution {
423 frame,
424 rho0,
425 rho1,
426 height,
427 } => {
428 let scale = rho0.abs().max(rho1.abs()).max(1.0);
430 if (rho0 - rho1).abs() <= 1e-9 * scale {
431 Ok(SplitSurface::Cylinder {
432 axis_point: frame.origin,
433 axis_dir: frame.axis,
434 radius: 0.5 * (rho0 + rho1),
435 })
436 } else {
437 let slope = (rho1 - rho0) / height;
439 let axial_apex = -rho0 / slope;
440 let apex = frame.origin.add(frame.axis.scale(axial_apex));
441 let axis_dir = if slope >= 0.0 {
443 frame.axis
444 } else {
445 frame.axis.scale(-1.0)
446 };
447 Ok(SplitSurface::Cone {
448 apex,
449 axis_dir,
450 half_angle: slope.abs().atan(),
451 })
452 }
453 }
454 AnalyticSurface::Sphere { frame, radius } => Ok(SplitSurface::Sphere {
455 center: frame.origin,
456 radius: *radius,
457 }),
458 AnalyticSurface::Torus {
459 frame,
460 major_radius,
461 minor_radius,
462 } => Ok(SplitSurface::Torus {
463 center: frame.origin,
464 axis_dir: frame.axis,
465 major_radius: *major_radius,
466 minor_radius: *minor_radius,
467 }),
468 AnalyticSurface::Revolution { .. } => Err(
469 "split_solid_by_face_surface: general revolved surfaces are not supported as a cut tool"
470 .into(),
471 ),
472 }
473}
474
475pub fn split_solid_by_face_surface(
482 solid: &BrepSolid,
483 surface: &NurbsSurface,
484) -> Result<Vec<BrepSolid>, String> {
485 let tool = recognized_split_surface(surface)?;
486 split_solid_by_surface(solid, &tool)
487}
488