Skip to main content

brep_kernel/
plane_section.rs

1//! The cut of a solid by a plane: where the plane meets the boundary, as
2//! polylines, and the area of the cut.
3//!
4//! The solid is cut by the plane ([`solid_piece_by_plane`]); the piece below
5//! it (or above it, when that cut declines) carries one cap face on the plane for every region of the cut, bounded by
6//! the section curves themselves. The area is those faces' areas, and the
7//! curves are their edges, each sampled from end to end with every chord
8//! within the caller's tolerance of the edge curve. Every sample is a point of
9//! an edge curve, so it lies on the plane and on the boundary to the accuracy
10//! the boolean built those edges to.
11
12use crate::{face_area, solid_piece_by_plane, BrepSolid, FaceRecord, KernelRefusal, KernelStage, NurbsCurve, Vec3};
13
14/// The covers [`caps`] cuts with, tightest first: a box just over the solid
15/// keeps the boolean's tolerances to the solid's own size.
16const COVERS: [f64; 4] = [1.2, 1.5, 2.0, 3.0];
17
18/// The faces of a piece of `solid` cut off by the plane through `origin`
19/// square to `normal` that lie in that plane (the caps), with the piece that
20/// holds them; `None` when the plane does not cut the solid.
21///
22/// The plane misses when every control point of the solid lies strictly on
23/// one side (each face and edge lies in the hull of its control points), and
24/// no boolean is run. Otherwise the piece below the plane is cut, then the
25/// piece above (both carry the same caps), with boxes from [`COVERS`] in turn
26/// until one cut goes through. A piece with no face on the plane is a miss when
27/// the other side is empty, or when the plane passes between the solid's lumps
28/// ([`lumps_part`]); a cut that declines at every box, or a solid on both
29/// sides with no face on the plane otherwise, is refused, never read as a miss.
30fn caps(solid: &BrepSolid, origin: Vec3, normal: Vec3) -> Result<Option<(BrepSolid, Vec<usize>)>, KernelRefusal> {
31    let unit = normal
32        .normalized()
33        .map_err(|_| KernelRefusal::input(KernelStage::Collect, "section_normal", "section: the plane normal has no direction"))?;
34    let refuse = |message: String| KernelRefusal::internal(KernelStage::Fragment, "section_split", format!("section: {message}"));
35    let surfaces = solid.shells.iter().flat_map(|shell| &shell.faces).flat_map(|face| face.surface.control_points.iter().flatten());
36    let curves = solid.edges.iter().flat_map(|edge| edge.curve.control_points.iter());
37    let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
38    for control in surfaces.chain(curves) {
39        let height = control.point().map_err(|message| refuse(message))?.sub(origin).dot(unit);
40        low = low.min(height);
41        high = high.max(height);
42    }
43    if !(low < 0.0 && high > 0.0) {
44        return Ok(None);
45    }
46    let mut declined = Vec::new();
47    let mut found = None;
48    'covers: for cover in COVERS {
49        for above in [false, true] {
50            match solid_piece_by_plane(solid, origin, unit, above, cover) {
51                Ok(piece) => {
52                    found = Some(piece);
53                    break 'covers;
54                }
55                Err(message) => declined.push(message),
56            }
57        }
58    }
59    let Some(piece) = found else {
60        return Err(refuse(declined.join("; ")));
61    };
62    // The control points straddle the plane, but the solid itself may not.
63    let Some(piece) = piece else {
64        return Ok(None);
65    };
66    let extent = piece.vertices.iter().fold(0.0f64, |extent, vertex| {
67        extent.max(vertex.point.x.abs()).max(vertex.point.y.abs()).max(vertex.point.z.abs())
68    });
69    let scale = 1.0 + extent;
70    let tolerance = 1e-9 * scale;
71    let on_plane = |face: &FaceRecord| -> bool {
72        if !face.surface.is_affine().unwrap_or(false) {
73            return false;
74        }
75        face.surface.control_points.iter().flatten().all(|control| {
76            control.point().is_ok_and(|point| point.sub(origin).dot(unit).abs() <= tolerance)
77        })
78    };
79    let faces: Vec<usize> = piece.shells.iter().flat_map(|shell| &shell.faces).enumerate().filter(|(_, face)| on_plane(face)).map(|(index, _)| index).collect();
80    if faces.is_empty() {
81        // No cap: the plane misses the solid when nothing of it lies on the
82        // other side (the piece is then the whole solid), or when the solid's
83        // lumps fall wholly to one side or the other: the two pieces then
84        // share out the solid's faces without cutting any, their volumes sum
85        // to the solid's, and every vertex of each lies clear of the plane on
86        // its own side.
87        let other = declined.len() % 2 == 0;
88        let mut other_declined = Vec::new();
89        for cover in COVERS {
90            match solid_piece_by_plane(solid, origin, unit, other, cover) {
91                Ok(None) => return Ok(None),
92                Ok(Some(other_piece)) => {
93                    if lumps_part(solid, &piece, &other_piece, origin, unit, other, tolerance) {
94                        return Ok(None);
95                    }
96                    return Err(refuse("the solid lies on both sides of the plane but the cut left no face on it".into()));
97                }
98                Err(message) => other_declined.push(message),
99            }
100        }
101        return Err(refuse(format!(
102            "the cut left no face on the plane, and the other side declined: {}",
103            other_declined.join("; ")
104        )));
105    }
106    Ok(Some((piece, faces)))
107}
108
109/// Whether `first` and `second`, the pieces of `solid` on the two sides of the
110/// plane (`second` above it when `second_above`), are its lumps parted whole:
111/// together they hold exactly the solid's faces, their volumes sum to the
112/// solid's, and every vertex of each lies more than `tolerance` from the plane
113/// on its own side. A cut that split a face adds faces, so a solid the plane
114/// truly crosses never passes.
115fn lumps_part(solid: &BrepSolid, first: &BrepSolid, second: &BrepSolid, origin: Vec3, unit: Vec3, second_above: bool, tolerance: f64) -> bool {
116    let faces = |body: &BrepSolid| body.shells.iter().map(|shell| shell.faces.len()).sum::<usize>();
117    if faces(first) + faces(second) != faces(solid) {
118        return false;
119    }
120    let side = |body: &BrepSolid, above: bool| {
121        body.vertices.iter().all(|vertex| {
122            let height = vertex.point.sub(origin).dot(unit);
123            if above { height > tolerance } else { height < -tolerance }
124        })
125    };
126    if !(side(first, !second_above) && side(second, second_above)) {
127        return false;
128    }
129    match (crate::solid_mass_properties(solid), crate::solid_mass_properties(first), crate::solid_mass_properties(second)) {
130        // A lost or turned lump moves the sum by a whole lump; the mass
131        // integrals of swept faces carry a few parts in 1e9.
132        (Ok(whole), Ok(a), Ok(b)) => (a.volume + b.volume - whole.volume).abs() <= 1e-6 * whole.volume.abs().max(f64::MIN_POSITIVE),
133        _ => false,
134    }
135}
136
137/// `curve` over `[t0, t1]` as points from end to end, every chord within
138/// `tolerance` of the curve at its quarter points: each knot span is halved
139/// until it is.
140fn sample_edge(curve: &NurbsCurve, t0: f64, t1: f64, tolerance: f64) -> Result<Vec<Vec3>, String> {
141    let (low, high) = (t0.min(t1), t0.max(t1));
142    let mut breaks: Vec<f64> = vec![low];
143    breaks.extend(curve.knots.iter().copied().filter(|&knot| knot > low && knot < high));
144    breaks.push(high);
145    breaks.dedup();
146    let chord_error = |a: f64, b: f64| -> Result<f64, String> {
147        let (p, q) = (curve.evaluate(a)?, curve.evaluate(b)?);
148        let chord = q.sub(p);
149        let length = chord.length();
150        let mut worst = 0.0f64;
151        for fraction in [0.25, 0.5, 0.75] {
152            let point = curve.evaluate(a + (b - a) * fraction)?;
153            let offset = point.sub(p);
154            let along = if length > 0.0 { offset.dot(chord) / (length * length) } else { 0.0 };
155            worst = worst.max(offset.sub(chord.scale(along.clamp(0.0, 1.0))).length());
156        }
157        Ok(worst)
158    };
159    let mut parameters = vec![low];
160    for pair in breaks.windows(2) {
161        // Depth-first halving of the span, at most 24 levels deep.
162        let mut start = pair[0];
163        let mut pending = vec![(pair[1], 0u32)];
164        while let Some((end, depth)) = pending.pop() {
165            if depth < 24 && chord_error(start, end)? > tolerance {
166                let middle = 0.5 * (start + end);
167                pending.push((end, depth + 1));
168                pending.push((middle, depth + 1));
169                continue;
170            }
171            parameters.push(end);
172            start = end;
173        }
174    }
175    let mut points = parameters.iter().map(|&t| curve.evaluate(t)).collect::<Result<Vec<_>, _>>()?;
176    if t1 < t0 {
177        points.reverse();
178    }
179    Ok(points)
180}
181
182/// Where the plane through `origin` square to `normal` cuts the boundary of
183/// `solid`, in pieces in any order: each piece is one edge of the cut, as
184/// points along it from end to end, every chord within `chord_tolerance` of
185/// the edge curve. The pieces join end to end into the closed curves of the
186/// cut; a piece that is a whole closed curve ends on its first point. Empty
187/// when the plane misses the solid.
188pub fn solid_section(
189    solid: &BrepSolid,
190    origin: Vec3,
191    normal: Vec3,
192    chord_tolerance: f64,
193) -> Result<Vec<Vec<Vec3>>, KernelRefusal> {
194    if !(chord_tolerance > 0.0 && chord_tolerance.is_finite()) {
195        return Err(KernelRefusal::input(KernelStage::Collect, "section_tolerance", "section: the chord tolerance must be positive"));
196    }
197    let Some((below, faces)) = caps(solid, origin, normal)? else {
198        return Ok(Vec::new());
199    };
200    let all: Vec<&FaceRecord> = below.shells.iter().flat_map(|shell| &shell.faces).collect();
201    let mut pieces = Vec::new();
202    for index in faces {
203        for coedge in all[index].loops.iter().flat_map(|loop_record| &loop_record.coedges) {
204            let edge = below.edges.iter().find(|edge| edge.id == coedge.edge_id).ok_or_else(|| {
205                KernelRefusal::internal(KernelStage::Collect, "section_edge", format!("section: edge {} is missing", coedge.edge_id))
206            })?;
207            if edge.degenerate {
208                continue;
209            }
210            let points = sample_edge(&edge.curve, edge.t0, edge.t1, chord_tolerance)
211                .map_err(|message| KernelRefusal::internal(KernelStage::Collect, "section_sample", format!("section: {message}")))?;
212            pieces.push(points);
213        }
214    }
215    Ok(pieces)
216}
217
218/// The area of the cut of `solid` by the plane through `origin` square to
219/// `normal`: the area of the faces the split leaves on that plane. Zero when
220/// the plane misses the solid.
221pub fn solid_section_area(solid: &BrepSolid, origin: Vec3, normal: Vec3) -> Result<f64, KernelRefusal> {
222    let Some((below, faces)) = caps(solid, origin, normal)? else {
223        return Ok(0.0);
224    };
225    let all: Vec<&FaceRecord> = below.shells.iter().flat_map(|shell| &shell.faces).collect();
226    let mut area = 0.0;
227    for index in faces {
228        area += face_area(all[index])
229            .map_err(|message| KernelRefusal::internal(KernelStage::Collect, "section_area", format!("section area: {message}")))?;
230    }
231    Ok(area)
232}
233