A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server
Booleans: resolve small tools in large parts, refuse silent no-ops (issue #23)
finalpantasy331372673947
diff --git a/crates/forma-core/src/boolean.rs b/crates/forma-core/src/boolean.rsindex a3ced83..d7f5aba 100644--- a/crates/forma-core/src/boolean.rs+++ b/crates/forma-core/src/boolean.rs@@ -1400,6 +1400,9 @@ fn eliminate_t_junctions(mesh: &mut PolyMesh, seg_tol: f64) {if ab_len_sq < end_tol_sq * 4.0 {continue;}+ // Endpoint exclusion as a fraction of the edge, capped to an absolute length so a+ // very long edge (large part, small cutter) still accepts seam vertices near its ends.+ let t_eps = (1e-5_f64).min(1e-5 / ab_len_sq.sqrt());let mut hits: SmallVec<[(f64, usize); 4]> = SmallVec::new();for &(_, bv) in &bx[lo..hi] {if bv == tri[0] || bv == tri[1] || bv == tri[2] {@@ -1414,7 +1417,7 @@ fn eliminate_t_junctions(mesh: &mut PolyMesh, seg_tol: f64) {continue;}let t = (q - a).dot(ab) / ab_len_sq;- if t > 1e-5 && t < 1.0 - 1e-5 {+ if t > t_eps && t < 1.0 - t_eps {let proj = a + ab * t;if (q - proj).len_sq() < seg_tol_sq {hits.push((t, bv));@@ -1746,12 +1749,125 @@ fn count_bad_or_unoriented_edges(mesh: &PolyMesh) -> usize {/// Execute a scale-invariant, tolerance-guided BVH-localized CSG boolean operation/// between two closed solids, with post-assembly manifold repair and perturbation retries.+/// Largest combined-extent / thinnest-operand-dimension ratio handled by normalizing to the+/// combined extent. Past it the operands are normalized to the thin feature instead.+const BOOL_FEATURE_RATIO: f64 = 32.0;+/// Upper bound on normalized coordinates (keeps absolute tolerances far above f64 round-off).+const BOOL_MAX_NORM_EXTENT: f64 = 1.0e6;+pub fn boolean_op(a: &PolyMesh,b: &PolyMesh,op: BoolOp,b_name: Option<&str>,op_id: u32,+) -> Result<PolyMesh, String> {+ let res = boolean_op_unchecked(a, b, op, b_name, op_id)?;+ if let Some(msg) = silent_noop_reason(a, b, op, &res) {+ return Err(msg);+ }+ Ok(res)+}++/// Safety net against a boolean that silently returns operand A untouched (or nothing) although+/// B measurably penetrates A. Only runs when the result looks unchanged, so it is free otherwise.+fn silent_noop_reason(a: &PolyMesh, b: &PolyMesh, op: BoolOp, res: &PolyMesh) -> Option<String> {+ let unchanged = match op {+ BoolOp::Difference | BoolOp::Union => {+ res.verts.len() == a.verts.len() && res.faces.len() <= a.faces.len().max(1) * 2 && {+ let (va, vr) = (a.signed_volume(), res.signed_volume());+ (va - vr).abs() <= 1e-12 * va.abs()+ }+ }+ BoolOp::Intersect => res.faces.is_empty(),+ };+ if !unchanged || a.faces.is_empty() || b.faces.is_empty() {+ return None;+ }+ let (bb_a, bb_b) = (a.aabb(), b.aabb());+ if !bb_a.is_valid() || !bb_b.is_valid() || b.signed_volume().abs() <= 0.0 {+ return None;+ }+ let sb = bb_b.size();+ let b_max = sb.x.max(sb.y).max(sb.z);+ if !(b_max > 0.0) || !b_max.is_finite() {+ return None;+ }+ let mut b_min = b_max;+ for d in [sb.x, sb.y, sb.z] {+ if d > b_max * 1e-12 && d < b_min {+ b_min = d;+ }+ }+ // Work in B-sized coordinates so the ray tolerances are small against the cutter.+ let c = bb_b.center();+ let inv = 1.0 / b_min;+ let to_local = |p: Vec3| (p - c) * inv;+ let mut tris: Vec<Tri> = Vec::with_capacity(a.faces.len() * 2);+ for fi in 0..a.faces.len() {+ for [i, j, k] in a.triangulate_face(fi) {+ if let Some(t) = Tri::from_verts(to_local(a.verts[i]), to_local(a.verts[j]), to_local(a.verts[k]), 0, 0, 0) {+ tris.push(t);+ }+ }+ }+ let bvh = TriBvh::build(&tris);+ let delta = 1e-3;+ let mut near: Vec<u32> = Vec::new();+ // For cut/intersect the evidence is a B vertex well inside A; for union, well outside A.+ let want_inside = !matches!(op, BoolOp::Union);+ // Sample B's surface: vertices plus face centroids (a long cutter can have every vertex+ // outside the part while its walls pass straight through it).+ let v_stride = (b.verts.len() / 48).max(1);+ let f_stride = (b.faces.len() / 48).max(1);+ let samples = b+ .verts+ .iter()+ .step_by(v_stride)+ .copied()+ .chain((0..b.faces.len()).step_by(f_stride).map(|fi| b.face_centroid(fi)));+ let mut evidence = false;+ for p in samples {+ if !p.is_finite() {+ continue;+ }+ let q = to_local(p);+ // Decisive only when the sample is on the wanted side of A and at least `delta` away+ // from A's surface (coincident or touching surfaces are legitimate no-ops).+ if bvh.point_inside(&tris, q) != want_inside {+ continue;+ }+ bvh.query_aabb(&Aabb { min: q, max: q }, delta, &mut near);+ let clear = near.iter().all(|&ti| {+ let t = &tris[ti as usize];+ (crate::spatial::closest_pt_on_tri(q, t.v[0], t.v[1], t.v[2]) - q).len_sq() > delta * delta+ });+ if clear {+ evidence = true;+ break;+ }+ }+ if !evidence {+ return None;+ }+ let sa = bb_a.size();+ let ratio = sa.x.max(sa.y).max(sa.z) / b_min;+ let (name, what) = match op {+ BoolOp::Difference => ("cut", "removed no material although the cutter penetrates the part"),+ BoolOp::Union => ("add", "added nothing although the tool extends outside the part"),+ BoolOp::Intersect => ("intersect", "returned nothing although the operands overlap"),+ };+ Some(format!(+ "{name}: {what} (part/tool size ratio {ratio:.1e} is beyond what the boolean tolerance resolves; rescale or split the operation)"+ ))+}++fn boolean_op_unchecked(+ a: &PolyMesh,+ b: &PolyMesh,+ op: BoolOp,+ b_name: Option<&str>,+ op_id: u32,) -> Result<PolyMesh, String> {let bb_a = a.aabb();let bb_b = b.aabb();@@ -1792,6 +1908,28 @@ pub fn boolean_op(// the geometry is far from unit scale or far from the origin, keeping all boolean// tolerances scale-invariant while avoiding unnecessary floating-point churn at unit scale.let needs_norm = scale < 0.25 || scale > 8.0 || center.len() > 1e3;+ // The kernel's weld/coplanarity tolerances are absolute in normalized space, so they must+ // be small against the smallest operand feature, not against the combined extent: a 2 mm+ // cutter in a 10 m part normalized to the part would fall below them and be dropped whole.+ // When the extents are far apart, normalize to the thinnest operand dimension instead.+ let feature = {+ let floor = scale * 1e-12;+ let mut f = scale;+ for bb in [&bb_a, &bb_b] {+ let s = bb.size();+ for d in [s.x, s.y, s.z] {+ if d > floor && d < f {+ f = d;+ }+ }+ }+ f+ };+ let scale = if scale > BOOL_FEATURE_RATIO * feature {+ (feature * BOOL_FEATURE_RATIO).max(scale / BOOL_MAX_NORM_EXTENT)+ } else {+ scale+ };let (an_buf, bn_buf);let (a_ref, b_ref): (&PolyMesh, &PolyMesh) = if needs_norm {let inv_scale = 1.0 / scale;diff --git a/crates/forma-core/src/spatial.rs b/crates/forma-core/src/spatial.rsindex a7e066e..f585c1d 100644--- a/crates/forma-core/src/spatial.rs+++ b/crates/forma-core/src/spatial.rs@@ -95,7 +95,7 @@ fn aabb_dist_sq(a: &Aabb, b: &Aabb) -> f64 {/// Closest point on triangle `(a, b, c)` to point `p` (Ericson, Real-Time Collision Detection).#[inline]-fn closest_pt_on_tri(p: Vec3, a: Vec3, b: Vec3, c: Vec3) -> Vec3 {+pub(crate) fn closest_pt_on_tri(p: Vec3, a: Vec3, b: Vec3, c: Vec3) -> Vec3 {let ab = b - a;let ac = c - a;let ap = p - a;diff --git a/crates/forma-core/tests/issue_regressions.rs b/crates/forma-core/tests/issue_regressions.rsindex f4e062a..b5fa8a4 100644--- a/crates/forma-core/tests/issue_regressions.rs+++ b/crates/forma-core/tests/issue_regressions.rs@@ -131,3 +131,66 @@ fn issue17_overlap_check_still_detects_crossing_contained_and_coplanar_shells()assert_eq!(inv.components, 2);let _ = MeshInvariants::compute(s.get_part("b").unwrap());}++// ---------------------------------------------------------------------------------------------+// Issue #23: `cut` silently did nothing at large part/cutter size ratios.+// ---------------------------------------------------------------------------------------------++#[test]+fn issue23_cut_resolves_small_cutter_in_large_part() {+ use forma_core::boolean::BoolOp;+ // 32-gon prism area for r = 1.+ let ngon_area = 0.5 * 32.0 * (2.0 * std::f64::consts::PI / 32.0).sin();+ for size in [1.0e3, 1.0e4, 1.0e5, 1.0e6] {+ let mut s = Scene::new();+ s.strict_manifold = true;+ s.add_box("p", size, size, size, Vec3::ZERO).unwrap();+ s.add_cyl("c", 1.0, 2.0 * size, 32, Vec3::ZERO, 'z').unwrap();+ let inv = s+ .boolean_parts("p", "c", BoolOp::Difference, false)+ .unwrap_or_else(|e| panic!("cut at ratio {size:e} must succeed: {e}"));+ assert_eq!(inv.genus, 1, "through hole must exist at ratio {size:e}");+ let removed = size * size * size - inv.volume;+ let expect = ngon_area * size;+ assert!(+ (removed - expect).abs() <= expect * 1e-3 + size * size * size * 1e-12,+ "ratio {size:e}: removed {removed} expected {expect}"+ );+ assert_eq!(inv.degenerate_faces, 0, "no slivers at ratio {size:e}");+ }+}++#[test]+fn issue23_millimetre_plate_small_hole_is_clean() {+ use forma_core::boolean::{has_self_intersections, BoolOp};+ let mut s = Scene::new();+ s.strict_manifold = true;+ s.add_box("p", 500.0, 300.0, 4.0, Vec3::ZERO).unwrap();+ s.add_cyl("c", 0.5, 10.0, 32, Vec3::ZERO, 'z').unwrap();+ let inv = s.boolean_parts("p", "c", BoolOp::Difference, false).unwrap();+ assert_eq!(inv.genus, 1);+ assert_eq!(inv.degenerate_faces, 0, "plate hole must not leave micro-sliver faces");+ assert!(!has_self_intersections(s.get_part("p").unwrap()));+}++#[test]+fn issue23_unresolvable_ratio_fails_loudly_never_silently() {+ use forma_core::boolean::BoolOp;+ // Far past f64-resolvable ratios the cut must either work or say why: never return the box.+ for size in [1.0e9, 1.0e12, 1.0e15] {+ let mut s = Scene::new();+ s.add_box("p", size, size, size, Vec3::ZERO).unwrap();+ // The tool is a needle a billion times longer than wide, which strict mode refuses as a+ // part of its own (negligible volume). The cut is what is under test, so strict goes on+ // once the tool exists.+ s.add_cyl("c", 1.0, 2.0 * size, 32, Vec3::ZERO, 'z').unwrap();+ s.strict_manifold = true;+ match s.boolean_parts("p", "c", BoolOp::Difference, false) {+ Ok(inv) => assert_eq!(inv.genus, 1, "ratio {size:e}: OK result must contain the hole"),+ Err(e) => {+ let msg = e.to_string();+ assert!(!msg.contains("components overlap"), "ratio {size:e}: misleading error: {msg}");+ }+ }+ }+}