Skip to main content

08_shell/
08_shell.rs

1//! Demo of `Solid::shell`:
2//! - Cube: remove top face, offset inward → open-top container
3//! - Sealed cube: empty open_faces → solid with an internal void (outer skin
4//!   + reversed inner shell)
5//! - Torus: bisect with a half-space to introduce planar cut faces, then
6//!   shell using those cut faces as the openings → thin-walled half-ring
7//!   with both cross-sections exposed
8
9use cadrum::{DVec3, Error, Solid};
10
11fn hollow_cube() -> Result<Solid, Error> {
12	let cube = Solid::cube(8.0, 8.0, 8.0);
13	// TopExp_Explorer order on a box is stable; +Z face ends up last.
14	let top = cube.iter_face().last().expect("cube has faces");
15	cube.shell(-1.0, [top])
16}
17
18fn sealed_cube() -> Result<Solid, Error> {
19	let cube = Solid::cube(8.0, 8.0, 8.0);
20	cube.shell(-1.0, std::iter::empty::<&cadrum::Face>())
21}
22
23fn halved_shelled_torus(thickness: f64) -> Result<Solid, Error> {
24	let torus = Solid::torus(6.0, 2.0, DVec3::Y);
25	// Bisect with Y=0 half-space (normal +Y): keep the +Y half of the ring — always 1 solid.
26	let cutter = Solid::half_space(DVec3::ZERO, -DVec3::Z);
27	// `iter_history()` yields [post_id, src_id] pairs for every result face.
28	// Filter to those whose src_id is one of the cutter's faces, then collect
29	// their post_ids — these are the planar cut faces in the result that we
30	// want to use as shell openings.
31	let cutter_face_ids: std::collections::HashSet<u64> =
32		cutter.iter_face().map(|f| f.id()).collect();
33	let halves = torus.intersect(&[cutter])?;
34	let half = halves.into_iter().next().ok_or(Error::BooleanOperationFailed)?;
35	let from_cutter: std::collections::HashSet<u64> = half
36		.iter_history()
37		.filter_map(|[post, src]| cutter_face_ids.contains(&src).then_some(post))
38		.collect();
39	half.shell(thickness, half.iter_face().filter(|f| from_cutter.contains(&f.id())))
40}
41
42fn main() -> Result<(), Error> {
43	let example_name = std::path::Path::new(file!()).file_stem().unwrap().to_str().unwrap();
44
45	let result = [
46		hollow_cube()?.color("#d0a878"),
47		sealed_cube()?.color("#6fbf73").translate(DVec3::Y * 10.0),
48		halved_shelled_torus(1.0)?.color("#ff5e00").translate(DVec3::X * 18.0),
49		halved_shelled_torus(-1.0)?.color("#0052ff").translate(DVec3::X * 18.0 + DVec3::Y * 10.0),
50	];
51
52	let mut f = std::fs::File::create(format!("{example_name}.step")).expect("failed to create STEP file");
53	cadrum::write_step(&result, &mut f).expect("failed to write STEP");
54
55	// Isometric view from (1, 1, 2) with shading so the cavity depth reads
56	// naturally.
57	let mut f = std::fs::File::create(format!("{example_name}.svg")).expect("failed to create SVG file");
58	cadrum::mesh(&result, 0.2).and_then(|m| m.write_svg(DVec3::new(1.0, 1.0, 2.0), DVec3::Z, true, true, &mut f)).expect("failed to write SVG");
59
60	println!("wrote {example_name}.step / {example_name}.svg");
61	Ok(())
62}