Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Chamfer: two distances and distance + angle on curved edges (#2893)

SS-EN3115c5035964
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 844db5037f..23b107875f 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -2691,6 +2691,34 @@ fn unequal_chamfers() {
assert!(s.execute("solid.chamfer", &json!({"edges": [[0, 15, 20]], "distance": 1, "distance2": 2, "angle": "30 deg"})).is_err());
}
+/// Unequal chamfers of a cylinder's circular rims: each cross-section is a right triangle
+/// revolved about the axis (Pappus: area × the path of its centroid).
+#[test]
+fn unequal_chamfers_on_circular_rims() {
+ use std::f64::consts::PI;
+ let ring = |r: [f64; 3], legs: (f64, f64)| 2.0 * PI * (r[0] + r[1] + r[2]) / 3.0 * 0.5 * legs.0 * legs.1;
+ let mut s = Session::default();
+ run(&mut s, "solid.cylinder", json!({"radius": 10, "height": 20}));
+ // The measured volume is of the meshed cylinder: compare what each chamfer takes away.
+ let full = volume(&mut s);
+ assert!(rel(full, PI * 100.0 * 20.0) < 1e-3);
+ // Top rim: 2 across the top (the face facing up), 3 down the wall.
+ run(&mut s, "solid.chamfer", json!({"edges": [[10, 0, 20]], "distance": 2, "distance2": 3}));
+ let top = ring([10.0, 8.0, 10.0], (2.0, 3.0));
+ assert!(rel(full - volume(&mut s), top) < 5e-3, "{} vs {top}", full - volume(&mut s));
+ // Bottom rim: 2 along the bottom at 30° from it (flipped: the wall would be first).
+ run(&mut s, "solid.chamfer", json!({"edges": [[10, 0, 0]], "distance": 2, "angle": "30 deg", "flip": true}));
+ let d2 = 2.0 * 30f64.to_radians().tan();
+ let bottom = ring([10.0, 8.0, 10.0], (2.0, d2));
+ assert!(rel(full - volume(&mut s), top + bottom) < 5e-3, "{} vs {}", full - volume(&mut s), top + bottom);
+ // Flipped on the top rim instead: 2 down the wall, 3 across the top (a different solid).
+ run(&mut s, "edit.undo", json!({}));
+ run(&mut s, "edit.undo", json!({}));
+ run(&mut s, "solid.chamfer", json!({"edges": [[10, 0, 20]], "distance": 2, "distance2": 3, "flip": true}));
+ let flipped = ring([10.0, 7.0, 10.0], (2.0, 3.0));
+ assert!(rel(full - volume(&mut s), flipped) < 5e-3, "{} vs {flipped}", full - volume(&mut s));
+}
+
/// An enclosure built in the usual order: shell, bosses, then the lip on the rim.
#[test]
fn lip_after_boss() {
diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rs
index 7f03087930..7df4951442 100644
--- a/crates/kernel/src/blend.rs
+++ b/crates/kernel/src/blend.rs
@@ -2295,9 +2295,11 @@ pub enum ChamferSide {
Angle(f64),
}
-/// A chamfer with different setbacks on the two faces of each (straight) edge: `d1` along the
-/// first face (the one facing up most, the other with `flip`), the second side by distance or
-/// angle.
+/// A chamfer with different setbacks on the two faces of each edge: `d1` along the first face
+/// (the one facing up most, the other with `flip`), the second side by distance or angle.
+/// Straight edges between planar faces are cut by prisms; curved edges where a planar face meets
+/// a wall (a circular rim between a plane and a cylinder or cone, convex or concave, and loops of
+/// lines and arcs) are chamfered along that face's loop.
pub fn chamfer_sides(body: &Body, edges: &[Vec3], d1: f64, side: ChamferSide, flip: bool) -> Result<Body> {
body.require_brep("chamfer")?;
let ok = |x: f64| x.is_finite() && x > 1e-6 && x < 1e6;
@@ -2314,15 +2316,85 @@ pub fn chamfer_sides(body: &Body, edges: &[Vec3], d1: f64, side: ChamferSide, fl
}
let size = crate::blend_fit::Size::Sides(d1, side, flip);
let counts = record::counts(&[body]);
- let mut cur = crate::boolean_record::operand(body, 0, &counts);
- for (k, p) in edges.iter().enumerate() {
- let t = chamfer_tool_sides(&cur, *p, d1, Some((side, flip)), k)?;
- let step = cut_one(&cur, &t)?.ok_or_else(|| KernelError::Failed("the chamfer removed everything".into()))?;
- cur = record::after(step, &cur, &counts);
- }
+ let cut = || -> Result<Body> {
+ let mut cur = crate::boolean_record::operand(body, 0, &counts);
+ for (k, p) in edges.iter().enumerate() {
+ let t = chamfer_tool_sides(&cur, *p, d1, Some((side, flip)), k)?;
+ let step = cut_one(&cur, &t)?.ok_or_else(|| KernelError::Failed("the chamfer removed everything".into()))?;
+ cur = record::after(step, &cur, &counts);
+ }
+ Ok(cur)
+ };
+ // A curved edge picked: the prisms cannot cut it, and cutting the others first moves what
+ // its pick lands on.
+ let picks_curved = {
+ let solid = body.deep_copy();
+ let ids = edge_ids(body, &solid, edges)?;
+ guard("chamfer", || Ok(Body::unique_edges(&solid).iter().any(|x| ids.contains(&x.id()) && curved_case(&solid, x, false))))?
+ };
+ let cur = match picks_curved {
+ true => chamfer_sides_curved(body, edges, d1, side, flip, None)?,
+ false => match cut() {
+ Ok(cur) => cur,
+ Err(e) => chamfer_sides_curved(body, edges, d1, side, flip, Some(e))?,
+ },
+ };
crate::blend_fit::accept(body, cur, edges, size)
}
+/// [`chamfer_sides`] of a selection with curved edges, or one the prisms could not cut (`e`:
+/// why) with edges running on smoothly into curved ones: whole loops of planar faces and runs of
+/// one are chamfered along the loop ([`crate::loopblend::loop_chamfer_sides`]), other edges still
+/// by a prism. A selection of straight edges only keeps the prisms' refusal.
+fn chamfer_sides_curved(body: &Body, edges: &[Vec3], d1: f64, side: ChamferSide, flip: bool, e: Option<KernelError>) -> Result<Body> {
+ let counts = record::counts(&[body]);
+ let mut cur = crate::boolean_record::healed(body)?;
+ let curved = {
+ let solid = cur.deep_copy();
+ let ids = edge_ids(&cur, &solid, edges)?;
+ guard("chamfer", || {
+ let all = Body::unique_edges(&solid);
+ let curved = |x: &mt::Edge| curved_case(&solid, x, false);
+ Ok(all
+ .iter()
+ .filter(|x| ids.contains(&x.id()))
+ .any(|x| curved(x) || smooth_chain(&solid, x).is_some_and(|chain| all.iter().any(|y| chain.contains(&y.id()) && curved(y)))))
+ })?
+ };
+ if !curved {
+ return Err(e.unwrap_or_else(|| unsupported("these edges")));
+ }
+ // The loop chamfer of the edges nearest `pts`, all on one planar face's loop.
+ let along_loop = |cur: &Body, pts: &[Vec3]| -> Result<Body> {
+ let size = cur.size();
+ let solid = cur.deep_copy();
+ let ids = edge_ids(cur, &solid, pts)?;
+ match crate::loopblend::loop_chamfer_sides(&solid, &ids, size, d1, side, flip) {
+ Some(res) => {
+ let (made, rec) = guard("chamfer", || res)?;
+ Ok(record::after(record::rebuilt(made, &[&solid], &rec)?, cur, &counts))
+ }
+ None => Err(unsupported(
+ "a two-distance or distance-angle chamfer of a curved edge that is not on the boundary of a planar face (an equal-distance chamfer may work there)",
+ )),
+ }
+ };
+ let (groups, rest) = loop_split(&cur, edges)?.unwrap_or_else(|| (Vec::new(), edges.to_vec()));
+ for g in &groups {
+ cur = along_loop(&cur, g)?;
+ }
+ for (k, p) in rest.iter().enumerate() {
+ cur = match chamfer_tool_sides(&cur, *p, d1, Some((side, flip)), k) {
+ Ok(t) => {
+ let step = cut_one(&cur, &t)?.ok_or_else(|| KernelError::Failed("the chamfer removed everything".into()))?;
+ record::after(step, &cur, &counts)
+ }
+ Err(_) => along_loop(&cur, std::slice::from_ref(p))?,
+ };
+ }
+ Ok(cur)
+}
+
/// The prism that cuts a chamfer: the body, which of its faces is the chamfer plane, and the
/// edge (of the body it chamfers, in its edge order) that face is made in place of.
pub(crate) struct Cutter {
diff --git a/crates/kernel/src/chamfer_sides_curved_tests.rs b/crates/kernel/src/chamfer_sides_curved_tests.rs
new file mode 100644
index 0000000000..53e97e93d2
--- /dev/null
+++ b/crates/kernel/src/chamfer_sides_curved_tests.rs
@@ -0,0 +1,257 @@
+//! Two-distance and distance-angle chamfers of curved edges: a circular rim between a planar
+//! face and a cylinder or cone, convex (a cylinder's top) and concave (a boss's foot), and a
+//! hole's rim. Each chamfer's cross-section is a triangle revolved about the axis, so its volume
+//! is the triangle's area times the path of its centroid (Pappus).
+
+use std::f64::consts::PI;
+
+use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3};
+
+use crate::build::{box_solid, extrude, extrude_tapered};
+use crate::{Body, BoolOp, ChamferSide, KernelError, boolean, chamfer, chamfer_sides};
+
+const TOL: f64 = 1e-3;
+
+fn volume(b: &Body) -> f64 {
+ b.volume_at(TOL).unwrap()
+}
+
+fn rel(a: f64, b: f64) -> f64 {
+ (a - b).abs() / b.abs().max(1e-12)
+}
+
+/// A cylinder of radius 10 and height 20 standing on XY, its seam at `seam`.
+fn cylinder(seam: f64) -> Body {
+ let region = Region2 { outer: Loop2::circle_from(Vec2::ZERO, 10.0, seam), holes: vec![] };
+ extrude(&Plane::XY, &[region], 0.0, 20.0).unwrap().pop().unwrap()
+}
+
+/// The volume of the ring swept by the triangle `(r, z)` corners about the Z axis.
+fn ring(t: [(f64, f64); 3]) -> f64 {
+ let [(r0, z0), (r1, z1), (r2, z2)] = t;
+ let area = 0.5 * ((r1 - r0) * (z2 - z0) - (r2 - r0) * (z1 - z0)).abs();
+ 2.0 * PI * (r0 + r1 + r2) / 3.0 * area
+}
+
+fn sound(b: &Body) {
+ assert!(b.validity().is_empty(), "{:?}", b.validity());
+ assert_eq!(b.lumps().unwrap().len(), 1);
+}
+
+const RIM: Vec3 = Vec3 { x: 10.0, y: 0.0, z: 20.0 };
+
+#[test]
+fn cylinder_rim_by_two_distances() {
+ for seam in [0.0, crate::build::SEAM_ANGLE] {
+ let c = cylinder(seam);
+ let base = volume(&c);
+ // 2 across the top (the face facing up), 3 down the wall.
+ let out = chamfer_sides(&c, &[RIM], 2.0, ChamferSide::Distance(3.0), false).unwrap();
+ sound(&out);
+ let removed = ring([(10.0, 20.0), (8.0, 20.0), (10.0, 17.0)]);
+ assert!((removed - 56.0 * PI).abs() < 1e-9);
+ assert!(rel(volume(&out), base - removed) < 1e-5, "seam {seam}: {} vs {}", volume(&out), base - removed);
+ // Cone faces in place of the rim, as the equal chamfer's.
+ assert_eq!(out.face_count(), chamfer(&c, &[RIM], 2.0).unwrap().face_count());
+ }
+}
+
+#[test]
+fn cylinder_rim_by_distance_and_angle() {
+ let c = cylinder(0.0);
+ let base = volume(&c);
+ // 2 across the top at 30° from it: down the wall 2·tan 30° (the faces are square).
+ let out = chamfer_sides(&c, &[RIM], 2.0, ChamferSide::Angle(30f64.to_radians()), false).unwrap();
+ sound(&out);
+ let d2 = 2.0 * 30f64.to_radians().tan();
+ let expected = base - ring([(10.0, 20.0), (8.0, 20.0), (10.0, 20.0 - d2)]);
+ assert!(rel(volume(&out), expected) < 1e-5, "{} vs {expected}", volume(&out));
+}
+
+#[test]
+fn cylinder_rim_flipped() {
+ let c = cylinder(0.0);
+ let base = volume(&c);
+ // Flipped: the wall is the first face, 2 down it and 3 across the top.
+ let out = chamfer_sides(&c, &[RIM], 2.0, ChamferSide::Distance(3.0), true).unwrap();
+ sound(&out);
+ let expected = base - ring([(10.0, 20.0), (7.0, 20.0), (10.0, 18.0)]);
+ assert!((base - expected - 54.0 * PI).abs() < 1e-9);
+ assert!(rel(volume(&out), expected) < 1e-5, "{} vs {expected}", volume(&out));
+ // At 60° from the wall: across the top 2·tan 60°.
+ let out = chamfer_sides(&c, &[RIM], 2.0, ChamferSide::Angle(60f64.to_radians()), true).unwrap();
+ let d2 = 2.0 * 60f64.to_radians().tan();
+ let expected = base - ring([(10.0, 20.0), (10.0 - d2, 20.0), (10.0, 18.0)]);
+ assert!(rel(volume(&out), expected) < 1e-5, "{} vs {expected}", volume(&out));
+}
+
+/// The bottom rim, as a box's bottom edge: the bottom faces down, so the wall is the first face.
+#[test]
+fn cylinder_bottom_rim_takes_the_wall_first() {
+ let c = cylinder(0.0);
+ let base = volume(&c);
+ let out = chamfer_sides(&c, &[Vec3::new(10.0, 0.0, 0.0)], 2.0, ChamferSide::Distance(3.0), false).unwrap();
+ sound(&out);
+ let expected = base - ring([(10.0, 0.0), (7.0, 0.0), (10.0, 2.0)]);
+ assert!(rel(volume(&out), expected) < 1e-5, "{} vs {expected}", volume(&out));
+}
+
+#[test]
+fn equal_distances_are_unchanged() {
+ let c = cylinder(0.0);
+ let base = volume(&c);
+ let equal = chamfer(&c, &[RIM], 2.0).unwrap();
+ let expected = base - ring([(10.0, 20.0), (8.0, 20.0), (10.0, 18.0)]);
+ assert!(rel(volume(&equal), expected) < 1e-5, "{} vs {expected}", volume(&equal));
+ // Two equal distances, and 45° on square faces, are the same chamfer.
+ for side in [ChamferSide::Distance(2.0), ChamferSide::Angle(PI / 4.0)] {
+ let out = chamfer_sides(&c, &[RIM], 2.0, side, false).unwrap();
+ assert!(rel(volume(&out), volume(&equal)) < 1e-7, "{side:?}: {} vs {}", volume(&out), volume(&equal));
+ assert_eq!(out.face_count(), equal.face_count());
+ }
+}
+
+/// A 40 × 40 × 10 plate with a hole of radius 5 through it at (20, 20).
+fn holed_plate() -> Body {
+ let plate = box_solid(Vec3::ZERO, Vec3::new(40.0, 40.0, 10.0)).unwrap();
+ let hole = crate::build::cylinder(Vec3::new(20.0, 20.0, -5.0), Vec3::Z, 5.0, 20.0).unwrap();
+ boolean(&plate, &hole, BoolOp::Cut).unwrap().unwrap()
+}
+
+#[test]
+fn hole_rim() {
+ let p = holed_plate();
+ let base = volume(&p);
+ let rim = Vec3::new(25.0, 20.0, 10.0);
+ // 2 across the top, away from the hole, and 3 down its wall: a countersink.
+ let out = chamfer_sides(&p, &[rim], 2.0, ChamferSide::Distance(3.0), false).unwrap();
+ sound(&out);
+ let removed = ring([(5.0, 10.0), (7.0, 10.0), (5.0, 7.0)]);
+ assert!((removed - 34.0 * PI).abs() < 1e-9);
+ assert!(rel(volume(&out), base - removed) < 1e-5, "{} vs {}", volume(&out), base - removed);
+ // Flipped, at 30° from the hole's wall.
+ let out = chamfer_sides(&p, &[rim], 2.0, ChamferSide::Angle(30f64.to_radians()), true).unwrap();
+ sound(&out);
+ let d2 = 2.0 * 30f64.to_radians().tan();
+ let expected = base - ring([(5.0, 10.0), (5.0 + d2, 10.0), (5.0, 8.0)]);
+ assert!(rel(volume(&out), expected) < 1e-5, "{} vs {expected}", volume(&out));
+}
+
+/// A concave rim: the foot of a boss of radius 5 standing 10 high on a 40 × 40 × 5 plate.
+#[test]
+fn boss_foot_fills() {
+ let plate = box_solid(Vec3::ZERO, Vec3::new(40.0, 40.0, 5.0)).unwrap();
+ let boss = crate::build::cylinder(Vec3::new(20.0, 20.0, 5.0), Vec3::Z, 5.0, 10.0).unwrap();
+ let b = boolean(&plate, &boss, BoolOp::Union).unwrap().unwrap();
+ let base = volume(&b);
+ let foot = Vec3::new(25.0, 20.0, 5.0);
+ // The equal chamfer fills a ring.
+ let equal = chamfer(&b, &[foot], 2.0).unwrap();
+ let filled = ring([(5.0, 5.0), (7.0, 5.0), (5.0, 7.0)]);
+ assert!(rel(volume(&equal), base + filled) < 1e-5, "{} vs {}", volume(&equal), base + filled);
+ // 2 across the plate (facing up), 3 up the boss.
+ let out = chamfer_sides(&b, &[foot], 2.0, ChamferSide::Distance(3.0), false).unwrap();
+ sound(&out);
+ let filled = ring([(5.0, 5.0), (7.0, 5.0), (5.0, 8.0)]);
+ assert!(rel(volume(&out), base + filled) < 1e-5, "{} vs {}", volume(&out), base + filled);
+ // 2 up the boss at 30° from it.
+ let out = chamfer_sides(&b, &[foot], 2.0, ChamferSide::Angle(30f64.to_radians()), true).unwrap();
+ sound(&out);
+ let d2 = 2.0 * 30f64.to_radians().tan();
+ let filled = ring([(5.0, 5.0), (5.0 + d2, 5.0), (5.0, 7.0)]);
+ assert!(rel(volume(&out), base + filled) < 1e-5, "{} vs {}", volume(&out), base + filled);
+}
+
+/// A frustum's top rim, between the top and a cone: the faces meet at 90° + the taper.
+#[test]
+fn cone_rim() {
+ let taper = 10f64.to_radians();
+ let region = Region2 { outer: Loop2::circle_from(Vec2::ZERO, 10.0, 0.0), holes: vec![] };
+ let f = extrude_tapered(&Plane::XY, &region, 20.0, 1.0, -taper).unwrap();
+ let base = volume(&f);
+ let top = 10.0 - 20.0 * taper.tan();
+ let rim = Vec3::new(top, 0.0, 20.0);
+ // Down the cone's slant, away from the top: (sin, −cos) of the taper.
+ let down = |d: f64| (top + d * taper.sin(), 20.0 - d * taper.cos());
+ // The cone is meshed less closely than the cylinder: compare what the chamfer takes away
+ // (within the mesh's error, about 1e-3 of it at this tolerance).
+ let out = chamfer_sides(&f, &[rim], 2.0, ChamferSide::Distance(3.0), false).unwrap();
+ sound(&out);
+ let removed = ring([(top, 20.0), (top - 2.0, 20.0), down(3.0)]);
+ assert!(rel(base - volume(&out), removed) < 3e-3, "{} vs {removed}", base - volume(&out));
+ // By an angle: the triangle edge–A–B has φ = 90° + taper at the edge and 40° at A.
+ let a = 40f64.to_radians();
+ let phi = PI / 2.0 + taper;
+ let d2 = 2.0 * a.sin() / (phi + a).sin();
+ let out = chamfer_sides(&f, &[rim], 2.0, ChamferSide::Angle(a), false).unwrap();
+ sound(&out);
+ let removed = ring([(top, 20.0), (top - 2.0, 20.0), down(d2)]);
+ assert!(rel(base - volume(&out), removed) < 3e-3, "{} vs {removed}", base - volume(&out));
+ // The equal chamfer, as before.
+ let out = chamfer(&f, &[rim], 2.0).unwrap();
+ let removed = ring([(top, 20.0), (top - 2.0, 20.0), down(2.0)]);
+ assert!(rel(base - volume(&out), removed) < 3e-3, "{} vs {removed}", base - volume(&out));
+}
+
+#[test]
+fn too_large_or_unsupported_is_refused() {
+ let c = cylinder(0.0);
+ // Across the whole top: the cone would end in a point.
+ assert!(chamfer_sides(&c, &[RIM], 10.0, ChamferSide::Distance(3.0), false).is_err());
+ assert!(chamfer_sides(&c, &[RIM], 12.0, ChamferSide::Distance(3.0), false).is_err());
+ // Down past the bottom.
+ assert!(chamfer_sides(&c, &[RIM], 2.0, ChamferSide::Distance(25.0), false).is_err());
+ // An angle that runs past the wall.
+ assert!(chamfer_sides(&c, &[RIM], 2.0, ChamferSide::Angle(PI / 2.0 + 0.01), false).is_err());
+ // A cylinder's seam is smooth: nothing to chamfer.
+ assert!(chamfer_sides(&c, &[Vec3::new(10.0, 0.0, 10.0)], 2.0, ChamferSide::Distance(3.0), false).is_err());
+ // A tilted cylinder cut flat: its rim on the cut is an ellipse, which the loop chamfer does
+ // not take. Refused as not supported, never a wrong solid.
+ let tilted = crate::build::cylinder(Vec3::new(0.0, 0.0, -10.0), Vec3::new(1.0, 0.0, 2.0), 5.0, 40.0).unwrap();
+ let cut = box_solid(Vec3::new(-50.0, -50.0, 10.0), Vec3::new(50.0, 50.0, 50.0)).unwrap();
+ let t = boolean(&tilted, &cut, BoolOp::Cut).unwrap().unwrap();
+ let solid = t.deep_copy();
+ let rim = crate::body::Body::unique_edges(&solid).iter().filter_map(crate::blend::edge_mid).find(|m| (m.z - 10.0).abs() < 1e-6).unwrap();
+ match chamfer_sides(&t, &[rim], 1.0, ChamferSide::Distance(2.0), false) {
+ Err(KernelError::Failed(m)) => assert!(m.starts_with("not supported yet"), "{m}"),
+ Err(e) => panic!("{e}"),
+ Ok(_) => panic!("an unequal chamfer of an elliptical rim was built"),
+ }
+}
+
+/// The top loop of a plate with rounded corners: lines and quarter circles, planar and
+/// cylindrical walls, chamfered all round (every edge of the loop picked).
+#[test]
+fn rounded_plate_top_loop() {
+ let b = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 10.0)).unwrap();
+ let corners = [Vec3::new(0.0, 0.0, 5.0), Vec3::new(40.0, 0.0, 5.0), Vec3::new(40.0, 30.0, 5.0), Vec3::new(0.0, 30.0, 5.0)];
+ let b = crate::fillet(&b, &corners, 5.0).unwrap();
+ let base = volume(&b);
+ let k = 5.0 * (1.0 - std::f64::consts::FRAC_1_SQRT_2);
+ let picks = [
+ Vec3::new(20.0, 0.0, 10.0),
+ Vec3::new(40.0, 15.0, 10.0),
+ Vec3::new(20.0, 30.0, 10.0),
+ Vec3::new(0.0, 15.0, 10.0),
+ Vec3::new(k, k, 10.0),
+ Vec3::new(40.0 - k, k, 10.0),
+ Vec3::new(40.0 - k, 30.0 - k, 10.0),
+ Vec3::new(k, 30.0 - k, 10.0),
+ ];
+ // Every pick is taken on the plate as given: cutting the lines first used to leave the arcs'
+ // picks nearest to the new chamfer faces' edges, which were cut instead (corner wedges).
+ let out = chamfer_sides(&b, &picks, 2.0, ChamferSide::Distance(3.0), false).unwrap();
+ sound(&out);
+ // 100 of straight sides with the triangle (2 × 3) and four quarter rings about the corners.
+ let removed = 100.0 * 3.0 + ring([(5.0, 10.0), (3.0, 10.0), (5.0, 7.0)]);
+ assert!(rel(base - volume(&out), removed) < 2e-3, "{} vs {removed}", base - volume(&out));
+ // Flipped: 2 down the walls, 3 across the top.
+ let out = chamfer_sides(&b, &picks, 2.0, ChamferSide::Distance(3.0), true).unwrap();
+ sound(&out);
+ let removed = 100.0 * 3.0 + ring([(5.0, 10.0), (2.0, 10.0), (5.0, 8.0)]);
+ assert!(rel(base - volume(&out), removed) < 2e-3, "{} vs {removed}", base - volume(&out));
+ // Equal distances: as the equal chamfer.
+ let equal = chamfer(&b, &picks, 2.0).unwrap();
+ let out = chamfer_sides(&b, &picks, 2.0, ChamferSide::Distance(2.0), false).unwrap();
+ assert!(rel(volume(&out), volume(&equal)) < 1e-9);
+}
diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs
index 4ea1228fba..046eb469cc 100644
--- a/crates/kernel/src/lib.rs
+++ b/crates/kernel/src/lib.rs
@@ -28,6 +28,8 @@ mod boundary;
mod boundary_network;
mod bridge;
mod build;
+#[cfg(test)]
+mod chamfer_sides_curved_tests;
mod clearance;
mod coaxial_overlap;
mod continuity;
diff --git a/crates/kernel/src/loopblend.rs b/crates/kernel/src/loopblend.rs
index d9f97c047b..89b21a2ef2 100644
--- a/crates/kernel/src/loopblend.rs
+++ b/crates/kernel/src/loopblend.rs
@@ -5,13 +5,15 @@
//! gets a blend face: a cylinder (or plane, for a chamfer) along a line, a torus (or cone) along
//! an arc, all meeting along the profile curves at the joints. Sharp joints at perpendicular
//! curved walls follow the intersections of the exact offsets, fitted within tolerance.
+//! A chamfer may also set back by different distances on the face and up the walls (two
+//! distances, or a distance and an angle: [`loop_chamfer_sides`]).
use std::collections::HashMap;
use solidcraft_geom::Vec3;
use truck_modeling::{self as mt, builder};
-use crate::blend::too_large;
+use crate::blend::{ChamferSide, too_large};
use crate::body::{Solid, from_p3, p3, v3};
use crate::record::Rebuild;
use crate::{KernelError, Result};
@@ -98,14 +100,15 @@ fn offset_joint(prev: &Seg, cur: &Seg, n: Vec3, d: f64) -> Option<Vec3> {
/// A curved-wall joint is generally not planar. Fit its exact offset slices rather than
/// projecting a circular section onto a tangent mitre and revolving that distorted section.
-fn offset_profile(prev: &Seg, cur: &Seg, n: Vec3, side: f64, r: f64, round: bool, tol: f64) -> Result<mt::Curve> {
+/// `(r, rw)`: the round's radius (`rw` unused), or a chamfer's setbacks on the face and up the wall.
+fn offset_profile(prev: &Seg, cur: &Seg, n: Vec3, side: f64, (r, rw): (f64, f64), round: bool, tol: f64) -> Result<mt::Curve> {
use mt::ParametricCurve;
let point = |u: f64| {
let (d, h) = if round {
let (sin, cos) = (u * std::f64::consts::FRAC_PI_2).sin_cos();
(r * (1.0 - sin), r * (1.0 - cos))
} else {
- (r * (1.0 - u), r * u)
+ (r * (1.0 - u), rw * u)
};
offset_joint(prev, cur, n, d).map(|p| p + n * (side * h))
};
@@ -231,13 +234,40 @@ fn face_normal(f: &mt::Face, p: Vec3) -> Option<Vec3> {
/// perpendicular walls, with what it built from `solid` (each blend face in place of its loop
/// edge). `None` when the edges are not such a loop.
pub(crate) fn loop_blend(solid: &Solid, edge_ids: &[mt::EdgeID], size: f64, r: f64, round: bool) -> Option<Result<(Solid, Rebuild)>> {
- match crate::guard("loop blend", || Ok(loop_blend_inner(solid, edge_ids, size, r, round))) {
+ loop_blend_sized(solid, edge_ids, size, Sizing::Equal { r, round })
+}
+
+/// [`loop_blend`] as a chamfer of `d1` on its first face and the second side by `side`. The
+/// first face is the one facing up most (the planar face or its wall, decided as for a straight
+/// edge, see [`crate::chamfer_sides`]), the other one with `flip`.
+pub(crate) fn loop_chamfer_sides(
+ solid: &Solid,
+ edge_ids: &[mt::EdgeID],
+ size: f64,
+ d1: f64,
+ side: ChamferSide,
+ flip: bool,
+) -> Option<Result<(Solid, Rebuild)>> {
+ loop_blend_sized(solid, edge_ids, size, Sizing::Sides { d1, side, flip })
+}
+
+/// How large a loop blend is.
+#[derive(Clone, Copy, Debug)]
+enum Sizing {
+ /// A round of radius `r` (`round`), or an equal-distance chamfer of `r`.
+ Equal { r: f64, round: bool },
+ /// A chamfer of `d1` on its first face, the second side by `side` ([`loop_chamfer_sides`]).
+ Sides { d1: f64, side: ChamferSide, flip: bool },
+}
+
+fn loop_blend_sized(solid: &Solid, edge_ids: &[mt::EdgeID], size: f64, sizing: Sizing) -> Option<Result<(Solid, Rebuild)>> {
+ match crate::guard("loop blend", || Ok(loop_blend_inner(solid, edge_ids, size, sizing))) {
Ok(result) => result,
Err(error) => Some(Err(error)),
}
}
-fn loop_blend_inner(solid: &Solid, edge_ids: &[mt::EdgeID], size: f64, r: f64, round: bool) -> Option<Result<(Solid, Rebuild)>> {
+fn loop_blend_inner(solid: &Solid, edge_ids: &[mt::EdgeID], size: f64, sizing: Sizing) -> Option<Result<(Solid, Rebuild)>> {
#[cfg(test)]
assert!(crate::guarded(), "loop selection must run inside the kernel guard");
let tol = (size * 1e-6).max(1e-7);
@@ -251,7 +281,7 @@ fn loop_blend_inner(solid: &Solid, edge_ids: &[mt::EdgeID], size: f64, r: f64, r
continue;
}
if ids.len() == edge_ids.len() {
- return Some(build(solid, si, &faces, fi, wi, n, size, tol, r, round, None));
+ return Some(build(solid, si, &faces, fi, wi, n, size, tol, sizing, None));
}
// A run of neighbouring edges of the loop (its ends meet unblended edges).
let m = ids.len();
@@ -260,7 +290,7 @@ fn loop_blend_inner(solid: &Solid, edge_ids: &[mt::EdgeID], size: f64, r: f64, r
if let [s0] = starts[..]
&& (0..edge_ids.len()).all(|j| inside(s0 + j))
{
- return Some(build(solid, si, &faces, fi, wi, n, size, tol, r, round, Some((s0, edge_ids.len()))));
+ return Some(build(solid, si, &faces, fi, wi, n, size, tol, sizing, Some((s0, edge_ids.len()))));
}
}
}
@@ -278,12 +308,17 @@ fn build(
n: Vec3,
size: f64,
tol: f64,
- r: f64,
- round: bool,
+ sizing: Sizing,
run: Option<(usize, usize)>,
) -> Result<(Solid, Rebuild)> {
#[cfg(test)]
assert!(crate::guarded(), "loop construction must run inside the kernel guard");
+ // `r`: the round's radius or the equal chamfer's size; an unequal chamfer's first distance
+ // (its setbacks come from `frame`).
+ let (r, round, sides) = match sizing {
+ Sizing::Equal { r, round } => (r, round, None),
+ Sizing::Sides { d1, side, flip } => (d1, false, Some((side, flip))),
+ };
let f = faces.get(fi).ok_or_else(|| KernelError::Failed("face".into()))?;
let wire = f.boundaries().get(wi).cloned().ok_or_else(|| KernelError::Failed("loop".into()))?;
let all_edges: Vec<mt::Edge> = wire.edge_iter().cloned().collect();
@@ -384,16 +419,83 @@ fn build(
let t = s.tangent(p)?.cross(gn).normalized()?;
Some(if t.dot(n * side) < 0.0 { -t } else { t })
};
- let frame = |i: usize, p: Vec3| -> Option<(Vec3, Vec3, f64, f64)> {
+ // An unequal chamfer: whether its first side is the planar face (else the walls). As for a
+ // straight edge, that is the one facing up most (a curved wall by its mean normal along each
+ // edge), the other with `flip`; it must be the same all round the loop.
+ let face_first = match sides {
+ None => true,
+ Some((_, flip)) => {
+ use mt::{BoundedCurve, ParametricCurve};
+ let up = Vec3::new(1e-6, 1e-3, 1.0);
+ let face_up = n.dot(up);
+ let mut first: Option<bool> = None;
+ for (pi, oi) in owner.iter().enumerate() {
+ if pi > 0 && owner.get(pi - 1) == Some(oi) {
+ continue;
+ }
+ let (Some(e), Some(g)) = (edges.get(*oi), walls.get(pi).and_then(|w| faces.get(*w))) else {
+ return Err(KernelError::Failed("loop edge".into()));
+ };
+ let c = e.curve();
+ let (t0, t1) = c.range_tuple();
+ let ups: Vec<f64> =
+ (0..=8).filter_map(|j| face_normal(g, from_p3(c.subs(t0 + (t1 - t0) * f64::from(j) / 8.0))).map(|gn| gn.dot(up))).collect();
+ if ups.is_empty() {
+ return Err(unsupported("wall normal"));
+ }
+ let wall_up = ups.iter().sum::<f64>() / ups.len() as f64;
+ let mine = (face_up >= wall_up) != flip;
+ if first.is_some_and(|x| x != mine) {
+ return Err(unsupported(
+ "an unequal chamfer round a loop whose first face changes along it (the face faces up more than some walls and less than others)",
+ ));
+ }
+ first = Some(mine);
+ }
+ first.unwrap_or(true)
+ }
+ };
+ // Into the face (m), up the wall (t), the setbacks along each and the distance from the edge
+ // to a round's centre.
+ let frame = |i: usize, p: Vec3| -> Option<(Vec3, Vec3, f64, f64, f64)> {
let s = segs.get(i)?;
let (m, t) = (into(s, p), up(i, p)?);
let phi = m.dot(t).clamp(-1.0, 1.0).acos();
if !(phi > 1e-3 && phi < std::f64::consts::PI - 1e-3) {
return None;
}
- let sb = if round { r / (phi / 2.0).tan() } else { r };
- Some((m, t, sb, r / (phi / 2.0).sin()))
+ let (sf, sw) = match sides {
+ None => {
+ let sb = if round { r / (phi / 2.0).tan() } else { r };
+ (sb, sb)
+ }
+ Some((cs, _)) => {
+ let d2 = match cs {
+ ChamferSide::Distance(d) => d,
+ // The triangle edge–A–B: angle φ at the edge, `a` at A (on the first side).
+ ChamferSide::Angle(a) => {
+ let den = (phi + a).sin();
+ if den <= 1e-9 {
+ return None;
+ }
+ r * a.sin() / den
+ }
+ };
+ if face_first { (r, d2) } else { (d2, r) }
+ }
+ };
+ Some((m, t, sf, sw, r / (phi / 2.0).sin()))
};
+ if let Some((ChamferSide::Angle(a), _)) = sides {
+ for (i, s) in segs.iter().enumerate() {
+ let p = s.start();
+ if let Some(t) = up(i, p)
+ && (into(s, p).dot(t).clamp(-1.0, 1.0).acos() + a).sin() <= 1e-9
+ {
+ return Err(KernelError::Invalid("that chamfer angle runs past the other face".into()));
+ }
+ }
+ }
// The straight seam between the walls at a sharp joint (direction away from the face).
let seam_dir = |i: usize, p: Vec3| -> Option<Vec3> {
let o = owner.get(i)?;
@@ -426,17 +528,17 @@ fn build(
let joint_point = |i: usize| if i < k { segs.get(i).map(|s| s.start()) } else { segs.last().map(|s| s.end()) };
for i in 0..nj {
let p = joint_point(i).unwrap_or_default();
- let (m, t, sb, dc) = frame(i.min(k - 1), p).ok_or_else(|| unsupported("the face and wall meet at an angle the blend can't take"))?;
+ let (m, t, sb, sbw, dc) = frame(i.min(k - 1), p).ok_or_else(|| unsupported("the face and wall meet at an angle the blend can't take"))?;
centres.push(p + (m + t).normalized().unwrap_or(m) * dc);
if !mitre.get(i).copied().unwrap_or(false) {
pa.push(p + m * sb);
- pb.push(p + t * sb);
+ pb.push(p + t * sbw);
continue;
}
// Sharp joint: the face rails meet where the two offset lines cross; the wall rails
// meet on the seam.
let ip = (i + k - 1) % k;
- let (m0, t0, sb0, _) = frame(ip, p).ok_or_else(|| unsupported("the face and wall meet at an angle the blend can't take"))?;
+ let (m0, t0, sb0, sbw0, _) = frame(ip, p).ok_or_else(|| unsupported("the face and wall meet at an angle the blend can't take"))?;
let (Some(d0), Some(d1)) = (segs.get(ip).and_then(|x| x.tangent(p)), segs.get(i).and_then(|x| x.tangent(p))) else {
return Err(unsupported("degenerate loop edge"));
};
@@ -447,7 +549,9 @@ fn build(
&& t0.dot(n * side) > 1.0 - 1e-9;
if exact {
let (Some(prev), Some(cur)) = (segs.get(ip), segs.get(i)) else { return Err(unsupported("corner segments")) };
- pa.push(offset_joint(prev, cur, n, r).ok_or_else(|| too_large("the blend's offset walls do not meet"))?);
+ pa.push(
+ offset_joint(prev, cur, n, if sides.is_some() { sb } else { r }).ok_or_else(|| too_large("the blend's offset walls do not meet"))?,
+ );
if let Some(slot) = curved_joint.get_mut(i) {
*slot = true;
}
@@ -456,10 +560,10 @@ fn build(
}
let e = seam_dir(i, p).ok_or_else(|| unsupported("a sharp corner without one straight seam"))?;
let (h0, h1) = (e.dot(t0), e.dot(t));
- if h0 < 1e-6 || h1 < 1e-6 || (sb0 / h0 - sb / h1).abs() > tol * 10.0 {
+ if h0 < 1e-6 || h1 < 1e-6 || (sbw0 / h0 - sbw / h1).abs() > tol * 10.0 {
return Err(unsupported("a sharp corner whose walls meet the blend differently"));
}
- pb.push(p + e * (sb / h1));
+ pb.push(p + e * (sbw / h1));
}
// Sharp joints between straight rim edges can extend beyond the old corner.
// Equal wall slopes reach this path instead of the corner builder, and must
@@ -480,6 +584,14 @@ fn build(
for (i, s) in segs.iter().enumerate() {
if let Seg::Arc { a, c, .. } = *s {
let toward = into(s, a).dot(c - a) > 0.0;
+ // An unequal chamfer's offset on the face; it never ends in a point (a cone's apex).
+ if sides.is_some() {
+ let reach = frame(i, a).map(|x| x.2).ok_or_else(|| unsupported("the face and wall meet at an angle the blend can't take"))?;
+ if toward && a.dist(c) <= reach + tol * 10.0 {
+ return Err(too_large("the chamfer is larger than a corner radius"));
+ }
+ continue;
+ }
if toward && (a.dist(c) - r).abs() <= tol * 10.0 && !mitre.get(i).copied().unwrap_or(true) && !mitre.get(nxt(i)).copied().unwrap_or(true)
{
if let Some(x) = collapsed.get_mut(i) {
@@ -548,7 +660,11 @@ fn build(
let (Some(a), Some(b)) = (va.get(i), vb.get(i)) else { return Err(KernelError::Failed("joint".into())) };
if curved_joint.get(i).copied().unwrap_or(false) {
let (Some(prev), Some(cur)) = (segs.get((i + k - 1) % k), segs.get(i)) else { return Err(unsupported("corner segments")) };
- let curve = offset_profile(prev, cur, n, side, r, round, (r * 1e-7).max(1e-9))?;
+ let setbacks = match sides {
+ None => (r, r),
+ Some(_) => joint_point(i).and_then(|p| frame(i.min(k - 1), p)).map(|x| (x.2, x.3)).ok_or_else(|| unsupported("frame"))?,
+ };
+ let curve = offset_profile(prev, cur, n, side, setbacks, round, (setbacks.0.min(setbacks.1) * 1e-7).max(1e-9))?;
profiles.push(mt::Edge::try_new(a, b, curve).map_err(|e| KernelError::Failed(format!("curved corner: {e}")))?);
continue;
}
@@ -566,7 +682,7 @@ fn build(
let d1 = segs.get(i).and_then(|x| x.tangent(p)).ok_or_else(|| unsupported("tangent"))?;
let (pa_i, pb_i) = (from_p3(a.point()), from_p3(b.point()));
let lam = (pa_i - p).dot(d1);
- let (_, t, sb, _) = frame(i, p).ok_or_else(|| unsupported("frame"))?;
+ let (_, t, sb, _, _) = frame(i, p).ok_or_else(|| unsupported("frame"))?;
let cc = centre(i) + d1 * lam;
let q = p + t * sb + d1 * lam;
let mid = cc + ((pa_i - cc) + (q - cc)).normalized().unwrap_or(t) * r;
@@ -604,11 +720,11 @@ fn build(
let piece_of = |s: &Seg| segs.iter().position(|x| std::ptr::eq(x, s)).unwrap_or(0);
let face_off = |p: Vec3, s: &Seg| {
let i = piece_of(s);
- frame(i, p).map(|(m, _, sb, _)| p + m * sb).unwrap_or(p)
+ frame(i, p).map(|(m, _, sb, _, _)| p + m * sb).unwrap_or(p)
};
let wall_off = |p: Vec3, s: &Seg| {
let i = piece_of(s);
- frame(i, p).map(|(_, t, sb, _)| p + t * sb).unwrap_or(p)
+ frame(i, p).map(|(_, t, _, sbw, _)| p + t * sbw).unwrap_or(p)
};
let face_rails: Vec<Option<mt::Edge>> = (0..k).map(|i| rail(&va, i, &face_off)).collect();
if face_rails.iter().zip(&collapsed).any(|(r, c)| r.is_none() && !c) {
@@ -773,11 +889,11 @@ fn build(
// The cross-section at the start, swept along the whole edge and beyond (the
// face may reach past the edge's ends at a mitre).
let d = (b - a).normalized().ok_or_else(|| unsupported("degenerate loop edge"))?;
- let (_, t, sb, _) = frame(i, a).ok_or_else(|| unsupported("frame"))?;
+ let (_, t, sb, sbw, _) = frame(i, a).ok_or_else(|| unsupported("frame"))?;
let m = into(s, a);
let ext = size;
let back = d * -ext;
- let (fa, wa) = (builder::vertex(p3(a + m * sb + back)), builder::vertex(p3(a + t * sb + back)));
+ let (fa, wa) = (builder::vertex(p3(a + m * sb + back)), builder::vertex(p3(a + t * sbw + back)));
let base = if round { builder::circle_arc(&fa, &wa, p3(profile_mid(i) + back)) } else { builder::line(&fa, &wa) };
vec![builder::tsweep(&base, v3(b - a + d * (2.0 * ext)))].into()
}
@@ -801,16 +917,24 @@ fn build(
Seg::Arc { a, c, axis, angle, .. } => {
// Sweep a radial section, not the shared corner curve: the latter can be
// nonplanar and would change the round's radius all along this edge.
- let (_, t, sb, _) = frame(i, a).ok_or_else(|| unsupported("frame"))?;
- let (fa, wa) = (builder::vertex(p3(a + into(s, a) * sb)), builder::vertex(p3(a + t * sb)));
+ let (_, t, sb, sbw, _) = frame(i, a).ok_or_else(|| unsupported("frame"))?;
+ let (fa, wa) = (builder::vertex(p3(a + into(s, a) * sb)), builder::vertex(p3(a + t * sbw)));
let base = if round { builder::circle_arc(&fa, &wa, p3(profile_mid(i))) } else { builder::line(&fa, &wa) };
builder::rsweep(&base, p3(c), v3(axis), mt::Rad(angle))
}
};
let mut surf = swept.face_iter().next().map(|x| x.oriented_surface()).ok_or_else(|| KernelError::Failed("blend surface".into()))?;
// Outward: toward the profile centre on a concave loop, away from it on a convex one.
+ // An unequal chamfer's profile has no centre: its middle, away from the edge on a concave
+ // loop (where the chamfer fills) and toward it on a convex one.
let (c, mid) = (centre(i), profile_mid(i));
- let outward = (c - mid) * side;
+ let (mid, outward) = match (sides, joint_point(i)) {
+ (Some(_), Some(p)) => {
+ let m = (from_p3(pr.front().point()) + from_p3(pr.back().point())) * 0.5;
+ (m, (m - p) * side)
+ }
+ _ => (mid, (c - mid) * side),
+ };
if let Some((u, v)) = surf.search_nearest_parameter(p3(mid), None, 100) {
let nn = surf.normal(u, v);
if Vec3::new(nn.x, nn.y, nn.z).dot(outward) < 0.0 {