Skip to main content

brep_kernel/blending/
fillet_tangent_chains.rs

1//! A fillet of edges and every edge their G1 tangent chains continue into:
2//! the fillet feature's "Follow tangent" selection, as one public call; and
3//! the fillet with the caller's options (follow tangents, refuse a pinch);
4//! and the equal-distance chamfer with the caller's options (follow tangents).
5use crate::{fillet_edges, BrepSolid, KernelRefusal, KernelStage, Vec3};
6
7/// [`fillet_edges`] of `edge_points`' edges and every unselected edge on the
8/// tangent chains through them (closed loops included: picking one straight
9/// edge of a prism whose upright corners are rounded rounds its whole top
10/// loop). The chains are walked as the fillet feature walks them
11/// (`tangent_chain_expansion`: from each end vertex the single edge whose
12/// tangent continues the chain within 1e-6, stopping at a sharp or ambiguous
13/// junction). `edge_names`, when given, names the picked edges; the edges the
14/// chains add carry their own names.
15pub fn fillet_edges_tangent_chains(
16    solid: &BrepSolid,
17    edge_points: &[Vec3],
18    edge_names: Option<&[String]>,
19    radius: f64,
20    name: Option<&str>,
21) -> Result<BrepSolid, KernelRefusal> {
22    let seeds = edge_points
23        .iter()
24        .map(|point| brep_blend::fillet::edges::resolve_edge_by_point(solid, *point))
25        .collect::<Result<Vec<u64>, KernelRefusal>>()?;
26    let added = crate::feature_pipeline::features::common::tangent_chain_expansion(solid, &seeds, &seeds)
27        .map_err(|error| KernelRefusal::internal(KernelStage::Collect, "tangent_chain", error))?;
28    if added.is_empty() {
29        return fillet_edges(solid, edge_points, edge_names, radius, false, name);
30    }
31    let mut points = edge_points.to_vec();
32    points.extend(added.iter().map(|(_, point, _)| *point));
33    let names = edge_names.map(|names| {
34        let mut all = names.to_vec();
35        all.extend(added.iter().map(|(_, _, name)| name.clone()));
36        all
37    });
38    fillet_edges(solid, &points, names.as_deref(), radius, false, name)
39}
40
41/// How [`fillet_edges_with_options`] reads a selection.
42#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
43pub struct FilletOptions {
44    /// Also fillet every edge the picked edges' tangent chains continue into
45    /// ([`fillet_edges_tangent_chains`]).
46    pub follow_tangent_chains: bool,
47    /// Refuse (InvalidInput) a selection whose blends overlap on a face lying
48    /// between two parallel picked edges with parallel walls beyond, unless
49    /// the radius is half the walls' distance (the full round). By default
50    /// the kernel builds such a pair as two balls each tangent to its own
51    /// faces, pinching to a ridge where they meet; a caller that wants every
52    /// ball to touch both faces it rolls on asks for the refusal
53    /// (`brep_blend::fillet::pinch_refusal`).
54    pub refuse_pinch: bool,
55}
56
57/// [`fillet_edges`] read with `options`: the selection widened along its
58/// tangent chains first when asked, and the pinch refused when asked (judged
59/// on the widened selection).
60pub fn fillet_edges_with_options(
61    solid: &BrepSolid,
62    edge_points: &[Vec3],
63    edge_names: Option<&[String]>,
64    radius: f64,
65    options: FilletOptions,
66    name: Option<&str>,
67) -> Result<BrepSolid, KernelRefusal> {
68    let (points, names) = widen_along_tangent_chains(solid, edge_points, edge_names, options.follow_tangent_chains)?;
69    if options.refuse_pinch {
70        if let Some(refusal) = brep_blend::fillet::pinch_refusal(solid, &points, radius) {
71            return Err(refusal);
72        }
73    }
74    let refused = match fillet_edges(solid, &points, names.as_deref(), radius, false, name) {
75        Ok(built) => return Ok(built),
76        Err(refused) => refused,
77    };
78    // A sliver the round swallows: answered where the plain build refuses.
79    match swallowed_face_route(solid, &points, names.as_deref(), radius, name) {
80        Some(Ok(built)) => Ok(built),
81        _ => Err(refused),
82    }
83}
84
85/// How [`chamfer_edges_with_options`] reads a selection.
86#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
87pub struct ChamferOptions {
88    /// Also chamfer every edge the picked edges' tangent chains continue into,
89    /// walked as [`fillet_edges_tangent_chains`] walks them: a hole's rim cut
90    /// as two half circles is one chain, so a point on either half chamfers
91    /// the whole rim.
92    pub follow_tangent_chains: bool,
93}
94
95/// An equal-distance chamfer ([`chamfer_edges_asymmetric`] with both
96/// setbacks `distance`) of `edge_points`' edges, read with `options`: the
97/// selection widened along its tangent chains first when asked. An edge the
98/// chains add takes the same distance and carries its own name.
99///
100/// [`chamfer_edges_asymmetric`]: crate::chamfer_edges_asymmetric
101pub fn chamfer_edges_with_options(
102    solid: &BrepSolid,
103    edge_points: &[Vec3],
104    edge_names: Option<&[String]>,
105    distance: f64,
106    options: ChamferOptions,
107    name: Option<&str>,
108) -> Result<BrepSolid, KernelRefusal> {
109    let (points, names) = widen_along_tangent_chains(solid, edge_points, edge_names, options.follow_tangent_chains)?;
110    crate::chamfer_edges_asymmetric(solid, &points, names.as_deref(), distance, distance, name)
111}
112
113/// `edge_points` (and their names) plus, when `follow`, a point on (and the
114/// name of) every unpicked edge on the picked edges' tangent chains.
115fn widen_along_tangent_chains(
116    solid: &BrepSolid,
117    edge_points: &[Vec3],
118    edge_names: Option<&[String]>,
119    follow: bool,
120) -> Result<(Vec<Vec3>, Option<Vec<String>>), KernelRefusal> {
121    let mut points = edge_points.to_vec();
122    let mut names = edge_names.map(|names| names.to_vec());
123    if follow {
124        let seeds = edge_points
125            .iter()
126            .map(|point| brep_blend::fillet::edges::resolve_edge_by_point(solid, *point))
127            .collect::<Result<Vec<u64>, KernelRefusal>>()?;
128        let added = crate::feature_pipeline::features::common::tangent_chain_expansion(solid, &seeds, &seeds)
129            .map_err(|error| KernelRefusal::internal(KernelStage::Collect, "tangent_chain", error))?;
130        points.extend(added.iter().map(|(_, point, _)| *point));
131        if let Some(names) = names.as_mut() {
132            names.extend(added.iter().map(|(_, _, name)| name.clone()));
133        }
134    }
135    Ok((points, names))
136}
137
138fn is_plane(face: &crate::topology::FaceRecord) -> bool {
139    let s = &face.surface;
140    s.degree_u == 1 && s.degree_v == 1 && s.control_points.len() == 2 && s.control_points[0].len() == 2 && face.surface.analytic().is_some_and(|a| matches!(a, crate::AnalyticSurface::Plane { .. }))
141}
142
143/// A SWALLOWED FACE: two parallel straight picked edges bound a planar strip
144/// between two planar faces that meet at a convex angle beyond it (a corner
145/// cut back by a sliver), and the round of that corner (its contacts
146/// `r · cot(φ/2)` from the corner along each face, φ the angle inside the
147/// material) reaches past both of the strip's edges: a ball of the radius
148/// cannot touch the strip, it rolls on the two faces beyond, and the strip
149/// goes. Every such strip is deleted in one heal (its neighbours extended to
150/// their meeting edge) and those edges filleted with the rest of the
151/// selection, each corner taking the first of its pair's names. `None`
152/// where no such pair is picked, or the heal refuses.
153fn swallowed_face_route(solid: &BrepSolid, edge_points: &[Vec3], edge_names: Option<&[String]>, radius: f64, name: Option<&str>) -> Option<Result<BrepSolid, KernelRefusal>> {
154    let ids: Vec<u64> = edge_points.iter().map(|p| brep_blend::fillet::edges::resolve_edge_by_point(solid, *p).ok()).collect::<Option<_>>()?;
155    let mut taken = vec![false; ids.len()];
156    let mut strips: Vec<u64> = Vec::new();
157    let mut corners: Vec<(usize, Vec3)> = Vec::new(); // (the pair's first index, a point on its corner edge)
158    for i in 0..ids.len() {
159        for j in i + 1..ids.len() {
160            if taken[i] || taken[j] {
161                continue;
162            }
163            let Ok((ea, fa)) = brep_blend::fillet::analyze::edge_and_faces(solid, ids[i]) else { continue };
164            let Ok((eb, fb)) = brep_blend::fillet::analyze::edge_and_faces(solid, ids[j]) else { continue };
165            if ea.curve.degree != 1 || eb.curve.degree != 1 || fa.len() != 2 || fb.len() != 2 {
166                continue;
167            }
168            let ends = |e: &crate::topology::EdgeRecord| -> Option<(Vec3, Vec3)> { Some((e.curve.evaluate(e.t0).ok()?, e.curve.evaluate(e.t1).ok()?)) };
169            let (Some((a0, a1)), Some((b0, b1))) = (ends(ea), ends(eb)) else { continue };
170            let (Ok(da), Ok(db)) = (a1.sub(a0).normalized(), b1.sub(b0).normalized()) else { continue };
171            if da.cross(db).length() > 1e-9 {
172                continue;
173            }
174            // The strip: the face both edges bound, its one loop of four.
175            let Some(strip) = fa.iter().find(|f| fb.iter().any(|g| g.id == f.id)) else { continue };
176            if !is_plane(strip) || strip.loops.len() != 1 || strip.loops[0].coedges.len() != 4 || strips.contains(&strip.id) {
177                continue;
178            }
179            let (pa, pb) = (a0.add(a1).scale(0.5), b0.add(b1).scale(0.5));
180            // The faces beyond, planar, meeting at a convex angle (not parallel).
181            let (Some(beyond_a), Some(beyond_b)) = (fa.iter().find(|f| f.id != strip.id), fb.iter().find(|f| f.id != strip.id)) else { continue };
182            if !is_plane(beyond_a) || !is_plane(beyond_b) {
183                continue;
184            }
185            let (Ok((on_a, na)), Ok((on_b, nb))) = (brep_blend::fillet::analyze::face_plane_normal(beyond_a, pa), brep_blend::fillet::analyze::face_plane_normal(beyond_b, pb)) else { continue };
186            if na.cross(nb).length() < 1e-9 {
187                continue;
188            }
189            // Their meeting line, at the strip's middle along the edges.
190            let middle = pa.add(pb).scale(0.5);
191            let det = na.dot(nb.cross(da));
192            if det.abs() < 1e-12 {
193                continue;
194            }
195            let corner = nb.cross(da).scale(na.dot(on_a)).add(da.cross(na).scale(nb.dot(on_b))).add(na.cross(nb).scale(da.dot(middle))).scale(1.0 / det);
196            // Convex: the strip's edges lie inside the material's wedge,
197            // behind both outward normals from the corner.
198            if !(pa.sub(corner).dot(nb) < 0.0 && pb.sub(corner).dot(na) < 0.0) {
199                continue;
200            }
201            // Swallowed: the corner's round reaches past both strip edges.
202            let inside = std::f64::consts::PI - na.dot(nb).clamp(-1.0, 1.0).acos();
203            if !(inside > 1e-9 && inside < std::f64::consts::PI - 1e-9) {
204                continue;
205            }
206            let setback = radius / (0.5 * inside).tan();
207            let from_corner = |p: Vec3| {
208                let off = p.sub(corner);
209                off.sub(da.scale(off.dot(da))).length()
210            };
211            if !(setback >= from_corner(pa) && setback >= from_corner(pb)) {
212                continue;
213            }
214            taken[i] = true;
215            taken[j] = true;
216            strips.push(strip.id);
217            corners.push((i, corner));
218        }
219    }
220    if strips.is_empty() {
221        return None;
222    }
223    let healed = crate::delete_faces_and_heal(solid, &strips).ok()?;
224    let mut points: Vec<Vec3> = Vec::new();
225    let mut names: Vec<String> = Vec::new();
226    for (k, point) in edge_points.iter().enumerate() {
227        if !taken[k] {
228            points.push(*point);
229            if let Some(given) = edge_names {
230                names.push(given.get(k).cloned().unwrap_or_default());
231            }
232        }
233    }
234    for &(first, corner) in &corners {
235        points.push(corner);
236        if let Some(given) = edge_names {
237            names.push(given.get(first).cloned().unwrap_or_default());
238        }
239    }
240    Some(fillet_edges(&healed, &points, edge_names.map(|_| names.as_slice()), radius, false, name))
241}
242
243