From 54b00fa7b1d3292d0a1bc263a47e96a233347a07 Mon Sep 17 00:00:00 2001 From: fkirill Date: Tue, 20 Oct 2026 01:04:24 +0300 Subject: [PATCH] Chamfer straight lips at tangent wall junctions (#2408) (#2490) Thanks @fkirill. --- crates/kernel/src/blend.rs | 98 +++++++++++++++++++ crates/kernel/src/curveblend.rs | 9 +- crates/kernel/tests/chamfer_curved_holder.rs | 90 +++++++++++++++++ .../chamfer_curved_holder_top_lip.json | 14 +++ 4 files changed, 210 insertions(+), 1 deletion(-) create mode 100644 crates/kernel/tests/chamfer_curved_holder.rs create mode 100644 examples/regressions/chamfer_curved_holder_top_lip.json diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rs index 484a95e28..60f349e4f 100644 --- a/crates/kernel/src/blend.rs +++ b/crates/kernel/src/blend.rs @@ -2187,6 +2187,11 @@ fn chamfer_built(body: &Body, edges: &[Vec3], distance: f64) -> Result { let blend_or_curved = |cur: &Body, p: &Vec3| -> Result { blend(cur, std::slice::from_ref(p), distance, Shape::Flat, "chamfer") .or_else(|e| blend_with(cur, std::slice::from_ref(p), distance, Shape::Flat, "chamfer", true).map_err(|_| e)) + .or_else(|e| { + chamfer_tool_curved(cur, *p, distance) + .and_then(|tool| cut_one(cur, &tool)?.ok_or_else(|| KernelError::Failed("the chamfer removed everything".into()))) + .map_err(|_| e) + }) }; for p in edges { let tool = chamfer_tool(&cur, *p, distance, 0); @@ -2424,6 +2429,99 @@ pub(crate) fn chamfer_tool(cur: &Body, p: Vec3, s: f64, k: usize) -> Result Result { + guard("straight curved chamfer", || { + let size = cur.size(); + let tolerance = (size * 1e-7).max(1e-9); + let (index, gap) = cur.nearest_edge(pick, (size * 2e-3).max(1e-3))?.ok_or_else(|| unsupported("no chamfer edge"))?; + if gap > size * 0.05 + 1e-3 { + return Err(unsupported("no nearby chamfer edge")); + } + let edge = Body::unique_edges(&cur.solid).into_iter().nth(index).ok_or_else(|| unsupported("chamfer edge"))?; + if !crate::curveblend::straight(&edge, tolerance * 10.0) { + return Err(unsupported("a straight plane/cylinder edge is required")); + } + let (p0, p1) = (vtx(edge.absolute_front()), vtx(edge.absolute_back())); + let along = (p1 - p0).normalized().ok_or_else(|| unsupported("zero-length chamfer edge"))?; + let faces: Vec<_> = cur.solid.face_iter().filter(|f| f.edge_iter().any(|e| e.id() == edge.id())).collect(); + let [f1, f2] = faces.as_slice() else { return Err(unsupported("the edge must have two faces")) }; + let kinds = (crate::surface_kind::surface_of(f1, size), crate::surface_kind::surface_of(f2, size)); + let (normal, axis) = match kinds { + (Some(crate::FaceSurface::Plane { normal, .. }), Some(crate::FaceSurface::Cylinder { axis, .. })) + | (Some(crate::FaceSurface::Cylinder { axis, .. }), Some(crate::FaceSurface::Plane { normal, .. })) => (normal, axis), + _ => return Err(unsupported("a straight plane/cylinder edge is required")), + }; + // A boolean intersection can carry slightly displaced ends and supporting surfaces. + // Check angular alignment here, then the swept contacts against the actual surfaces. + if normal.dot(axis).abs() > 1e-5 || axis.cross(along).len() > 1e-5 { + return Err(unsupported("the cylinder must run along the chamfer edge")); + } + let d = if axis.dot(along) < 0.0 { -axis } else { axis }; + let mid = (p0 + p1) * 0.5; + let (n1, n2) = ( + crate::curveblend::project(f1, mid, None).map(|p| p.1).ok_or_else(|| unsupported("chamfer normal"))?, + crate::curveblend::project(f2, mid, None).map(|p| p.1).ok_or_else(|| unsupported("chamfer normal"))?, + ); + let used = f1.boundary_iters().into_iter().flatten().find(|e| e.id() == edge.id()).ok_or_else(|| unsupported("chamfer edge use"))?; + let tangent = (vtx(used.back()) - vtx(used.front())).normalized().ok_or_else(|| unsupported("chamfer tangent"))?; + if tangent.dot(n1.cross(n2)) <= 1e-9 { + return Err(unsupported("a convex chamfer edge is required")); + } + let (a, b) = crate::curveblend::straight_chamfer_contacts(f1, f2, mid, *d, distance, tolerance) + .ok_or_else(|| unsupported("the chamfer section does not fit"))?; + let fit_tolerance = (size * 1e-5).clamp(1e-5, 0.001); + for (face, point) in [(*f1, a), (*f2, b)] { + for along in [-0.5, -0.25, 0.0, 0.25, 0.5] { + let swept = point + d * (along * p0.dist(p1)); + if crate::curveblend::project(face, swept, None).is_none_or(|(q, _, _)| q.dist(swept) > fit_tolerance) { + return Err(unsupported("the chamfer section varies along the edge")); + } + } + } + // Contacts must lie on the trimmed faces, not merely their infinite supports. A + // fine mesh and an inward probe larger than its chord error also reject a bevel that + // has already used up the top face. Reuse that mesh for all cutter clearance probes. + let mesh = cur.tessellate_with(tolerance * 10.0, true)?; + let inset = (tolerance * 100.0).min(distance * 0.01); + for (face, point) in [(*f1, a), (*f2, b)] { + let (_, normal, _) = crate::curveblend::project(face, point, None).ok_or_else(|| unsupported("chamfer contact"))?; + if !mesh.contains(point - normal * inset) { + return Err(too_large("the chamfer runs past a neighbouring face")); + } + } + let outward = (n1 + n2).normalized().ok_or_else(|| unsupported("chamfer direction"))?; + let across = (a - b).normalized().ok_or_else(|| unsupported("chamfer section"))?; + let reach = distance * 4.0 + size * 0.02; + let center = (a + b + mid) / 3.0; + let a = a + across * reach; + let b = b - across * reach; + if mesh.contains(a) || mesh.contains(b) { + return Err(unsupported("the chamfer cutter crosses a neighbouring face")); + } + let extension = (distance * 2.0).max(size * 0.01); + let half = p0.dist(p1) * 0.5; + if [-1.0, 1.0].into_iter().any(|side| mesh.contains(center + d * (side * (half + extension * 0.5)))) { + return Err(unsupported("chamfers ending at a concave corner")); + } + let plane = solidcraft_geom::Plane::from_normal(mid - d * (p0.dist(p1) * 0.5 + extension), d).ok_or_else(|| unsupported("chamfer plane"))?; + let points = [a, b, mid + outward * reach].map(|q| plane.to_local(q)); + let mut profile = solidcraft_geom::Loop2::polygon(&points); + let mut segment = 0; + if profile.signed_area() < 0.0 { + profile = profile.reversed(); + segment = profile.segs.len().saturating_sub(1); + } + let region = solidcraft_geom::Region2 { outer: profile, holes: vec![] }; + let body = + crate::build::extrude(&plane, &[region], 0.0, p0.dist(p1) + 2.0 * extension)?.pop().ok_or_else(|| unsupported("chamfer cutter"))?; + let face = body.history().and_then(|h| h.faces.iter().position(|f| f.origins == [FaceOrigin::Profile { segment }])); + Ok(Cutter { body, face, edge: index, extension_inside: false }) + }) +} + fn chamfer_tool_sides(cur: &Body, p: Vec3, s: f64, sides: Option<(ChamferSide, bool)>, k: usize) -> Result { let (edge, mut f) = edge_frame(cur, p)?; // Setbacks along each face: equal, or by the second side's rule. diff --git a/crates/kernel/src/curveblend.rs b/crates/kernel/src/curveblend.rs index 37b606a54..e01cf5ee6 100644 --- a/crates/kernel/src/curveblend.rs +++ b/crates/kernel/src/curveblend.rs @@ -653,6 +653,13 @@ fn solve_from( None } +/// Contacts of a convex chamfer in a cross-section normal to a straight edge. The caller +/// checks that sweeping the section stays on both supports within the fitting tolerance. +pub(crate) fn straight_chamfer_contacts(f1: &mt::Face, f2: &mt::Face, p: Vec3, d: Vec3, r: f64, tolerance: f64) -> Option<(Vec3, Vec3)> { + let section = solve(&[f1], &[f2], p, d, r, -1.0, 0.0, None, tolerance)?; + Some((section.q1, section.q2)) +} + /// The section whose two contacts are `chord` apart: the ball's radius is `chord / (2 sin(ψ/2))` /// for the `ψ` between the two outward normals where it touches, `|q1 − q2| = 2 r sin(ψ/2)`. The /// normals turn as the ball grows against curved faces, so the width is measured on the solved @@ -931,7 +938,7 @@ fn revolve(ctrl: [mt::Vector4; 3], c: Vec3, axis: Vec3, angle: f64) -> Option bool { +pub(crate) fn straight(e: &mt::Edge, tol: f64) -> bool { use mt::{BoundedCurve, ParametricCurve}; let c = e.curve(); if matches!(c, mt::Curve::Line(_)) { diff --git a/crates/kernel/tests/chamfer_curved_holder.rs b/crates/kernel/tests/chamfer_curved_holder.rs new file mode 100644 index 000000000..00e715efc --- /dev/null +++ b/crates/kernel/tests/chamfer_curved_holder.rs @@ -0,0 +1,90 @@ +//! #2408, reconstructed from the public screenshot (the original design is unavailable). +//! A cylindrical side cut through a rounded bar leaves a very short seam where the top lip +//! meets the tangent junction of the bar's straight and round walls. The chamfer must trim +//! against the round wall instead of extending that short seam outside the solid. + +use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3}; +use solidcraft_kernel::{Body, BoolOp, boolean, chamfer, cylinder, extrude}; +use std::f64::consts::PI; + +fn holder() -> Body { + let segs = vec![ + Seg2::Line { a: Vec2::new(0.0, 10.0), b: Vec2::new(0.0, 70.0) }, + Seg2::Arc { center: Vec2::new(10.0, 70.0), radius: 10.0, start: PI, sweep: -PI }, + Seg2::Line { a: Vec2::new(20.0, 70.0), b: Vec2::new(20.0, 10.0) }, + Seg2::Arc { center: Vec2::new(10.0, 10.0), radius: 10.0, start: 0.0, sweep: -PI }, + ]; + let bar = extrude(&Plane::XY, &[Region2 { outer: Loop2 { segs }, holes: vec![] }], 0.0, 60.0).unwrap().pop().unwrap(); + let tool = cylinder(Vec3::new(-1.0, 70.0, 60.0), Vec3::X, 60.0, 22.0).unwrap(); + boolean(&bar, &tool, BoolOp::Cut).unwrap().unwrap() +} + +/// Integrate the removed horizontal strips analytically across the capsule's width, then +/// use Simpson integration in height. The rolling section's centre is 2 below the top and +/// 62 from the cutter's axis; its wall contact is 60/62 of that vector from the axis. +fn expected_removed(distance: f64) -> f64 { + let center_y = 70.0 - ((60.0 + distance).powi(2) - distance.powi(2)).sqrt(); + let contact_y = 70.0 + (center_y - 70.0) * 60.0 / (60.0 + distance); + let depth = distance * 60.0 / (60.0 + distance); + let area = |y: f64| { + let u = (y - 10.0).clamp(-10.0, 0.0); + u * (100.0 - u * u).sqrt() + 100.0 * (u / 10.0).asin() + 20.0 * (y - 10.0).max(0.0) + }; + let n = 4000; + let h = depth / n as f64; + (0..=n) + .map(|i| { + let z = i as f64 * h; + let cut = 70.0 - (3600.0 - z * z).sqrt(); + let bevel = center_y + (contact_y - center_y) * z / depth; + let weight = if i == 0 || i == n { + 1.0 + } else if i % 2 == 0 { + 2.0 + } else { + 4.0 + }; + weight * (area(cut) - area(bevel)) + }) + .sum::() + * h + / 3.0 +} + +#[test] +fn chamfer_the_top_lip_at_a_tangent_wall_junction() { + let body = holder(); + let made = chamfer(&body, &[Vec3::new(10.0, 10.0, 60.0)], 2.0).unwrap(); + assert!(made.validity().is_empty(), "{:?}", made.validity()); + assert_eq!(made.crossed_face_loops().unwrap(), 0); + let history = made.history().expect("the chamfer retains exact face provenance"); + assert!(history.faces.iter().any(|f| f.origins.iter().any(|o| matches!(o, solidcraft_kernel::history::FaceOrigin::Edge { operand: 0, .. })))); + let mesh = |body: &Body| body.tessellate_with(0.0005, true).unwrap(); + let before = mesh(&body).measure().volume; + let after = mesh(&made); + let removed = before - after.measure().volume; + let expected = expected_removed(2.0); + eprintln!("removed {removed:.8} mm³, expected {expected:.8} mm³"); + assert!((removed - expected).abs() < 0.03, "removed {removed}, expected {expected}"); + assert!(!made.contains(Vec3::new(10.0, 9.5, 59.5)), "the old corner was removed"); + assert!(made.contains(Vec3::new(10.0, 7.0, 59.5)), "material behind the bevel remains"); + assert!(made.contains(Vec3::new(10.0, 10.0, 55.0)), "material below the bevel remains"); + // A closed mesh's signed volume is independent of the origin. + let volume_about = |origin: Vec3| { + after + .triangles + .iter() + .map(|t| { + let [a, b, c] = t.map(|i| after.positions[i as usize] - origin); + a.dot(b.cross(c)) / 6.0 + }) + .sum::() + }; + assert!((volume_about(Vec3::ZERO) - volume_about(Vec3::new(-100.0, 50.0, 30.0))).abs() < 0.01); +} + +#[test] +fn a_chamfer_that_uses_up_the_holder_top_is_refused() { + let body = holder(); + assert!(chamfer(&body, &[Vec3::new(10.0, 10.0, 60.0)], 30.0).is_err()); +} diff --git a/examples/regressions/chamfer_curved_holder_top_lip.json b/examples/regressions/chamfer_curved_holder_top_lip.json new file mode 100644 index 000000000..97118f494 --- /dev/null +++ b/examples/regressions/chamfer_curved_holder_top_lip.json @@ -0,0 +1,14 @@ +{ + "description":"Original reconstruction of issue #2408: a 20 mm wide slot, extruded 60 mm, cut with an R60 horizontal cylinder whose top lip meets the slot's tangent junction. Chamfer that top lip by 2 mm.", + "commands":[ + {"command":"sketch.create","params":{"plane":"XY"}}, + {"command":"sketch.slot.center_to_center","params":{"p0":[10,10],"p1":[10,70],"width":20}}, + {"command":"sketch.finish","params":{}}, + {"command":"solid.extrude","params":{"distance":60,"operation":"new"}}, + {"command":"sketch.create","params":{"plane":{"origin":[-1,0,0],"x_dir":[0,1,0],"y_dir":[0,0,1]}}}, + {"command":"sketch.circle.center","params":{"center":[70,60],"radius":60}}, + {"command":"sketch.finish","params":{}}, + {"command":"solid.extrude","params":{"distance":22,"operation":"cut"}}, + {"command":"solid.chamfer","params":{"distance":2,"edges":[[10,10,60]]}} + ] +}