diff --git a/crates/geom/src/brep/form.rs b/crates/geom/src/brep/form.rs index 55f8a53cf..1356137f9 100644 --- a/crates/geom/src/brep/form.rs +++ b/crates/geom/src/brep/form.rs @@ -319,12 +319,18 @@ const EXTENT_POINTS: usize = 32; /// The parameter box of a face on `label` over its boundary: each loop's points (`loops`, in /// order along each loop) projected onto the label, a periodic parameter unwrapped from one point -/// to the next. What the face's NURBS form ([`surface`]) is built over; no pcurve is involved. +/// to the next, and each loop after the first a whole number of periods along where that keeps +/// the box smallest. What the face's NURBS form ([`surface`]) is built over; no pcurve is +/// involved. pub fn extent(label: &Surface, loops: &[Vec<(&Curve, [f64; 2], bool)>]) -> Option<[[f64; 2]; 2]> { let eval = super::eval::SurfaceEval::new(label).ok()?; let period = eval.domain().period; let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); for l in loops { + // A loop is unwrapped from its own first point, so it can come out whole periods away + // from the loops before it (a hole beside the seam projects to the seam's other side), + // and a box over both is more than a turn wide. + let (mut l_lo, mut l_hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]); let mut prev: Option<[f64; 2]> = None; for (c, [t0, t1], forward) in l { let curve = super::eval::CurveEval::new(c).ok()?; @@ -343,8 +349,8 @@ pub fn extent(label: &Surface, loops: &[Vec<(&Curve, [f64; 2], bool)>]) -> Optio let pole = eval.pole(q); for d in 0..2 { if !pole.get(d).copied().unwrap_or(false) { - lo[d] = lo[d].min(q[d]); - hi[d] = hi[d].max(q[d]); + l_lo[d] = l_lo[d].min(q[d]); + l_hi[d] = l_hi[d].max(q[d]); } } if !pole.iter().any(|p| *p) { @@ -352,6 +358,23 @@ pub fn extent(label: &Surface, loops: &[Vec<(&Curve, [f64; 2], bool)>]) -> Optio } } } + for d in 0..2 { + if !(l_lo[d] <= l_hi[d]) { + continue; + } + let shift = match period.get(d) { + Some(Some(per)) if lo[d] <= hi[d] => { + // The whole periods around the ones that bring the loop's middle to the box's, + // the one giving the smallest box. + let k = ((lo[d] + hi[d] - l_lo[d] - l_hi[d]) / (2.0 * per)).round(); + let span = |k: f64| hi[d].max(l_hi[d] + k * per) - lo[d].min(l_lo[d] + k * per); + [k, k - 1.0, k + 1.0].into_iter().min_by(|a, b| span(*a).total_cmp(&span(*b))).unwrap_or(k) * per + } + _ => 0.0, + }; + lo[d] = lo[d].min(l_lo[d] + shift); + hi[d] = hi[d].max(l_hi[d] + shift); + } } // At most one turn round a periodic direction; a boundary that never goes round it (a face // bounded by its seam alone) covers the whole turn from there. diff --git a/crates/geom/src/brep/tests.rs b/crates/geom/src/brep/tests.rs index 62bdc35cb..bd913a50c 100644 --- a/crates/geom/src/brep/tests.rs +++ b/crates/geom/src/brep/tests.rs @@ -802,3 +802,30 @@ fn analytic_records_are_unbounded_with_independent_frames() { assert!(radius(f64::NAN).is_err()); assert!(surface(&Surface::Torus { frame: a_frame(), major_radius: 1., minor_radius: 2. }, 0, &mut Budget(0)).is_err()); } + +/// A cylinder face round its axis with a hole beside its seam: the seam at 350 degrees (so its +/// loop projects from 350 degrees on), the hole at 15..25 degrees (which on its own projects a +/// turn below). The face's box is the outer loop's turn with the hole in it; the hole's own +/// placement made a box from 15 degrees that cut the turn short and left the seam outside it +/// (#4598: a bored rod read back with its bore's pcurve a period off its face). +#[test] +fn a_hole_beside_the_seam_lies_in_its_face_turn() { + let (r, h) = (20.0f64, 60.0); + let cylinder = Surface::Cylinder { frame: Frame { origin: [0.; 3], x_axis: [1., 0., 0.], y_axis: [0., 1., 0.] }, radius: r }; + let s = -10f64.to_radians(); + let at = |a: f64, z: f64| [r * a.cos(), r * a.sin(), z]; + let ring = |z: f64| Curve::Circle { frame: Frame { origin: [0., 0., z], x_axis: [s.cos(), s.sin(), 0.], y_axis: [-s.sin(), s.cos(), 0.] }, radius: r }; + let (bottom, top) = (ring(0.), ring(h)); + let seam = Curve::Line { start: at(s, 0.), end: at(s, h) }; + let (a0, a1) = (15f64.to_radians(), 25f64.to_radians()); + let hole = + Curve::Spline { knots: vec![0., 0., 1., 2., 3., 4., 4.], points: vec![at(a0, 25.), at(a1, 25.), at(a1, 35.), at(a0, 35.), at(a0, 25.)] }; + let outer = vec![(&bottom, [0., TAU], true), (&seam, [0., 1.], true), (&top, [0., TAU], false), (&seam, [0., 1.], false)]; + let inner = vec![(&hole, [0., 4.], true)]; + let [u, v] = form::extent(&cylinder, &[outer, inner]).expect("an extent"); + assert!((u[1] - u[0] - TAU).abs() < 1e-9, "one turn: {u:?}"); + assert!((u[0].rem_euclid(TAU) - s.rem_euclid(TAU)).abs() < 1e-9, "from the seam: {u:?}"); + let hole_u = a0 + ((u[0] - a0) / TAU).ceil() * TAU; + assert!(hole_u > u[0] && hole_u + (a1 - a0) < u[1], "the hole in the turn: {u:?}"); + assert!(v[0].abs() < 1e-9 && (v[1] - h).abs() < 1e-9, "{v:?}"); +} diff --git a/crates/kernel/src/blend.rs b/crates/kernel/src/blend.rs index 28047c909..fcf7969ae 100644 --- a/crates/kernel/src/blend.rs +++ b/crates/kernel/src/blend.rs @@ -388,7 +388,10 @@ pub fn chamfer_sides(body: &Body, edges: &[Vec3], d1: f64, side: ChamferSide, fl /// tangentially (within 0.5° at a shared vertex), until no more do. Each pick takes its edge as a /// blend does (a pick at a vertex where a seam meets a rim takes the rim). An edge only one face /// uses ends a chain, and so do a seam and a smooth edge (its two faces meet tangentially, within -/// 0.5°): they have no corner to round. Picks that find no edge are refused. +/// 0.5°): they have no corner to round. A chain does not run on into an edge of the other +/// convexity (a boss's concave base running on tangentially as the convex rim of its overhang): +/// a round cannot pass from one side of the faces to the other, so it ends at that vertex. +/// Picks that find no edge are refused. pub fn tangent_chain(body: &Body, picks: &[Vec3]) -> Result> { /// Edges meeting at an angle below this continue one another. const TANGENT_DEGREES: f64 = 0.5; @@ -423,6 +426,23 @@ pub fn tangent_chain(body: &Body, picks: &[Vec3]) -> Result> { _ => false, } }; + // Whether edge `e` is convex at its end `v` (its faces meet at less than 180° inside the + // body): the direction into its second face, square to it, points against its first face's + // outward normal. A face lies to the left of its loop seen from its surface's natural normal. + // None for an edge without exactly two uses, or where a normal cannot be found. + let convex = |e: usize, v: u32| -> Option { + let edge = rec.rec.edges.get(e)?; + let [ua, ub] = edge.uses.as_slice() else { return None }; + let forward_b = match rec.rec.faces.get(ub.face as usize)?.loops.get(ub.r#loop as usize)? { + Loop::Edges { edges } => edges.get(ub.position as usize)?.forward, + Loop::Vertex { .. } => return None, + }; + let p = rec.point(v)?; + let along = rec.tangent(e, edge.vertices[0] != v)?; + let natural_b = rec.normal_at(ub.face as usize, p, accept)? * rec.side(ub.face as usize)?; + let into_b = natural_b.cross(if forward_b { along } else { along * -1.0 }); + Some(into_b.dot(rec.normal_at(ua.face as usize, p, accept)?) < 0.0) + }; let mut k = 0; while k < chain.len() { let Some(&e) = chain.get(k) else { break }; @@ -435,7 +455,8 @@ pub fn tangent_chain(body: &Body, picks: &[Vec3]) -> Result> { if passed_over || chain.contains(&f) || other.uses.len() < 2 || !other.vertices.contains(&v) || smooth(f) { continue; } - if leaving(f, v).is_some_and(|g| d.dot(g) < -cos) { + let turns_over = matches!((convex(e, v), convex(f, v)), (Some(a), Some(b)) if a != b); + if !turns_over && leaving(f, v).is_some_and(|g| d.dot(g) < -cos) { chain.push(f); } } @@ -610,7 +631,14 @@ mod tests { assert!(fillet_g2(&body, &[], 2.0).is_err()); assert!(fillet_g2(&body, &[Vec3::new(f64::NAN, 0.0, 0.0)], 2.0).is_err()); assert!(fillet_g2(&body, &[Vec3::new(1000.0, 0.0, 0.0)], 2.0).is_err()); - assert!(fillet_g2(&body, &edge, 25.0).is_err()); + // Wider than the faces (20), over their far edges, cliffs: cut as if they went on. The + // section is the quintic from 25 out on each face, its inner control points a third and + // two thirds of the way to the corner; it takes the region between it and the corner + // inside the 20 x 20 section (clipped polygon of the curve, 2e5 pieces), along 20. + let wide = fillet_g2(&body, &edge, 25.0).unwrap(); + let v = crate::measure(&wide).unwrap().volume; + assert!((v - 6138.1606889014).abs() < 1e-6 * 6138.1606889014, "{v}"); + assert!(wide.validity().is_empty()); } /// A box with a cylinder joined across one side (#556): the bottom edge of that side runs @@ -813,7 +841,15 @@ mod tests { for point in [Vec3::new(slope * 2.0, 2.0, 20.0), Vec3::new(40.0 - slope * 2.0, 2.0, 20.0)] { assert!(has_vertex(&result, point, 1e-8)); } - assert!(chamfer(&body, &pick, 25.0).is_err()); + // Past the faces (20 deep, 20 high), over their far edges, cliffs: cut as if the + // faces and the sloped end planes went on. The plane 25 back on each face takes, of + // the section, z >= y - 5 (y, z in [0, 20]), each line of it 40 - 2 slope y long + // between the end planes: 11500 - 4625 slope. + let past = chamfer(&body, &pick, 25.0).unwrap(); + let removed = 11500.0 - 4625.0 * slope; + let actual = crate::measure(&body).unwrap().volume - crate::measure(&past).unwrap().volume; + assert!((actual - removed).abs() < 1e-6 * removed, "{actual} vs {removed}"); + assert!(past.validity().is_empty()); // A fillet ends in each sloped end plane along an ellipse: the removed section's // length is taken at its centroid, c from the edge. let rounded = fillet(&body, &pick, 2.0).unwrap(); diff --git a/crates/kernel/src/blend_variable.rs b/crates/kernel/src/blend_variable.rs index 1d253077c..78206dd24 100644 --- a/crates/kernel/src/blend_variable.rs +++ b/crates/kernel/src/blend_variable.rs @@ -557,8 +557,17 @@ mod tests { let g = fillet_variable(&b, Vec3::new(10.0, 10.0, 30.0), Vec3::new(10.0, 0.0, 30.0), 3.0, 3.0).unwrap(); let k = crate::fillet(&b, &[Vec3::new(10.0, 10.0, 30.0)], 3.0).unwrap(); assert!(rel(measure(&g).unwrap().volume, measure(&k).unwrap().volume) < 1e-6); - // Too big for the faces: refused. - assert!(fillet_variable(&b, Vec3::new(10.0, 10.0, 30.0), Vec3::new(10.0, 0.0, 30.0), 2.0, 50.0).is_err()); + // Wider than the faces: past r = 10 the contact on the top leaves it across its far edge + // x = 0 (past r = 30 the one on the side across its bottom), cliffs. The round is built as + // if the faces went on, and what it removes is cut from the box: at each y the section of + // the r x r square at the edge less the quarter disc about (10 - r, 30 - r), inside + // [0, 10] x [0, 30], in closed form (a, b from the disc's centre: a, b in [0, r], + // a^2 + b^2 >= r^2, a >= r - 10, b >= r - 30), integrated along y by Gauss-Legendre + // between the kinks at r = 10 and 30: 2453.81232061 removed, 3546.18767939 left (to 1e-4, + // as the variable rounds above). + let w = fillet_variable(&b, Vec3::new(10.0, 10.0, 30.0), Vec3::new(10.0, 0.0, 30.0), 2.0, 50.0).unwrap(); + let vw = measure(&w).unwrap().volume; + assert!(rel(vw, 3546.1876793935) < 1e-4, "{vw} vs 3546.1876793935"); } /// A radius through a middle point: straight pieces (exact: each piece removes @@ -704,9 +713,15 @@ mod tests { assert!(fillet_variable_spline(&b, at, start, &unclamped).is_err()); let dips = RadiusSpline { radii: vec![2.0, 0.0, 0.0, 3.0, 2.0], ..law.clone() }; assert!(fillet_variable_spline(&b, at, start, &dips).is_err()); - // A middle radius beyond the faces: too large. + // A middle radius beyond the faces (up to 21.25 on the top 10 wide): the contact on the top + // leaves it across its far edge, a cliff, and the round is cut as if the top went on: at + // each y the r x r square at the edge less the quarter disc about (10 - r, 30 - r), inside + // [0, 10] x [0, 30], in closed form, integrated along y (Gauss-Legendre, split at the + // knot and where r crosses 10): 726.5334566720 removed. let big = RadiusSpline { radii: vec![2.0, 2.0, 40.0, 3.0, 2.0], ..law }; - assert!(matches!(fillet_variable_spline(&b, at, start, &big), Err(KernelError::TooLarge(_)))); + let wide = fillet_variable_spline(&b, at, start, &big).unwrap(); + let vw = fine_volume(&wide); + assert!(rel(vw, 6000.0 - 726.5334566720) < 1e-4, "{vw} vs {}", 6000.0 - 726.5334566720); } #[test] diff --git a/crates/kernel/src/heal.rs b/crates/kernel/src/heal.rs index 3b712c0c3..3fde7c24d 100644 --- a/crates/kernel/src/heal.rs +++ b/crates/kernel/src/heal.rs @@ -58,6 +58,6 @@ pub(crate) fn heal(body: &Body, keep: &[Vec]) -> Result { } } let tolerance = record.tolerance * 10.0; - let (healed, history) = crate::offset_backend::run("healing", body, |b| b.merge_faces(&kept, tolerance))?; + let (healed, history) = crate::offset_backend::run("healing", body, None, |b| b.merge_faces(&kept, tolerance))?; Ok(healed.with_checked_history(history, &crate::record::counts(&[body])).with_split_lines(body.splits.clone())) } diff --git a/crates/kernel/src/modify_history_tests.rs b/crates/kernel/src/modify_history_tests.rs index 4dc845d13..89f355277 100644 --- a/crates/kernel/src/modify_history_tests.rs +++ b/crates/kernel/src/modify_history_tests.rs @@ -552,6 +552,17 @@ mod smlib { verified(&r, &plate, reach(2.5 * 1.5)); } + /// A 40 x 40 x 10 plate with an r2 hole 3 from its side, shelled 1.5 open at the top: the + /// hole's offset just reaches the side's, so the walls would meet along a line. Refused, + /// saying so and with the wall, never as SMLib's bare status. + #[test] + fn a_shell_whose_walls_would_meet_is_refused_saying_so() { + let hole = Loop2::circle(Vec2::new(5.0, 20.0), 2.0); + let plate = extrude(&Plane::XY, &[Region2 { outer: square(0.0, 0.0, 40.0, 40.0), holes: vec![hole] }], 0.0, 10.0).unwrap().pop().unwrap(); + let e = offset_backend::shell(&plate, &[Vec3::new(35.0, 20.0, 10.0)], 1.5).unwrap_err().to_string(); + assert!(e.contains("the 1.5 mm walls would meet along a line"), "{e}"); + } + #[test] fn offset_moves_a_face() { let b = ell(); diff --git a/crates/kernel/src/offset_backend.rs b/crates/kernel/src/offset_backend.rs index 5c20eea9c..bf88f4ed2 100644 --- a/crates/kernel/src/offset_backend.rs +++ b/crates/kernel/src/offset_backend.rs @@ -26,10 +26,19 @@ fn failed(op: &str, what: &str, e: impl std::fmt::Display) -> KernelError { KernelError::Failed(format!("SMLib {op}: {what}: {e}")) } -/// The error for SMLib's refusal of `op`, in the words of the operation. -fn refused(op: &str, e: SmError) -> KernelError { +/// The error for SMLib's refusal of `op`, in the words of the operation; `wall` is its wall's +/// thickness, where it has one. +fn refused(op: &str, wall: Option, e: SmError) -> KernelError { match e { SmError::NoRoom => KernelError::Invalid(format!("{op}: the wall is too thick: it leaves no room inside the body")), + // The walls just meet: thinner they stay apart, thicker they cross and merge. + SmError::WallsTouch => { + let wall = wall.map(|t| format!(" {t} mm")).unwrap_or_default(); + KernelError::Invalid(format!( + "{op}: the{wall} walls would meet along a line (between a hole and the side, for example), which leaves no solid there; \ + use a thinner or thicker wall, or move the feature" + )) + } SmError::NoMatch { point } => KernelError::Invalid(format!("{op}: no face at selection point {}", point + 1)), SmError::Ambiguous { point } => KernelError::Invalid(format!("{op}: selection point {} is as near to two faces", point + 1)), SmError::Unsupported => KernelError::Failed(format!("not supported yet: SMLib {op} for this geometry")), @@ -48,12 +57,18 @@ fn points(p: &[Vec3]) -> Vec<[f64; 3]> { } /// Runs `op` on `b` in SMLib, tagged as operand 0, and brings the result back with SMLib's -/// history over `[b]` (none where an order cannot be matched). -pub(crate) fn run(name: &str, b: &Body, op: impl FnOnce(&Brep) -> std::result::Result) -> Result<(Body, Option)> { +/// history over `[b]` (none where an order cannot be matched). `wall`: the operation's wall +/// thickness, for its refusals. +pub(crate) fn run( + name: &str, + b: &Body, + wall: Option, + op: impl FnOnce(&Brep) -> std::result::Result, +) -> Result<(Body, Option)> { b.require_brep(name)?; let (sb, ob) = smlib_body_ordered(b)?; let tagged = sb.tagged(0).map_err(|e| failed(name, "tag", e))?; - let r = op(&tagged).map_err(|e| refused(name, e))?; + let r = op(&tagged).map_err(|e| refused(name, wall, e))?; let check = r.check(CheckLevel::All).map_err(|e| failed(name, "check", e))?; if !check.is_valid() { let input = sb.check(CheckLevel::All).is_ok_and(|c| !c.is_valid()); @@ -84,7 +99,7 @@ pub(crate) fn shell(b: &Body, open: &[Vec3], thickness: f64) -> Result { let opened = crate::offset::with_same_surface(b, &picked); let tol = pick_tolerance(b); let pts = points(&face_points(b, &opened)?); - let (r, h) = run("shell", b, |s| s.shell(&pts, tol, -thickness))?; + let (r, h) = run("shell", b, Some(thickness), |s| s.shell(&pts, tol, -thickness))?; let h = h.and_then(|h| with_offsets(&r, b, h, thickness)); Ok(r.with_checked_history(h, &record::counts(&[b]))) } @@ -96,7 +111,7 @@ pub(crate) fn offset_faces(b: &Body, chosen: &[usize], distance: f64) -> Result< let at = face_points(b, chosen)?; let tol = pick_tolerance(b); let pts = points(&at); - let (r, h) = run("offset faces", b, |s| s.offset_faces(&pts, tol, distance))?; + let (r, h) = run("offset faces", b, None, |s| s.offset_faces(&pts, tol, distance))?; let h = h.map(|mut h| { for f in &mut h.faces { if f.change == Change::Kept && f.origins.iter().any(|o| matches!(o, FaceOrigin::Face { face, .. } if chosen.contains(face))) { @@ -114,7 +129,7 @@ pub(crate) fn thicken(b: &Body, thickness: f64, symmetric: bool) -> Result if !(thickness.is_finite() && thickness.abs() > 1e-9) { return Err(KernelError::Invalid("thickness must be non-zero".into())); } - let (r, h) = run("thicken", b, |s| s.thicken(thickness, symmetric))?; + let (r, h) = run("thicken", b, Some(thickness.abs()), |s| s.thicken(thickness, symmetric))?; let step = if symmetric { thickness.abs() / 2.0 } else { thickness.abs() }; // The walls first, while the sheet's edges still carry their tags on both copies. let h = h.map(with_edge_walls).and_then(|h| with_offsets(&r, b, h, step)); @@ -138,7 +153,7 @@ pub(crate) fn draft(b: &Body, at: &[Vec3], neutral: &solidcraft_geom::Plane, pul let tol = pick_tolerance(b); let pts = points(&face_points(b, &chosen)?); let o = neutral.origin; - let (r, h) = run("draft", b, |s| s.draft(&pts, tol, [o.x, o.y, o.z], [normal.x, normal.y, normal.z], [pull.x, pull.y, pull.z], angle))?; + let (r, h) = run("draft", b, None, |s| s.draft(&pts, tol, [o.x, o.y, o.z], [normal.x, normal.y, normal.z], [pull.x, pull.y, pull.z], angle))?; let h = h.map(|mut h| { for f in &mut h.faces { if f.change == Change::Kept && f.origins.iter().any(|o| matches!(o, FaceOrigin::Face { face, .. } if chosen.contains(face))) { diff --git a/crates/kernel/src/tests.rs b/crates/kernel/src/tests.rs index 948bf5be5..356246efd 100644 --- a/crates/kernel/src/tests.rs +++ b/crates/kernel/src/tests.rs @@ -396,16 +396,19 @@ fn fillet_max_each_reduces_only_where_the_radius_does_not_fit() { .unwrap() .unwrap(); let edges = [Vec3::new(21.0, 15.0, 30.0), Vec3::new(40.0, 0.0, 10.0)]; - assert!(matches!(fillet(&body, &edges, 4.0), Err(KernelError::TooLarge(_)))); - let (one, _) = fillet_max(&body, &edges, 4.0).unwrap(); + // R4 on the fin's top edge runs over the fin's 2 mm top, past its far edge (a cliff): it is + // cut as if the top went on, so both edges take 4. The fin's section loses the 4 x 4 square + // at its edge less the quarter disc about (17, 26), inside the fin (x >= 19): 2 x 4 less the + // disc's part, in closed form; the corner's round (1 − π/4)·16 along 20. + let both = fillet(&body, &edges, 4.0).unwrap(); let (radii, b) = fillet_max_each(&body, &edges, 4.0).unwrap(); - assert_eq!(radii.get(1), Some(&4.0), "{radii:?}"); - let fin_r = radii.first().copied().unwrap(); - assert!(fin_r < 4.0 && (fin_r - one).abs() < 1e-9, "{radii:?}, one radius {one}"); + assert_eq!(radii, vec![4.0, 4.0], "{radii:?}"); assert!(b.validity().is_empty(), "{:?}", b.validity()); - // Each round takes (1 − π/4)·r² along its edge: the fin's 30 long, the corner's 20. - let removed = (1.0 - PI / 4.0) * (fin_r * fin_r * 30.0 + 16.0 * 20.0); - assert!(rel(measure(&b).unwrap().volume, block + fin - removed) < 2e-4); + let disc = |a: f64| 0.5 * (a * (16.0 - a * a).max(0.0).sqrt() + 16.0 * (a / 4.0).asin()); + let fin_section = 2.0 * 4.0 - (disc(4.0) - disc(2.0)); + let removed = fin_section * 30.0 + (1.0 - PI / 4.0) * 16.0 * 20.0; + assert!(rel(measure(&both).unwrap().volume, block + fin - removed) < 1e-6, "{}", measure(&both).unwrap().volume); + assert!(rel(measure(&b).unwrap().volume, block + fin - removed) < 1e-6); // The post's four edges limit each other: one radius, as `fillet_max`. let post = box_solid(Vec3::new(14.0, 0.0, 0.0), Vec3::new(28.0, 6.0, 10.0)).unwrap(); let mids = [Vec3::new(14.0, 0.0, 5.0), Vec3::new(28.0, 0.0, 5.0), Vec3::new(14.0, 6.0, 5.0), Vec3::new(28.0, 6.0, 5.0)]; diff --git a/crates/smlib/src/ffi/ops.rs b/crates/smlib/src/ffi/ops.rs index 47c055c6b..1e09aabe8 100644 --- a/crates/smlib/src/ffi/ops.rs +++ b/crates/smlib/src/ffi/ops.rs @@ -19,6 +19,7 @@ pub const ERR_NO_ROOM: i32 = -1103; pub const ERR_NO_CUT: i32 = -1104; pub const ERR_UNSUPPORTED: i32 = -1105; pub const ERR_NO_EFFECT: i32 = -1107; +pub const ERR_WALLS_TOUCH: i32 = -1110; pub const BOOLEAN_UNION: i32 = 0; pub const BOOLEAN_SUBTRACT: i32 = 1; diff --git a/crates/smlib/src/lib.rs b/crates/smlib/src/lib.rs index e36f63c94..557bb7cce 100644 --- a/crates/smlib/src/lib.rs +++ b/crates/smlib/src/lib.rs @@ -52,6 +52,10 @@ pub enum Error { /// No room for the operation: an inward offset (a shell's wall, faces moved in) leaves none /// inside the body, or a blend is larger than the faces it rolls on allow. NoRoom, + /// An offset whose walls would meet (a shell's): the offsets of two faces touch without + /// crossing, a hole's wall offset just reaching a side's, so the result would pinch to + /// nothing along a line. A thinner or a thicker wall builds. + WallsTouch, /// SMLib cannot build this exactly yet (a variable radius whose law has a corner). Unsupported, /// SMLib reported success but the operation did nothing: a blend that made no face, a face @@ -83,6 +87,7 @@ impl std::fmt::Display for Error { Error::NoMatch { point } => write!(f, "selection point {} is not near any edge or face", point + 1), Error::Ambiguous { point } => write!(f, "selection point {} is equally near to two edges or faces", point + 1), Error::NoRoom => write!(f, "there is no room for it: an offset leaves none inside the body, or a blend is larger than its faces allow"), + Error::WallsTouch => write!(f, "the offset's walls would meet along a line, which leaves no solid there"), Error::Unsupported => write!(f, "not supported yet: SMLib cannot build this exactly"), Error::NoEffect => write!(f, "SMLib made no change: it reported success, but the operation did nothing"), Error::NotExact => write!(f, "SMLib cannot build this exactly in the input's geometry"), @@ -114,6 +119,7 @@ fn error(s: i32) -> Error { ffi::ERR_EMPTY => Error::Empty, ffi::ops::ERR_NOT_SOLID => Error::NotSolid, ffi::ops::ERR_NO_ROOM => Error::NoRoom, + ffi::ops::ERR_WALLS_TOUCH => Error::WallsTouch, ffi::ops::ERR_UNSUPPORTED => Error::Unsupported, ffi::ops::ERR_NO_EFFECT => Error::NoEffect, ffi::trim::ERR_NOT_EXACT => Error::NotExact, diff --git a/crates/smlib/src/ops.rs b/crates/smlib/src/ops.rs index b0debecd9..f273409ac 100644 --- a/crates/smlib/src/ops.rs +++ b/crates/smlib/src/ops.rs @@ -182,7 +182,9 @@ impl Brep { /// Hollowed to a wall of `thickness` (negative: inside the original surface, positive: /// outside), open at the faces nearest to `open_faces` (each within `tolerance`); none gives - /// a closed hollow body. An inward wall that leaves no room inside is [`Error::NoRoom`]. + /// a closed hollow body. An inward wall that leaves no room inside is [`Error::NoRoom`]; one + /// whose walls would just meet (a hole exactly twice the wall from a side) is + /// [`Error::WallsTouch`]. pub fn shell(&self, open_faces: &[[f64; 3]], tolerance: f64, thickness: f64) -> Result { self.pick_op(ffi::ops::Pick::Shell, open_faces, tolerance, thickness, true) } diff --git a/crates/smlib/src/ops_tests.rs b/crates/smlib/src/ops_tests.rs index c29a63850..cad5ca805 100644 --- a/crates/smlib/src/ops_tests.rs +++ b/crates/smlib/src/ops_tests.rs @@ -207,12 +207,15 @@ fn hostile_inputs_are_errors() { assert_eq!(c.shell(&[[10.0, 10.0, 20.0]], 0.1, t).unwrap_err(), Error::Argument, "thickness {t}"); } // Sizes SMLib cannot build fail as errors, whatever SMLib says. - for (what, r) in [("radius larger than the cube", c.fillet(&mid, 0.1, 50.0)), ("chamfer past the faces", c.chamfer(&mid, 0.1, 30.0))] { - match r { - Ok(b) => panic!("{what}: SMLib built a body of volume {:?}, counts {:?}", b.volume(ACC), b.counts()), - Err(e) => eprintln!("{what}: {e:?}"), - } + match c.fillet(&mid, 0.1, 50.0) { + Ok(b) => panic!("radius larger than the cube: SMLib built a body of volume {:?}, counts {:?}", b.volume(ACC), b.counts()), + Err(e) => eprintln!("radius larger than the cube: {e:?}"), } + // A chamfer past the faces runs over their far edges, cliffs: it is cut as if the faces went + // on (the plane y + z = 10 through the setbacks 30 back from the edge y = z = 20), leaving the + // triangle y + z <= 10 of the cube's section along x: 50 x 20. + let past = c.chamfer(&mid, 0.1, 30.0).unwrap(); + assert!((volume(&past) - 1000.0).abs() < 1e-6 * 1000.0, "{}", volume(&past)); // A wall with no room inside it never reaches SMLib's offset. assert_eq!(c.shell(&[[10.0, 10.0, 20.0]], 0.1, -15.0).unwrap_err(), Error::NoRoom); assert_eq!(c.offset_faces(&[[10.0, 10.0, 20.0]], 0.1, -20.0).unwrap_err(), Error::NoRoom); @@ -220,6 +223,24 @@ fn hostile_inputs_are_errors() { assert_untouched(&c, 8000.0, [6, 12, 8]); } +/// Rig case shell/4711: a 60 x 40 x 10 block with an r3 through hole at (22.5, 7), 4 from the +/// front face, and a 10 x 10 notch on that edge, shelled 2 inward open at the bottom: the hole's +/// offset (r5) is tangent to the front's (y = 2), so the walls meet along a line and the offset +/// bounds no solid there. Refused as such; 1.5 (the walls apart) and 2.5 (crossing, merged) +/// build. +#[test] +fn a_shell_whose_walls_would_meet_is_refused_as_such() { + let block = Brep::make_box([0.0; 3], [60.0, 40.0, 10.0]).unwrap(); + let pin = Brep::make_cylinder([22.5, 7.0, -5.0], 3.0, 20.0).unwrap(); + let notch = Brep::make_box([25.0, -5.0, -5.0], [10.0, 10.0, 20.0]).unwrap(); + let part = block.boolean(&pin, BooleanOp::Subtract).unwrap().unwrap().boolean(¬ch, BooleanOp::Subtract).unwrap().unwrap(); + let bottom = [[50.0, 30.0, 0.0]]; + assert_eq!(part.shell(&bottom, 0.1, -2.0).unwrap_err(), Error::WallsTouch); + for t in [1.5, 2.5] { + shot(&part.shell(&bottom, 0.1, -t).unwrap(), &format!("shell-4711-{t}")); + } +} + #[test] fn boolean_history_through_tagged_operands() { // A slot across the top of the cube: the cube's 6 faces give 7 result faces (the top is cut diff --git a/tests/kernel-cases/fillets/1080-chamfer-runs-into-openings-refused/expected.json b/tests/kernel-cases/fillets/1080-chamfer-runs-into-openings-refused/expected.json index a3a100c22..20456ae04 100644 --- a/tests/kernel-cases/fillets/1080-chamfer-runs-into-openings-refused/expected.json +++ b/tests/kernel-cases/fillets/1080-chamfer-runs-into-openings-refused/expected.json @@ -3,8 +3,9 @@ "tangency-labs/solidcraft#1080", "tangency-labs/solidcraft#1124" ], - "what": "a 9 mm chamfer on the top front edge of a cube with square openings 5 mm in must be refused: it would cut through the rims of the openings", - "source": "invariants", - "method": "cube 20 with three orthogonal 10x10 through openings; the top face opening starts 5 mm from the front edge and the front opening 5 mm below the top edge, so a 9 mm setback runs past the face between the edge and the openings and the chamfer plane would cross the openings and leave slivers. The right answer is a clean refusal; nothing is built.", - "outcome": "refused" -} \ No newline at end of file + "what": "a 9 mm chamfer on the top front edge of a cube with square openings 5 mm in runs past the 5 mm between the edge and the openings: built as if the faces went on over the openings, then cut by them (cliff overflow); it never bridges an opening", + "source": "analytic", + "method": "cube 20 less three orthogonal 10x10 through openings (cross): V0 = 4000. The chamfer plane takes, of the section, the triangle y + (20 - z) <= 9 (y >= 0, z <= 20), area 40.5, along x: 810; less its parts inside the openings: the x opening (y, z in [5, 15]) misses it (z >= 11 + y >= 16 there), the y opening (z in [5, 15], x in [5, 15]) holds y in [0, 4], z in [11 + y, 15]: area 8, times 10 = 80, the z opening (y in [5, 15], x in [5, 15]) holds y in [5, 9], z in [11 + y, 20]: area 8, times 10 = 80. V = 4000 - (810 - 160) = 3350.", + "body_count": 1, + "volume_mm3": 3350.0 +} diff --git a/tests/kernel-cases/shell/4711-shell-block-with-hole-clipped-by-notch/expected.json b/tests/kernel-cases/shell/4711-shell-block-with-hole-clipped-by-notch/expected.json index b24bdcebb..7fd02ee41 100644 --- a/tests/kernel-cases/shell/4711-shell-block-with-hole-clipped-by-notch/expected.json +++ b/tests/kernel-cases/shell/4711-shell-block-with-hole-clipped-by-notch/expected.json @@ -2,9 +2,9 @@ "sources": [ "tangency-labs/solidcraft#4711" ], - "what": "a 2 mm shell, open at the bottom, of a 60x40x10 block whose r3 through hole breaks out into a 10x10 notch at its edge: truck took 75 s and failed ('boolean Cut: no result')", + "what": "a 2 mm shell, open at the bottom, of a 60x40x10 block with an r3 through hole 4 mm from its front face, beside a 10x10 notch at that edge: the walls from the hole and from the front would meet along a line, so the right answer is a refusal that says so (truck took 75 s and failed ('boolean Cut: no result'); SMLib refused it, but as 'status 1027')", "source": "invariants", - "method": "every wall has room for 2 mm (the thinnest, between the hole and the block's side, is 4 mm), so the shell exists: one valid closed body with one shell, open at the bottom. The cavity's corners at the hole's break-out follow the offset surfaces, so the volume is not closed-form (the reporter's script)", - "body_count": 1, - "shells": 1 + "method": "the hole (centre (22.5, 7), r3) is 7 - 3 = 4 mm from the front face y = 0, and two 2 mm walls take 4 = 2 x 2 mm: the hole wall's offset (r 3 + 2 = 5) is tangent to the front's (y = 2) at (22.5, 2), so the cavity pinches to zero thickness along the line x = 22.5, y = 2, which bounds no solid. A thinner wall leaves the walls apart, a thicker one makes them cross and merge; at exactly 2 mm the shell is refused, naming the cause. Expected message: \"shell: the 2 mm walls would meet along a line (between a hole and the side, for example), which leaves no solid there; use a thinner or thicker wall, or move the feature\".", + "outcome": "refused", + "refusal": "shell: the 2 mm walls would meet along a line (between a hole and the side, for example), which leaves no solid there; use a thinner or thicker wall, or move the feature" }