A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server
Overlap check: single triangle BVH across shells with a work budget (issue #17)
finalpantasy763ecad7f6e8
diff --git a/crates/forma-core/src/boolean.rs b/crates/forma-core/src/boolean.rsindex 74cef6d..a3ced83 100644--- a/crates/forma-core/src/boolean.rs+++ b/crates/forma-core/src/boolean.rs@@ -2100,9 +2100,16 @@ fn tris_overlap_3d(a: &Tri, b: &Tri, scale: f64) -> bool {/// Zero cost for single-component meshes; cleanly permits valid negative-volume inner cavities/// (e.g. closed `shell(..., open_top=false)`) whose triangles do not intersect the outer shell.pub fn has_overlapping_components(mesh: &PolyMesh) -> bool {+ check_overlapping_components(mesh) == OverlapCheck::Overlap+}++/// Multi-shell overlap check in near-linear time: shells are labelled by union-find, then a+/// single triangle BVH finds candidate pairs across shells. A work budget bounds pathological+/// layouts; when it runs out the result is `Unverified` instead of a multi-minute stall.+pub fn check_overlapping_components(mesh: &PolyMesh) -> OverlapCheck {let n_faces = mesh.faces.len();if n_faces < 2 {- return false;+ return OverlapCheck::Clear;}// 1. Sort-based face-edge Union-Find to partition connected shell components@@ -2159,89 +2166,260 @@ pub fn has_overlapping_components(mesh: &PolyMesh) -> bool {let nc = comp_faces.len();if nc <= 1 {- return false;+ return OverlapCheck::Clear;}- // 2. Per-component AABB and signed volume (fast O(N) pass)- let mut comp_bbs: Vec<Aabb> = Vec::with_capacity(nc);+ // 2. Per-component signed volume and global bounds (fast O(N) pass)let mut comp_vols: Vec<f64> = Vec::with_capacity(nc);let mut global_bb = Aabb::empty();for c_faces in &comp_faces {- let mut bb = Aabb::empty();let mut vol6 = 0.0;for &fi in c_faces {for &vi in &mesh.faces[fi].verts {- bb.include(mesh.verts[vi]);+ global_bb.include(mesh.verts[vi]);}for [a, b, c] in mesh.triangulate_face(fi) {vol6 += mesh.verts[a].dot(mesh.verts[b].cross(mesh.verts[c]));}}- global_bb.min = global_bb.min.min(bb.min);- global_bb.max = global_bb.max.max(bb.max);- comp_bbs.push(bb);comp_vols.push(vol6 / 6.0);}-+ if !global_bb.is_valid() {+ return OverlapCheck::Clear;+ }let mesh_scale = global_bb.size().x.max(global_bb.size().y).max(global_bb.size().z).max(1e-9);- let aabb_eps = 1e-6 * mesh_scale;- // 3. Lazy per-component triangle + BVH build ONLY for components with an AABB overlap- let mut comp_data: Vec<Option<(Vec<Tri>, TriBvh)>> = (0..nc).map(|_| None).collect();- let ensure_comp = |cid: usize, comp_data: &mut [Option<(Vec<Tri>, TriBvh)>]| {- if comp_data[cid].is_some() {- return;+ // 3. One BVH over every triangle (tagged with its shell id) instead of a shell-pair loop:+ // O(T log T + candidate pairs). A first pass runs in world axes; if thin diagonal shells+ // make the axis-aligned boxes useless, a second pass runs in the mesh's dominant frame.+ if let Some(r) = overlap_pass(mesh, &comp_faces, &comp_vols, mesh_scale, None, OVERLAP_WORLD_BUDGET) {+ return r;+ }+ let frame = dominant_edge_frame(mesh);+ match overlap_pass(mesh, &comp_faces, &comp_vols, mesh_scale, Some(frame), OVERLAP_FRAME_BUDGET) {+ Some(r) => r,+ None => OverlapCheck::Unverified,+ }+}++/// Outcome of the multi-shell overlap check.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum OverlapCheck {+ /// No two shells cross, overlap or contain each other.+ Clear,+ /// At least two shells cross, overlap coplanar, or one solid sits inside another.+ Overlap,+ /// The work budget ran out before the mesh could be cleared (pathological shell layout).+ Unverified,+}++/// Candidate triangle-pair / BVH-node visits allowed for the world-axis pass.+const OVERLAP_WORLD_BUDGET: u64 = 6_000_000;+/// Candidate visits allowed for the retry in the dominant-direction frame.+const OVERLAP_FRAME_BUDGET: u64 = 40_000_000;++/// Orthonormal frame whose first axis is the dominant direction of the mesh's longest+/// triangle edges (power iteration on their length-weighted covariance). Deterministic.+fn dominant_edge_frame(mesh: &PolyMesh) -> [Vec3; 3] {+ let mut c = [[0.0f64; 3]; 3];+ for fi in 0..mesh.faces.len() {+ for [a, b, cc] in mesh.triangulate_face(fi) {+ let p = [mesh.verts[a], mesh.verts[b], mesh.verts[cc]];+ let mut best = Vec3::ZERO;+ for k in 0..3 {+ let e = p[(k + 1) % 3] - p[k];+ if e.len_sq() > best.len_sq() {+ best = e;+ }+ }+ let l = best.len();+ if !l.is_finite() || l < 1e-300 {+ continue;+ }+ let d = [best.x, best.y, best.z];+ for (r, row) in c.iter_mut().enumerate() {+ for (s, cell) in row.iter_mut().enumerate() {+ *cell += d[r] * d[s] / l;+ }+ }}- let mut tris = Vec::with_capacity(comp_faces[cid].len() * 2);- for &fi in &comp_faces[cid] {+ }+ let mut v = Vec3::new(0.6123, 0.5231, 0.5929).normalized();+ for _ in 0..64 {+ let w = Vec3::new(+ c[0][0] * v.x + c[0][1] * v.y + c[0][2] * v.z,+ c[1][0] * v.x + c[1][1] * v.y + c[1][2] * v.z,+ c[2][0] * v.x + c[2][1] * v.y + c[2][2] * v.z,+ );+ let l = w.len();+ if !l.is_finite() || l < 1e-300 {+ break;+ }+ v = w / l;+ }+ let helper = if v.x.abs() < 0.9 { Vec3::new(1.0, 0.0, 0.0) } else { Vec3::new(0.0, 1.0, 0.0) };+ let u = v.cross(helper).normalized();+ let w = v.cross(u).normalized();+ [v, u, w]+}++/// One pass of the multi-shell overlap check. `None` means the work budget ran out.+fn overlap_pass(+ mesh: &PolyMesh,+ comp_faces: &[Vec<usize>],+ comp_vols: &[f64],+ mesh_scale: f64,+ frame: Option<[Vec3; 3]>,+ budget: u64,+) -> Option<OverlapCheck> {+ let nc = comp_faces.len();+ let aabb_eps = 1e-6 * mesh_scale;+ let xf = |p: Vec3| -> Vec3 {+ match &frame {+ Some(f) => Vec3::new(p.dot(f[0]), p.dot(f[1]), p.dot(f[2])),+ None => p,+ }+ };++ // Shell id rides in `tag_idx`; `first_tri[c]` is the first triangle of shell c.+ let mut tris: Vec<Tri> = Vec::with_capacity(mesh.faces.len() * 2);+ let mut first_tri: Vec<u32> = vec![u32::MAX; nc];+ for (cid, c_faces) in comp_faces.iter().enumerate() {+ for &fi in c_faces {for [a, b, c] in mesh.triangulate_face(fi) {- if let Some(t) = Tri::from_verts(mesh.verts[a], mesh.verts[b], mesh.verts[c], 0, 0, 0) {+ if let Some(t) = Tri::from_verts(xf(mesh.verts[a]), xf(mesh.verts[b]), xf(mesh.verts[c]), cid as u32, 0, 0) {+ if first_tri[cid] == u32::MAX {+ first_tri[cid] = tris.len() as u32;+ }tris.push(t);}}}- let bvh = TriBvh::build(&tris);- comp_data[cid] = Some((tris, bvh));- };+ }+ let bvh = TriBvh::build(&tris);+ let mut work: u64 = 0;+ // Triangle-triangle crossing or coplanar face overlap between different shellslet mut hits: Vec<u32> = Vec::with_capacity(32);- for ci in 0..nc {- for cj in (ci + 1)..nc {- if !comp_bbs[ci].overlaps(&comp_bbs[cj], aabb_eps) {+ for (i, ta) in tris.iter().enumerate() {+ bvh.query_aabb(&ta.aabb, aabb_eps, &mut hits);+ work += hits.len() as u64 + 1;+ for &j in &hits {+ let j = j as usize;+ if j <= i {continue;}- ensure_comp(ci, &mut comp_data);- ensure_comp(cj, &mut comp_data);- let (tris_i, bvh_i) = comp_data[ci].as_ref().unwrap();- let (tris_j, bvh_j) = comp_data[cj].as_ref().unwrap();-- // Check triangle-triangle crossing or coplanar face overlap- for ta in tris_i {- bvh_j.query_aabb(&ta.aabb, aabb_eps, &mut hits);- for &tb_idx in &hits {- if tris_overlap_3d(ta, &tris_j[tb_idx as usize], mesh_scale) {- return true;- }- }+ let tb = &tris[j];+ if tb.tag_idx != ta.tag_idx && tris_overlap_3d(ta, tb, mesh_scale) {+ return Some(OverlapCheck::Overlap);}+ }+ if work > budget {+ return None;+ }+ }- // Check solid-inside-solid full containment (skip valid negative-volume inner cavities!)- if comp_vols[ci] > 1e-12 && comp_vols[cj] > 1e-12 {- if let Some(t0) = tris_i.first() {- if bvh_j.point_inside(tris_j, t0.centroid) {- return true;- }+ // Solid-inside-solid full containment (valid negative-volume inner cavities are skipped):+ // one ray per positive shell through the shared BVH, crossing parity counted per other shell.+ const RAYS: [Vec3; 3] = [+ Vec3 { x: 0.7310552815, y: 0.5178911243, z: 0.4442371891 },+ Vec3 { x: 0.3917284512, y: 0.8129471638, z: 0.4309184726 },+ Vec3 { x: 0.5521938476, y: 0.2917463851, z: 0.7809815432 },+ ];+ let n_pos = comp_vols.iter().filter(|v| **v > 1e-12).count();+ if n_pos < 2 {+ return Some(OverlapCheck::Clear);+ }+ let mut crossings: Vec<u32> = vec![0; nc];+ let mut touched: Vec<u32> = Vec::new();+ let mut stack: SmallVec<[u32; 64]> = SmallVec::new();+ for ci in 0..nc {+ if comp_vols[ci] <= 1e-12 || first_tri[ci] == u32::MAX {+ continue;+ }+ let p = tris[first_tri[ci] as usize].centroid;+ let mut resolved = false;+ for ray_dir in &RAYS {+ let inv_dir = Vec3::new(1.0 / ray_dir.x, 1.0 / ray_dir.y, 1.0 / ray_dir.z);+ for &t in &touched {+ crossings[t as usize] = 0;+ }+ touched.clear();+ let mut grazing = false;+ stack.clear();+ if !bvh.nodes.is_empty() {+ stack.push(0);+ }+ 'walk: while let Some(ni) = stack.pop() {+ work += 1;+ let node = &bvh.nodes[ni as usize];+ if !ray_hits_aabb(p, inv_dir, &node.aabb) {+ continue;}- if let Some(t0) = tris_j.first() {- if bvh_i.point_inside(tris_i, t0.centroid) {- return true;+ if node.count > 0 {+ let s = node.left as usize;+ let e = s + node.count as usize;+ for &ti in &bvh.indices[s..e] {+ let t = &tris[ti as usize];+ let cj = t.tag_idx as usize;+ if cj == ci || comp_vols[cj] <= 1e-12 {+ continue;+ }+ if !ray_hits_aabb_padded(p, inv_dir, &t.aabb, 1e-4) {+ continue;+ }+ match ray_tri_intersect(p, *ray_dir, t.v[0], t.v[1], t.v[2]) {+ RayHit::Hit => {+ if crossings[cj] == 0 {+ touched.push(cj as u32);+ }+ crossings[cj] += 1;+ }+ RayHit::Graze => {+ grazing = true;+ break 'walk;+ }+ RayHit::Miss => {}+ }}+ } else {+ stack.push(node.left);+ stack.push(node.right);}}+ if work > budget {+ return None;+ }+ if !grazing {+ resolved = true;+ break;+ }+ }+ if resolved {+ if touched.iter().any(|&t| crossings[t as usize] & 1 == 1) {+ return Some(OverlapCheck::Overlap);+ }+ } else {+ // Every ray grazed an edge or vertex: exact generalized winding number per shell.+ work += tris.len() as u64;+ if work > budget {+ return None;+ }+ let mut wn: Vec<f64> = vec![0.0; nc];+ for t in &tris {+ let cj = t.tag_idx as usize;+ if cj == ci || comp_vols[cj] <= 1e-12 {+ continue;+ }+ wn[cj] += winding_number(std::slice::from_ref(t), p);+ }+ if wn.iter().any(|w| w.abs() > 0.5) {+ return Some(OverlapCheck::Overlap);+ }}}- false+ Some(OverlapCheck::Clear)}/// Fast BVH-accelerated geometric self-intersection detector for a single mesh.diff --git a/crates/forma-core/src/scene.rs b/crates/forma-core/src/scene.rsindex f2cf2cb..6cc89cc 100644--- a/crates/forma-core/src/scene.rs+++ b/crates/forma-core/src/scene.rs@@ -269,7 +269,12 @@ impl Scene {reason: format!("zero or negligible volume solid (vol={:.3e})", inv.signed_volume),});}- if inv.components > 1 && crate::boolean::has_overlapping_components(&mesh) {+ let overlap = if inv.components > 1 {+ crate::boolean::check_overlapping_components(&mesh)+ } else {+ crate::boolean::OverlapCheck::Clear+ };+ if overlap == crate::boolean::OverlapCheck::Overlap {return Err(SceneError::InvariantViolation {part: name,reason: format!(@@ -278,6 +283,15 @@ impl Scene {),});}+ if overlap == crate::boolean::OverlapCheck::Unverified {+ return Err(SceneError::InvariantViolation {+ part: name,+ reason: format!(+ "shell overlap check exceeded its work budget ({} shells too densely interleaved to verify; union or split the part, or run without --strict)",+ inv.components+ ),+ });+ }}self.last_modified = Some(name.clone());self.parts.insert(name, Arc::new(mesh));@@ -550,13 +564,24 @@ impl Scene {inv.watertight, inv.consistent_winding, inv.non_manifold_edges, inv.boundary_edges, inv.volume));}- if inv.components > 1 && crate::boolean::has_overlapping_components(mesh) {+ let overlap = if inv.components > 1 {+ crate::boolean::check_overlapping_components(mesh)+ } else {+ crate::boolean::OverlapCheck::Clear+ };+ if overlap == crate::boolean::OverlapCheck::Overlap {all_manifold = false;warnings.push(format!("part '{name}' has overlapping/self-intersecting shells ({} components; use union=true)",inv.components));}+ if overlap == crate::boolean::OverlapCheck::Unverified {+ warnings.push(format!(+ "part '{name}': shell overlap check skipped, work budget exceeded ({} shells too densely interleaved to verify)",+ inv.components+ ));+ }if inv.degenerate_faces > 0 {warnings.push(format!("part '{name}' has {} micro-sliver faces", inv.degenerate_faces));}diff --git a/crates/forma-core/tests/issue_regressions.rs b/crates/forma-core/tests/issue_regressions.rsnew file mode 100644index 0000000..f4e062a--- /dev/null+++ b/crates/forma-core/tests/issue_regressions.rs@@ -0,0 +1,133 @@+//! Regression tests for upstream issues (one or more tests per issue number).+use forma_core::boolean::{check_overlapping_components, has_overlapping_components, OverlapCheck};+use forma_core::invariants::MeshInvariants;+use forma_core::math::Vec3;+use forma_core::mesh::PolyMesh;+use forma_core::Scene;+use std::time::Instant;++fn add_tet(m: &mut PolyMesh, a: Vec3, b: Vec3, c: Vec3, d: Vec3) {+ let base = m.verts.len();+ for p in [a, b, c, d] {+ m.add_vert(p);+ }+ // Outward winding when (b-a) x (c-a) points away from d.+ let flip = (b - a).cross(c - a).dot(d - a) > 0.0;+ let tris = [[0, 1, 2], [0, 3, 1], [1, 3, 2], [2, 3, 0]];+ for t in tris {+ let (i, j, k) = if flip { (t[0], t[2], t[1]) } else { (t[0], t[1], t[2]) };+ m.add_face(vec![base + i, base + j, base + k], 0, None);+ }+}++/// Issue #17 repro: N long thin parallel tetrahedra along (1,1,0). No two intersect,+/// but every pair of axis-aligned shell boxes overlaps.+fn sliver_mesh(n: usize) -> PolyMesh {+ let mut m = PolyMesh::new();+ let l = 10.0;+ let w = (0.25 * l * 0.5 / n as f64).min(0.001);+ for k in 0..n {+ let c = k as f64 * (l * 0.5 / n as f64);+ add_tet(+ &mut m,+ Vec3::new(c, 0.0, 0.0),+ Vec3::new(c + w, 0.0, 0.0),+ Vec3::new(c + l, l, 0.0),+ Vec3::new(c, 0.0, w),+ );+ }+ m+}++/// Thousands of small loose shells, as in an import made of many separate pieces: a jittered grid of tets.+fn loose_shell_mesh(n: usize) -> PolyMesh {+ let mut m = PolyMesh::new();+ let side = (n as f64).cbrt().ceil() as usize;+ let mut s: u64 = 0x9E3779B97F4A7C15;+ let mut rnd = move || {+ s ^= s << 13;+ s ^= s >> 7;+ s ^= s << 17;+ (s >> 11) as f64 / (1u64 << 53) as f64+ };+ for k in 0..n {+ let (i, j, l) = (k % side, (k / side) % side, k / (side * side));+ let o = Vec3::new(i as f64 + rnd() * 0.2, j as f64 + rnd() * 0.2, l as f64 + rnd() * 0.2);+ add_tet(+ &mut m,+ o,+ o + Vec3::new(0.5, 0.05, 0.0),+ o + Vec3::new(0.1, 0.5, 0.05),+ o + Vec3::new(0.2, 0.2, 0.6),+ );+ }+ m+}++#[test]+fn issue17_overlap_check_is_near_linear_on_thousands_of_shells() {+ // 8,000 diagonal slivers took 35 s in the shell-pair loop; 6,000 loose shells are the+ // shape of an imported mesh made of many small pieces. Both must clear in well under a second each.+ let slivers = sliver_mesh(8000);+ let t0 = Instant::now();+ let r = check_overlapping_components(&slivers);+ let dt_sliver = t0.elapsed().as_secs_f64();+ assert_eq!(r, OverlapCheck::Clear, "parallel slivers do not overlap");++ let loose = loose_shell_mesh(6000);+ let t1 = Instant::now();+ let r2 = check_overlapping_components(&loose);+ let dt_loose = t1.elapsed().as_secs_f64();+ assert_eq!(r2, OverlapCheck::Clear, "jittered grid shells do not overlap");++ println!("issue17: 8000 slivers {dt_sliver:.3}s, 6000 loose shells {dt_loose:.3}s");+ assert!(dt_sliver < 1.0, "8000 slivers took {dt_sliver:.2}s (was ~35 s)");+ assert!(dt_loose < 1.0, "6000 loose shells took {dt_loose:.2}s");+}++#[test]+fn issue17_strict_eval_path_on_slivers_is_fast_and_ok() {+ let mut s = Scene::new();+ s.strict_manifold = true;+ let t0 = Instant::now();+ let inv = s.set_part("m", sliver_mesh(4000)).expect("valid disjoint slivers pass strict");+ let obs = s.observe(0.0, None);+ let dt = t0.elapsed().as_secs_f64();+ assert_eq!(inv.components, 4000);+ assert!(obs.warnings.iter().all(|w| !w.contains("overlap")), "{:?}", obs.warnings);+ assert!(dt < 2.0, "strict set_part + observe on 4000 slivers took {dt:.2}s (was ~7 s)");+}++#[test]+fn issue17_overlap_check_still_detects_crossing_contained_and_coplanar_shells() {+ // Crossing shells among thousands of clean ones.+ let mut m = loose_shell_mesh(3000);+ let o = Vec3::new(0.05, 0.05, 0.05);+ add_tet(&mut m, o, o + Vec3::new(0.5, 0.05, 0.0), o + Vec3::new(0.1, 0.5, 0.05), o + Vec3::new(0.2, 0.2, 0.6));+ assert!(has_overlapping_components(&m), "a shell crossing another must be reported");++ // A small solid fully inside a large one (no triangle crossings at all).+ let mut big = PolyMesh::new();+ add_tet(&mut big, Vec3::new(0.0, 0.0, 0.0), Vec3::new(10.0, 0.0, 0.0), Vec3::new(0.0, 10.0, 0.0), Vec3::new(0.0, 0.0, 10.0));+ add_tet(&mut big, Vec3::new(1.0, 1.0, 1.0), Vec3::new(2.0, 1.0, 1.0), Vec3::new(1.0, 2.0, 1.0), Vec3::new(1.0, 1.0, 2.0));+ assert_eq!(check_overlapping_components(&big), OverlapCheck::Overlap, "contained solid must be reported");++ // Same two shells far apart: clear.+ let mut apart = PolyMesh::new();+ add_tet(&mut apart, Vec3::new(0.0, 0.0, 0.0), Vec3::new(10.0, 0.0, 0.0), Vec3::new(0.0, 10.0, 0.0), Vec3::new(0.0, 0.0, 10.0));+ add_tet(&mut apart, Vec3::new(21.0, 1.0, 1.0), Vec3::new(22.0, 1.0, 1.0), Vec3::new(21.0, 2.0, 1.0), Vec3::new(21.0, 1.0, 2.0));+ assert_eq!(check_overlapping_components(&apart), OverlapCheck::Clear);++ // Slivers with one crossing sliver: the dominant-frame retry must still see it.+ let mut sl = sliver_mesh(8000);+ add_tet(&mut sl, Vec3::new(4.0, 6.0, -1.0), Vec3::new(4.2, 6.0, -1.0), Vec3::new(9.0, 2.0, 1.0), Vec3::new(4.0, 6.2, -1.0));+ assert_eq!(check_overlapping_components(&sl), OverlapCheck::Overlap, "crossing sliver must be reported");++ // A valid closed shell (negative-volume inner cavity) stays clear.+ let mut s = Scene::new();+ s.strict_manifold = true;+ s.add_box("b", 2.0, 2.0, 2.0, Vec3::ZERO).unwrap();+ let inv = s.shell("b", 0.2, false).expect("closed shell is a valid two-shell solid");+ assert_eq!(inv.components, 2);+ let _ = MeshInvariants::compute(s.get_part("b").unwrap());+}