Skip to main content

brep_boolean/edit/
split.rs

1//! Cut / split a body by a plane (Golovanov §6.4).
2//!
3//! The split reuses the ROBUST boolean rather than a bespoke classifier: the
4//! plane is realised as two very large half-space TOOL boxes (one covering each
5//! side of the plane), and each output piece is `Intersect(solid, tool)`. The
6//! boolean machinery imprints the cut plane onto the solid and re-closes the
7//! shell, so both pieces inherit the kernel's validated, watertight topology.
8
9use 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
18/// Axis-aligned bounding box of a solid: its vertices, and the control points
19/// of every face's surface and every edge's curve.
20///
21/// The vertices alone do not bound a body whose faces bulge past them: a torus
22/// has one vertex, so the box read as degenerate and the split refused; a
23/// sphere's are its two poles, a segment on the axis. A rational patch or curve
24/// with positive weights lies in the hull of its control points, so they bound
25/// it (loosely, which a tool three diagonals wide does not mind).
26fn 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
41/// A boolean result counts as an empty piece when it carries no face geometry —
42/// i.e. the half-space tool did not overlap the solid on that side.
43fn is_empty_piece(solid: &BrepSolid) -> bool {
44    solid.shells.is_empty() || solid.shells.iter().all(|shell| shell.faces.is_empty())
45}
46
47/// Build the affine placing a local, origin-centred cube so its local +Z axis
48/// maps to `n`, +X to `u`, +Y to `v`, and its centre lands at `center`. The
49/// columns of the rotation are `[u v n]` (a right-handed, det = +1 frame), so
50/// the map is a proper rigid motion (no orientation reversal needed).
51fn 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, //
54        u.y, v.y, n.y, center.y, //
55        u.z, v.z, n.z, center.z, //
56        0.0, 0.0, 0.0, 1.0,
57    ])
58}
59
60/// Split `solid` into two pieces by the plane through `plane_point` with normal
61/// `plane_normal`. Returns `(below, above)` where `below` is the piece on the
62/// −n side of the plane and `above` the piece on the +n side.
63///
64/// Contract: when the plane does not actually divide the solid into two
65/// non-degenerate pieces (it misses the body, or is tangent so one side is
66/// empty), this returns `Err("split_solid_by_plane: plane does not intersect
67/// the solid")` rather than a degenerate/empty piece.
68pub fn split_solid_by_plane(
69    solid: &BrepSolid,
70    plane_point: Vec3,
71    plane_normal: Vec3,
72) -> Result<(BrepSolid, BrepSolid), String> {
73    let options = BooleanOptions::default();
74    let cut = |cover: f64| -> Result<_, String> {
75        let (tool_below, tool_above) = plane_tools(solid, plane_point, plane_normal, cover)?;
76        Ok((
77            boolean_operation(solid, &tool_below, BooleanOperation::Intersect, &options),
78            boolean_operation(solid, &tool_above, BooleanOperation::Intersect, &options),
79        ))
80    };
81    // Three diagonals first, as every caller has read the pieces' cap
82    // carriers. Where that cut fails, a box 1.2 diagonals across, which still
83    // covers the solid: the wider cut face resolves small sections on it
84    // coarser, and a ball 1.8e-4 wider than its rod, a plate with a grid of
85    // holes and a chain of links each came back from the 3x box with an open
86    // loop and cut cleanly at 1.2x.
87    let (mut below, mut above) = cut(3.0)?;
88    if below.is_err() || above.is_err() {
89        (below, above) = cut(1.2)?;
90    }
91
92    match (below, above) {
93        (Ok(below), Ok(above)) if !is_empty_piece(&below) && !is_empty_piece(&above) => {
94            Ok((below, above))
95        }
96        _ => Err("split_solid_by_plane: plane does not intersect the solid".into()),
97    }
98}
99
100/// The piece of `solid` on one side of the plane through `plane_point` with
101/// normal `plane_normal`: the −n side when `above` is false, the +n side when
102/// it is true. The cutting box spans `cover` times the diagonal of the
103/// solid's control-point box (at least 1; [`split_solid_by_plane`] uses 3),
104/// centred on that box's centre projected onto the plane, so it covers every
105/// part of the solid on its side whenever the plane meets that box.
106/// `Ok(None)` when nothing of the solid lies on that side; an error only when
107/// the cut itself fails, so a caller can tell a plane that misses from a
108/// boolean that declined (which [`split_solid_by_plane`] reports alike).
109pub fn solid_piece_by_plane(
110    solid: &BrepSolid,
111    plane_point: Vec3,
112    plane_normal: Vec3,
113    above: bool,
114    cover: f64,
115) -> Result<Option<BrepSolid>, String> {
116    if !(cover >= 1.0 && cover.is_finite()) {
117        return Err("solid_piece_by_plane: the cover must be at least 1".into());
118    }
119    let (tool_below, tool_above) = plane_tools(solid, plane_point, plane_normal, cover)?;
120    let tool = if above { tool_above } else { tool_below };
121    let piece = boolean_operation(solid, &tool, BooleanOperation::Intersect, &BooleanOptions::default())
122        .map_err(|error| format!("solid_piece_by_plane: {error}"))?;
123    Ok((!is_empty_piece(&piece)).then_some(piece))
124}
125
126/// The two half-space tool boxes of a plane cut of `solid`, each `cover`
127/// times the solid's diagonal on a side: (below, above).
128fn plane_tools(
129    solid: &BrepSolid,
130    plane_point: Vec3,
131    plane_normal: Vec3,
132    cover: f64,
133) -> Result<(BrepSolid, BrepSolid), String> {
134    let n = plane_normal.normalized()?;
135    // Orthonormal frame (n, u, v): u ⟂ n (unit), v = n × u (unit); [u v n] is
136    // right-handed so the tool placement is a proper rotation.
137    let u = n.perpendicular()?;
138    let v = n.cross(u);
139
140    let bounds = solid_aabb(solid);
141    if !bounds.minimum.x.is_finite() {
142        return Err("split_solid_by_plane: solid has no geometry".into());
143    }
144    let diagonal = bounds.diagonal();
145    if diagonal <= 0.0 {
146        return Err("split_solid_by_plane: solid is degenerate".into());
147    }
148    // A tool box `cover` × the solid diagonal on every side (3× for the
149    // split) covers the body in the plane's tangent directions.
150    let length = cover * diagonal;
151    let half = 0.5 * length;
152
153    // Centre the tool in the tangent (u, v) plane on the projection of the AABB
154    // centre onto the cut plane, so the box brackets the whole solid regardless
155    // of where `plane_point` sits within it. Along n it is offset by ±half so
156    // the tool's cut face lands exactly on the plane.
157    let center = bounds.minimum.add(bounds.maximum).scale(0.5);
158    let center_on_plane = center.sub(n.scale(center.sub(plane_point).dot(n)));
159
160    // Local cube centred at the local origin, spanning [-half, half]³.
161    let cube = make_box_brep(Vec3::new(-half, -half, -half), length, length, length)?;
162
163    // BELOW: tool centred at plane − n·half, so its +n face lies on the plane
164    // and it extends distance `length` along −n, covering the −n side.
165    let below_center = center_on_plane.sub(n.scale(half));
166    let tool_below = transform_brep(&cube, frame_transform(u, v, n, below_center)?, false)?;
167
168    // ABOVE: mirror to the +n side (centre at plane + n·half).
169    let above_center = center_on_plane.add(n.scale(half));
170    let tool_above = transform_brep(&cube, frame_transform(u, v, n, above_center)?, false)?;
171    Ok((tool_below, tool_above))
172}
173
174// ---------------------------------------------------------------------------
175// Generalized split by an analytic surface (Golovanov §6.4).
176//
177// The plane case above splits a body against two large half-space TOOL boxes.
178// The analytic cases generalize that idea: an unbounded/bounded analytic
179// surface (cylinder, cone, sphere, torus) is realised as ONE CLOSED SOLID
180// region big enough to span the body wherever it matters, and the two output
181// pieces are the boolean `Intersect` (inside the tool region) and `Subtract`
182// (outside it) of the body against that region.  Because every cut runs
183// through the validated boolean machinery, each piece inherits watertight
184// topology, the cut surface is imprinted onto the body, and the two volumes
185// sum to the original.
186// ---------------------------------------------------------------------------
187
188/// A closed analytic tool region used to cut a body.  Each variant is realised
189/// as a closed solid (unbounded carriers are capped well beyond the body) whose
190/// interior is one side of the analytic surface.
191#[derive(Clone, Copy, Debug, Deserialize)]
192#[serde(tag = "type", rename_all = "lowercase")]
193pub enum SplitSurface {
194    /// Infinite plane through `point` with `normal`; delegates to the plane path.
195    Plane { point: Vec3, normal: Vec3 },
196    /// Infinite cylinder about the axis line through `axis_point` along
197    /// `axis_dir`, of the given `radius`.  Interior = inside the cylinder.
198    Cylinder {
199        axis_point: Vec3,
200        axis_dir: Vec3,
201        radius: f64,
202    },
203    /// Sphere centred at `center`.  Interior = inside the ball.
204    Sphere { center: Vec3, radius: f64 },
205    /// Single-nappe cone with its apex at `apex`, opening along `+axis_dir`,
206    /// with the given `half_angle` (radians, apex half-angle).  Interior =
207    /// inside the cone.
208    Cone {
209        apex: Vec3,
210        axis_dir: Vec3,
211        half_angle: f64,
212    },
213    /// Torus centred at `center` about `axis_dir`.  Interior = inside the tube.
214    Torus {
215        center: Vec3,
216        axis_dir: Vec3,
217        major_radius: f64,
218        minor_radius: f64,
219    },
220}
221
222/// Bounds + a sane margin/diagonal for a body, erroring on empty/degenerate
223/// geometry the same way the plane path does.
224fn solid_extent(solid: &BrepSolid) -> Result<(Aabb, f64), String> {
225    let bounds = solid_aabb(solid);
226    if !bounds.minimum.x.is_finite() {
227        return Err("split_solid_by_surface: solid has no geometry".into());
228    }
229    let diagonal = bounds.diagonal();
230    if diagonal <= 0.0 {
231        return Err("split_solid_by_surface: solid is degenerate".into());
232    }
233    Ok((bounds, diagonal))
234}
235
236/// Build the closed tool solid for an analytic tool, sized to fully span the
237/// body wherever the analytic surface passes through it.
238fn build_tool_solid(solid: &BrepSolid, tool: &SplitSurface) -> Result<BrepSolid, String> {
239    let (_, diagonal) = solid_extent(solid)?;
240    let margin = diagonal.max(1.0);
241    match *tool {
242        SplitSurface::Plane { .. } => {
243            Err("build_tool_solid: plane is handled by the plane path".into())
244        }
245        SplitSurface::Cylinder {
246            axis_point,
247            axis_dir,
248            radius,
249        } => {
250            if radius <= 0.0 {
251                return Err("split_solid_by_surface: cylinder radius must be positive".into());
252            }
253            let axis = axis_dir.normalized()?;
254            // Extend the capped cylinder a full margin beyond the body's span
255            // along the axis so its caps never cut the body.
256            let (t_min, t_max) = axis_span(solid, axis_point, axis);
257            let base = axis_point.add(axis.scale(t_min - margin));
258            let height = (t_max - t_min) + 2.0 * margin;
259            make_cylinder_brep(base, axis, radius, height)
260        }
261        SplitSurface::Sphere { center, radius } => {
262            if radius <= 0.0 {
263                return Err("split_solid_by_surface: sphere radius must be positive".into());
264            }
265            // A sphere is already a closed, bounded region.
266            make_sphere_brep(center, radius, Vec3::new(0.0, 0.0, 1.0))
267        }
268        SplitSurface::Cone {
269            apex,
270            axis_dir,
271            half_angle,
272        } => {
273            if !(half_angle > 0.0 && half_angle < std::f64::consts::FRAC_PI_2) {
274                return Err("split_solid_by_surface: cone half-angle must be in (0, pi/2)".into());
275            }
276            let axis = axis_dir.normalized()?;
277            // Distance of the farthest body point along +axis from the apex.
278            let (_, d_max) = axis_span(solid, apex, axis);
279            if d_max <= 0.0 {
280                return Err(
281                    "split_solid_by_surface: cone does not reach the solid (body is behind the apex)"
282                        .into(),
283                );
284            }
285            let big_h = d_max + margin;
286            // Realise the nappe as a cone whose apex sits at `apex` and whose
287            // base cap lands `big_h` past it along +axis: base at apex+axis·H,
288            // built with axis pointing back to the apex so top(0-radius)=apex.
289            let base = apex.add(axis.scale(big_h));
290            let base_radius = big_h * half_angle.tan();
291            make_cone_brep(base, axis.scale(-1.0), base_radius, 0.0, big_h)
292        }
293        SplitSurface::Torus {
294            center,
295            axis_dir,
296            major_radius,
297            minor_radius,
298        } => {
299            if minor_radius <= 0.0 || major_radius <= 0.0 {
300                return Err("split_solid_by_surface: torus radii must be positive".into());
301            }
302            // A torus is already a closed, bounded region.
303            make_torus_brep(center, axis_dir, major_radius, minor_radius)
304        }
305    }
306}
307
308/// Signed span `[min, max]` of the body's vertices projected onto the axis line
309/// through `origin` along the unit direction `axis`.
310fn axis_span(solid: &BrepSolid, origin: Vec3, axis: Vec3) -> (f64, f64) {
311    let mut t_min = f64::INFINITY;
312    let mut t_max = f64::NEG_INFINITY;
313    for vertex in &solid.vertices {
314        let t = vertex.point.sub(origin).dot(axis);
315        t_min = t_min.min(t);
316        t_max = t_max.max(t);
317    }
318    (t_min, t_max)
319}
320
321/// Split `solid` into pieces by an analytic tool surface (Golovanov §6.4).
322///
323/// For the `Plane` tool this is exactly `split_solid_by_plane`, returned as
324/// `[below, above]`.  For a closed analytic tool region (cylinder / sphere /
325/// cone / torus) the two pieces are `[inside, outside]` where `inside =
326/// solid ∩ tool` and `outside = solid − tool`.  Both pieces are guaranteed
327/// non-empty and valid; their volumes sum to the original.
328///
329/// Contract: when the tool does not actually divide the body into two
330/// non-degenerate pieces (it misses the body, or wholly contains / is wholly
331/// contained so one side is empty), this returns a clear `Err` rather than a
332/// degenerate/empty piece.
333pub fn split_solid_by_surface(
334    solid: &BrepSolid,
335    tool: &SplitSurface,
336) -> Result<Vec<BrepSolid>, String> {
337    if let SplitSurface::Plane { point, normal } = *tool {
338        let (below, above) = split_solid_by_plane(solid, point, normal)?;
339        return Ok(vec![below, above]);
340    }
341
342    let tool_solid = build_tool_solid(solid, tool)?;
343    let options = BooleanOptions::default();
344    let inside = boolean_operation(solid, &tool_solid, BooleanOperation::Intersect, &options);
345    let outside = boolean_operation(solid, &tool_solid, BooleanOperation::Subtract, &options);
346
347    match (inside, outside) {
348        (Ok(inside), Ok(outside))
349            if !is_empty_piece(&inside)
350                && !is_empty_piece(&outside)
351                && inside.validate().is_empty()
352                && outside.validate().is_empty() =>
353        {
354            Ok(vec![inside, outside])
355        }
356        _ => Err("split_solid_by_surface: tool surface does not divide the solid".into()),
357    }
358}
359
360/// Map a face's exact analytic carrier to the closed tool region that splits a
361/// body by that surface.  Reuses the kernel's own analytic recognition so the
362/// caller only has to hand over the selected face's surface (no host-side
363/// geometry extraction).  Unrecognized / general-revolution carriers are
364/// reported as unsupported (deferred), never approximated.
365fn recognized_split_surface(surface: &NurbsSurface) -> Result<SplitSurface, String> {
366    let analytic = surface
367        .analytic()
368        .ok_or("split_solid_by_face_surface: selected face is not an analytic surface")?;
369    match analytic {
370        AnalyticSurface::Plane {
371            origin,
372            u_dir,
373            v_dir,
374            ..
375        } => {
376            let normal = u_dir.cross(*v_dir).normalized()?;
377            Ok(SplitSurface::Plane {
378                point: *origin,
379                normal,
380            })
381        }
382        AnalyticSurface::RuledRevolution {
383            frame,
384            rho0,
385            rho1,
386            height,
387        } => {
388            // Cylinder when the two radii coincide, otherwise a cone/frustum.
389            let scale = rho0.abs().max(rho1.abs()).max(1.0);
390            if (rho0 - rho1).abs() <= 1e-9 * scale {
391                Ok(SplitSurface::Cylinder {
392                    axis_point: frame.origin,
393                    axis_dir: frame.axis,
394                    radius: 0.5 * (rho0 + rho1),
395                })
396            } else {
397                // radius(axial) = rho0 + slope·axial, apex where radius = 0.
398                let slope = (rho1 - rho0) / height;
399                let axial_apex = -rho0 / slope;
400                let apex = frame.origin.add(frame.axis.scale(axial_apex));
401                // The nappe opens in the direction of increasing radius.
402                let axis_dir = if slope >= 0.0 {
403                    frame.axis
404                } else {
405                    frame.axis.scale(-1.0)
406                };
407                Ok(SplitSurface::Cone {
408                    apex,
409                    axis_dir,
410                    half_angle: slope.abs().atan(),
411                })
412            }
413        }
414        AnalyticSurface::Sphere { frame, radius } => Ok(SplitSurface::Sphere {
415            center: frame.origin,
416            radius: *radius,
417        }),
418        AnalyticSurface::Torus {
419            frame,
420            major_radius,
421            minor_radius,
422        } => Ok(SplitSurface::Torus {
423            center: frame.origin,
424            axis_dir: frame.axis,
425            major_radius: *major_radius,
426            minor_radius: *minor_radius,
427        }),
428        AnalyticSurface::Revolution { .. } => Err(
429            "split_solid_by_face_surface: general revolved surfaces are not supported as a cut tool"
430                .into(),
431        ),
432    }
433}
434
435/// Split `solid` by the analytic carrier of a selected face `surface`
436/// (Golovanov §6.4).  The face may be a plane, cylinder, cone, or sphere; the
437/// carrier is extended to fully span the body.  Returns the two pieces
438/// (`[below, above]` for a plane, `[inside, outside]` otherwise).  Errors on
439/// non-analytic / general-revolution faces, or when the carrier does not
440/// cleanly divide the body.
441pub fn split_solid_by_face_surface(
442    solid: &BrepSolid,
443    surface: &NurbsSurface,
444) -> Result<Vec<BrepSolid>, String> {
445    let tool = recognized_split_surface(surface)?;
446    split_solid_by_surface(solid, &tool)
447}
448