mod automation;
mod cuboct;
mod frame;
mod infill;
mod mesher;
mod region;
mod strut;
mod tpms;
mod voxel;
pub use automation::{CuboctAssemblyPlan, CuboctAssemblyStep};
pub use cuboct::{ChiralRule, Cuboct, Hand};
pub use frame::{CuboctFrame, FrameMaterial, FrameResponse};
pub use infill::Infill;
pub use region::Region;
pub use strut::{Segment, Strut};
pub use tpms::Tpms;
pub use voxel::{CuboctAssembly, CuboctJoint, CuboctJointKind};
use crate::core::BufferGeometry;
use crate::math::{Box3, Vector3};
use mesher::IsoGrid;
use std::f32::consts::TAU;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LatticeKind {
Tpms(Tpms),
Strut(Strut),
Infill(Infill),
Cuboct(Cuboct),
}
impl LatticeKind {
pub fn all() -> Vec<LatticeKind> {
Tpms::ALL
.into_iter()
.map(LatticeKind::Tpms)
.chain(Strut::ALL.into_iter().map(LatticeKind::Strut))
.chain(Infill::ALL.into_iter().map(LatticeKind::Infill))
.chain(Cuboct::ALL.into_iter().map(LatticeKind::Cuboct))
.collect()
}
pub fn name(self) -> &'static str {
match self {
LatticeKind::Tpms(t) => t.name(),
LatticeKind::Strut(s) => s.name(),
LatticeKind::Infill(i) => i.name(),
LatticeKind::Cuboct(c) => c.name(),
}
}
pub fn from_name(name: &str) -> Option<LatticeKind> {
Tpms::from_name(name)
.map(LatticeKind::Tpms)
.or_else(|| Strut::from_name(name).map(LatticeKind::Strut))
.or_else(|| Infill::from_name(name).map(LatticeKind::Infill))
.or_else(|| Cuboct::from_name(name).map(LatticeKind::Cuboct))
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum LatticeStyle {
#[default]
Sheet,
Solid,
}
const PADDING: usize = 6;
const MIN_DIM: usize = PADDING;
#[derive(Clone, Copy, Debug)]
enum Spacing {
Size(Vector3),
Count([usize; 3]),
}
pub struct Lattice<'a> {
kind: LatticeKind,
style: LatticeStyle,
bounds: Box3,
spacing: Spacing,
thickness: f32,
resolution: usize,
max_samples: usize,
skin: f32,
pinned_bounds: bool,
grade: Option<Box<dyn Fn(Vector3) -> f32 + Sync + Send + 'a>>,
trim: Option<Box<dyn Fn(Vector3) -> f32 + Sync + Send + 'a>>,
clip: Option<Box<dyn Fn(Vector3) -> f32 + Sync + Send + 'a>>,
shape: f32,
program: Option<crate::geometries::lattice::voxel::CuboctProgram<'a>>,
chiral_rule: Option<ChiralRule>,
}
impl<'a> Lattice<'a> {
pub fn new(kind: LatticeKind) -> Self {
Self {
kind,
style: LatticeStyle::default(),
bounds: Box3::from_center_and_size(Vector3::ZERO, Vector3::new(1.0, 1.0, 1.0)),
spacing: Spacing::Count([4, 4, 4]),
thickness: 0.05,
resolution: 16,
max_samples: 8_000_000,
skin: 0.0,
pinned_bounds: false,
grade: None,
trim: None,
clip: None,
shape: 0.15,
program: None,
chiral_rule: None,
}
}
pub fn bounds(mut self, bounds: Box3) -> Self {
self.bounds = bounds;
self.pinned_bounds = true;
self
}
pub fn size(mut self, size: Vector3) -> Self {
self.bounds = Box3::from_center_and_size(Vector3::ZERO, size);
self.pinned_bounds = true;
self
}
pub fn fill(mut self, region: Region<'a>) -> Self {
let bounds = region.bounds();
if !self.pinned_bounds && !bounds.is_empty() {
self.bounds = bounds;
}
self.trim = Some(region.into_field());
self
}
pub fn skin(mut self, thickness: f32) -> Self {
self.skin = thickness.max(0.0);
self
}
pub fn cell_size(mut self, cell: Vector3) -> Self {
self.spacing = Spacing::Size(cell);
self
}
pub fn cells(mut self, cells: [usize; 3]) -> Self {
self.spacing = Spacing::Count(cells);
self
}
pub fn shape(mut self, shape: f32) -> Self {
self.shape = shape.max(0.0);
self
}
pub fn program(mut self, program: impl Fn(i32, i32, i32) -> Cuboct + Sync + Send + 'a) -> Self {
self.program = Some(Box::new(program));
self
}
pub fn chiral_rule(mut self, rule: ChiralRule) -> Self {
self.chiral_rule = Some(rule);
self
}
pub fn thickness(mut self, thickness: f32) -> Self {
self.thickness = thickness;
self
}
pub fn style(mut self, style: LatticeStyle) -> Self {
self.style = style;
self
}
pub fn resolution(mut self, samples_per_cell: usize) -> Self {
self.resolution = samples_per_cell.max(2);
self
}
pub fn max_samples(mut self, max_samples: usize) -> Self {
self.max_samples = max_samples.max(64);
self
}
pub fn sample_grid(&self) -> [usize; 3] {
self.grid().0 .0
}
pub fn wall_samples(&self) -> f32 {
match self.wall_width() {
Some(width) => {
let step = self.grid().0 .2;
width / step.x.max(step.y).max(step.z)
}
None => f32::INFINITY,
}
}
fn wall_width(&self) -> Option<f32> {
match (self.kind, self.style) {
(LatticeKind::Tpms(_), LatticeStyle::Solid) => None,
_ => Some(self.thickness.abs()),
}
}
pub fn resolve_walls(mut self, samples: f32) -> Self {
let Some(thickness) = self.wall_width() else {
return self;
};
if thickness <= 0.0 || samples <= 0.0 {
return self;
}
let cell = self.resolved_cell();
let widest = cell.x.max(cell.y).max(cell.z);
let needed = (samples * widest / thickness).ceil();
if needed.is_finite() && needed > 0.0 {
self.resolution = self.resolution.max(needed as usize);
}
self
}
pub fn grade(mut self, grade: impl Fn(Vector3) -> f32 + Sync + Send + 'a) -> Self {
self.grade = Some(Box::new(grade));
self
}
pub fn trim(mut self, keep: impl Fn(Vector3) -> f32 + Sync + Send + 'a) -> Self {
self.trim = Some(Box::new(keep));
self
}
pub fn clip(mut self, region: Region<'a>) -> Self {
self.clip = Some(region.into_field());
self
}
pub fn relative_density(&self) -> f32 {
self.occupancy(self.density_resolution())
}
fn density_resolution(&self) -> usize {
self.resolution.min(12)
}
pub fn fit_relative_density(mut self, target: f32) -> Self {
let target = target.clamp(0.0, 1.0);
let cell = self.resolved_cell();
let span = cell.x.min(cell.y).min(cell.z).max(1e-6);
let signed = matches!(
(self.kind, self.style),
(LatticeKind::Tpms(_), LatticeStyle::Solid)
);
let grid = self.density_grid(self.density_resolution());
let mut hi = span;
for _ in 0..16 {
self.thickness = hi;
if self.occupancy_on(&grid) >= target {
break;
}
hi *= 2.0;
}
let mut lo = if signed { -span } else { 0.0 };
if signed {
for _ in 0..16 {
self.thickness = lo;
if self.occupancy_on(&grid) <= target {
break;
}
lo *= 2.0;
}
}
for _ in 0..20 {
let mid = 0.5 * (lo + hi);
self.thickness = mid;
if self.occupancy_on(&grid) < target {
lo = mid;
} else {
hi = mid;
}
}
self.thickness = 0.5 * (lo + hi);
self
}
pub fn current_thickness(&self) -> f32 {
self.thickness
}
pub fn build(&self) -> BufferGeometry {
let (grid, sampler) = self.grid();
let ([nx, ny, nz], origin, step) = grid;
let Some(total) = nx.checked_mul(ny).and_then(|v| v.checked_mul(nz)) else {
return BufferGeometry::new();
};
let mut values = vec![0.0f32; total];
crate::utils::parallel::par_fill_chunks(&mut values, nx * ny, |k, slab| {
let z = origin.z + k as f32 * step.z;
for j in 0..ny {
let y = origin.y + j as f32 * step.y;
for i in 0..nx {
let x = origin.x + i as f32 * step.x;
slab[j * nx + i] = sampler.value(Vector3::new(x, y, z));
}
}
});
IsoGrid {
dims: [nx, ny, nz],
origin,
step,
values,
}
.triangulate()
}
fn chiral_n(&self) -> i32 {
match self.spacing {
Spacing::Count([nx, ..]) => nx as i32,
Spacing::Size(_) => {
let size = self.bounds.size();
let cell = self.resolved_cell();
(size.x / cell.x).round().max(0.0) as i32
}
}
}
fn resolved_cell(&self) -> Vector3 {
let size = self.bounds.size();
match self.spacing {
Spacing::Size(c) => Vector3::new(
c.x.abs().max(1e-6),
c.y.abs().max(1e-6),
c.z.abs().max(1e-6),
),
Spacing::Count([nx, ny, nz]) => Vector3::new(
size.x / nx.max(1) as f32,
size.y / ny.max(1) as f32,
size.z / nz.max(1) as f32,
),
}
}
fn grid(&self) -> (([usize; 3], Vector3, Vector3), Sampler<'_>) {
let cell = self.resolved_cell();
let size = self.bounds.size();
let resolution = self.resolution.max(2);
let mut step = Vector3::new(
cell.x / resolution as f32,
cell.y / resolution as f32,
cell.z / resolution as f32,
);
let dims_for = |step: Vector3| -> [usize; 3] {
let count = |extent: f32, step: f32| -> usize {
#[allow(clippy::neg_cmp_op_on_partial_ord)]
if !(step > 0.0) {
return MIN_DIM;
}
((extent / step).ceil() as usize)
.saturating_add(PADDING)
.max(MIN_DIM)
};
[
count(size.x, step.x),
count(size.y, step.y),
count(size.z, step.z),
]
};
let mut dims = dims_for(step);
for _ in 0..32 {
let total = dims[0].saturating_mul(dims[1]).saturating_mul(dims[2]);
if total <= self.max_samples || dims == [MIN_DIM; 3] || !step.x.is_finite() {
break;
}
let shrink = (self.max_samples as f64 / total as f64).cbrt();
step = step * (1.0 / shrink.clamp(1e-9, 0.95) as f32);
dims = dims_for(step);
}
let origin = Vector3::new(
self.bounds.min.x - 2.5 * step.x,
self.bounds.min.y - 2.5 * step.y,
self.bounds.min.z - 2.5 * step.z,
);
((dims, origin, step), self.sampler(cell, step, true))
}
fn sampler(&self, cell: Vector3, step: Vector3, clipped: bool) -> Sampler<'_> {
let cuboct_cached = match (self.kind, self.program.is_some(), self.chiral_rule) {
(LatticeKind::Cuboct(c), false, None) => Some(c.segments(self.shape)),
_ => None,
};
Sampler {
kind: self.kind,
style: self.style,
phase: self.bounds.min,
cell,
omega: Vector3::new(TAU / cell.x, TAU / cell.y, TAU / cell.z),
half: self.thickness * 0.5,
margin: 3.0 * step.x.max(step.y).max(step.z),
skin: self.skin,
bounds: self.bounds,
grade: self.grade.as_deref(),
trim: self.trim.as_deref(),
clip: if clipped { self.clip.as_deref() } else { None },
cuboct_shape: self.shape,
cuboct_rule: self.chiral_rule,
cuboct_n: self.chiral_n(),
cuboct_program: self.program.as_deref(),
cuboct_cached,
}
}
fn occupancy(&self, samples_per_cell: usize) -> f32 {
self.occupancy_on(&self.density_grid(samples_per_cell))
}
fn density_grid(&self, samples_per_cell: usize) -> DensityGrid {
let cell = self.resolved_cell();
let size = self.bounds.size();
let mut res = samples_per_cell.max(2) as f32;
let count =
|extent: f32, cell: f32, res: f32| (((extent / cell) * res).ceil() as usize).max(1);
let mut dims = [
count(size.x, cell.x, res),
count(size.y, cell.y, res),
count(size.z, cell.z, res),
];
for _ in 0..32 {
let total = dims[0].saturating_mul(dims[1]).saturating_mul(dims[2]);
if total <= self.max_samples {
break;
}
res *= (self.max_samples as f64 / total as f64)
.cbrt()
.clamp(1e-9, 0.95) as f32;
let next = [
count(size.x, cell.x, res),
count(size.y, cell.y, res),
count(size.z, cell.z, res),
];
if next == dims {
break;
}
dims = next;
}
let stride = Vector3::new(
size.x / dims[0] as f32,
size.y / dims[1] as f32,
size.z / dims[2] as f32,
);
let mut points = Vec::with_capacity(dims[0] * dims[1] * dims[2]);
for k in 0..dims[2] {
for j in 0..dims[1] {
for i in 0..dims[0] {
let at = jitter(i, j, k);
points.push(Vector3::new(
self.bounds.min.x + (i as f32 + at[0]) * stride.x,
self.bounds.min.y + (j as f32 + at[1]) * stride.y,
self.bounds.min.z + (k as f32 + at[2]) * stride.z,
));
}
}
}
let cuts = match self.trim.as_deref() {
Some(trim) => crate::utils::parallel::par_map(&points, |p| trim(*p)),
None => Vec::new(),
};
DensityGrid {
points,
cuts,
cell,
stride,
}
}
fn occupancy_on(&self, grid: &DensityGrid) -> f32 {
if grid.points.is_empty() {
return 0.0;
}
let sampler = self.sampler(grid.cell, grid.stride, false);
let chunk = grid.points.len().div_ceil(64).max(1);
let counts =
crate::utils::parallel::par_map_range(grid.points.len().div_ceil(chunk), |c| {
let lo = c * chunk;
let hi = (lo + chunk).min(grid.points.len());
let (mut solid, mut part) = (0usize, 0usize);
for n in lo..hi {
let cut = grid.cuts.get(n).copied();
if cut.is_none_or(|c| c > 0.0) {
part += 1;
if sampler.value_at(grid.points[n], cut) > 0.0 {
solid += 1;
}
}
}
(solid, part)
});
let (solid, part) = counts
.iter()
.fold((0usize, 0usize), |acc, c| (acc.0 + c.0, acc.1 + c.1));
if part == 0 {
return 0.0;
}
solid as f32 / part as f32
}
}
struct DensityGrid {
points: Vec<Vector3>,
cuts: Vec<f32>,
cell: Vector3,
stride: Vector3,
}
fn jitter(i: usize, j: usize, k: usize) -> [f32; 3] {
let mut h = (i as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15)
^ (j as u64).wrapping_mul(0xbf58_476d_1ce4_e5b9)
^ (k as u64).wrapping_mul(0x94d0_49bb_1331_11eb);
let mut out = [0.0f32; 3];
for axis in &mut out {
h ^= h >> 33;
h = h.wrapping_mul(0xff51_afd7_ed55_8ccd);
h ^= h >> 33;
*axis = (h >> 40) as f32 / (1u32 << 24) as f32;
}
out
}
struct Sampler<'a> {
kind: LatticeKind,
style: LatticeStyle,
phase: Vector3,
cell: Vector3,
omega: Vector3,
half: f32,
margin: f32,
skin: f32,
bounds: Box3,
grade: Option<&'a (dyn Fn(Vector3) -> f32 + Sync + Send)>,
trim: Option<&'a (dyn Fn(Vector3) -> f32 + Sync + Send)>,
clip: Option<&'a (dyn Fn(Vector3) -> f32 + Sync + Send)>,
cuboct_shape: f32,
cuboct_rule: Option<ChiralRule>,
cuboct_n: i32,
cuboct_program: Option<&'a (dyn Fn(i32, i32, i32) -> Cuboct + Sync + Send)>,
cuboct_cached: Option<Vec<Segment>>,
}
impl Sampler<'_> {
fn value(&self, p: Vector3) -> f32 {
self.value_at(p, self.trim.map(|t| t(p)))
}
fn value_at(&self, p: Vector3, cut: Option<f32>) -> f32 {
let half = match self.grade {
Some(g) => self.half * g(p).max(0.0),
None => self.half,
};
let mut boundary = self.box_distance(p);
let mut depth = self.plan_distance(p);
if let Some(cut) = cut {
boundary = boundary.min(cut);
depth = depth.min(cut);
}
let solid = match self.kind {
LatticeKind::Strut(s) => {
let cull = half.max(0.0) + self.margin;
let d = strut::distance(p, self.phase, self.cell, s.segments(), cull);
half - d
}
LatticeKind::Cuboct(c) => {
let cull = half.max(0.0) + self.margin;
let d = if let Some(ref segs) = self.cuboct_cached {
strut::distance(p, self.phase, self.cell, segs, cull)
} else {
cuboct::distance(
p,
self.phase,
self.cell,
cull,
|i, j, k| match self.cuboct_program {
Some(f) => f(i, j, k),
None => c,
},
self.cuboct_shape,
self.cuboct_rule,
self.cuboct_n,
)
};
half - d
}
LatticeKind::Infill(i) => half - infill::distance(i, p, self.phase, self.cell, depth),
LatticeKind::Tpms(t) => {
let sd = self.tpms_distance(t, p);
match self.style {
LatticeStyle::Sheet => half - sd.abs(),
LatticeStyle::Solid => sd + half,
}
}
};
let filled = solid.min(boundary);
let clip = |v: f32| match self.clip {
Some(c) => v.min(c(p)),
None => v,
};
if self.skin <= 0.0 {
return clip(filled);
}
clip(filled.max(boundary.min(self.skin - boundary)))
}
fn tpms_distance(&self, t: Tpms, p: Vector3) -> f32 {
let (value, g) = t.value_and_gradient(
(p.x - self.phase.x) * self.omega.x,
(p.y - self.phase.y) * self.omega.y,
(p.z - self.phase.z) * self.omega.z,
);
let gradient = Vector3::new(
g[0] * self.omega.x,
g[1] * self.omega.y,
g[2] * self.omega.z,
);
value / gradient.length().max(1e-6)
}
fn plan_distance(&self, p: Vector3) -> f32 {
let lo = self.bounds.min;
let hi = self.bounds.max;
(p.x - lo.x).min(hi.x - p.x).min(p.y - lo.y).min(hi.y - p.y)
}
fn box_distance(&self, p: Vector3) -> f32 {
let lo = self.bounds.min;
let hi = self.bounds.max;
(p.x - lo.x)
.min(hi.x - p.x)
.min(p.y - lo.y)
.min(hi.y - p.y)
.min(p.z - lo.z)
.min(hi.z - p.z)
}
}
pub struct LatticeGeometry;
impl LatticeGeometry {
pub fn new(
kind: LatticeKind,
size: Vector3,
cells: [usize; 3],
thickness: f32,
) -> BufferGeometry {
Lattice::new(kind)
.size(size)
.cells(cells)
.thickness(thickness)
.build()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
fn geom_of(kind: LatticeKind) -> BufferGeometry {
Lattice::new(kind)
.size(Vector3::new(2.0, 2.0, 2.0))
.cells([2, 2, 2])
.thickness(0.14)
.resolution(12)
.build()
}
fn assert_watertight(geom: &BufferGeometry, what: &str) {
let index = geom
.index
.as_ref()
.unwrap_or_else(|| panic!("{what}: no index"));
assert!(!index.is_empty(), "{what}: no triangles");
let mut edges: HashMap<(u32, u32), i32> = HashMap::new();
for t in index.chunks_exact(3) {
for e in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] {
let (key, dir) = if e.0 < e.1 {
((e.0, e.1), 1)
} else {
((e.1, e.0), -1)
};
*edges.entry(key).or_insert(0) += dir;
}
}
let open = edges.values().filter(|&&v| v != 0).count();
assert_eq!(open, 0, "{what}: {open} unpaired edges");
}
#[test]
fn every_tpms_builds_watertight() {
for t in Tpms::ALL {
let kind = LatticeKind::Tpms(t);
assert_watertight(&geom_of(kind), t.name());
}
}
#[test]
fn every_strut_builds_watertight() {
for s in Strut::ALL {
let kind = LatticeKind::Strut(s);
assert_watertight(&geom_of(kind), s.name());
}
}
#[test]
fn every_infill_builds_watertight() {
for i in Infill::ALL {
let kind = LatticeKind::Infill(i);
assert_watertight(&geom_of(kind), i.name());
}
}
#[test]
fn every_cuboct_builds_watertight() {
for c in Cuboct::ALL {
let kind = LatticeKind::Cuboct(c);
assert_watertight(&geom_of(kind), c.name());
}
}
#[test]
fn a_programmed_chiral_column_builds_watertight() {
let m = 4i32;
let geom = Lattice::new(LatticeKind::Cuboct(Cuboct::ChiralCcw))
.size(Vector3::new(2.0, 2.0, 4.0))
.cells([2, 2, 4])
.thickness(0.14)
.resolution(12)
.chiral_rule(ChiralRule::R2)
.program(move |_, _, k| Cuboct::column_half(k, m))
.build();
assert_watertight(&geom, "chiral column");
}
#[test]
fn every_generator_is_named_once() {
let all = LatticeKind::all();
assert_eq!(
all.len(),
Tpms::ALL.len() + Strut::ALL.len() + Infill::ALL.len() + Cuboct::ALL.len()
);
let mut names: Vec<&str> = all.iter().map(|k| k.name()).collect();
names.sort_unstable();
let before = names.len();
names.dedup();
assert_eq!(before, names.len(), "duplicate generator name");
for kind in all {
assert_eq!(LatticeKind::from_name(kind.name()), Some(kind));
}
assert_eq!(LatticeKind::from_name("gyroidal"), None);
}
#[test]
fn building_twice_gives_the_same_mesh() {
let build = || {
Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(3.0, 3.0, 3.0))
.cells([3, 3, 3])
.thickness(0.2)
.resolution(14)
.trim(|p| 1.4 - p.length())
.build()
};
let (a, b) = (build(), build());
assert_eq!(a.index, b.index);
for name in ["position", "normal", "uv"] {
assert_eq!(
a.get_attribute(name).unwrap().array,
b.get_attribute(name).unwrap().array,
"{name} differs between builds"
);
}
}
#[test]
fn resolve_walls_puts_samples_across_the_wall() {
let thin = Lattice::new(LatticeKind::Tpms(Tpms::Lidinoid))
.size(Vector3::new(20.0, 20.0, 20.0))
.cells([3, 3, 3])
.thickness(0.25);
assert!(thin.wall_samples() < 1.0, "{}", thin.wall_samples());
let resolved = Lattice::new(LatticeKind::Tpms(Tpms::Lidinoid))
.size(Vector3::new(20.0, 20.0, 20.0))
.cells([3, 3, 3])
.thickness(0.25)
.max_samples(64_000_000)
.resolve_walls(4.0);
assert!(
resolved.wall_samples() >= 4.0,
"only {} samples",
resolved.wall_samples()
);
assert!(resolved.sample_grid()[0] > thin.sample_grid()[0]);
}
#[test]
fn the_sample_budget_still_wins_over_resolve_walls() {
let lattice = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(20.0, 20.0, 20.0))
.cells([3, 3, 3])
.thickness(0.05)
.max_samples(150_000)
.resolve_walls(8.0);
let dims = lattice.sample_grid();
assert!(dims[0] * dims[1] * dims[2] <= 150_000, "{dims:?}");
assert!(lattice.wall_samples() < 8.0);
}
#[test]
fn solid_style_builds_watertight() {
for t in [Tpms::Gyroid, Tpms::SchwarzP, Tpms::IWP] {
let geom = Lattice::new(LatticeKind::Tpms(t))
.size(Vector3::new(2.0, 2.0, 2.0))
.cells([2, 2, 2])
.style(LatticeStyle::Solid)
.thickness(0.0)
.resolution(12)
.build();
assert_watertight(&geom, t.name());
}
}
#[test]
fn geometry_stays_inside_the_bounds() {
let geom = geom_of(LatticeKind::Tpms(Tpms::Gyroid));
let pos = geom.get_attribute("position").unwrap();
for v in pos.array.chunks_exact(3) {
for a in v {
assert!(a.abs() <= 1.0 + 1e-3, "{a} escapes the box");
}
}
}
#[test]
fn attributes_are_complete() {
let geom = geom_of(LatticeKind::Strut(Strut::Octet));
let count = geom.get_attribute("position").unwrap().count();
assert_eq!(geom.get_attribute("normal").unwrap().count(), count);
assert_eq!(geom.get_attribute("uv").unwrap().count(), count);
for i in geom.index.as_ref().unwrap() {
assert!((*i as usize) < count);
}
}
#[test]
fn thicker_walls_mean_more_material() {
let base = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2]);
let thin = base.thickness(0.2).relative_density();
let thick = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.thickness(0.6)
.relative_density();
assert!(thin < thick, "{thin} !< {thick}");
assert!(thin > 0.0 && thick < 1.0);
}
#[test]
fn density_fit_lands_on_target() {
for kind in [
LatticeKind::Tpms(Tpms::Gyroid),
LatticeKind::Tpms(Tpms::Diamond),
LatticeKind::Strut(Strut::Octet),
LatticeKind::Strut(Strut::Bcc),
LatticeKind::Cuboct(Cuboct::Rigid),
LatticeKind::Infill(Infill::Grid),
LatticeKind::Infill(Infill::Honeycomb),
] {
for target in [0.2f32, 0.45] {
let lattice = Lattice::new(kind)
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.fit_relative_density(target);
let got = lattice.relative_density();
assert!(
(got - target).abs() < 0.01,
"{} wanted {target}, got {got} at thickness {}",
kind.name(),
lattice.current_thickness()
);
assert!(lattice.current_thickness() > 0.0);
}
}
}
#[test]
fn every_tpms_builds_solid_as_well_as_sheet() {
for t in Tpms::ALL {
let geom = Lattice::new(LatticeKind::Tpms(t))
.size(Vector3::new(2.0, 2.0, 2.0))
.cells([2, 2, 2])
.style(LatticeStyle::Solid)
.thickness(0.0)
.resolution(12)
.build();
assert_watertight(&geom, t.name());
}
}
#[test]
fn solid_density_climbs_with_the_offset() {
for t in [Tpms::Gyroid, Tpms::Diamond, Tpms::IWP] {
let density = |offset: f32| {
Lattice::new(LatticeKind::Tpms(t))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.style(LatticeStyle::Solid)
.thickness(offset)
.relative_density()
};
let steps: Vec<f32> = [-1.5f32, -0.75, 0.0, 0.75, 1.5]
.into_iter()
.map(density)
.collect();
for pair in steps.windows(2) {
assert!(
pair[1] > pair[0],
"{}: density went {:?} as the offset grew",
t.name(),
steps
);
}
assert!(steps[0] < 0.2 && *steps.last().unwrap() > 0.8, "{steps:?}");
}
}
#[test]
fn solid_style_fits_a_density_target() {
for t in [Tpms::Gyroid, Tpms::SchwarzP, Tpms::Diamond] {
for target in [0.2f32, 0.5, 0.8] {
let lattice = Lattice::new(LatticeKind::Tpms(t))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.style(LatticeStyle::Solid)
.fit_relative_density(target);
let got = lattice.relative_density();
assert!(
(got - target).abs() < 0.02,
"{} solid wanted {target}, got {got} at offset {}",
t.name(),
lattice.current_thickness()
);
}
}
}
#[test]
fn a_solid_lattice_fills_a_region_and_takes_a_skin() {
let geom = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.fill(Region::sphere(Vector3::ZERO, 3.0))
.cells([2, 2, 2])
.style(LatticeStyle::Solid)
.thickness(0.0)
.resolution(14)
.skin(0.3)
.build();
assert_watertight(&geom, "solid in a sphere with a skin");
let pos = geom.get_attribute("position").unwrap();
for v in pos.array.chunks_exact(3) {
let r = Vector3::new(v[0], v[1], v[2]).length();
assert!(r <= 3.05, "{r} escaped the sphere");
}
}
#[test]
fn the_wall_guard_knows_a_solid_lattice_has_no_wall() {
let solid = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.style(LatticeStyle::Solid)
.thickness(0.05);
assert!(
solid.wall_samples().is_infinite(),
"a solid lattice has no wall to resolve, got {}",
solid.wall_samples()
);
let asked = solid.resolution;
assert_eq!(
Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.style(LatticeStyle::Solid)
.thickness(0.05)
.resolve_walls(2.5)
.resolution,
asked,
"resolve_walls should leave a solid lattice alone"
);
let sheet = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.thickness(0.05);
assert!(sheet.wall_samples().is_finite() && sheet.wall_samples() < 1.0);
}
#[test]
fn the_density_fit_reaches_targets_outside_one_cell_of_thickness() {
for (style, targets) in [
(LatticeStyle::Sheet, [0.02f32, 0.97]),
(LatticeStyle::Solid, [0.02, 0.97]),
] {
for target in targets {
let lattice = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.style(style)
.fit_relative_density(target);
let got = lattice.relative_density();
assert!(
(got - target).abs() < 0.02,
"{style:?} wanted {target}, got {got} at {}",
lattice.current_thickness()
);
}
}
}
#[test]
fn grading_a_solid_lattice_needs_an_offset_to_scale() {
let halves = |offset: f32| {
let side = |lo: f32, hi: f32| {
Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.bounds(Box3::new(
Vector3::new(lo, -1.0, -1.0),
Vector3::new(hi, 1.0, 1.0),
))
.cell_size(Vector3::new(1.0, 1.0, 1.0))
.style(LatticeStyle::Solid)
.thickness(offset)
.grade(|p| (p.x + 2.0) * 0.5)
.relative_density()
};
(side(-2.0, 0.0), side(0.0, 2.0))
};
let (left, right) = halves(0.0);
assert!((left - right).abs() < 1e-6, "{left} vs {right}");
let (left, right) = halves(0.3);
assert!(right > left + 0.1, "{left} vs {right}");
}
#[test]
fn every_combination_comes_out_closed() {
for kind in LatticeKind::all() {
for style in [LatticeStyle::Sheet, LatticeStyle::Solid] {
let solid_tpms =
style == LatticeStyle::Solid && matches!(kind, LatticeKind::Tpms(_));
for skin in [0.0f32, 0.25] {
for filled in [false, true] {
let lattice = Lattice::new(kind)
.size(Vector3::new(3.0, 3.0, 3.0))
.cells([2, 2, 2])
.style(style)
.thickness(if solid_tpms { 0.0 } else { 0.35 })
.resolution(10)
.skin(skin);
let lattice = if filled {
lattice.fill(Region::sphere(Vector3::ZERO, 1.5))
} else {
lattice
};
let geom = lattice.build();
let what = format!("{} {style:?} skin={skin} fill={filled}", kind.name());
assert_watertight(&geom, &what);
for name in ["position", "normal", "uv"] {
let attr = geom.get_attribute(name).unwrap();
assert!(
attr.array.iter().all(|v| v.is_finite()),
"{what}: non-finite {name}"
);
}
}
}
}
}
}
#[test]
fn degenerate_settings_produce_a_mesh_or_nothing_but_never_a_panic() {
let cases: Vec<(&str, Lattice<'_>)> = vec![
(
"no cells",
Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(2.0, 2.0, 2.0))
.cells([0, 0, 0])
.thickness(0.2),
),
(
"no size",
Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::ZERO)
.cells([2, 2, 2])
.thickness(0.2),
),
(
"inside-out bounds",
Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(-2.0, -2.0, -2.0))
.cells([2, 2, 2])
.thickness(0.2),
),
(
"thickness past the cell",
Lattice::new(LatticeKind::Strut(Strut::Bcc))
.size(Vector3::new(2.0, 2.0, 2.0))
.cells([2, 2, 2])
.thickness(500.0)
.resolution(8),
),
];
for (what, lattice) in cases {
let geom = lattice.build();
if let Some(pos) = geom.get_attribute("position") {
assert!(
pos.array.iter().all(|v| v.is_finite()),
"{what}: non-finite position"
);
}
assert!(lattice.relative_density().is_finite(), "{what}: density");
}
}
#[test]
fn solid_style_at_zero_thickness_is_half_dense() {
let density = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.style(LatticeStyle::Solid)
.thickness(0.0)
.relative_density();
assert!((density - 0.5).abs() < 0.05, "{density}");
}
#[test]
fn grading_moves_material_across_the_part() {
let half = |lo: f32, hi: f32| {
Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.bounds(Box3::new(
Vector3::new(lo, -1.0, -1.0),
Vector3::new(hi, 1.0, 1.0),
))
.cell_size(Vector3::new(1.0, 1.0, 1.0))
.thickness(0.2)
.grade(|p| (p.x + 2.0) * 0.5)
.relative_density()
};
let (left, right) = (half(-2.0, 0.0), half(0.0, 2.0));
assert!(
right > left * 2.0,
"grading did not bias the wall: {left} / {right}"
);
let geom = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(4.0, 2.0, 2.0))
.cell_size(Vector3::new(1.0, 1.0, 1.0))
.thickness(0.2)
.resolution(12)
.grade(|p| (p.x + 2.0) * 0.5)
.build();
assert_watertight(&geom, "graded");
}
#[test]
fn filling_a_region_takes_its_bounds_and_its_shape() {
let radius = 3.0f32;
let lattice = Lattice::new(LatticeKind::Strut(Strut::Octet))
.fill(Region::sphere(Vector3::new(1.0, 0.0, -0.5), radius))
.cells([3, 3, 3])
.thickness(0.4)
.resolution(14);
let bounds = Box3::from_center_and_size(
Vector3::new(1.0, 0.0, -0.5),
Vector3::new(1.0, 1.0, 1.0) * (radius * 2.0),
);
assert_eq!(lattice.bounds, bounds);
let geom = lattice.build();
assert_watertight(&geom, "sphere fill");
let pos = geom.get_attribute("position").unwrap();
for v in pos.array.chunks_exact(3) {
let r = (Vector3::new(v[0], v[1], v[2]) - Vector3::new(1.0, 0.0, -0.5)).length();
assert!(r <= radius + 1e-2, "{r} escaped the sphere");
}
}
#[test]
fn an_explicit_box_beats_the_region_either_way_round() {
let want = Box3::new(Vector3::new(-1.0, -1.0, -1.0), Vector3::new(1.0, 1.0, 1.0));
let region = || Region::sphere(Vector3::ZERO, 8.0);
let after = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.fill(region())
.bounds(want);
let before = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.bounds(want)
.fill(region());
assert_eq!(after.bounds, want);
assert_eq!(before.bounds, want);
}
#[test]
fn a_lattice_fills_a_swept_curve() {
use crate::curves::{CatmullRomCurve3, Curve3};
let curve = CatmullRomCurve3::new(vec![
Vector3::new(-3.0, 0.0, 0.0),
Vector3::new(-1.0, 1.5, 0.5),
Vector3::new(1.0, -1.5, -0.5),
Vector3::new(3.0, 0.0, 0.0),
]);
let geom = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.fill(Region::tube(&curve, 1.0, 48))
.cell_size(Vector3::new(0.9, 0.9, 0.9))
.thickness(0.14)
.resolution(12)
.build();
assert_watertight(&geom, "tube fill");
let samples: Vec<Vector3> = (0..=64).map(|i| curve.get_point(i as f32 / 64.0)).collect();
let pos = geom.get_attribute("position").unwrap();
for v in pos.array.chunks_exact(3) {
let p = Vector3::new(v[0], v[1], v[2]);
let near = samples
.iter()
.map(|s| (p - *s).length())
.fold(f32::MAX, f32::min);
assert!(near <= 1.05, "{near} outside the tube");
}
}
#[test]
fn density_is_measured_against_the_part_not_its_box() {
let solid_sphere = Lattice::new(LatticeKind::Strut(Strut::Cubic))
.fill(Region::sphere(Vector3::ZERO, 3.0))
.cells([2, 2, 2])
.thickness(20.0)
.relative_density();
assert!(solid_sphere > 0.99, "{solid_sphere} — the part is full");
let fitted = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.fill(Region::sphere(Vector3::ZERO, 3.0))
.cells([2, 2, 2])
.fit_relative_density(0.7);
assert!((fitted.relative_density() - 0.7).abs() < 0.02);
let boxed = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(4.0, 4.0, 4.0))
.cells([2, 2, 2])
.fit_relative_density(0.3);
assert!((boxed.relative_density() - 0.3).abs() < 0.02);
}
#[test]
fn a_skin_wraps_the_fill_and_bonds_to_it() {
let plain = Lattice::new(LatticeKind::Strut(Strut::Bcc))
.fill(Region::sphere(Vector3::ZERO, 3.0))
.cells([3, 3, 3])
.thickness(0.3)
.resolution(14);
let bare = plain.relative_density();
let skinned = Lattice::new(LatticeKind::Strut(Strut::Bcc))
.fill(Region::sphere(Vector3::ZERO, 3.0))
.cells([3, 3, 3])
.thickness(0.3)
.resolution(14)
.skin(0.4);
assert!(
skinned.relative_density() > bare,
"a skin adds material: {bare} to {}",
skinned.relative_density()
);
let geom = skinned.build();
assert_watertight(&geom, "skinned");
for dir in [
Vector3::new(1.0, 0.0, 0.0),
Vector3::new(0.0, -1.0, 0.0),
Vector3::new(0.0, 0.0, 1.0),
Vector3::new(0.577, 0.577, 0.577),
] {
let just_inside = dir.normalize() * 2.9;
let just_outside = dir.normalize() * 3.2;
let sampler = skinned.grid().1;
assert!(
sampler.value(just_inside) > 0.0,
"skin has a gap at {dir:?}"
);
assert!(sampler.value(just_outside) < 0.0, "skin bulges at {dir:?}");
}
}
#[test]
fn a_region_with_nothing_in_it_builds_nothing() {
let empty = Region::sphere(Vector3::new(-9.0, 0.0, 0.0), 1.0)
.intersection(Region::sphere(Vector3::new(9.0, 0.0, 0.0), 1.0));
assert!(empty.bounds().is_empty());
let geom = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.fill(empty)
.cells([2, 2, 2])
.thickness(0.1)
.build();
assert!(geom.get_attribute("position").is_none());
}
#[test]
fn a_clip_cuts_after_the_skin_rather_than_before() {
let keep_negative_x = || {
Region::cuboid(Box3::new(
Vector3::new(0.0, -9.0, -9.0),
Vector3::new(9.0, 9.0, 9.0),
))
.invert()
};
let sectioned = Lattice::new(LatticeKind::Strut(Strut::Bcc))
.fill(Region::sphere(Vector3::ZERO, 3.0))
.cells([3, 3, 3])
.thickness(0.5)
.resolution(16)
.skin(0.4)
.clip(keep_negative_x());
let sampler = sectioned.grid().1;
assert!(sampler.value(Vector3::new(-2.9, 0.0, 0.0)) > 0.0);
assert!(sampler.value(Vector3::new(2.9, 0.0, 0.0)) < 0.0);
let void = (0..40)
.map(|i| Vector3::new(-0.05, -2.6 + i as f32 * 0.13, 0.0))
.any(|p| sampler.value(p) < 0.0);
assert!(void, "the cut face was skinned over");
assert_watertight(§ioned.build(), "sectioned");
let whole = Lattice::new(LatticeKind::Strut(Strut::Bcc))
.fill(Region::sphere(Vector3::ZERO, 3.0))
.cells([3, 3, 3])
.thickness(0.5)
.resolution(16)
.skin(0.4);
assert!((sectioned.relative_density() - whole.relative_density()).abs() < 1e-6);
}
#[cfg(feature = "mesh-bvh")]
#[test]
fn a_lattice_fills_a_mesh() {
use crate::geometries::SphereGeometry;
let sphere = SphereGeometry::new(2.0, 32, 24);
let region = Region::mesh(&sphere).expect("a bvh over a sphere");
assert!(region.contains(Vector3::ZERO));
assert!(!region.contains(Vector3::new(3.0, 0.0, 0.0)));
assert!((region.distance(Vector3::ZERO) - 2.0).abs() < 0.05);
let geom = Lattice::new(LatticeKind::Strut(Strut::Octet))
.fill(region)
.cells([2, 2, 2])
.thickness(0.3)
.resolution(12)
.build();
assert_watertight(&geom, "mesh fill");
let pos = geom.get_attribute("position").unwrap();
for v in pos.array.chunks_exact(3) {
let r = Vector3::new(v[0], v[1], v[2]).length();
assert!(r <= 2.05, "{r} escaped the mesh");
}
}
#[cfg(feature = "openscad")]
#[test]
fn a_lattice_fills_a_scad_model() {
let region = Region::scad("difference(){ cube(20, center=true); sphere(12, $fn=32); }")
.expect("valid scad");
assert!(!region.contains(Vector3::ZERO));
assert!(region.contains(Vector3::new(9.0, 9.0, 9.0)));
let geom = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.fill(region)
.cells([3, 3, 3])
.thickness(0.7)
.resolution(10)
.build();
assert_watertight(&geom, "scad fill");
}
#[test]
fn trimming_clips_to_the_field() {
let radius = 0.8f32;
let geom = Lattice::new(LatticeKind::Strut(Strut::Bcc))
.size(Vector3::new(2.0, 2.0, 2.0))
.cells([2, 2, 2])
.thickness(0.16)
.resolution(16)
.trim(move |p| radius - p.length())
.build();
assert_watertight(&geom, "trimmed");
let pos = geom.get_attribute("position").unwrap();
for v in pos.array.chunks_exact(3) {
let r = Vector3::new(v[0], v[1], v[2]).length();
assert!(r <= radius + 1e-2, "{r} outside the trim sphere");
}
}
#[test]
fn anisotropic_cells_stretch_the_pattern() {
let crossings = |geom: &BufferGeometry, axis: usize| {
let pos = geom.get_attribute("position").unwrap();
let mut lo = 0;
for v in pos.array.chunks_exact(3) {
if v[axis] < 0.0 {
lo += 1;
}
}
lo
};
let geom = Lattice::new(LatticeKind::Tpms(Tpms::SchwarzP))
.size(Vector3::new(4.0, 4.0, 4.0))
.cell_size(Vector3::new(4.0, 4.0, 1.0))
.thickness(0.2)
.resolution(10)
.build();
assert_watertight(&geom, "anisotropic");
assert!(crossings(&geom, 0) > 0 && crossings(&geom, 2) > 0);
}
#[test]
fn zero_thickness_makes_nothing() {
let geom = Lattice::new(LatticeKind::Strut(Strut::Cubic))
.size(Vector3::new(2.0, 2.0, 2.0))
.cells([2, 2, 2])
.thickness(0.0)
.build();
assert!(geom.get_attribute("position").is_none());
}
#[test]
fn the_sample_budget_is_respected() {
let lattice = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(100.0, 100.0, 100.0))
.cell_size(Vector3::new(10.0, 10.0, 10.0))
.thickness(2.0)
.resolution(64)
.max_samples(200_000);
let dims = lattice.sample_grid();
let total = dims[0] * dims[1] * dims[2];
assert!(total <= 200_000, "{dims:?} over budget");
assert!(total > 100_000, "{dims:?} gave up too much");
assert!(!lattice.build().index.as_ref().unwrap().is_empty());
}
#[test]
fn the_budget_wins_over_the_sampling_rate() {
let lattice = Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(100.0, 100.0, 100.0))
.cell_size(Vector3::new(1.0, 1.0, 1.0))
.max_samples(1_000);
let dims = lattice.sample_grid();
let total = dims[0] * dims[1] * dims[2];
assert!(total <= 1_000, "{dims:?} is {total}, over a budget of 1000");
assert!(lattice.thickness(0.2).wall_samples() < 1.0);
}
#[test]
fn an_unpayable_grid_comes_back_as_a_mesh_rather_than_a_panic() {
for lattice in [
Lattice::new(LatticeKind::Tpms(Tpms::Gyroid))
.size(Vector3::new(2.0, 2.0, 2.0))
.cell_size(Vector3::ZERO)
.thickness(0.2),
Lattice::new(LatticeKind::Strut(Strut::Octet))
.size(Vector3::new(1000.0, 1000.0, 1000.0))
.cell_size(Vector3::new(0.001, 0.001, 0.001))
.thickness(0.0005),
] {
let lattice = lattice.max_samples(200_000);
let dims = lattice.sample_grid();
let total = dims[0] * dims[1] * dims[2];
assert!(total <= 200_000, "{dims:?} is {total}");
let geom = lattice.build();
if let Some(pos) = geom.get_attribute("position") {
assert!(pos.array.iter().all(|v| v.is_finite()));
}
assert!(lattice.relative_density().is_finite());
}
}
#[test]
fn the_one_shot_constructor_matches_the_builder() {
let kind = LatticeKind::Tpms(Tpms::Gyroid);
let size = Vector3::new(2.0, 2.0, 2.0);
let direct = LatticeGeometry::new(kind, size, [2, 2, 2], 0.14);
let built = Lattice::new(kind)
.size(size)
.cells([2, 2, 2])
.thickness(0.14)
.build();
assert_eq!(
direct.get_attribute("position").unwrap().count(),
built.get_attribute("position").unwrap().count()
);
}
}