Skip to main content

brep_blend/blending/fillet/
faces.rs

1//! A fillet between two faces that need not share an edge: a ball of `radius`
2//! rolling while it touches both, what lies outside its path between its
3//! contacts going, faces between them included.
4//!
5//! Built where both faces are planes and the faces between them (each sharing
6//! an edge with both) are planes too, ending on planes square to the line the
7//! two faces' planes meet in (a prism's chamfered or faceted corner): the
8//! material between those faces and that line is put back (a triangular prism
9//! on the line and the far edges of the faces between, united and its
10//! coplanar faces merged), and the sharp edge that leaves on the line is
11//! filleted at `radius`. Where the ball's contacts fall short of the faces
12//! between (on them, not beyond), the ball does not touch the two faces alone
13//! and the call is refused by name, as it is for any other configuration.
14use super::*;
15
16const ENTRY: &str = "fillet_faces";
17
18fn unsupported(what: &'static str, message: String) -> KernelRefusal {
19    KernelRefusal::unsupported(KernelStage::Classify, what, format!("{ENTRY}: {message}"))
20}
21
22/// The outward unit normal of a planar face, if it is one.
23fn outward_plane_normal(face: &FaceRecord) -> Option<Vec3> {
24    let s = &face.surface;
25    if s.degree_u != 1 || s.degree_v != 1 {
26        return None;
27    }
28    let pts: Vec<Vec3> = s.control_points.iter().flatten().filter_map(|c| c.point().ok()).collect();
29    if pts.len() < 3 {
30        return None;
31    }
32    let n = pts[1].sub(pts[0]).cross(pts[pts.len() - 1].sub(pts[0]));
33    let n = if n.length() > 0.0 { n } else { pts[2].sub(pts[0]).cross(pts[1].sub(pts[0])) };
34    let mut n = n.normalized().ok()?;
35    let scale = pts.iter().map(|p| p.sub(pts[0]).length()).fold(0.0, f64::max).max(1.0);
36    if pts.iter().any(|p| n.dot(p.sub(pts[0])).abs() > 1e-10 * scale) {
37        return None;
38    }
39    // The carrier's own normal, turned by the face's sense.
40    let [u0, u1] = s.domain_u().ok()?;
41    let [v0, v1] = s.domain_v().ok()?;
42    let carrier = s.normal(0.5 * (u0 + u1), 0.5 * (v0 + v1)).ok()?;
43    if carrier.dot(n) < 0.0 {
44        n = n.scale(-1.0);
45    }
46    Some(if face.same_sense { n } else { n.scale(-1.0) })
47}
48
49/// The face the point lies on.
50fn face_at(solid: &BrepSolid, point: Vec3) -> Result<u64, KernelRefusal> {
51    // Within a millionth of the solid's own size (its vertices' box), wherever it stands.
52    let (lo, hi) = solid.vertices.iter().fold((Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY)), |(lo, hi), v| {
53        (Vec3::new(lo.x.min(v.point.x), lo.y.min(v.point.y), lo.z.min(v.point.z)), Vec3::new(hi.x.max(v.point.x), hi.y.max(v.point.y), hi.z.max(v.point.z)))
54    });
55    let size = hi.sub(lo).length();
56    let near = if size.is_finite() && size > 0.0 { 1e-6 * size } else { 1e-9 };
57    let mut best: Option<(f64, u64)> = None;
58    for face in solid.shells.iter().flat_map(|s| s.faces.iter()) {
59        let Ok(q) = crate::project_point_to_surface(&face.surface, point) else { continue };
60        if q.distance > near {
61            continue;
62        }
63        let inside = crate::classification::parameter_point_in_face(face, crate::Vec2 { x: q.u, y: q.v }, 1e-9).map(|c| c != crate::classification::PolygonClass::Outside).unwrap_or(false);
64        if inside && best.map_or(true, |b| q.distance < b.0) {
65            best = Some((q.distance, face.id));
66        }
67    }
68    best.map(|b| b.1).ok_or_else(|| KernelRefusal::input(KernelStage::Collect, "face_point", format!("{ENTRY}: no face of the solid holds the point {point:?}")))
69}
70
71fn face_vertices(solid: &BrepSolid, face: &FaceRecord) -> Vec<Vec3> {
72    let mut ids: Vec<u64> = Vec::new();
73    for c in face.loops.iter().flat_map(|l| l.coedges.iter()) {
74        if let Some(e) = solid.edges.iter().find(|e| e.id == c.edge_id) {
75            for v in [e.start_vertex_id, e.end_vertex_id] {
76                if !ids.contains(&v) {
77                    ids.push(v);
78                }
79            }
80        }
81    }
82    ids.iter().filter_map(|id| solid.vertices.iter().find(|v| v.id == *id).map(|v| v.point)).collect()
83}
84
85fn face_edges(face: &FaceRecord) -> Vec<u64> {
86    face.loops.iter().flat_map(|l| l.coedges.iter().map(|c| c.edge_id)).collect()
87}
88
89/// Rounds between the faces `point_a` and `point_b` lie on by a ball of `radius`
90/// (see the module's account of what is built and what is refused).
91pub fn fillet_faces(solid: &BrepSolid, point_a: Vec3, point_b: Vec3, radius: f64, name: Option<&str>) -> Result<BrepSolid, KernelRefusal> {
92    let _operation = crate::blend::BlendOperation::enter();
93    if !(radius > 0.0) || !radius.is_finite() {
94        return Err(KernelRefusal::input(KernelStage::Collect, "fillet_faces_radius", format!("{ENTRY}: the radius must be positive")));
95    }
96    if solid.shells.len() != 1 {
97        return Err(unsupported("fillet_faces_shells", "the solid has more than one shell".into()));
98    }
99    let (ia, ib) = (face_at(solid, point_a)?, face_at(solid, point_b)?);
100    if ia == ib {
101        return Err(KernelRefusal::input(KernelStage::Collect, "fillet_faces_same", format!("{ENTRY}: both points lie on one face")));
102    }
103    let faces = &solid.shells[0].faces;
104    let (fa, fb) = (faces.iter().find(|f| f.id == ia).expect("face"), faces.iter().find(|f| f.id == ib).expect("face"));
105    let (na, nb) = match (outward_plane_normal(fa), outward_plane_normal(fb)) {
106        (Some(a), Some(b)) => (a, b),
107        _ => return Err(unsupported("fillet_faces_planes", "both faces must be planes".into())),
108    };
109    let e = na.cross(nb);
110    if e.length() < 1e-9 {
111        return Err(unsupported("fillet_faces_parallel", "the faces' planes do not meet".into()));
112    }
113    let e = e.normalized().or_refuse(KernelStage::Classify, "normalized")?;
114    let (va, vb) = (face_vertices(solid, fa), face_vertices(solid, fb));
115    let (Some(&qa), Some(&qb)) = (va.first(), vb.first()) else {
116        return Err(unsupported("fillet_faces_vertices", "a face has no vertices".into()));
117    };
118    // The line the planes meet in: K with na·K = na·qa, nb·K = nb·qb, e·K = e·(middle of the faces).
119    let middle = va.iter().chain(&vb).fold(Vec3::new(0.0, 0.0, 0.0), |s, p| s.add(*p)).scale(1.0 / (va.len() + vb.len()) as f64);
120    let (da, db, de) = (na.dot(qa), nb.dot(qb), e.dot(middle));
121    let denominator = na.dot(nb.cross(e));
122    let k = nb.cross(e).scale(da).add(e.cross(na).scale(db)).add(na.cross(nb).scale(de)).scale(1.0 / denominator);
123    let scale = va.iter().chain(&vb).map(|p| p.sub(k).length()).fold(0.0, f64::max).max(1.0);
124    let tol = 1e-9 * scale;
125    // Each face's direction away from the line, in its plane.
126    let away = |n: Vec3, verts: &[Vec3]| -> Option<Vec3> {
127        let d = e.cross(n).normalized().ok()?;
128        let reach = verts.iter().map(|p| d.dot(p.sub(k))).fold(0.0, |a: f64, b| if b.abs() > a.abs() { b } else { a });
129        Some(if reach < 0.0 { d.scale(-1.0) } else { d })
130    };
131    let (Some(ua), Some(ub)) = (away(na, &va), away(nb, &vb)) else { return Err(unsupported("fillet_faces_planes", "the faces' directions from their line are undefined".into())) };
132    // A convex corner: each face's outward normal points away from the other face.
133    if na.dot(ub) > -1e-9 || nb.dot(ua) > -1e-9 {
134        return Err(unsupported("fillet_faces_concave", "the faces meet in a concave corner; only a convex one is rounded here".into()));
135    }
136    // The faces between: those sharing an edge with each and running along
137    // the line.
138    let (ea, eb) = (face_edges(fa), face_edges(fb));
139    // (running along the line: an end face shares an edge with each too, but
140    // stands square to it)
141    let between: Vec<&FaceRecord> = faces
142        .iter()
143        .filter(|f| f.id != ia && f.id != ib)
144        .filter(|f| {
145            let own = face_edges(f);
146            own.iter().any(|x| ea.contains(x)) && own.iter().any(|x| eb.contains(x))
147        })
148        .filter(|f| outward_plane_normal(f).is_none_or(|n| n.dot(e).abs() < 1e-6))
149        .collect();
150    if between.is_empty() {
151        return Err(unsupported("fillet_faces_between", "no face lies between the two (they share an edge: fillet that edge)".into()));
152    }
153    let mut far = [0.0f64; 2];
154    let (mut tmin, mut tmax) = (f64::INFINITY, f64::NEG_INFINITY);
155    let mut corners: Vec<f64> = Vec::new();
156    for face in &between {
157        if outward_plane_normal(face).is_none() {
158            return Err(unsupported("fillet_faces_between", "a face between the two is not a plane".into()));
159        }
160        for p in face_vertices(solid, face) {
161            let r = p.sub(k);
162            // Within the wedge between the two planes, toward the solid.
163            if na.dot(r) > tol || nb.dot(r) > tol {
164                return Err(unsupported("fillet_faces_between", "a face between the two reaches past their planes".into()));
165            }
166            if na.dot(r).abs() <= tol {
167                far[0] = far[0].max(ua.dot(r));
168            }
169            if nb.dot(r).abs() <= tol {
170                far[1] = far[1].max(ub.dot(r));
171            }
172            let t = e.dot(r);
173            tmin = tmin.min(t);
174            tmax = tmax.max(t);
175            corners.push(t);
176        }
177    }
178    // The faces between end on two planes square to the line.
179    if corners.iter().any(|&t| (t - tmin).abs() > tol && (t - tmax).abs() > tol) || !(tmax - tmin > tol) {
180        return Err(unsupported("fillet_faces_ends", "the faces between do not end on planes square to the line the two faces meet in".into()));
181    }
182    if !(far[0] > tol && far[1] > tol) {
183        return Err(unsupported("fillet_faces_between", "the faces between do not reach each face".into()));
184    }
185    // The ball's contacts must clear the faces between, and the ball itself
186    // must stand clear of each of their planes (its centre on the bisector,
187    // `radius / sin(θ/2)` from the line, at least `radius` from each).
188    let theta = ua.dot(ub).clamp(-1.0, 1.0).acos();
189    let contact = radius / (0.5 * theta).tan();
190    if !(contact > far[0].max(far[1]) * (1.0 + 1e-9)) {
191        return Err(unsupported(
192            "fillet_faces_contact",
193            format!("a ball of radius {radius} touches the faces {contact:.6} from their line, not past the faces between ({:.6}); it would touch those too", far[0].max(far[1])),
194        ));
195    }
196    let bisector = ua.add(ub).normalized().or_refuse(KernelStage::Classify, "normalized")?;
197    let centre = k.add(bisector.scale(radius / (0.5 * theta).sin()));
198    for face in &between {
199        let n = outward_plane_normal(face).expect("planar");
200        let on = face_vertices(solid, face).first().copied().unwrap_or(k);
201        let clearance = n.dot(on.sub(centre));
202        if !(clearance >= radius * (1.0 - 1e-9)) {
203            return Err(unsupported(
204                "fillet_faces_contact",
205                format!("a ball of radius {radius} between the faces stands {clearance:.6} from a face between them; it would touch it, not pass it"),
206            ));
207        }
208    }
209    // Put back the material between the faces between and the line, merge the
210    // coplanar faces that leaves, and round the sharp edge on the line.
211    let base = k.add(e.scale(tmin));
212    let triangle = [base, base.add(ua.scale(far[0])), base.add(ub.scale(far[1]))];
213    let curves: Vec<NurbsCurve> = (0..3).map(|i| make_line(triangle[i], triangle[(i + 1) % 3]).or_refuse(KernelStage::Fragment, "make_line")).collect::<Result<_, _>>()?;
214    let wedge = extrude_profile_brep(&curves, e, tmax - tmin)?;
215    let united = boolean_operation(solid, &wedge, crate::BooleanOperation::Union, &Default::default())?;
216    let merged = crate::merge_same_surface_faces(&united, 1e-7).unwrap_or(united);
217    let on_line = k.add(e.scale(0.5 * (tmin + tmax)));
218    let result = fillet_edges(&merged, &[on_line], None, radius, false, name)?;
219    Ok(result)
220}