use manifold_rust::manifold::Manifold;
use manifold_rust::types::{BooleanEngine, MeshGL64, OpType};
use super::Op;
#[cfg(test)]
use crate::core::BufferAttribute;
use crate::core::BufferGeometry;
fn to_mesh(g: &BufferGeometry) -> Option<MeshGL64> {
let pos = g.get_attribute("position")?;
let verts: Vec<f64> = pos.array.iter().map(|v| *v as f64).collect();
let tri_verts: Vec<u64> = match &g.index {
Some(idx) => idx.iter().map(|i| *i as u64).collect(),
None => (0..(verts.len() / 3) as u64).collect(),
};
if tri_verts.len() < 3 {
return None;
}
Some(MeshGL64 {
num_prop: 3,
vert_properties: verts,
tri_verts,
..Default::default()
})
}
fn from_manifold(m: &Manifold) -> BufferGeometry {
let mesh = m.get_mesh_gl64(-1);
let stride = mesh.num_prop.max(3) as usize;
let vert = |i: u64| -> super::V3 {
let o = i as usize * stride;
[
mesh.vert_properties[o],
mesh.vert_properties[o + 1],
mesh.vert_properties[o + 2],
]
};
let tris: Vec<[super::V3; 3]> = mesh
.tri_verts
.chunks_exact(3)
.map(|t| [vert(t[0]), vert(t[1]), vert(t[2])])
.collect();
super::build_geometry(&tris)
}
pub fn boolean(a: &BufferGeometry, b: &BufferGeometry, op: Op) -> Option<BufferGeometry> {
let (ma, mb) = (to_mesh(a)?, to_mesh(b)?);
let import = |m: &MeshGL64| {
let strict = Manifold::from_mesh_gl64(m);
if strict.status() == manifold_rust::types::Error::NoError {
strict
} else {
Manifold::from_mesh_gl64_robust(m)
}
};
let (ma, mb) = (import(&ma), import(&mb));
if ma.status() != manifold_rust::types::Error::NoError
|| mb.status() != manifold_rust::types::Error::NoError
{
REJECTED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
return None;
}
let out = ma.boolean_with_engine(
&mb,
match op {
Op::Union => OpType::Add,
Op::Difference => OpType::Subtract,
Op::Intersection => OpType::Intersect,
},
BooleanEngine::Auto,
);
if out.status() != manifold_rust::types::Error::NoError {
return None;
}
let g = from_manifold(&out);
if !super::is_closed_manifold(&super::triangles(&g)) {
REJECTED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
return None;
}
Some(g)
}
pub fn rejected_results() -> usize {
REJECTED.load(std::sync::atomic::Ordering::Relaxed)
}
static REJECTED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
#[cfg(test)]
mod tests {
use super::*;
fn cube(size: f32, at: [f32; 3]) -> BufferGeometry {
let src: BufferGeometry = crate::geometries::BoxGeometry::new(size, size, size);
let pos = src.get_attribute("position").expect("position");
let moved: Vec<f32> = pos
.array
.chunks(3)
.flat_map(|v| [v[0] + at[0], v[1] + at[1], v[2] + at[2]])
.collect();
let mut g = BufferGeometry::new();
g.set_attribute("position", BufferAttribute::new(moved, 3));
if let Some(i) = &src.index {
g.set_index(i.clone());
}
g
}
fn watertight(g: &BufferGeometry) -> bool {
use std::collections::HashMap;
let tris = super::super::triangles(g);
let key = |p: [f64; 3]| {
(
(p[0] * 1e5).round() as i64,
(p[1] * 1e5).round() as i64,
(p[2] * 1e5).round() as i64,
)
};
let mut e: HashMap<_, u32> = HashMap::new();
for t in &tris {
for k in 0..3 {
let (mut u, mut v) = (key(t[k]), key(t[(k + 1) % 3]));
if u > v {
std::mem::swap(&mut u, &mut v);
}
*e.entry((u, v)).or_insert(0) += 1;
}
}
!e.is_empty() && e.values().all(|&c| c == 2)
}
#[test]
fn overlapping_cubes_are_watertight_for_every_op() {
let a = cube(10.0, [0.0; 3]);
let b = cube(10.0, [5.0, 5.0, 5.0]);
for op in [Op::Union, Op::Difference, Op::Intersection] {
let g = boolean(&a, &b, op).expect("manifold boolean");
assert!(watertight(&g), "{op:?} produced a mesh with cracks");
}
}
#[test]
fn a_shared_face_is_resolved_not_guessed() {
let a = cube(10.0, [0.0; 3]);
let b = cube(10.0, [10.0, 0.0, 0.0]);
let g = boolean(&a, &b, Op::Union).expect("manifold boolean");
assert!(watertight(&g), "coincident faces left cracks");
let v = super::super::metrics::volume(&super::super::triangles(&g));
assert!(
(v.abs() - 2000.0).abs() < 1e-6,
"union of two 10³ cubes = 2000, got {v}"
);
}
#[test]
fn disjoint_difference_is_the_original() {
let a = cube(10.0, [0.0; 3]);
let b = cube(2.0, [100.0, 0.0, 0.0]);
let g = boolean(&a, &b, Op::Difference).expect("manifold boolean");
let v = super::super::metrics::volume(&super::super::triangles(&g));
assert!(
(v.abs() - 1000.0).abs() < 1e-6,
"cutting nothing away, got {v}"
);
}
}