From 336de90a479b0e9415578fe18017aaeae94ded6e Mon Sep 17 00:00:00 2001 From: pnooyen Date: Fri, 4 Dec 2026 02:37:52 +0700 Subject: [PATCH 1/3] fix(core): close boolean seams at slivers and near-parallel faces Two independent ways a boolean of two closed solids came out open: - eliminate_t_junctions split any edge that passed within seg_tol of a boundary vertex, including edges already closed by two faces. When a face is a fan with a sliver thinner than seg_tol (e.g. a board face after one drilled hole), the next cut's seam vertices sit within seg_tol of both long edges of the sliver, and the face beyond it split its closed edge too: overlapping fragments, non-manifold edges. The perturbation retries cannot help since the sliver is in operand A. Only open (boundary or non-manifold) edges are split now. - classify_point_vs_mesh treated a fragment as coplanar with an opposing triangle at |n.n'| > 1 - 1e-5, but subdivide_tri_local treats a pair as coplanar only at > 1 - 1e-6 and otherwise cuts it along the crossing line. For nearly parallel pairs in between (two faceted rounds of the same radius), fragments within 1e-5 of the other plane were called coplanar and the rest classified by winding, so each side switched at a different fragment and open strips were left. The classifier uses the splitter's threshold now. Adds tests/boolean_seams.rs: two holes drilled in a line, seeded chains of 24 holes into one and into four faces of a board (each step closed, volume exact), and round prisms with different facet counts intersected. --- crates/forma-core/src/boolean.rs | 35 ++++-- crates/forma-core/tests/boolean_seams.rs | 131 +++++++++++++++++++++++ 2 files changed, 158 insertions(+), 8 deletions(-) create mode 100644 crates/forma-core/tests/boolean_seams.rs diff --git a/crates/forma-core/src/boolean.rs b/crates/forma-core/src/boolean.rs index 229d2d8..8ff6653 100644 --- a/crates/forma-core/src/boolean.rs +++ b/crates/forma-core/src/boolean.rs @@ -725,11 +725,13 @@ fn classify_point_vs_mesh( other_bvh: &TriBvh, local_cands: &[u32], ) -> Loc { - // Check if `p` lies on a coplanar triangle of `other` + // Check if `p` lies on a coplanar triangle of `other`, by the normal test `subdivide_tri_local` + // splits with: a nearly parallel pair it cut along their crossing line is classified by winding + // on both sides of it, never as coplanar on the fragments that happen to lie within 1e-5 of it. for &ci in local_cands { let tb = &other_tris[ci as usize]; let dn = n_p.dot(tb.normal); - if dn.abs() > 1.0 - 1e-5 && (tb.normal.dot(p) - tb.w).abs() < 1e-5 { + if dn.abs() > 1.0 - 1e-6 && (tb.normal.dot(p) - tb.w).abs() < 1e-5 { if point_in_tri_3d(p, tb) { return if dn > 0.0 { Loc::CoplanarSame @@ -1385,6 +1387,19 @@ fn canonical_tri(a: usize, b: usize, c: usize) -> ([usize; 3], i32) { /// Fast sort-based boundary vertex extraction (no HashMap SipHash overhead). fn collect_bad_verts(mesh: &PolyMesh) -> Vec { + verts_of_edges(&collect_bad_edges(mesh)) +} + +/// Sorted, deduplicated endpoints of `edges`. +fn verts_of_edges(edges: &[(usize, usize)]) -> Vec { + let mut verts: Vec = edges.iter().flat_map(|&(a, b)| [a, b]).collect(); + verts.sort_unstable(); + verts.dedup(); + verts +} + +/// Sorted keys of the boundary + non-manifold edges (zero HashMaps). +fn collect_bad_edges(mesh: &PolyMesh) -> Vec<(usize, usize)> { let mut edges: Vec<(usize, usize)> = Vec::with_capacity(mesh.faces.len() * 3); for f in &mesh.faces { let n = f.verts.len(); @@ -1397,7 +1412,7 @@ fn collect_bad_verts(mesh: &PolyMesh) -> Vec { } } edges.sort_unstable(); - let mut bad: Vec = Vec::new(); + let mut bad: Vec<(usize, usize)> = Vec::new(); let mut i = 0; while i < edges.len() { let e = edges[i]; @@ -1406,13 +1421,10 @@ fn collect_bad_verts(mesh: &PolyMesh) -> Vec { j += 1; } if j - i != 2 { - bad.push(e.0); - bad.push(e.1); + bad.push(e); } i = j; } - bad.sort_unstable(); - bad.dedup(); bad } @@ -1532,7 +1544,8 @@ fn eliminate_t_junctions(mesh: &mut PolyMesh, seg_tol: f64) { if mesh.faces.len() >= max_faces { return; } - let bverts = collect_bad_verts(mesh); + let bedges = collect_bad_edges(mesh); + let bverts = verts_of_edges(&bedges); if bverts.is_empty() { return; } @@ -1606,6 +1619,12 @@ fn eliminate_t_junctions(mesh: &mut PolyMesh, seg_tol: f64) { if ab_len_sq < end_tol_sq * 4.0 { continue; } + // Only an open edge has a T-junction. A closed one stays whole even when a vertex + // lies within `seg_tol` of it (past a neighbouring sliver thinner than `seg_tol`): + // splitting it on one side only would open it. + if bedges.binary_search(&edge_key(tri[ei], tri[(ei + 1) % 3])).is_err() { + continue; + } let e_min = a.min(b) - Vec3::splat(pad); let e_max = a.max(b) + Vec3::splat(pad); // Endpoint exclusion as a fraction of the edge, capped to an absolute length so a diff --git a/crates/forma-core/tests/boolean_seams.rs b/crates/forma-core/tests/boolean_seams.rs new file mode 100644 index 0000000..72a4032 --- /dev/null +++ b/crates/forma-core/tests/boolean_seams.rs @@ -0,0 +1,131 @@ +//! Boolean seams that must close: +//! - Holes drilled one after another into one face of a board. The first cut leaves the face as a +//! fan with a long sliver from a corner to the hole's rim, thinner than the T-junction tolerance; +//! the second cut's seam vertices then lie within that tolerance of both its long edges. +//! - Two round prisms of the same radius with different facets (near-parallel faces crossing at +//! small angles), intersected. + +use forma_core::boolean::{boolean_op, BoolOp}; +use forma_core::invariants::MeshInvariants; +use forma_core::math::Vec3; +use forma_core::mesh::PolyMesh; +use forma_core::primitives::{make_box, make_cone}; + +/// 564 x 560 x 18, from (18, 0, 100) to (582, 560, 118). +fn board() -> PolyMesh { + let mut b = make_box(564.0, 560.0, 18.0, 0); + b.translate(Vec3::new(300.0, 280.0, 109.0)); + b +} + +/// A 25-sided rod of radius 4, 9.5 long along `axis` (a column-major rotation) from `at`. +fn rod(axis: [f64; 9], at: Vec3) -> PolyMesh { + let mut c = make_cone(4.0, 4.0, 9.5, 25, 0); + c.translate(Vec3::new(0.0, 0.0, 4.75)); + let m = axis; + for v in &mut c.verts { + let (x, y, z) = (v.x, v.y, v.z); + *v = Vec3::new(m[0] * x + m[3] * y + m[6] * z, m[1] * x + m[4] * y + m[7] * z, m[2] * x + m[5] * y + m[8] * z) + at; + } + c +} + +/// Up from the bottom face, turned a quarter about z; down from the top face; into the front +/// face (y = 0); into the left face (x = 18). +const UP: [f64; 9] = [0.0, -1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]; +const DOWN: [f64; 9] = [1.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, -1.0]; +const ALONG_Y: [f64; 9] = [1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0]; +const ALONG_X: [f64; 9] = [0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0]; + +#[test] +fn two_holes_in_a_line_leave_a_closed_board() { + let once = boolean_op(&board(), &rod(UP, Vec3::new(550.0, 50.0, 99.5)), BoolOp::Difference, None, 0).unwrap(); + assert!(MeshInvariants::compute(&once).is_valid_solid(), "first hole"); + let twice = boolean_op(&once, &rod(UP, Vec3::new(550.0, 510.0, 99.5)), BoolOp::Difference, None, 0).unwrap(); + let inv = MeshInvariants::compute(&twice); + assert!(inv.is_valid_solid(), "second hole: {inv:?}"); +} + +/// Drills `holes` 9 mm deep holes, one by one, at seeded positions into the board's `faces` (0 +/// bottom, 1 top, 2 front, 3 left), half of them on a 32 mm grid so rims line up; after each the +/// board must be a closed solid with one more hole's volume gone. +fn drill_seeded(seed: u64, holes: usize, faces: &[usize]) { + let mut s = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1; + let mut next = move || { + s ^= s << 13; + s ^= s >> 7; + s ^= s << 17; + (s >> 11) as f64 / (1u64 << 53) as f64 + }; + let hole = 0.5 * 25.0 * 16.0 * (2.0 * std::f64::consts::PI / 25.0).sin() * 9.0; + let mut part = board(); + let expected = MeshInvariants::compute(&part).volume; + let mut taken: Vec<(usize, f64, f64)> = Vec::new(); + let mut k = 0; + while k < holes { + let face = faces[(next() * faces.len() as f64) as usize]; + let grid = next() < 0.5; + // (u, v) on the face: x then y, x then z, or y then z; clear of the board's edges. + let (u_lo, u_hi, v_lo, v_hi) = match face { + 0 | 1 => (50.0, 550.0, 30.0, 530.0), + 2 => (30.0, 570.0, 109.0, 109.0), + _ => (30.0, 530.0, 109.0, 109.0), + }; + let pick = |t: f64, lo: f64, hi: f64| if grid { lo + (t * (hi - lo) / 32.0).floor() * 32.0 } else { lo + t * (hi - lo) }; + let (u, v) = (pick(next(), u_lo, u_hi), pick(next(), v_lo, v_hi)); + // Top and bottom holes meet at mid-thickness, so they keep clear of each other too. + let near = |f: usize| f == face || f.max(face) == 1; + if taken.iter().any(|&(f, tu, tv)| near(f) && (tu - u).hypot(tv - v) < 12.0) { + continue; + } + taken.push((face, u, v)); + let tool = match face { + 0 => rod(UP, Vec3::new(u, v, 99.5)), + 1 => rod(DOWN, Vec3::new(u, v, 118.5)), + 2 => rod(ALONG_Y, Vec3::new(u, -0.5, v)), + _ => rod(ALONG_X, Vec3::new(17.5, u, v)), + }; + part = boolean_op(&part, &tool, BoolOp::Difference, None, 0).unwrap(); + k += 1; + let inv = MeshInvariants::compute(&part); + let want = expected - k as f64 * hole; + assert!(inv.is_valid_solid(), "seed {seed}, hole {k} {:?}: {inv:?}", taken.last().unwrap()); + assert!((inv.volume - want).abs() < 1e-6 * want, "seed {seed}, hole {k}: volume {} not {want}", inv.volume); + } +} + +#[test] +fn many_holes_in_one_face_leave_a_closed_board() { + for seed in 0..20 { + drill_seeded(seed, 24, &[0]); + } +} + +#[test] +fn many_holes_in_several_faces_leave_a_closed_board() { + for seed in 110..120 { + drill_seeded(seed, 24, &[0, 1, 2, 3]); + } +} + +#[test] +fn round_prisms_with_different_facets_intersect_closed() { + for na in [120usize, 122, 124] { + for nb in [120usize, 122, 124] { + for turn in [0.0f64, 0.1] { + let a = make_cone(450.0, 450.0, 100.0, na, 0); + let mut b = make_cone(450.0, 450.0, 300.0, nb, 0); + let (sin, cos) = turn.to_radians().sin_cos(); + for v in &mut b.verts { + *v = Vec3::new(v.x * cos - v.y * sin, v.x * sin + v.y * cos, v.z); + } + let both = boolean_op(&a, &b, BoolOp::Intersect, None, 0).unwrap(); + let inv = MeshInvariants::compute(&both); + let va = MeshInvariants::compute(&a).volume; + assert!(inv.is_valid_solid(), "{na} and {nb} sides, turned {turn} deg: {inv:?}"); + // Both are within their sagitta (~0.1 mm) of the same round. + assert!(inv.volume <= va * (1.0 + 1e-9) && inv.volume > va * (1.0 - 1e-3), "{na} and {nb} sides, turned {turn} deg: volume {} of {va}", inv.volume); + } + } + } +} From 49b0365c922d19b23b197149b6717420f0ee3128 Mon Sep 17 00:00:00 2001 From: pnooyen Date: Fri, 4 Dec 2026 02:54:26 +0700 Subject: [PATCH 2/3] fix(core): point_in_tri_3d tolerance as a distance Each edge test in point_in_tri_3d is the edge length times the point's signed distance inside that edge, and it was compared against a fixed -1e-7. Past a short edge that admits points far outside the triangle: for an edge 1e-4 long (normalized), points up to 1e-3 beyond it. Faces next to sliver triangles were then classified CoplanarSame/Opp with triangles they do not touch. Scale each edge's tolerance by its length so it is a distance of 1e-7 for every edge. --- crates/forma-core/src/boolean.rs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/forma-core/src/boolean.rs b/crates/forma-core/src/boolean.rs index 8ff6653..78ba21c 100644 --- a/crates/forma-core/src/boolean.rs +++ b/crates/forma-core/src/boolean.rs @@ -707,7 +707,9 @@ fn point_in_tri_3d(p: Vec3, t: &Tri) -> bool { let c0 = e0.cross(p - t.v[0]).dot(t.normal); let c1 = e1.cross(p - t.v[1]).dot(t.normal); let c2 = e2.cross(p - t.v[2]).dot(t.normal); - c0 >= -1e-7 && c1 >= -1e-7 && c2 >= -1e-7 + // Each `c` is the edge's length times `p`'s distance inside it: the tolerance is a distance, + // or a short edge would take in points far past it. + c0 >= -1e-7 * e0.len() && c1 >= -1e-7 * e1.len() && c2 >= -1e-7 * e2.len() } #[derive(Clone, Copy, PartialEq, Eq)] @@ -3073,3 +3075,17 @@ fn self_intersection_pass(mesh: &PolyMesh, frame: Option<[Vec3; 3]>, budget: u64 } OverlapCheck::Clear } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn point_in_tri_tolerance_is_a_distance_even_past_a_short_edge() { + // A long sliver whose short edge, 1e-4 long, closes it at x = 1. + let t = Tri::from_verts(Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(1.0, 1e-4, 0.0), 0, 0, 0).unwrap(); + assert!(point_in_tri_3d(Vec3::new(0.999, 0.5e-4, 0.0), &t)); + // 1e-4 past the short edge, within the wedge of the long ones: outside. + assert!(!point_in_tri_3d(Vec3::new(1.0001, 0.5e-4, 0.0), &t)); + } +} From a3a1eaf23d0c671f0e8db00d76383c95b7800648 Mon Sep 17 00:00:00 2001 From: pnooyen Date: Fri, 4 Dec 2026 09:14:38 +0700 Subject: [PATCH 3/3] fix(core): point_in_tri_3d tolerance to the edges, not past a sharp corner A point outside a triangle counted as on it when it was within 1e-7 of each edge's line. Past a needle triangle's sharp corner both long edges' lines stay within 1e-7 of each other for far longer than the needle (at 3.5e-5 rad, millimetres), so a coplanar face beside it was split into a sliver past the corner and classified coplanar with the needle. Two boxes that only touch side by side then reported a small shared volume. Now a point outside is on the triangle only within 1e-7 of one of its edges (the segment, after projecting onto the triangle's plane). --- crates/forma-core/src/boolean.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/crates/forma-core/src/boolean.rs b/crates/forma-core/src/boolean.rs index 78ba21c..7932c36 100644 --- a/crates/forma-core/src/boolean.rs +++ b/crates/forma-core/src/boolean.rs @@ -707,9 +707,16 @@ fn point_in_tri_3d(p: Vec3, t: &Tri) -> bool { let c0 = e0.cross(p - t.v[0]).dot(t.normal); let c1 = e1.cross(p - t.v[1]).dot(t.normal); let c2 = e2.cross(p - t.v[2]).dot(t.normal); - // Each `c` is the edge's length times `p`'s distance inside it: the tolerance is a distance, - // or a short edge would take in points far past it. - c0 >= -1e-7 * e0.len() && c1 >= -1e-7 * e1.len() && c2 >= -1e-7 * e2.len() + if c0 >= 0.0 && c1 >= 0.0 && c2 >= 0.0 { + return true; + } + // Outside, `p` is in when within 1e-7 of an edge, the edge itself and not its line: past a + // needle's sharp corner both long edges' lines stay that close for far longer than the needle. + let q = p - t.normal * (t.normal.dot(p) - t.w); + [(t.v[0], e0), (t.v[1], e1), (t.v[2], e2)].into_iter().any(|(a, e)| { + let s = (q - a).dot(e) / e.len_sq().max(1e-300); + (q - (a + e * s.clamp(0.0, 1.0))).len_sq() <= 1e-14 + }) } #[derive(Clone, Copy, PartialEq, Eq)] @@ -3087,5 +3094,9 @@ mod tests { assert!(point_in_tri_3d(Vec3::new(0.999, 0.5e-4, 0.0), &t)); // 1e-4 past the short edge, within the wedge of the long ones: outside. assert!(!point_in_tri_3d(Vec3::new(1.0001, 0.5e-4, 0.0), &t)); + // 1e-3 past its sharp corner, within 1e-7 of both long edges' lines: outside. + assert!(!point_in_tri_3d(Vec3::new(-1e-3, -0.5e-7, 0.0), &t)); + // Within 1e-7 of an edge: in. + assert!(point_in_tri_3d(Vec3::new(0.5, -0.5e-7, 0.0), &t) && point_in_tri_3d(Vec3::new(-0.5e-7, 0.0, 0.0), &t)); } }