Skip to content

armgit / forma

Public Imported from GitHub
0

A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server

Detect face crossings and contained components in clearance queries

Alex9001c48d32eacad9
diff --git a/crates/forma-core/src/invariants.rs b/crates/forma-core/src/invariants.rs
index 56daa08..160e320 100644
--- a/crates/forma-core/src/invariants.rs
+++ b/crates/forma-core/src/invariants.rs
@@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
#[inline]
-fn dsu_find(parent: &mut [u32], mut x: u32) -> u32 {
+pub(crate) fn dsu_find(parent: &mut [u32], mut x: u32) -> u32 {
while parent[x as usize] != x {
let gp = parent[parent[x as usize] as usize];
parent[x as usize] = gp;
@@ -16,7 +16,7 @@ fn dsu_find(parent: &mut [u32], mut x: u32) -> u32 {
}
#[inline]
-fn dsu_union(parent: &mut [u32], a: u32, b: u32) {
+pub(crate) fn dsu_union(parent: &mut [u32], a: u32, b: u32) {
let ra = dsu_find(parent, a);
let rb = dsu_find(parent, b);
if ra != rb {
diff --git a/crates/forma-core/src/spatial.rs b/crates/forma-core/src/spatial.rs
index ebfe37b..a7e066e 100644
--- a/crates/forma-core/src/spatial.rs
+++ b/crates/forma-core/src/spatial.rs
@@ -176,6 +176,30 @@ fn closest_pts_seg_seg(p1: Vec3, q1: Vec3, p2: Vec3, q2: Vec3) -> (Vec3, Vec3) {
(p1 + d1 * s, p2 + d2 * t)
}
+/// A transverse segment can pierce the interior of a face with every vertex
+/// and edge pair still a positive distance apart. Coplanar contact is already
+/// covered by the vertex/face and edge/edge distance tests below.
+fn piercing_point(edges: &[Vec3; 3], face: &[Vec3; 3]) -> Option<Vec3> {
+ let normal = (face[1] - face[0]).cross(face[2] - face[0]);
+ let heights = edges.map(|p| (p - face[0]).dot(normal));
+ for i in 0..3 {
+ let j = (i + 1) % 3;
+ let (a, b) = (heights[i], heights[j]);
+ if a == b || a.min(b) > 0.0 || a.max(b) < 0.0 {
+ continue;
+ }
+ let p = edges[i].lerp(edges[j], a / (a - b));
+ let inside = (0..3).all(|k| {
+ let edge = face[(k + 1) % 3] - face[k];
+ edge.cross(p - face[k]).dot(normal) >= 0.0
+ });
+ if inside {
+ return Some(p);
+ }
+ }
+ None
+}
+
#[inline]
fn tri_tri_closest(t1: &[Vec3; 3], t2: &[Vec3; 3]) -> (f64, Vec3, Vec3) {
let mut best_d2 = f64::INFINITY;
@@ -236,72 +260,77 @@ fn point_inside_tris(tris: &[FastTri], p: Vec3) -> bool {
(sum / (4.0 * PI)).abs() > 0.5
}
-/// Exact minimum surface distance & collision check between two meshes.
-pub fn clearance(a: &PolyMesh, b: &PolyMesh) -> ClearanceReport {
- let bba = a.aabb();
- let bbb = b.aabb();
- let gap = [
- (bba.min.x - bbb.max.x).max(bbb.min.x - bba.max.x),
- (bba.min.y - bbb.max.y).max(bbb.min.y - bba.max.y),
- (bba.min.z - bbb.max.z).max(bbb.min.z - bba.max.z),
- ];
- let tris_a = mesh_tris(a);
- let tris_b = mesh_tris(b);
- if tris_a.is_empty() || tris_b.is_empty() {
- return ClearanceReport {
- min_distance: f64::INFINITY,
- intersecting: false,
- closest_a: [0.0; 3],
- closest_b: [0.0; 3],
- aabb_gap: gap,
- };
- }
-
- let mut best_d2 = f64::INFINITY;
- let mut best_a = tris_a[0].v[0];
- let mut best_b = tris_b[0].v[0];
-
- for ta in &tris_a {
- if aabb_dist_sq(&ta.aabb, &bbb) >= best_d2 {
+fn closest_surfaces(a: &[FastTri], b: &[FastTri], bounds_b: &Aabb) -> (f64, Vec3, Vec3) {
+ let mut best = (f64::INFINITY, Vec3::ZERO, Vec3::ZERO);
+ for ta in a {
+ if aabb_dist_sq(&ta.aabb, bounds_b) >= best.0 {
continue;
}
- for tb in &tris_b {
- if aabb_dist_sq(&ta.aabb, &tb.aabb) >= best_d2 {
+ for tb in b {
+ let lower_bound = aabb_dist_sq(&ta.aabb, &tb.aabb);
+ if lower_bound >= best.0 {
continue;
}
- let (d2, pa, pb) = tri_tri_closest(&ta.v, &tb.v);
- if d2 < best_d2 {
- best_d2 = d2;
- best_a = pa;
- best_b = pb;
- if best_d2 < 1e-12 {
- break;
+ if lower_bound == 0.0 {
+ if let Some(p) = piercing_point(&ta.v, &tb.v).or_else(|| piercing_point(&tb.v, &ta.v)) {
+ return (0.0, p, p);
+ }
+ }
+ let candidate = tri_tri_closest(&ta.v, &tb.v);
+ if candidate.0 < best.0 {
+ best = candidate;
+ if best.0 == 0.0 {
+ return best;
}
}
- }
- if best_d2 < 1e-12 {
- break;
}
}
+ best
+}
- let mut intersecting = best_d2 < 1e-10;
- if !intersecting && bba.overlaps(&bbb, 1e-6) {
- // Check complete containment (one mesh entirely inside the other)
- let pa = tris_a[0].v[0];
- let pb = tris_b[0].v[0];
- if (bbb.overlaps(&Aabb { min: pa, max: pa }, 1e-6) && point_inside_tris(&tris_b, pa))
- || (bba.overlaps(&Aabb { min: pb, max: pb }, 1e-6) && point_inside_tris(&tris_a, pb))
- {
- intersecting = true;
- best_d2 = 0.0;
+/// With disjoint surfaces, containment is constant on each connected component.
+/// Sample each used component once, including smaller islands after the first.
+fn has_contained_component(mesh: &PolyMesh, other: &[FastTri], bounds: &Aabb) -> bool {
+ use crate::invariants::{dsu_find, dsu_union};
+ let mut parents: Vec<u32> = (0..mesh.verts.len() as u32).collect();
+ for face in &mesh.faces {
+ for pair in face.verts.windows(2) {
+ dsu_union(&mut parents, pair[0] as u32, pair[1] as u32);
}
}
+ let mut checked = vec![false; parents.len()];
+ for face in &mesh.faces {
+ let Some(&vertex) = face.verts.first() else { continue };
+ let id = dsu_find(&mut parents, vertex as u32) as usize;
+ if !std::mem::replace(&mut checked[id], true) {
+ let p = mesh.verts[vertex];
+ if bounds.overlaps(&Aabb { min: p, max: p }, 0.0) && point_inside_tris(other, p) {
+ return true;
+ }
+ }
+ }
+ false
+}
+/// Minimum surface distance with contact and solid containment detection.
+pub fn clearance(a: &PolyMesh, b: &PolyMesh) -> ClearanceReport {
+ let bba = a.aabb();
+ let bbb = b.aabb();
+ let gap = [
+ (bba.min.x - bbb.max.x).max(bbb.min.x - bba.max.x),
+ (bba.min.y - bbb.max.y).max(bbb.min.y - bba.max.y),
+ (bba.min.z - bbb.max.z).max(bbb.min.z - bba.max.z),
+ ];
+ let tris_a = mesh_tris(a);
+ let tris_b = mesh_tris(b);
+ let (d2, pa, pb) = closest_surfaces(&tris_a, &tris_b, &bbb);
+ let intersecting = d2 < 1e-10 || (d2.is_finite() && bba.overlaps(&bbb, 0.0)
+ && (has_contained_component(a, &tris_b, &bbb) || has_contained_component(b, &tris_a, &bba)));
ClearanceReport {
- min_distance: if intersecting { 0.0 } else { best_d2.sqrt() },
+ min_distance: if intersecting { 0.0 } else { d2.sqrt() },
intersecting,
- closest_a: best_a.to_array(),
- closest_b: best_b.to_array(),
+ closest_a: pa.to_array(),
+ closest_b: pb.to_array(),
aabb_gap: gap,
}
}
diff --git a/crates/forma-core/tests/clearance_fit.rs b/crates/forma-core/tests/clearance_fit.rs
new file mode 100644
index 0000000..fbd15e5
--- /dev/null
+++ b/crates/forma-core/tests/clearance_fit.rs
@@ -0,0 +1,77 @@
+use forma_core::{math::Vec3, primitives::make_box, spatial::clearance, PolyMesh};
+
+fn bar(x: f64, y: f64, z: f64, at: Vec3) -> PolyMesh {
+ let mut mesh = make_box(x, y, z, 0);
+ mesh.translate(at);
+ mesh
+}
+
+#[test]
+fn transverse_face_piercing_has_a_shared_witness() {
+ let mut a = bar(1.0, 0.08, 0.10, Vec3::ZERO);
+ let mut b = bar(0.08, 1.0, 0.06, Vec3::new(0.08, 0.10, 0.005));
+ for rotation in [0.0, 17.0, 82.0] {
+ a.rotate_deg(rotation, 7.0, 3.0);
+ b.rotate_deg(rotation, 7.0, 3.0);
+ for (p, q) in [(&a, &b), (&b, &a)] {
+ let hit = clearance(p, q);
+ assert!(hit.intersecting);
+ assert_eq!(hit.min_distance, 0.0);
+ assert_eq!(hit.closest_a, hit.closest_b);
+ }
+ }
+}
+
+#[test]
+fn contact_coplanar_and_positive_gap() {
+ let a = bar(1.0, 0.08, 0.10, Vec3::ZERO);
+ for (z, gap) in [(0.08, 0.0), (0.081, 0.001), (0.09, 0.01)] {
+ let b = bar(0.08, 1.0, 0.06, Vec3::new(0.08, 0.10, z));
+ let hit = clearance(&a, &b);
+ assert_eq!(hit.intersecting, gap == 0.0);
+ assert!((hit.min_distance - gap).abs() < 1e-10);
+ }
+}
+
+#[test]
+fn contained_islands_are_independent_of_order() {
+ let outer = bar(0.5, 0.5, 0.5, Vec3::ZERO);
+ let inner = bar(0.03, 0.08, 0.01, Vec3::new(0.1, 0.1, 0.1));
+ let mut islands = bar(0.05, 0.05, 0.05, Vec3::new(1.0, 0.0, 0.0));
+ assert!(!clearance(&islands, &outer).intersecting);
+ islands.append_mesh(&inner);
+ assert!(clearance(&islands, &outer).intersecting);
+ assert!(clearance(&outer, &islands).intersecting);
+}
+
+#[test]
+fn empty_mesh_has_no_contact() {
+ let empty = PolyMesh::new();
+ let mesh = make_box(1.0, 1.0, 1.0, 0);
+ for (a, b) in [(&empty, &mesh), (&mesh, &empty)] {
+ let hit = clearance(a, b);
+ assert!(!hit.intersecting);
+ assert!(hit.min_distance.is_infinite());
+ }
+}
+
+#[test]
+fn translated_boxes_agree_with_analytical_distance() {
+ let a = bar(0.9, 0.07, 0.11, Vec3::ZERO);
+ for x in [-0.51_f64, -0.4, 0.0, 0.07, 0.49, 0.65] {
+ for y in [-0.4_f64, 0.09, 0.6] {
+ for z in [-0.16_f64, -0.02, 0.01, 0.09] {
+ let b = bar(0.09, 0.83, 0.05, Vec3::new(x, y, z));
+ let distance = Vec3::new(
+ (x.abs() - 0.495).max(0.0),
+ (y.abs() - 0.45).max(0.0),
+ (z.abs() - 0.08).max(0.0),
+ )
+ .len();
+ let result = clearance(&a, &b);
+ assert_eq!(result.intersecting, distance == 0.0);
+ assert!((result.min_distance - distance).abs() < 1e-8);
+ }
+ }
+ }
+}