Skip to main content

brep_render/sketch/
corner.rs

1//! Sketch corner fillet and chamfer: two lines meeting at one shared point are
2//! trimmed back and joined by a tangent arc (fillet) or a straight cut (chamfer).
3//!
4//! The corner point itself stays, as a construction point held on both lines
5//! (point-on-line `⏛`): the virtual sharp. Every constraint that named the corner
6//! (a rectangle's perpendiculars, a side's length) keeps its meaning, and the new
7//! profile edges are tied to it by constraints, so the corner stays parametric
8//! when the sketch is dragged or re-solved:
9//! - fillet: the arc is tangent to both lines, held as the radius square to
10//!   each line at its tangent point (`⟂`), and carries a radius dimension
11//!   (`⟺` with `displayStyle: "radius"`);
12//! - chamfer: a distance dimension from the virtual sharp to the first cut point,
13//!   and either an equal distance to the second (`⇌`) or an angle (`∠`) between
14//!   the first line and the cut.
15//!
16//! Values are left for the solver to seed from the exact geometry built here
17//! (`value: null`, `valueNeedsSetup: true`), so the dimensions read what was asked.
18
19use super::doc::{id_key, SketchDoc, SketchGeometry, SketchPoint};
20use serde_json::{Map, Value};
21
22/// How a chamfer is sized.
23#[derive(Clone, Copy, Debug, PartialEq)]
24pub enum ChamferSize {
25    /// Both cut points `distance` from the corner.
26    Equal { distance: f64 },
27    /// The first cut point `distance` from the corner along the first line, the
28    /// cut at `angle_degrees` to that line.
29    DistanceAngle { distance: f64, angle_degrees: f64 },
30}
31
32/// The fillet and chamfer tools' options (the sketch tool-options panel).
33#[derive(Clone, Copy, Debug, PartialEq)]
34pub struct CornerOptions {
35    /// The fillet radius.
36    pub radius: f64,
37    /// Whether a chamfer is sized by an angle as well (`Distance + angle`) or is
38    /// equal both ways (`Equal distance`).
39    pub chamfer_by_angle: bool,
40    /// The chamfer distance (from the corner, along the first line).
41    pub chamfer_distance: f64,
42    /// The chamfer angle to the first line, in degrees (`Distance + angle`).
43    pub chamfer_angle_degrees: f64,
44}
45
46impl Default for CornerOptions {
47    fn default() -> Self {
48        Self { radius: 1.0, chamfer_by_angle: false, chamfer_distance: 1.0, chamfer_angle_degrees: 45.0 }
49    }
50}
51
52impl CornerOptions {
53    /// The chamfer size these options describe.
54    pub fn chamfer_size(&self) -> ChamferSize {
55        if self.chamfer_by_angle {
56            ChamferSize::DistanceAngle { distance: self.chamfer_distance, angle_degrees: self.chamfer_angle_degrees }
57        } else {
58            ChamferSize::Equal { distance: self.chamfer_distance }
59        }
60    }
61}
62
63/// What a fillet or chamfer added: the new profile edge and the constraints.
64#[derive(Clone, Debug, PartialEq)]
65pub struct CornerEdit {
66    /// The arc (fillet) or line (chamfer) inserted at the corner.
67    pub edge: Value,
68    /// The constraints added (their ids).
69    pub constraints: Vec<Value>,
70}
71
72/// The two lines meeting at `corner`, each with its far endpoint.
73struct Corner {
74    corner: (f64, f64),
75    lines: [(Value, Value, (f64, f64)); 2],
76}
77
78fn point_xy(doc: &SketchDoc, id: &Value) -> Option<(f64, f64)> {
79    doc.point(id).map(|p| (p.x, p.y))
80}
81
82/// The two lines that share `corner` as an endpoint. Refuses anything else, by
83/// name, so the sketch is never left half-edited.
84fn corner_lines(doc: &SketchDoc, corner: &Value) -> Result<Corner, String> {
85    let key = id_key(corner);
86    let at = point_xy(doc, corner).ok_or_else(|| "the corner point is not in the sketch".to_string())?;
87    let touching: Vec<&SketchGeometry> = doc.geometries.iter().filter(|g| g.points.iter().any(|p| id_key(p) == key)).collect();
88    if touching.len() != 2 {
89        return Err(format!("no shared corner: {} curves meet at this point (a corner is two)", touching.len()));
90    }
91    let mut lines = Vec::new();
92    for geometry in touching {
93        if geometry.geom_type != "line" {
94            return Err(format!("only corners of two lines are supported yet (this one has a {})", geometry.geom_type));
95        }
96        if geometry.points.len() != 2 {
97            return Err("a line of the corner is malformed".to_string());
98        }
99        let far = if id_key(&geometry.points[0]) == key { &geometry.points[1] } else { &geometry.points[0] };
100        if id_key(far) == key {
101            return Err("a line of the corner has no length".to_string());
102        }
103        let far_xy = point_xy(doc, far).ok_or_else(|| "a corner line's endpoint is missing".to_string())?;
104        if (far_xy.0 - at.0).hypot(far_xy.1 - at.1) <= 1e-9 {
105            return Err("a line of the corner has no length".to_string());
106        }
107        lines.push((geometry.id.clone(), far.clone(), far_xy));
108    }
109    let [first, second]: [(Value, Value, (f64, f64)); 2] = lines.try_into().map_err(|_| "no shared corner".to_string())?;
110    Ok(Corner { corner: at, lines: [first, second] })
111}
112
113/// The corner nearest `(u, v)` within `radius`: a point two lines share. `None`
114/// when no such point is in reach.
115pub fn corner_near(doc: &SketchDoc, u: f64, v: f64, radius: f64) -> Option<Value> {
116    doc.points
117        .iter()
118        .filter(|p| (p.x - u).hypot(p.y - v) <= radius)
119        .filter(|p| corner_lines(doc, &p.id).is_ok())
120        .min_by(|a, b| (a.x - u).hypot(a.y - v).total_cmp(&(b.x - u).hypot(b.y - v)))
121        .map(|p| p.id.clone())
122}
123
124fn add_point(doc: &mut SketchDoc, (x, y): (f64, f64)) -> Value {
125    let id = doc.next_point_id();
126    doc.points.push(SketchPoint { id: id.clone(), x, y, fixed: false, construction: false, external_reference: false });
127    id
128}
129
130fn add_geometry(doc: &mut SketchDoc, geom_type: &str, points: Vec<Value>) -> Value {
131    let id = doc.next_geometry_id();
132    let mut extra = Map::new();
133    extra.insert("construction".to_string(), Value::Bool(false));
134    doc.geometries.push(SketchGeometry { id: id.clone(), geom_type: geom_type.to_string(), points, extra });
135    id
136}
137
138/// Append a constraint (always: the corner's new points are fresh, so none can
139/// already exist), its value left for the solver to seed.
140fn add_constraint(doc: &mut SketchDoc, ctype: &str, points: Vec<Value>, display_style: &str) -> Value {
141    let id = doc.next_constraint_id();
142    let mut raw = Map::new();
143    raw.insert("id".to_string(), id.clone());
144    raw.insert("type".to_string(), Value::String(ctype.to_string()));
145    raw.insert("points".to_string(), Value::Array(points));
146    raw.insert("labelX".to_string(), Value::from(0));
147    raw.insert("labelY".to_string(), Value::from(0));
148    raw.insert("displayStyle".to_string(), Value::String(display_style.to_string()));
149    raw.insert("value".to_string(), Value::Null);
150    raw.insert("valueNeedsSetup".to_string(), Value::Bool(true));
151    doc.constraints.push(super::doc::SketchConstraint { raw });
152    id
153}
154
155/// Swap the corner endpoint of line `line` for `with`.
156fn retarget_line(doc: &mut SketchDoc, line: &Value, corner: &Value, with: &Value) {
157    let key = id_key(corner);
158    if let Some(geometry) = doc.geometry_mut(line) {
159        for point in geometry.points.iter_mut() {
160            if id_key(point) == key {
161                *point = with.clone();
162            }
163        }
164    }
165}
166
167/// Turn the corner into the virtual sharp: a construction point held on both
168/// (now shortened) lines.
169fn keep_virtual_sharp(doc: &mut SketchDoc, corner: &Value, on: [(&Value, &Value); 2], constraints: &mut Vec<Value>) {
170    if let Some(point) = doc.point_mut(corner) {
171        point.construction = true;
172    }
173    for (far, cut) in on {
174        constraints.push(add_constraint(doc, "⏛", vec![far.clone(), cut.clone(), corner.clone()], ""));
175    }
176}
177
178fn unit((x, y): (f64, f64)) -> (f64, f64) {
179    let length = x.hypot(y);
180    (x / length, y / length)
181}
182
183/// The corner's two unit directions (towards each line's far end), the angle
184/// between them, and each line's length.
185fn directions(corner: &Corner) -> Result<([(f64, f64); 2], f64, [f64; 2]), String> {
186    let (px, py) = corner.corner;
187    let vectors = corner.lines.each_ref().map(|(_, _, (x, y))| (x - px, y - py));
188    let lengths = vectors.map(|(x, y)| x.hypot(y));
189    let units = vectors.map(unit);
190    let cross = units[0].0 * units[1].1 - units[0].1 * units[1].0;
191    let dot = units[0].0 * units[1].0 + units[0].1 * units[1].1;
192    let angle = cross.abs().atan2(dot);
193    if angle <= 1e-6 || angle >= std::f64::consts::PI - 1e-6 {
194        return Err("the two lines are parallel: there is no corner to round or cut".to_string());
195    }
196    Ok((units, angle, lengths))
197}
198
199/// Round the corner at point `corner` with a tangent arc of `radius`.
200pub fn fillet_corner(doc: &mut SketchDoc, corner: &Value, radius: f64) -> Result<CornerEdit, String> {
201    if !(radius.is_finite() && radius > 1e-9) {
202        return Err("the fillet radius must be positive".to_string());
203    }
204    let shape = corner_lines(doc, corner)?;
205    let (units, angle, lengths) = directions(&shape)?;
206    let back = radius / (angle / 2.0).tan();
207    let shorter = lengths[0].min(lengths[1]);
208    if back >= shorter {
209        return Err(format!(
210            "the radius is too large for this corner: it needs {back:.6} along each line, the shorter is {shorter:.6} (largest radius {:.6})",
211            shorter * (angle / 2.0).tan()
212        ));
213    }
214    let (px, py) = shape.corner;
215    let tangent = units.map(|(x, y)| (px + x * back, py + y * back));
216    let bisector = unit((units[0].0 + units[1].0, units[0].1 + units[1].1));
217    let reach = radius / (angle / 2.0).sin();
218    let centre = (px + bisector.0 * reach, py + bisector.1 * reach);
219    let [(first, first_far, _), (second, second_far, _)] = shape.lines;
220    let first_cut = add_point(doc, tangent[0]);
221    let second_cut = add_point(doc, tangent[1]);
222    let centre_id = add_point(doc, centre);
223    retarget_line(doc, &first, corner, &first_cut);
224    retarget_line(doc, &second, corner, &second_cut);
225    // The arc runs counter-clockwise from start to end: the short way round.
226    let turn = (tangent[0].0 - centre.0) * (tangent[1].1 - centre.1) - (tangent[0].1 - centre.1) * (tangent[1].0 - centre.0);
227    let (start, end) = if turn > 0.0 { (first_cut.clone(), second_cut.clone()) } else { (second_cut.clone(), first_cut.clone()) };
228    let edge = add_geometry(doc, "arc", vec![centre_id.clone(), start.clone(), end]);
229    let mut constraints = Vec::new();
230    // Tangency at each joint is the radius standing square to the line there
231    // (`⟂ [centre, cut, cut, far]`). The solver's tangent row (the centre's
232    // distance to the line against a radius) leaves the tangent point free to
233    // first order along its line, since every distance from the centre is
234    // stationary at the foot: two such rows add no rank and the fillet would
235    // read as two degrees free and two constraints redundant. The square
236    // radius pins each tangent point; with the radius dimension and the arc's
237    // implied equal-radius row it makes the arc tangent to both lines.
238    constraints.push(add_constraint(doc, "⟂", vec![centre_id.clone(), first_cut.clone(), first_cut.clone(), first_far.clone()], ""));
239    constraints.push(add_constraint(doc, "⟂", vec![centre_id.clone(), second_cut.clone(), second_cut.clone(), second_far.clone()], ""));
240    constraints.push(add_constraint(doc, "⟺", vec![centre_id, start], "radius"));
241    keep_virtual_sharp(doc, corner, [(&first_far, &first_cut), (&second_far, &second_cut)], &mut constraints);
242    Ok(CornerEdit { edge, constraints })
243}
244
245/// Round several corners at once with one radius (the selection's Fillet). The
246/// corners are taken in the order given, which is the order the user selected
247/// them: the first one rounded keeps its radius dimension, and every later arc
248/// drops its own and is tied to the first by an equal-radius constraint
249/// (`⊜ [first centre, first start, centre, start]`), so editing the one
250/// dimension resizes them all. A point that is not a corner of two lines is
251/// skipped and returned with the reason.
252pub fn fillet_corners(doc: &mut SketchDoc, corners: &[Value], radius: f64) -> (Vec<(Value, CornerEdit)>, Vec<(Value, String)>) {
253    let mut done: Vec<(Value, CornerEdit)> = Vec::new();
254    let mut refused = Vec::new();
255    let mut first: Option<(Value, Value)> = None;
256    for corner in corners {
257        match fillet_corner(doc, corner, radius) {
258            Ok(mut edit) => {
259                let arc = doc.geometries.iter().find(|g| id_key(&g.id) == id_key(&edit.edge)).map(|g| g.points.clone());
260                if let Some([centre, start, _end]) = arc.as_deref() {
261                    match &first {
262                        None => first = Some((centre.clone(), start.clone())),
263                        Some((first_centre, first_start)) => {
264                            // Trade this arc's own radius dimension for an equal radius to the first arc.
265                            if let Some(radius_id) = edit.constraints.iter().find(|id| {
266                                doc.constraints.iter().any(|c| {
267                                    c.raw.get("id").map(id_key) == Some(id_key(id))
268                                        && c.ctype() == Some("⟺")
269                                        && c.raw.get("displayStyle").and_then(Value::as_str) == Some("radius")
270                                })
271                            }) {
272                                let radius_id = radius_id.clone();
273                                doc.constraints.retain(|c| c.raw.get("id").map(id_key) != Some(id_key(&radius_id)));
274                                edit.constraints.retain(|id| id_key(id) != id_key(&radius_id));
275                            }
276                            let equal = add_constraint(
277                                doc,
278                                "⊜",
279                                vec![first_centre.clone(), first_start.clone(), centre.clone(), start.clone()],
280                                "",
281                            );
282                            edit.constraints.push(equal);
283                        }
284                    }
285                }
286                done.push((corner.clone(), edit));
287            }
288            Err(message) => refused.push((corner.clone(), message)),
289        }
290    }
291    (done, refused)
292}
293
294/// Cut the corner at point `corner` with a straight line sized by `size`.
295pub fn chamfer_corner(doc: &mut SketchDoc, corner: &Value, size: ChamferSize) -> Result<CornerEdit, String> {
296    let shape = corner_lines(doc, corner)?;
297    let (units, angle, lengths) = directions(&shape)?;
298    let (first_back, second_back) = match size {
299        ChamferSize::Equal { distance } => {
300            if !(distance.is_finite() && distance > 1e-9) {
301                return Err("the chamfer distance must be positive".to_string());
302            }
303            (distance, distance)
304        }
305        ChamferSize::DistanceAngle { distance, angle_degrees } => {
306            if !(distance.is_finite() && distance > 1e-9) {
307                return Err("the chamfer distance must be positive".to_string());
308            }
309            let cut = angle_degrees.to_radians();
310            // The triangle corner, first cut point, second cut point: angle
311            // `angle` at the corner, `cut` at the first cut point.
312            let far = std::f64::consts::PI - angle - cut;
313            if !(cut > 1e-6 && far > 1e-6) {
314                return Err(format!(
315                    "the chamfer angle must lie between 0 and {:.4} degrees at this corner",
316                    (std::f64::consts::PI - angle).to_degrees()
317                ));
318            }
319            (distance, distance * cut.sin() / far.sin())
320        }
321    };
322    for (back, length) in [(first_back, lengths[0]), (second_back, lengths[1])] {
323        if back >= length {
324            return Err(format!("the chamfer is too large for this corner: it needs {back:.6} along a line {length:.6} long"));
325        }
326    }
327    let (px, py) = shape.corner;
328    let cuts = [(px + units[0].0 * first_back, py + units[0].1 * first_back), (px + units[1].0 * second_back, py + units[1].1 * second_back)];
329    let [(first, first_far, _), (second, second_far, _)] = shape.lines;
330    let first_cut = add_point(doc, cuts[0]);
331    let second_cut = add_point(doc, cuts[1]);
332    retarget_line(doc, &first, corner, &first_cut);
333    retarget_line(doc, &second, corner, &second_cut);
334    let edge = add_geometry(doc, "line", vec![first_cut.clone(), second_cut.clone()]);
335    let mut constraints = Vec::new();
336    constraints.push(add_constraint(doc, "⟺", vec![corner.clone(), first_cut.clone()], ""));
337    match size {
338        ChamferSize::Equal { .. } => {
339            constraints.push(add_constraint(doc, "⇌", vec![corner.clone(), first_cut.clone(), corner.clone(), second_cut.clone()], ""));
340        }
341        ChamferSize::DistanceAngle { .. } => {
342            // Between the cut and the first line towards the corner (the
343            // virtual sharp): the angle asked for.
344            constraints.push(add_constraint(doc, "∠", vec![first_cut.clone(), corner.clone(), first_cut.clone(), second_cut.clone()], ""));
345        }
346    }
347    keep_virtual_sharp(doc, corner, [(&first_far, &first_cut), (&second_far, &second_cut)], &mut constraints);
348    Ok(CornerEdit { edge, constraints })
349}
350