Skip to main content

brep_kernel/construction/
draft_roof.rs

1//! A drafted extrusion carried past the taper that closes its section: the
2//! roof.
3//!
4//! [`crate::extrude_profile_brep_draft`] builds the drafted walls up to a far
5//! section that is still the profile's offset, and refuses by name once the
6//! taper has closed part of it. For a profile of straight sides the solid past
7//! that taper is still plain: every wall is a plane leaning in over its side,
8//! and the solid is what lies under all of them between the profile's plane and
9//! the far one. Where the profile is convex that is the common part of the
10//! half-spaces under the walls. Where it has a notch (a run of sides that turn
11//! the other way, between two corners of its hull), what lies OUTSIDE the walls
12//! of the notch's sides, all of them at once, is cut out of that: the notch
13//! grown as its walls lean. Both are convex, so the solid is the convex body
14//! of the hull's walls less one convex body for each notch, cut by the kernel's
15//! boolean; every face is a plane and nothing is fitted.
16use crate::{BooleanOperation, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, OrRefuse, RefusalClass, Vec3};
17
18/// The prefix of every refusal of this operation.
19pub const DRAFT_ROOF_REFUSAL: &str = "draftRoof";
20
21fn refuse(what: &'static str, message: String) -> KernelRefusal {
22    KernelRefusal::unsupported(KernelStage::Classify, what, format!("{DRAFT_ROOF_REFUSAL}: {message}"))
23}
24
25/// The solid of `profile` extruded by `distance` along `direction` with its
26/// walls drafted inward by `draft_angle_rad`, whether or not the taper closes
27/// the section before the far end.
28///
29/// Where [`crate::extrude_profile_brep_draft`] builds, this is its solid,
30/// unchanged. Where it refuses because the taper closes the section
31/// (`draft_section_closes`), the solid under the leaning walls is built: a
32/// rectangle drafted past half its width ends in a ridge, an L in a ridge over
33/// each arm. Its faces are, in order: the walls, those of each side of the
34/// profile together and in the profile's order (sides that run on in one line
35/// have one wall, told as the first of them); the face in the profile's plane;
36/// and the face in the far plane, if the walls leave one. The extrusion runs
37/// square to the profile's plane.
38///
39/// Refuses, by name: a profile with a side that is not straight
40/// (`roof_side`), a taper that is refused as closing but does not lean inward
41/// (`roof_taper`), a notch that has a notch of its own (`roof_nested_notch`;
42/// its sides must all turn the same way), and a result with a face that joins
43/// no wall standing on its own side (`roof_wall`: a wall would have cut
44/// material that is not under it).
45pub fn extrude_profile_brep_draft_roof(profile: &[NurbsCurve], direction: Vec3, distance: f64, draft_angle_rad: f64) -> Result<BrepSolid, KernelRefusal> {
46    match crate::extrude_profile_brep_draft(profile, direction, distance, draft_angle_rad, None) {
47        Err(error) if matches!(&error.class, RefusalClass::InvalidInput { what } if what == "draft_section_closes") => {}
48        other => return other,
49    }
50    let stage = KernelStage::Collect;
51    // the corners, each side straight
52    let mut corners: Vec<Vec3> = Vec::with_capacity(profile.len());
53    for (index, side) in profile.iter().enumerate() {
54        let [t0, t1] = side.domain().or_refuse(stage, "draftRoof.domain")?;
55        let (from, to) = (side.evaluate(t0).or_refuse(stage, "draftRoof.end")?, side.evaluate(t1).or_refuse(stage, "draftRoof.end")?);
56        let chord = to.sub(from);
57        for k in 1..8 {
58            let point = side.evaluate(t0 + (t1 - t0) * k as f64 / 8.0).or_refuse(stage, "draftRoof.point")?;
59            if point.sub(from).cross(chord).length() > 1e-9 * chord.length().max(1e-300) * chord.length() {
60                return Err(refuse("roof_side", format!("side {index} of the profile is not straight; the roof is built over straight sides only")));
61            }
62        }
63        corners.push(from);
64    }
65    // The extrusion runs square to the profile's own plane, on the side `direction` and the
66    // distance's sign give (the drafted extrusion takes a direction within a few degrees of that
67    // normal; the profile is not moved onto another plane).
68    let normal = crate::polygon::newell_normal(&corners).normalized().or_refuse(stage, "draftRoof.plane")?;
69    let toward = direction.dot(normal) * distance;
70    if toward == 0.0 {
71        return Err(refuse("roof_taper", "the extrusion's direction lies in the profile's plane".into()));
72    }
73    let up = normal.scale(toward.signum());
74    // the section's inset for each unit of height, by the drafted extrusion's own law
75    // (distance · tan(draft) over the whole height): it closes only where that is positive
76    let slope = distance.signum() * draft_angle_rad.tan();
77    if !(slope > 0.0 && slope.is_finite()) {
78        return Err(refuse("roof_taper", "the section is refused as closing, but its taper does not lean inward".into()));
79    }
80    let origin = corners[0];
81    let x = corners[1].sub(origin);
82    let x = x.sub(up.scale(x.dot(up))).normalized().or_refuse(stage, "draftRoof.frame")?;
83    let y = up.cross(x);
84    let all: Vec<[f64; 2]> = corners.iter().map(|corner| [corner.sub(origin).dot(x), corner.sub(origin).dot(y)]).collect();
85    // Sides that run on in one line are one wall: only the corners where the outline turns are
86    // kept, and the wall is told as the first of its sides.
87    let reach = all.iter().map(|p| p[0].hypot(p[1])).fold(0.0, f64::max);
88    let kept: Vec<usize> = (0..all.len())
89        .filter(|&k| {
90            let (a, b, c) = (all[(k + all.len() - 1) % all.len()], all[k], all[(k + 1) % all.len()]);
91            let (u, v) = ([b[0] - a[0], b[1] - a[1]], [c[0] - b[0], c[1] - b[1]]);
92            (u[0] * v[1] - u[1] * v[0]).abs() > 1e-12 * reach * reach || u[0] * v[0] + u[1] * v[1] < 0.0
93        })
94        .collect();
95    if kept.len() < 3 {
96        return Err(refuse("roof_side", "the profile has fewer than three corners".into()));
97    }
98    let sides = profile.len();
99    let count = kept.len();
100    let mut flat: Vec<[f64; 2]> = kept.iter().map(|&k| all[k]).collect();
101    // Everything below is built in the profile's own frame (its first corner at the origin, its
102    // plane z = 0, the extrusion along +z) and carried to its place at the end, so that no
103    // tolerance depends on where the profile lies. The walls have closed by the height at which
104    // the inset reaches the profile's extent, so the far plane is never taken above twice that:
105    // a far end beyond the roof's top changes nothing.
106    let placement = crate::AffineTransform {
107        elements: [x.x, y.x, up.x, origin.x, x.y, y.y, up.y, origin.y, x.z, y.z, up.z, origin.z, 0.0, 0.0, 0.0, 1.0],
108    };
109    let (x, y, up, origin) = (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), Vec3::new(0.0, 0.0, 1.0), Vec3::new(0.0, 0.0, 0.0));
110    let extent = flat.iter().map(|p| p[0].hypot(p[1])).fold(0.0, f64::max);
111    let height = distance.abs().min(2.0 * extent / slope);
112    let size = extent.max(height);
113    // counter-clockwise seen from the far side; `source[i]`: the profile's side that side i is
114    let area: f64 = (0..count).map(|i| flat[i][0] * flat[(i + 1) % count][1] - flat[(i + 1) % count][0] * flat[i][1]).sum();
115    let mut source: Vec<usize> = kept.clone();
116    if area < 0.0 {
117        flat.reverse();
118        // corner i is now corner count − 1 − i; side i runs from it to the next: the side count − 2 − i
119        source = (0..count).map(|i| kept[(2 * count - 2 - i) % count]).collect();
120    }
121    let point = |p: [f64; 2], z: f64| origin.add(x.scale(p[0])).add(y.scale(p[1])).add(up.scale(z));
122    // the wall over side i, as n · p ≤ d
123    let wall = |i: usize| -> (Vec3, f64) {
124        let (a, b) = (flat[i], flat[(i + 1) % count]);
125        let length = (b[0] - a[0]).hypot(b[1] - a[1]);
126        let out = x.scale((b[1] - a[1]) / length).add(y.scale(-(b[0] - a[0]) / length));
127        let normal = out.add(up.scale(slope)).scale(1.0 / (1.0 + slope * slope).sqrt());
128        (normal, normal.dot(point(a, 0.0)))
129    };
130    // the hull, keeping corners that lie on its sides
131    let turn = |a: [f64; 2], b: [f64; 2], c: [f64; 2]| (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]);
132    let mut order: Vec<usize> = (0..count).collect();
133    order.sort_by(|&p, &q| flat[p][0].total_cmp(&flat[q][0]).then(flat[p][1].total_cmp(&flat[q][1])));
134    let mut hull: Vec<usize> = Vec::new();
135    for pass in 0..2 {
136        let start = hull.len();
137        let list: Vec<usize> = if pass == 0 { order.clone() } else { order.iter().rev().copied().collect() };
138        for index in list {
139            while hull.len() >= start + 2 && turn(flat[hull[hull.len() - 2]], flat[hull[hull.len() - 1]], flat[index]) < -1e-12 * size * size {
140                hull.pop();
141            }
142            hull.push(index);
143        }
144        hull.pop();
145    }
146    // corners on a hull side that the hull's walk picked out of the profile's order are dropped
147    let on_hull: Vec<usize> = { let mut kept = hull.clone(); kept.sort_unstable(); kept.dedup(); kept };
148    let far = 4.0 * size + 4.0 * (slope.abs() * height);
149    let mut body_planes: Vec<(Vec3, f64)> = vec![(up.scale(-1.0), -up.dot(origin)), (up, up.dot(origin) + height)];
150    let mut notches: Vec<Vec<(Vec3, f64)>> = Vec::new();
151    for (k, &from) in on_hull.iter().enumerate() {
152        let to = on_hull[(k + 1) % on_hull.len()];
153        if (from + 1) % count == to {
154            body_planes.push(wall(from));
155            continue;
156        }
157        // a notch: the sides from `from` round to `to`; the hull's own side across its mouth is upright
158        let (a, b) = (flat[from], flat[to]);
159        let length = (b[0] - a[0]).hypot(b[1] - a[1]);
160        let out = x.scale((b[1] - a[1]) / length).add(y.scale(-(b[0] - a[0]) / length));
161        body_planes.push((out, out.dot(point(a, 0.0))));
162        let mut planes: Vec<(Vec3, f64)> = Vec::new();
163        let mut i = from;
164        while i != to {
165            let next = (i + 1) % count;
166            if next != to && turn(flat[i], flat[next], flat[(next + 1) % count]) > -1e-12 * size * size {
167                return Err(refuse("roof_nested_notch", format!("the notch between corners {from} and {to} of the profile has a corner that turns back in (a notch within a notch); the roof is built where every notch's sides turn one way")));
168            }
169            let (normal, d) = wall(i);
170            planes.push((normal.scale(-1.0), -d));
171            i = next;
172        }
173        // closed off far outside the solid, so that the notch's body is bounded
174        let centre = point([0.0, 0.0], 0.5 * height);
175        for axis in [x, y, up] {
176            planes.push((axis, axis.dot(centre) + far));
177            planes.push((axis.scale(-1.0), -axis.dot(centre) + far));
178        }
179        notches.push(planes);
180    }
181    let solid_of = |planes: &[(Vec3, f64)]| -> Result<BrepSolid, KernelRefusal> {
182        let (points, faces) = crate::solid_sweep_caps::polyhedron_of_planes(planes)?;
183        let polygons: Vec<Vec<Vec3>> = faces.iter().map(|face| face.iter().map(|&c| points[c]).collect()).collect();
184        crate::solid_from_polygons(&polygons)
185    };
186    let mut operands = vec![solid_of(&body_planes)?];
187    for planes in &notches {
188        operands.push(solid_of(planes)?);
189    }
190    let roof = if operands.len() == 1 { operands.pop().expect("one") } else { crate::boolean_operation_nary(&operands, BooleanOperation::Subtract)? };
191
192    // the faces by the plane they lie in
193    // by the footprint's size: a tall roof over a small footprint has walls no farther apart for its height
194    let tolerance = 1e-7 * extent + 1e-12 * size;
195    let on_plane = |face: &crate::FaceRecord, plane: &(Vec3, f64)| -> bool {
196        let Ok(mut vertices) = face_points(&roof, face) else { return false };
197        vertices.truncate(64);
198        !vertices.is_empty() && vertices.iter().all(|p| (plane.0.dot(*p) - plane.1).abs() <= tolerance)
199    };
200    let faces = &roof.shells.first().ok_or_else(|| refuse("roof_empty", "the walls leave no solid".into()))?.faces;
201    let mut taken = vec![false; faces.len()];
202    let mut ordered: Vec<usize> = Vec::with_capacity(faces.len());
203    let mut by_source: Vec<Vec<usize>> = vec![Vec::new(); sides];
204    for i in 0..count {
205        let plane = wall(i);
206        let mine: Vec<usize> = (0..faces.len()).filter(|&f| !taken[f] && on_plane(&faces[f], &plane)).collect();
207        // one piece, standing on its own side
208        let foot = point([0.5 * (flat[i][0] + flat[(i + 1) % count][0]), 0.5 * (flat[i][1] + flat[(i + 1) % count][1])], 0.0);
209        let stands = |f: usize| face_edges(&roof, &faces[f]).iter().any(|edge| crate::project_point_to_curve(&edge.curve, foot).map(|hit| hit.distance <= tolerance).unwrap_or(false));
210        let Some(first) = mine.iter().copied().find(|&f| stands(f)) else {
211            return Err(refuse("roof_wall", format!("the wall over side {} of the profile does not stand on its side", source[i])));
212        };
213        let mut reached = vec![first];
214        let mut grew = true;
215        while grew {
216            grew = false;
217            for &f in &mine {
218                if reached.contains(&f) {
219                    continue;
220                }
221                let edges: Vec<u64> = faces[f].loops.iter().flat_map(|l| l.coedges.iter().map(|c| c.edge_id)).collect();
222                if reached.iter().any(|&g| faces[g].loops.iter().flat_map(|l| &l.coedges).any(|c| edges.contains(&c.edge_id))) {
223                    reached.push(f);
224                    grew = true;
225                }
226            }
227        }
228        // faces in this plane that do not join it are another side's (two sides in one line share
229        // their wall's plane), or nobody's: what is left over at the end is refused
230        reached.sort_unstable();
231        for &f in &reached {
232            taken[f] = true;
233        }
234        by_source[source[i]] = reached;
235    }
236    for mine in by_source {
237        ordered.extend(mine);
238    }
239    for plane in &body_planes[..2] {
240        let caps: Vec<usize> = (0..faces.len()).filter(|&f| !taken[f] && on_plane(&faces[f], plane)).collect();
241        for &f in &caps {
242            taken[f] = true;
243        }
244        ordered.extend(caps);
245    }
246    if taken.iter().any(|t| !t) {
247        return Err(refuse("roof_wall", "the solid has a face that joins no wall standing on its own side: a wall would cut material that is not under it".into()));
248    }
249    let mut roof = roof.clone();
250    let shell = &mut roof.shells[0];
251    let all = std::mem::take(&mut shell.faces);
252    let mut slots: Vec<Option<crate::FaceRecord>> = all.into_iter().map(Some).collect();
253    shell.faces = ordered.into_iter().map(|f| slots[f].take().expect("each face once")).collect();
254    crate::transform_brep(&roof, placement, false).or_refuse(KernelStage::Fragment, "draftRoof.place")
255}
256
257fn face_edges<'a>(solid: &'a BrepSolid, face: &crate::FaceRecord) -> Vec<&'a crate::topology::EdgeRecord> {
258    let ids: Vec<u64> = face.loops.iter().flat_map(|l| l.coedges.iter().map(|c| c.edge_id)).collect();
259    solid.edges.iter().filter(|edge| ids.contains(&edge.id)).collect()
260}
261
262/// The ends of a face's edges.
263fn face_points(solid: &BrepSolid, face: &crate::FaceRecord) -> Result<Vec<Vec3>, String> {
264    let mut points = Vec::new();
265    for edge in face_edges(solid, face) {
266        points.push(edge.curve.evaluate(edge.t0)?);
267        points.push(edge.curve.evaluate(edge.t1)?);
268        points.push(edge.curve.evaluate(0.5 * (edge.t0 + edge.t1))?);
269    }
270    Ok(points)
271}
272