Skip to content

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

Fix shelling revolved barrels (#2421) (#2486)

fkirill42e991069f2d
diff --git a/ROADMAP.md b/ROADMAP.md
index b4fc0c9c02..c0739fc142 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -459,10 +459,11 @@ completed drawings publish atomically. The browser still exports synchronously.
and author occurrence paths retain the chosen placements; missing/split faces refuse rather
than retarget. General free-form profiles, seams, stepped cylinders and other curved surfaces
remain unsupported. STEP round-trip and independent radial/volume checks cover this subset.
-- Shell and offset faces work on bodies of planes, cylinders, cones and spheres (convex or not:
+- Shell and offset faces work on bodies of planes, cylinders, cones, spheres and tori (convex or not:
filleted boxes, bosses, domes, countersinks; corners where four or more planes meet, such as a
floor falling to a drain, as long as the corner's edges are all convex or all concave); draft on convex planar bodies and on walls (planes, cylinders → cones) between caps; lofts through three or more sections are smooth (B-spline sides through every section), two
- sections ruled.
+ sections ruled. Circular-meridian barrels retain curved inner walls through either axial
+ opening (#2421).
- Sketch corner tools: fillet and all three chamfer modes pick a connected corner even when
its endpoint overlaps the fixed origin or a loose point. Ordinary drawing still snaps to
diff --git a/crates/kernel/src/offset.rs b/crates/kernel/src/offset.rs
index 7dd0c24907..b5ef68c799 100644
--- a/crates/kernel/src/offset.rs
+++ b/crates/kernel/src/offset.rs
@@ -28,8 +28,9 @@ pub(crate) enum Surf {
/// outward normal points away from the axis.
Cone { v: Vec3, a: Vec3, half: f64, convex: bool },
/// Axis point and unit axis, the tube's centre circle (radius `big` at height `h` along the
- /// axis) and the tube radius; `convex` when the outward normal points away from the tube's
- /// centre.
+ /// axis) and the tube radius; `big` is negative on the inner sheet of a spindle torus,
+ /// whose meridian circle's centre lies across the axis. `convex` when the outward normal
+ /// points away from the tube's centre.
Torus { o: Vec3, a: Vec3, big: f64, h: f64, r: f64, convex: bool },
}
@@ -292,9 +293,10 @@ fn torus_of(f: &mt::Face, s: &[(Vec3, Vec3)], tol: f64) -> Option<Surf> {
}
let x = crate::polyhedron::solve3_pub(m, rhs)?;
let (big, h, r) = (x[0], x[1], x[2]);
- // (A tube wider than its circle, a spindle torus, is fine: blends use its outer part, where
- // each point's tube centre is the one on its own side of the axis.)
- if !(big > 1e-9 && r.abs() > 1e-9) {
+ // A spindle torus also has an inner sheet: a barrel revolved from an arc whose
+ // centre is across the axis. Its signed ring radius is negative; retain that sign
+ // so distances, normals and the moved meridian use the centre on the opposite side.
+ if !(big.abs() > 1e-9 && r.abs() > 1e-9) {
return None;
}
let t = Surf::Torus { o, a, big, h, r: r.abs(), convex: r > 0.0 };
diff --git a/crates/kernel/src/polyhedron.rs b/crates/kernel/src/polyhedron.rs
index 35e20477a7..94c52b1530 100644
--- a/crates/kernel/src/polyhedron.rs
+++ b/crates/kernel/src/polyhedron.rs
@@ -9,7 +9,7 @@ use solidcraft_geom::{Plane, Vec3};
use truck_modeling::{self as mt, builder};
use crate::body::{Body, Solid, from_p3, p3, v3};
-use crate::history::{EdgeOrigin, FaceOrigin, FaceProv, History};
+use crate::history::{Change, EdgeOrigin, FaceOrigin, FaceProv, History};
use crate::record;
use crate::{KernelError, Result, guard};
@@ -490,6 +490,9 @@ fn shell_planar(b: &Body, open: &[Vec3], thickness: f64) -> Result<Body> {
"the rim would have no thickness: an open face meets a round of radius {r:.4} mm tangentially, and the shell is {thickness:.4} mm thick (make the round smaller than the thickness)"
)));
}
+ if let Some(shell) = shell_barrel(&healed, &opened, thickness)? {
+ return Ok(record::after(shell, &healed, &record::counts(&[b])));
+ }
let margin = thickness + size * 0.05;
shell_opened(b, &healed, open, &opened, thickness, margin).map_err(|e| match rim_without_thickness(&healed, &opened, thickness, false) {
Some(r) => unsupported_shell(&format!(
@@ -499,6 +502,83 @@ fn shell_planar(b: &Body, open: &[Vec3], thickness: f64) -> Result<Body> {
})
}
+/// A convex circular-meridian barrel between two axial caps. Sew its exact inset walls
+/// to the original walls at annular rims: a Boolean of the two spindle sheets cannot
+/// reliably find their cap intersections, and sweeping an inset cap makes a cylindrical
+/// lip that cuts away part of the curved wall.
+fn shell_barrel(b: &Body, opened: &[usize], thickness: f64) -> Result<Option<Body>> {
+ use crate::offset::Surf;
+ if b.solid.boundaries().len() != 1 || b.face_count() > 256 {
+ return Ok(None);
+ }
+ let faces: Vec<mt::Face> = b.solid.face_iter().cloned().collect();
+ let tol = (b.size() * 1e-7).max(1e-9) * 100.0;
+ let surfs: Option<Vec<Surf>> = faces.iter().map(|f| crate::offset::surf_of(f, tol)).collect();
+ let Some(surfs) = surfs else { return Ok(None) };
+ let Some((centre, axis, big, radius)) = surfs.iter().find_map(|s| match *s {
+ Surf::Torus { o, a, big, h, r, convex: true } if big < -tol => Some((o + a * h, a, big, r)),
+ _ => None,
+ }) else {
+ return Ok(None);
+ };
+ let mut caps = Vec::new();
+ for (i, s) in surfs.iter().enumerate() {
+ match *s {
+ Surf::Torus { o, a, big: ring, h, r, convex: true }
+ if (o + a * h).dist(centre) < tol && a.dot(axis).abs() > 1.0 - 1e-9 && (ring - big).abs() < tol && (r - radius).abs() < tol => {}
+ Surf::Plane { n, d } if n.dot(axis).abs() > 1.0 - 1e-9 && faces.get(i).is_some_and(|f| f.boundaries().len() == 1) => {
+ caps.push((i, (d - n.dot(centre)) / n.dot(axis), n.dot(axis)));
+ }
+ _ => return Ok(None),
+ }
+ }
+ if caps.len() != 2 || opened.iter().any(|i| !caps.iter().any(|c| c.0 == *i)) {
+ return Ok(None);
+ }
+ caps.sort_by(|a, b| a.1.total_cmp(&b.1));
+ let (Some(&(lower, lo, down)), Some(&(upper, hi, up))) = (caps.first(), caps.get(1)) else { return Ok(None) };
+ if down >= 0.0 || up <= 0.0 {
+ return Ok(None);
+ }
+ let lo = lo + if opened.contains(&lower) { 0.0 } else { thickness };
+ let hi = hi - if opened.contains(&upper) { 0.0 } else { thickness };
+ let inner_radius = radius - thickness;
+ if lo >= hi || inner_radius <= 0.0 || [lo, hi].iter().any(|z| inner_radius * inner_radius - z * z <= big * big) {
+ return Err(KernelError::Invalid("shell thickness leaves no barrel cavity".into()));
+ }
+ let cavity = offset_planar(b, |i, _| if opened.contains(&i) { 0.0 } else { -thickness })?;
+ let history = cavity.history().ok_or_else(|| unsupported_shell("the barrel cavity has no face history"))?;
+ // Every wall must still be the one offset of its source, in source order. No collapsed
+ // faces or changed topology can be sewn by this construction.
+ if cavity.face_count() != faces.len()
+ || history.faces.iter().enumerate().any(|(i, f)| f.origins.as_slice() != [FaceOrigin::Face { operand: 0, face: i }])
+ {
+ return Err(unsupported_shell("the barrel cavity changed topology"));
+ }
+ let inner: Vec<mt::Face> = cavity.solid.face_iter().cloned().collect();
+ let mut out = Vec::new();
+ let mut provenance = Vec::new();
+ for (i, outer) in faces.iter().enumerate() {
+ let inset = inner.get(i).ok_or_else(|| unsupported_shell("the barrel cavity lost a face"))?;
+ if opened.contains(&i) {
+ let mut wires = outer.absolute_boundaries().to_vec();
+ wires.extend(inset.absolute_boundaries().iter().map(|w| w.inverse()));
+ let mut rim = mt::Face::try_new(wires, outer.surface()).map_err(|e| KernelError::Failed(format!("shell rim: {e}")))?;
+ if !outer.orientation() {
+ rim.invert();
+ }
+ out.push(rim);
+ provenance.push(record::from_face(0, i, Change::Modified));
+ } else {
+ out.extend([outer.clone(), inset.inverse()]);
+ provenance.extend([record::from_face(0, i, Change::Kept), record::generated(vec![FaceOrigin::Offset { operand: 0, face: i }])]);
+ }
+ }
+ let solid = Solid::try_new(vec![out.into()]).map_err(|e| KernelError::Failed(format!("shell barrel: {e}")))?;
+ let copies = record::edges_by_identity(&cavity, history).filter_map(|(id, origins)| origins.into_iter().next().map(|o| (id, o))).collect();
+ record::attach(Body::new(solid)?, &[record::Operand::new(b)], Some(provenance), copies).map(Some)
+}
+
/// The radius of a convex round (cylinder or torus) that meets an open face tangentially and
/// is at least `thickness`: the cavity's wall then passes through the rim where the round meets
/// the open face, leaving nothing between them.
diff --git a/crates/kernel/src/surface_kind.rs b/crates/kernel/src/surface_kind.rs
index ee72bf1cda..c601536a3a 100644
--- a/crates/kernel/src/surface_kind.rs
+++ b/crates/kernel/src/surface_kind.rs
@@ -33,6 +33,8 @@ pub enum FaceSurface {
radius: f64,
},
/// Centre of the ring, its axis, the ring (major) and tube (minor) radii.
+ /// `major` is signed: negative on a spindle torus's inner sheet, whose tube centre
+ /// lies across the axis from the face (a revolved barrel).
Torus {
center: Vec3,
axis: UnitVec3,
diff --git a/crates/kernel/tests/shell_barrel.rs b/crates/kernel/tests/shell_barrel.rs
new file mode 100644
index 0000000000..718d626f3c
--- /dev/null
+++ b/crates/kernel/tests/shell_barrel.rs
@@ -0,0 +1,92 @@
+//! #2421: shelling a circular-meridian barrel must retain its curved wall through the rim.
+
+use std::f64::consts::PI;
+
+use solidcraft_geom::{Loop2, Plane, Region2, Seg2, Vec2, Vec3};
+use solidcraft_kernel::history::FaceOrigin;
+use solidcraft_kernel::*;
+
+const RADIUS: f64 = 24.0;
+const CENTRE: f64 = -10.0;
+const HALF_HEIGHT: f64 = 13.4;
+
+fn barrel() -> Body {
+ let angle = (HALF_HEIGHT / RADIUS).asin();
+ let end_radius = CENTRE + RADIUS * angle.cos();
+ let region = Region2 {
+ outer: Loop2 {
+ segs: vec![
+ Seg2::Line { a: Vec2::ZERO, b: Vec2::new(end_radius, 0.0) },
+ Seg2::Arc { center: Vec2::new(CENTRE, HALF_HEIGHT), radius: RADIUS, start: -angle, sweep: 2.0 * angle },
+ Seg2::Line { a: Vec2::new(end_radius, 2.0 * HALF_HEIGHT), b: Vec2::new(0.0, 2.0 * HALF_HEIGHT) },
+ Seg2::Line { a: Vec2::new(0.0, 2.0 * HALF_HEIGHT), b: Vec2::ZERO },
+ ],
+ },
+ holes: vec![],
+ };
+ let plane = Plane::new(Vec3::ZERO, Vec3::X, Vec3::Z).unwrap();
+ revolve(&plane, &[region], Vec2::ZERO, Vec2::Y, 2.0 * PI).unwrap().pop().unwrap()
+}
+
+// Integral of pi * (CENTRE + sqrt(r^2 - (z-HALF_HEIGHT)^2))^2.
+fn integral(r: f64, z: f64) -> f64 {
+ let u = z - HALF_HEIGHT;
+ PI * ((CENTRE * CENTRE + r * r) * u - u.powi(3) / 3.0 + CENTRE * (u * (r * r - u * u).sqrt() + r * r * (u / r).asin()))
+}
+
+fn check_volume(body: &Body, lo: f64, hi: f64) {
+ let want = integral(RADIUS, 2.0 * HALF_HEIGHT) - integral(RADIUS, 0.0) - (integral(RADIUS - 2.0, hi) - integral(RADIUS - 2.0, lo));
+ let volume = measure(body).unwrap().volume;
+ assert!((volume - want).abs() < want * 1e-3, "{volume} vs {want}");
+}
+
+#[test]
+fn shell_of_a_revolved_barrel() {
+ let barrel = barrel();
+ let side = (0..barrel.face_count())
+ .find_map(|i| match face_surface(&barrel, i) {
+ Some(s @ FaceSurface::Torus { major, minor, .. }) if (major - CENTRE).abs() < 1e-6 && (minor - RADIUS).abs() < 1e-6 => Some(s),
+ _ => None,
+ })
+ .expect("barrel side is the inner sheet of a spindle torus");
+ assert!(side.nearest(Vec3::new(15.0, 0.0, HALF_HEIGHT)).unwrap().dist(Vec3::new(14.0, 0.0, HALF_HEIGHT)) < 1e-6);
+ let result = shell(&barrel, &[Vec3::new(0.0, 0.0, 2.0 * HALF_HEIGHT)], 2.0).unwrap();
+ assert!(result.validity().is_empty(), "{:?}", result.validity());
+ assert_eq!(result.shell_count(), 1);
+ let mesh = result.tessellate(0.005).unwrap();
+ assert!(mesh.contains(Vec3::new(0.0, 0.0, 1.0)), "closed floor");
+ assert!(!mesh.contains(Vec3::new(0.0, 0.0, 3.0)), "open cavity");
+ assert!(mesh.contains(Vec3::new(13.0, 0.0, HALF_HEIGHT)), "barrel wall");
+ assert!(!mesh.contains(Vec3::new(11.0, 0.0, HALF_HEIGHT)), "inside wall");
+ assert!(mesh.contains(Vec3::new(8.0, 0.0, 26.7)), "curved wall reaches the rim without a cylindrical lip cutting it away");
+ check_volume(&result, 2.0, 2.0 * HALF_HEIGHT);
+ let history = result.history().expect("exact shell face history");
+ assert_eq!(history.operands, 1);
+ assert_eq!(history.faces.iter().filter(|f| matches!(f.origins.as_slice(), [FaceOrigin::Offset { operand: 0, .. }])).count(), 4);
+ let step = step_export(&[&result], "barrel shell").unwrap();
+ let imported = step_import(&step).unwrap();
+ assert_eq!(imported.bodies.len(), 1);
+ let round_trip = &imported.bodies.first().unwrap().body;
+ assert!(round_trip.validity().is_empty());
+ check_volume(round_trip, 2.0, 2.0 * HALF_HEIGHT);
+}
+
+#[test]
+fn barrel_shell_opens_either_or_both_caps_and_refuses_a_vanished_cavity() {
+ let barrel = barrel();
+ for both in [false, true] {
+ let mut opened = vec![Vec3::ZERO];
+ if both {
+ opened.push(Vec3::new(0.0, 0.0, 2.0 * HALF_HEIGHT));
+ }
+ let result = shell(&barrel, &opened, 2.0).unwrap();
+ assert!(result.validity().is_empty());
+ let mesh = result.tessellate(0.005).unwrap();
+ assert!(!mesh.contains(Vec3::new(0.0, 0.0, 1.0)));
+ assert_eq!(mesh.contains(Vec3::new(0.0, 0.0, 25.8)), !both);
+ check_volume(&result, 0.0, 2.0 * HALF_HEIGHT - if both { 0.0 } else { 2.0 });
+ }
+ for thickness in [11.0, 24.0] {
+ assert!(shell(&barrel, &[Vec3::ZERO], thickness).is_err());
+ }
+}