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

fix(core): planar-trimmed solidify cavity and manifold boolean seam repair (#78, #80) (#118)

Nebula45b791434f0e
diff --git a/crates/forma-core/src/boolean.rs b/crates/forma-core/src/boolean.rs
index 980d7fd..a036e80 100644
--- a/crates/forma-core/src/boolean.rs
+++ b/crates/forma-core/src/boolean.rs
@@ -1189,10 +1189,23 @@ fn assemble_clean_mesh(out_tris: Vec<OutTri>, tag_table: &[SmallVec<[String; 2]>
prune_folded_flaps(&mut m);
m.compact_unused_verts();
bad = count_bad_or_unoriented_edges(&m);
+ if bad > 0 && bad <= 24 {
+ if seal_micro_tri_holes(&mut m) {
+ bad = count_bad_or_unoriented_edges(&m);
+ }
+ }
+ if bad > 0 && count_bad_edges(&m) == 0 {
+ fix_isolated_flipped_faces(&mut m);
+ bad = count_bad_or_unoriented_edges(&m);
+ }
}
}
+ if bad == 0 && m.faces.len() > 12 {
+ unfold_coplanar_slivers(&mut m);
+ }
if bad == 0 && m.faces.len() > 24 {
simplify_coplanar_mesh(&mut m);
+ unfold_coplanar_slivers(&mut m);
}
for f in &mut m.faces {
let tid = f.op_id as usize;
@@ -1204,6 +1217,268 @@ fn assemble_clean_mesh(out_tris: Vec<OutTri>, tag_table: &[SmallVec<[String; 2]>
(m, bad)
}
+/// Seal isolated 3-edge micro-sliver boundary holes `(a -> b -> c -> a)` left when `emit_poly_tris`
+/// drops a near-collinear seam triangle (height < 1e-4). Adds the matching closing triangle `[a, c, b]`
+/// (inheriting material/tag from the longest adjacent edge), which `unfold_coplanar_slivers` then
+/// immediately edge-flips into two healthy triangles.
+fn seal_micro_tri_holes(mesh: &mut PolyMesh) -> bool {
+ let nf = mesh.faces.len();
+ if nf < 4 {
+ return false;
+ }
+ let mut half_edges: Vec<(u64, usize, usize, u32)> = Vec::with_capacity(nf * 3);
+ for (fi, f) in mesh.faces.iter().enumerate() {
+ if f.verts.len() != 3 {
+ continue;
+ }
+ for ei in 0..3 {
+ let u = f.verts[ei];
+ let v = f.verts[(ei + 1) % 3];
+ if u == v {
+ continue;
+ }
+ let (lo, hi) = if u < v { (u as u64, v as u64) } else { (v as u64, u as u64) };
+ half_edges.push(((lo << 32) | hi, u, v, fi as u32));
+ }
+ }
+ half_edges.sort_unstable_by_key(|&(ek, _, _, fi)| (ek, fi));
+
+ // Collect strictly naked boundary half-edges `(u -> v)` (undirected count == 1)
+ let mut b_edges: Vec<(usize, usize, u32)> = Vec::new();
+ let mut i = 0;
+ while i < half_edges.len() {
+ let ek = half_edges[i].0;
+ let mut j = i + 1;
+ while j < half_edges.len() && half_edges[j].0 == ek {
+ j += 1;
+ }
+ if j - i == 1 {
+ b_edges.push((half_edges[i].1, half_edges[i].2, half_edges[i].3));
+ }
+ i = j;
+ }
+ if b_edges.len() < 3 || b_edges.len() > 48 {
+ return false;
+ }
+
+ // Match 3-cycles `(a -> b), (b -> c), (c -> a)` where each vertex has unique outgoing edge
+ let mut used = vec![false; b_edges.len()];
+ let mut added = false;
+ for i0 in 0..b_edges.len() {
+ if used[i0] {
+ continue;
+ }
+ let (a, b, f0) = b_edges[i0];
+ let Some(i1) = (0..b_edges.len()).find(|&k| !used[k] && b_edges[k].0 == b) else {
+ continue;
+ };
+ let (_, c, f1) = b_edges[i1];
+ if c == a || c == b {
+ continue;
+ }
+ let Some(i2) = (0..b_edges.len()).find(|&k| !used[k] && b_edges[k].0 == c && b_edges[k].1 == a) else {
+ continue;
+ };
+ let f2 = b_edges[i2].2;
+ let pa = mesh.verts[a];
+ let pb = mesh.verts[b];
+ let pc = mesh.verts[c];
+ let e0 = (pb - pa).len();
+ let e1 = (pc - pb).len();
+ let e2 = (pa - pc).len();
+ let max_e = e0.max(e1).max(e2).max(1e-12);
+ let h = (pb - pa).cross(pc - pa).len() / max_e;
+ // Only seal genuine micro-sliver seam holes (height < 1e-4)
+ if h < 1e-4 {
+ let src_fi = if e0 >= e1 && e0 >= e2 {
+ f0 as usize
+ } else if e1 >= e2 {
+ f1 as usize
+ } else {
+ f2 as usize
+ };
+ let src = &mesh.faces[src_fi];
+ let mut nf_face = Face::new(SmallVec::from_slice(&[a, c, b]), src.lineage, src.op_id);
+ nf_face.mat_id = src.mat_id;
+ mesh.faces.push(nf_face);
+ used[i0] = true;
+ used[i1] = true;
+ used[i2] = true;
+ added = true;
+ }
+ }
+ added
+}
+
+/// On a closed undirected 2-manifold (`NM == 0 && B == 0`), flip any isolated triangle whose 3
+/// edges ALL share the same half-edge direction as their manifold neighbors (e.g., a micro-sliver
+/// whose vertices were snapped past collinearity). Subsequent `unfold_coplanar_slivers` then
+/// replaces any resulting 180°-folded coplanar pair with two properly oriented triangles.
+fn fix_isolated_flipped_faces(mesh: &mut PolyMesh) {
+ let nf = mesh.faces.len();
+ if nf < 4 {
+ return;
+ }
+ let mut half_edges: Vec<(u64, u32, u8)> = Vec::with_capacity(nf * 3);
+ for (fi, f) in mesh.faces.iter().enumerate() {
+ if f.verts.len() != 3 {
+ continue;
+ }
+ for ei in 0..3 {
+ let u = f.verts[ei];
+ let v = f.verts[(ei + 1) % 3];
+ if u == v {
+ continue;
+ }
+ if u < v {
+ half_edges.push((((u as u64) << 32) | (v as u64), fi as u32, 0));
+ } else {
+ half_edges.push((((v as u64) << 32) | (u as u64), fi as u32, 1));
+ }
+ }
+ }
+ half_edges.sort_unstable_by_key(|&(ek, fi, _)| (ek, fi));
+ let mut bad_edge_cnt = vec![0u8; nf];
+ let mut i = 0;
+ while i < half_edges.len() {
+ let ek = half_edges[i].0;
+ let mut j = i + 1;
+ while j < half_edges.len() && half_edges[j].0 == ek {
+ j += 1;
+ }
+ if j - i == 2 && half_edges[i].2 == half_edges[i + 1].2 {
+ bad_edge_cnt[half_edges[i].1 as usize] += 1;
+ bad_edge_cnt[half_edges[i + 1].1 as usize] += 1;
+ }
+ i = j;
+ }
+ for (fi, &cnt) in bad_edge_cnt.iter().enumerate() {
+ if cnt == 3 && mesh.faces[fi].verts.len() == 3 {
+ mesh.faces[fi].verts.swap(1, 2);
+ }
+ }
+}
+
+/// Unfold 180°-folded coplanar sliver triangles across shared interior manifold edges via exact
+/// zero-geometry-change edge flips `(a, b) -> (c, d)`. Preserves manifoldness, winding, and volume
+/// while eliminating self-intersections caused by seam snapping across ultra-thin coplanar wedges.
+fn unfold_coplanar_slivers(mesh: &mut PolyMesh) {
+ let nf = mesh.faces.len();
+ if nf < 4 {
+ return;
+ }
+ for _pass in 0..4 {
+ // Build sorted undirected edge -> incident face list (zero HashMap)
+ let mut edge_inc: Vec<(u64, u32, u8)> = Vec::with_capacity(nf * 3);
+ for (fi, f) in mesh.faces.iter().enumerate() {
+ if f.verts.len() != 3 {
+ continue;
+ }
+ for ei in 0..3 {
+ let u = f.verts[ei];
+ let v = f.verts[(ei + 1) % 3];
+ if u == v {
+ continue;
+ }
+ let (lo, hi) = if u < v { (u as u64, v as u64) } else { (v as u64, u as u64) };
+ edge_inc.push(((lo << 32) | hi, fi as u32, ei as u8));
+ }
+ }
+ edge_inc.sort_unstable();
+ let has_edge = |u: usize, v: usize| -> bool {
+ let (lo, hi) = if u < v { (u as u64, v as u64) } else { (v as u64, u as u64) };
+ let ek = (lo << 32) | hi;
+ edge_inc.binary_search_by_key(&ek, |&(k, _, _)| k).is_ok()
+ };
+
+ let mut flipped_face = vec![false; nf];
+ let mut added_edges: Vec<u64> = Vec::new();
+ let mut flipped_any = false;
+
+ let mut i = 0;
+ while i < edge_inc.len() {
+ let ek = edge_inc[i].0;
+ let mut j = i + 1;
+ while j < edge_inc.len() && edge_inc[j].0 == ek {
+ j += 1;
+ }
+ if j - i == 2 {
+ let f1 = edge_inc[i].1 as usize;
+ let e1 = edge_inc[i].2 as usize;
+ let f2 = edge_inc[i + 1].1 as usize;
+ let e2 = edge_inc[i + 1].2 as usize;
+ if !flipped_face[f1]
+ && !flipped_face[f2]
+ && mesh.faces[f1].mat_id == mesh.faces[f2].mat_id
+ && mesh.faces[f1].op_id == mesh.faces[f2].op_id
+ {
+ let a = mesh.faces[f1].verts[e1];
+ let b = mesh.faces[f1].verts[(e1 + 1) % 3];
+ let c = mesh.faces[f1].verts[(e1 + 2) % 3];
+ let a2 = mesh.faces[f2].verts[e2];
+ let b2 = mesh.faces[f2].verts[(e2 + 1) % 3];
+ let d = mesh.faces[f2].verts[(e2 + 2) % 3];
+ // Must be consistently opposed half-edges: f1 has (a -> b), f2 has (b -> a)
+ if a2 == b && b2 == a && c != d {
+ let pa = mesh.verts[a];
+ let pb = mesh.verts[b];
+ let pc = mesh.verts[c];
+ let pd = mesh.verts[d];
+ let n1 = (pb - pa).cross(pc - pa);
+ let n2 = (pa - pb).cross(pd - pb);
+ let l1 = n1.len();
+ let l2 = n2.len();
+ // Detect either:
+ // (1) 180°-folded coplanar pair (opposite normals on the same plane), OR
+ // (2) Zero-area / collinear bridge sliver lying on the shared edge of a larger
+ // coplanar triangle (which blocks direct vertex sharing across a rim!).
+ let is_folded = l1 > 1e-18 && l2 > 1e-18 && n1.dot(n2) < -(1.0 - 1e-4) * l1 * l2;
+ let is_collinear_cap =
+ (l1 > 1e-14 && l2 <= 1e-10 * l1) || (l2 > 1e-14 && l1 <= 1e-10 * l2);
+ if is_folded || is_collinear_cap {
+ let n_true = if l2 >= l1 { n2 / l2 } else { n1 / l1 };
+ let plane_ok = (pc - pa).dot(n_true).abs() < 1e-6
+ && (pd - pa).dot(n_true).abs() < 1e-6;
+ if plane_ok {
+ let nt1 = (pd - pa).cross(pc - pa);
+ let nt2 = (pb - pd).cross(pc - pd);
+ let lt1 = nt1.len();
+ let lt2 = nt2.len();
+ let min_a = if is_folded {
+ 1e-12 * l1.max(l2)
+ } else {
+ (1e-10 * l1.max(l2)).max(l1.min(l2) * 10.0)
+ };
+ if lt1 > min_a
+ && lt2 > min_a
+ && nt1.dot(n_true) > lt1 * (1.0 - 1e-4)
+ && nt2.dot(n_true) > lt2 * (1.0 - 1e-4)
+ && !has_edge(c, d)
+ {
+ let (lo, hi) = if c < d { (c as u64, d as u64) } else { (d as u64, c as u64) };
+ let new_ek = (lo << 32) | hi;
+ if !added_edges.contains(&new_ek) {
+ mesh.faces[f1].verts = SmallVec::from_slice(&[a, d, c]);
+ mesh.faces[f2].verts = SmallVec::from_slice(&[d, b, c]);
+ flipped_face[f1] = true;
+ flipped_face[f2] = true;
+ added_edges.push(new_ek);
+ flipped_any = true;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ i = j;
+ }
+ if !flipped_any {
+ break;
+ }
+ }
+}
+
/// Strictly manifold-preserving, zero-error coplanar & collinear-ridge half-edge collapse.
/// Enforces the exact Edelsbrunner Link Condition (`|N(u) ∩ N(v)| == 2`, `shared_faces == 2`)
/// plus positive oriented area preservation so `WT=true, NM=0` and exact volume are invariant.
@@ -1695,20 +1970,39 @@ fn eliminate_t_junctions(mesh: &mut PolyMesh, seg_tol: f64) {
let mut next_is_new: Vec<bool> = Vec::with_capacity(mesh.faces.len() + 64);
let mut did_split = false;
- for (fi_old, f) in mesh.faces.drain(..).enumerate() {
+ // When scanning interior (`count == 2`) edges in the `!bad_edges_only` fallback, collect
+ // proposals first and only split a non-bad edge if BOTH incident triangles split it at the
+ // exact same vertex list. Half-splitting a manifold edge always breaks topology.
+ let mut deferred_splits: Vec<Option<(usize, SmallVec<[usize; 4]>, bool)>> = if !bad_edges_only {
+ vec![None; mesh.faces.len()]
+ } else {
+ Vec::new()
+ };
+
+ let nf_cur = mesh.faces.len();
+ let mut old_faces = if bad_edges_only {
+ std::mem::take(&mut mesh.faces)
+ } else {
+ Vec::new()
+ };
+
+ for fi_old in 0..nf_cur {
+ let f_ref: &Face = if bad_edges_only { &old_faces[fi_old] } else { &mesh.faces[fi_old] };
let is_new = face_is_new.get(fi_old).copied().unwrap_or(true);
- if f.verts.len() != 3 || new_faces.len() >= max_faces {
- new_faces.push(f);
- next_is_new.push(false);
+ if f_ref.verts.len() != 3 || (bad_edges_only && new_faces.len() >= max_faces) {
+ if bad_edges_only {
+ new_faces.push(std::mem::replace(&mut old_faces[fi_old], Face::new(SmallVec::new(), 0, 0)));
+ next_is_new.push(false);
+ }
continue;
}
- let tri = [f.verts[0], f.verts[1], f.verts[2]];
+ let tri = [f_ref.verts[0], f_ref.verts[1], f_ref.verts[2]];
let mut edge_bad_flags = [true; 3];
let mut bad_edge_cnt = 3usize;
if bad_edges_only {
// O(1) reject: ~95% of faces have zero boundary vertices and cannot own a T-junction edge!
if !bad_mask[tri[0]] && !bad_mask[tri[1]] && !bad_mask[tri[2]] {
- new_faces.push(f);
+ new_faces.push(std::mem::replace(&mut old_faces[fi_old], Face::new(SmallVec::new(), 0, 0)));
next_is_new.push(false);
continue;
}
@@ -1726,14 +2020,12 @@ fn eliminate_t_junctions(mesh: &mut PolyMesh, seg_tol: f64) {
}
}
if bad_edge_cnt == 0 {
- new_faces.push(f);
+ new_faces.push(std::mem::replace(&mut old_faces[fi_old], Face::new(SmallVec::new(), 0, 0)));
next_is_new.push(false);
continue;
}
}
if !bad_edges_only && !is_new && bvh_new.is_none() {
- new_faces.push(f);
- next_is_new.push(false);
continue;
}
let p0 = mesh.verts[tri[0]];
@@ -1761,16 +2053,20 @@ fn eliminate_t_junctions(mesh: &mut PolyMesh, seg_tol: f64) {
&bverts
};
if verts_slice.is_empty() {
- new_faces.push(f);
- next_is_new.push(false);
+ if bad_edges_only {
+ new_faces.push(std::mem::replace(&mut old_faces[fi_old], Face::new(SmallVec::new(), 0, 0)));
+ next_is_new.push(false);
+ }
continue;
}
let n_orig = (p1 - p0).cross(p2 - p0);
let orig_area2_sq = n_orig.len_sq();
if orig_area2_sq < 1e-24 {
- new_faces.push(f);
- next_is_new.push(false);
+ if bad_edges_only {
+ new_faces.push(std::mem::replace(&mut old_faces[fi_old], Face::new(SmallVec::new(), 0, 0)));
+ next_is_new.push(false);
+ }
continue;
}
let min_dot = 1e-10 * orig_area2_sq;
@@ -1848,24 +2144,100 @@ fn eliminate_t_junctions(mesh: &mut PolyMesh, seg_tol: f64) {
}
}
- if let Some((ei, hits)) = best_edge {
- did_split = true;
- let a = tri[ei];
- let b = tri[(ei + 1) % 3];
- let c = tri[(ei + 2) % 3];
- let mut prev = a;
- for &(_, bv) in &hits {
- let mut nf = f.clone();
- nf.verts = SmallVec::from_slice(&[prev, bv, c]);
- new_faces.push(nf);
+ if bad_edges_only {
+ let f = std::mem::replace(&mut old_faces[fi_old], Face::new(SmallVec::new(), 0, 0));
+ if let Some((ei, hits)) = best_edge {
+ did_split = true;
+ let a = tri[ei];
+ let b = tri[(ei + 1) % 3];
+ let c = tri[(ei + 2) % 3];
+ let mut prev = a;
+ for &(_, bv) in &hits {
+ let mut nf = f.clone();
+ nf.verts = SmallVec::from_slice(&[prev, bv, c]);
+ new_faces.push(nf);
+ next_is_new.push(true);
+ prev = bv;
+ }
+ let mut last_f = f;
+ last_f.verts = SmallVec::from_slice(&[prev, b, c]);
+ new_faces.push(last_f);
next_is_new.push(true);
- prev = bv;
+ } else {
+ new_faces.push(f);
+ next_is_new.push(false);
+ }
+ } else if let Some((ei, hits)) = best_edge {
+ let u = tri[ei];
+ let v = tri[(ei + 1) % 3];
+ let is_bad = bad_mask[u] && bad_mask[v] && {
+ let (lo, hi) = if u < v { (u as u64, v as u64) } else { (v as u64, u as u64) };
+ bad_edges.binary_search(&((lo << 32) | hi)).is_ok()
+ };
+ let hit_ids: SmallVec<[usize; 4]> = hits.iter().map(|&(_, bv)| bv).collect();
+ deferred_splits[fi_old] = Some((ei, hit_ids, is_bad));
+ }
+ }
+
+ if !bad_edges_only {
+ // Pair-match proposed splits on interior (`!is_bad`) edges: only commit if BOTH
+ // incident faces propose splitting the same edge at the exact same vertices.
+ let mut interior_props: Vec<(u64, usize, SmallVec<[usize; 4]>)> = Vec::new();
+ for (fi, prop) in deferred_splits.iter().enumerate() {
+ if let Some((ei, hit_ids, false)) = prop {
+ let fv = &mesh.faces[fi].verts;
+ let u = fv[*ei];
+ let v = fv[(*ei + 1) % 3];
+ let (ek, canon_hits) = if u < v {
+ (((u as u64) << 32) | (v as u64), hit_ids.clone())
+ } else {
+ let mut rev = hit_ids.clone();
+ rev.reverse();
+ (((v as u64) << 32) | (u as u64), rev)
+ };
+ interior_props.push((ek, fi, canon_hits));
+ }
+ }
+ interior_props.sort_unstable_by_key(|&(ek, fi, _)| (ek, fi));
+ let mut k = 0;
+ while k < interior_props.len() {
+ let ek = interior_props[k].0;
+ let mut m = k + 1;
+ while m < interior_props.len() && interior_props[m].0 == ek {
+ m += 1;
+ }
+ let matched_pair = (m - k) == 2 && interior_props[k].2 == interior_props[k + 1].2;
+ if !matched_pair {
+ for item in &interior_props[k..m] {
+ deferred_splits[item.1] = None;
+ }
+ }
+ k = m;
+ }
+
+ for (fi_old, f) in mesh.faces.drain(..).enumerate() {
+ if new_faces.len() < max_faces {
+ if let Some((ei, hit_ids, _)) = &deferred_splits[fi_old] {
+ did_split = true;
+ let tri = [f.verts[0], f.verts[1], f.verts[2]];
+ let a = tri[*ei];
+ let b = tri[(*ei + 1) % 3];
+ let c = tri[(*ei + 2) % 3];
+ let mut prev = a;
+ for &bv in hit_ids {
+ let mut nf = f.clone();
+ nf.verts = SmallVec::from_slice(&[prev, bv, c]);
+ new_faces.push(nf);
+ next_is_new.push(true);
+ prev = bv;
+ }
+ let mut last_f = f;
+ last_f.verts = SmallVec::from_slice(&[prev, b, c]);
+ new_faces.push(last_f);
+ next_is_new.push(true);
+ continue;
+ }
}
- let mut last_f = f;
- last_f.verts = SmallVec::from_slice(&[prev, b, c]);
- new_faces.push(last_f);
- next_is_new.push(true);
- } else {
new_faces.push(f);
next_is_new.push(false);
}
@@ -1934,6 +2306,7 @@ fn repair_seam_micro_edges(mesh: &mut PolyMesh) {
&& f.verts[2] != f.verts[0]
});
cancel_opposing_and_dup_tris(mesh);
+ unfold_coplanar_slivers(mesh);
eliminate_t_junctions(mesh, snap_tol.clamp(1e-5, 2e-5));
cancel_opposing_and_dup_tris(mesh);
} else if snap_tol > 1e-5 && snap_tol <= 2e-5 {
diff --git a/crates/forma-core/src/deform.rs b/crates/forma-core/src/deform.rs
index d81e963..c535002 100644
--- a/crates/forma-core/src/deform.rs
+++ b/crates/forma-core/src/deform.rs
@@ -214,6 +214,25 @@ pub fn solidify_mesh(
if in_n.len_sq() < 1e-12 {
has_pinched_face = true;
} else if (-in_n).dot(orig_n) <= 1e-4 {
+ // On densely sampled solids with flat Z caps (e.g. smooth lofts/revolves where
+ // vertical ring spacing <= wall thickness), 1-to-1 vertex-miter offset pushes the
+ // bottom/top cap rim past the adjacent side ring even though the surface curvature
+ // easily accommodates `thickness`. Fall back to offsetting the side walls with
+ // side-only normals and trimming/capping the inner cavity at the exact offset Z plane(s).
+ if thickness > 0.0 && inner_fac < -1e-9 {
+ if let Some(trimmed) = solidify_trimmed_z_caps(
+ mesh,
+ &keep_faces,
+ &v_disp,
+ thickness,
+ outer_fac,
+ inner_fac,
+ open_top,
+ op_id,
+ ) {
+ return Ok(trimmed);
+ }
+ }
return Err(format!(
"solidify thickness ({thickness}) inverts offset faces / self-intersects; reduce thickness"
));
@@ -253,6 +272,531 @@ pub fn solidify_mesh(
Ok(out)
}
+/// Check whether two 2D segments `(a, b)` and `(c, d)` properly cross.
+#[inline]
+fn segs_intersect_2d(a: (f64, f64), b: (f64, f64), c: (f64, f64), d: (f64, f64)) -> bool {
+ let orient = |p: (f64, f64), q: (f64, f64), r: (f64, f64)| -> f64 {
+ (q.0 - p.0) * (r.1 - p.1) - (q.1 - p.1) * (r.0 - p.0)
+ };
+ let o1 = orient(a, b, c);
+ let o2 = orient(a, b, d);
+ let o3 = orient(c, d, a);
+ let o4 = orient(c, d, b);
+ (o1 * o2 < 0.0) && (o3 * o4 < 0.0)
+}
+
+/// Returns `true` if a closed 2D polygon loop has any non-adjacent self-intersecting edges.
+fn loop_self_intersects_2d(pts: &[(f64, f64)]) -> bool {
+ let n = pts.len();
+ if n < 4 {
+ return false;
+ }
+ for i in 0..n {
+ let a = pts[i];
+ let b = pts[(i + 1) % n];
+ for j in (i + 2)..n {
+ if i == 0 && j == n - 1 {
+ continue;
+ }
+ let c = pts[j];
+ let d = pts[(j + 1) % n];
+ if segs_intersect_2d(a, b, c, d) {
+ return true;
+ }
+ }
+ }
+ false
+}
+
+/// Clip an open triangle mesh (with original face normals) against half-space `dir · p <= d_plane`
+/// (with `dir = ±Z`), cap the resulting open loop(s) on `z = z_plane` with outward normal `+dir`,
+/// and preserve the vertex-index map for untouched vertices (e.g. open-top rim vertices).
+fn clip_and_cap_wall_z(
+ wall: &PolyMesh,
+ orig_normals: &[Vec3],
+ orig_to_wall: &mut [Option<usize>],
+ z_plane: f64,
+ keep_above: bool,
+ cap_mat_id: u16,
+ op_id: u32,
+) -> Option<(PolyMesh, Vec<Vec3>)> {
+ let bb = wall.aabb();
+ if !bb.is_valid() {
+ return None;
+ }
+ let eps = (1e-6 * bb.size().len()).max(1e-10);
+ let dir = if keep_above { -Vec3::Z } else { Vec3::Z };
+ let sd: Vec<f64> = wall
+ .verts
+ .iter()
+ .map(|v| if keep_above { z_plane - v.z } else { v.z - z_plane })
+ .collect();
+
+ let mut out = PolyMesh::new();
+ out.materials = wall.materials.clone();
+ let mut out_normals: Vec<Vec3> = Vec::with_capacity(wall.faces.len());
+ let mut vert_map: Vec<Option<usize>> = vec![None; wall.verts.len()];
+ let mut edge_cut: std::collections::BTreeMap<(usize, usize), usize> = std::collections::BTreeMap::new();
+
+ let get_kept_v = |vi: usize, vert_map: &mut [Option<usize>], out: &mut PolyMesh| -> usize {
+ if let Some(id) = vert_map[vi] {
+ return id;
+ }
+ let mut p = wall.verts[vi];
+ if sd[vi].abs() <= eps {
+ p.z = z_plane;
+ }
+ let id = out.add_vert(p);
+ vert_map[vi] = Some(id);
+ id
+ };
+ let get_cut_v = |u: usize,
+ v: usize,
+ edge_cut: &mut std::collections::BTreeMap<(usize, usize), usize>,
+ vert_map: &mut [Option<usize>],
+ out: &mut PolyMesh| -> usize {
+ if sd[u].abs() <= eps {
+ return get_kept_v(u, vert_map, out);
+ }
+ if sd[v].abs() <= eps {
+ return get_kept_v(v, vert_map, out);
+ }
+ let key = edge_key(u, v);
+ if let Some(&id) = edge_cut.get(&key) {
+ return id;
+ }
+ let (a, b) = if u < v { (u, v) } else { (v, u) };
+ let t = (sd[a] / (sd[a] - sd[b])).clamp(0.0, 1.0);
+ let mut p = wall.verts[a].lerp(wall.verts[b], t);
+ p.z = z_plane;
+ let id = out.add_vert(p);
+ edge_cut.insert(key, id);
+ id
+ };
+
+ for (fi, f) in wall.faces.iter().enumerate() {
+ if f.verts.len() != 3 {
+ continue;
+ }
+ let tri = [f.verts[0], f.verts[1], f.verts[2]];
+ let orig_n = orig_normals[fi];
+ let mat_id = f.mat_id;
+ let emit = |out: &mut PolyMesh, out_normals: &mut Vec<Vec3>, a: usize, b: usize, c: usize| -> bool {
+ if a == b || b == c || c == a {
+ return true;
+ }
+ let n = (out.verts[b] - out.verts[a]).cross(out.verts[c] - out.verts[a]);
+ let nl = n.len();
+ if nl > 1e-14 && orig_n.len_sq() > 1e-12 && (n / nl).dot(orig_n) <= 1e-4 {
+ return false;
+ }
+ let id = out.add_face(smallvec![a, b, c], op_id, None);
+ out.faces[id].mat_id = mat_id;
+ out_normals.push(orig_n);
+ true
+ };
+
+ let kept = [sd[tri[0]] <= eps, sd[tri[1]] <= eps, sd[tri[2]] <= eps];
+ let n_kept = kept.iter().filter(|&&k| k).count();
+ match n_kept {
+ 0 => {}
+ 3 => {
+ if sd[tri[0]] < -eps || sd[tri[1]] < -eps || sd[tri[2]] < -eps {
+ let a = get_kept_v(tri[0], &mut vert_map, &mut out);
+ let b = get_kept_v(tri[1], &mut vert_map, &mut out);
+ let c = get_kept_v(tri[2], &mut vert_map, &mut out);
+ if !emit(&mut out, &mut out_normals, a, b, c) {
+ return None;
+ }
+ }
+ }
+ 1 => {
+ let k = if kept[0] { 0 } else if kept[1] { 1 } else { 2 };
+ let a_orig = tri[k];
+ let b_orig = tri[(k + 1) % 3];
+ let c_orig = tri[(k + 2) % 3];
+ if sd[a_orig] < -eps {
+ let a = get_kept_v(a_orig, &mut vert_map, &mut out);
+ let p_ab = get_cut_v(a_orig, b_orig, &mut edge_cut, &mut vert_map, &mut out);
+ let p_ac = get_cut_v(a_orig, c_orig, &mut edge_cut, &mut vert_map, &mut out);
+ if !emit(&mut out, &mut out_normals, a, p_ab, p_ac) {
+ return None;
+ }
+ }
+ }
+ 2 => {
+ let c_pos = if !kept[0] { 0 } else if !kept[1] { 1 } else { 2 };
+ let a_orig = tri[(c_pos + 1) % 3];
+ let b_orig = tri[(c_pos + 2) % 3];
+ let c_orig = tri[c_pos];
+ if sd[a_orig].abs() <= eps && sd[b_orig].abs() <= eps {
+ continue;
+ }
+ let a = get_kept_v(a_orig, &mut vert_map, &mut out);
+ let b = get_kept_v(b_orig, &mut vert_map, &mut out);
+ let p_bc = get_cut_v(b_orig, c_orig, &mut edge_cut, &mut vert_map, &mut out);
+ let p_ac = get_cut_v(a_orig, c_orig, &mut edge_cut, &mut vert_map, &mut out);
+ if !emit(&mut out, &mut out_normals, a, b, p_bc) {
+ return None;
+ }
+ if !emit(&mut out, &mut out_normals, a, p_bc, p_ac) {
+ return None;
+ }
+ }
+ _ => unreachable!(),
+ }
+ }
+
+ if out.faces.is_empty() {
+ return None;
+ }
+
+ for slot in orig_to_wall.iter_mut() {
+ *slot = slot.and_then(|old_vi| vert_map[old_vi]);
+ }
+
+ let plane_tol = (2.0 * eps).max(1e-9);
+ let mut directed: std::collections::BTreeMap<(usize, usize), usize> = std::collections::BTreeMap::new();
+ for f in &out.faces {
+ let n = f.verts.len();
+ for i in 0..n {
+ let u = f.verts[i];
+ let v = f.verts[(i + 1) % n];
+ *directed.entry((u, v)).or_insert(0) += 1;
+ }
+ }
+ let mut next_map: std::collections::BTreeMap<usize, Vec<usize>> = std::collections::BTreeMap::new();
+ let mut boundary_count = 0usize;
+ for (&(u, v), &cnt) in &directed {
+ let rev_cnt = directed.get(&(v, u)).copied().unwrap_or(0);
+ if cnt > rev_cnt
+ && (out.verts[u].z - z_plane).abs() <= plane_tol
+ && (out.verts[v].z - z_plane).abs() <= plane_tol
+ {
+ if cnt - rev_cnt != 1 {
+ return None;
+ }
+ next_map.entry(v).or_default().push(u);
+ boundary_count += 1;
+ }
+ }
+ if boundary_count < 3 {
+ return None;
+ }
+
+ let bu = Vec3::X;
+ let bv = dir.cross(bu);
+ let proj2d = |vi: usize| -> (f64, f64) { (out.verts[vi].dot(bu), out.verts[vi].dot(bv)) };
+
+ let mut loops: Vec<Vec<usize>> = Vec::new();
+ while let Some((&start, nexts)) = next_map.iter().find(|(_, vs)| !vs.is_empty()) {
+ let first_next = nexts[0];
+ let mut loop_v = vec![start];
+ if let Some(vs) = next_map.get_mut(&start) {
+ vs.remove(0);
+ }
+ let mut prev = start;
+ let mut cur = first_next;
+ let mut guard = boundary_count + 2;
+ while cur != start && guard > 0 {
+ guard -= 1;
+ loop_v.push(cur);
+ let cands = next_map.get_mut(&cur)?;
+ if cands.is_empty() {
+ return None;
+ }
+ let pick = if cands.len() == 1 {
+ 0
+ } else {
+ let p_prev = proj2d(prev);
+ let p_cur = proj2d(cur);
+ let in_ang = (p_prev.1 - p_cur.1).atan2(p_prev.0 - p_cur.0);
+ let mut best_i = 0usize;
+ let mut best_ang = f64::INFINITY;
+ for (ci, &nv) in cands.iter().enumerate() {
+ let pn = proj2d(nv);
+ let ang = (pn.1 - p_cur.1).atan2(pn.0 - p_cur.0);
+ let mut diff = ang - in_ang;
+ while diff <= 0.0 {
+ diff += std::f64::consts::TAU;
+ }
+ if diff < best_ang {
+ best_ang = diff;
+ best_i = ci;
+ }
+ }
+ best_i
+ };
+ let nxt = cands.remove(pick);
+ prev = cur;
+ cur = nxt;
+ }
+ if cur != start || loop_v.len() < 3 {
+ return None;
+ }
+ loops.push(loop_v);
+ }
+
+ let mut outers: Vec<(Vec<(f64, f64)>, Vec<usize>, f64)> = Vec::new();
+ let mut holes: Vec<(Vec<(f64, f64)>, Vec<usize>)> = Vec::new();
+ for lv in loops {
+ let pts: Vec<(f64, f64)> = lv.iter().map(|&vi| proj2d(vi)).collect();
+ if loop_self_intersects_2d(&pts) {
+ return None;
+ }
+ let area = crate::curves::poly_area_2d(&pts);
+ if area > 1e-12 {
+ outers.push((pts, lv, area));
+ } else if area < -1e-12 {
+ holes.push((pts, lv));
+ }
+ }
+ if outers.is_empty() {
+ return None;
+ }
+
+ let mut assigned_holes: Vec<Vec<(Vec<(f64, f64)>, Vec<usize>)>> = vec![Vec::new(); outers.len()];
+ for (h_pts, h_idx) in holes {
+ let probe = h_pts[0];
+ let mut best_outer: Option<(usize, f64)> = None;
+ for (oi, (o_pts, _, o_area)) in outers.iter().enumerate() {
+ if crate::curves::pt_in_poly_2d(probe, o_pts) {
+ if best_outer.is_none_or(|(_, ba)| *o_area < ba) {
+ best_outer = Some((oi, *o_area));
+ }
+ }
+ }
+ let oi = best_outer?.0;
+ assigned_holes[oi].push((h_pts, h_idx));
+ }
+
+ for ((o_pts, o_idx, _), o_holes) in outers.into_iter().zip(assigned_holes.into_iter()) {
+ let cap_tris = crate::curves::triangulate_polygon_with_holes_2d(&o_pts, &o_idx, &o_holes);
+ if cap_tris.is_empty() {
+ return None;
+ }
+ for [a, b, c] in cap_tris {
+ let fi = out.add_face(smallvec![a, b, c], op_id, None);
+ out.faces[fi].mat_id = cap_mat_id;
+ out_normals.push(dir);
+ }
+ }
+
+ Some((out, out_normals))
+}
+
+/// Planar-trimmed cavity fallback for `solidify_mesh` on solids with flat Z bottom/top caps
+/// meeting densely spaced side rings (where 1-to-1 vertex-miter offset folds the cap rim past
+/// the adjacent side ring). Offsets side faces along side-only pseudonormals and trims/caps the
+/// inner cavity at exact offset Z planes (`z_min + inward` / `z_max - inward`).
+#[allow(clippy::too_many_arguments)]
+fn solidify_trimmed_z_caps(
+ mesh: &PolyMesh,
+ keep_faces: &[usize],
+ outer_v_disp: &[Vec3],
+ thickness: f64,
+ outer_fac: f64,
+ inner_fac: f64,
+ open_top: bool,
+ op_id: u32,
+) -> Option<PolyMesh> {
+ let bb = mesh.aabb();
+ let z_tol = (1e-4 * bb.size().z).max(1e-9);
+ let inward = thickness * (-inner_fac);
+ if inward <= 1e-12 || inward >= bb.size().z - 2.0 * z_tol {
+ return None;
+ }
+
+ let mut bot_faces: Vec<usize> = Vec::new();
+ let mut top_faces: Vec<usize> = Vec::new();
+ let mut side_faces: Vec<usize> = Vec::with_capacity(keep_faces.len());
+ for &fi in keep_faces {
+ let f = &mesh.faces[fi];
+ let n = mesh.face_normal(fi);
+ let z_avg = f.verts.iter().map(|&vi| mesh.verts[vi].z).sum::<f64>() / (f.verts.len().max(1) as f64);
+ let all_bot = f.verts.iter().all(|&vi| (mesh.verts[vi].z - bb.min.z).abs() < z_tol);
+ let all_top = f.verts.iter().all(|&vi| (mesh.verts[vi].z - bb.max.z).abs() < z_tol);
+ if (n.z < -0.85 && (z_avg - bb.min.z).abs() < z_tol) || (n.len_sq() < 1e-12 && all_bot) {
+ bot_faces.push(fi);
+ } else if !open_top
+ && ((n.z > 0.85 && (z_avg - bb.max.z).abs() < z_tol) || (n.len_sq() < 1e-12 && all_top))
+ {
+ top_faces.push(fi);
+ } else {
+ side_faces.push(fi);
+ }
+ }
+ if side_faces.is_empty() || (bot_faces.is_empty() && top_faces.is_empty()) {
+ return None;
+ }
+
+ let z_floor = if !bot_faces.is_empty() { Some(bb.min.z + inward) } else { None };
+ let z_ceil = if !top_faces.is_empty() { Some(bb.max.z - inward) } else { None };
+ if let (Some(zf), Some(zc)) = (z_floor, z_ceil) {
+ if zf >= zc - 2.0 * z_tol {
+ return None;
+ }
+ }
+
+ let nv = mesh.verts.len();
+ let mut v_norm = vec![Vec3::ZERO; nv];
+ let mut v_face_normals: Vec<Vec<Vec3>> = vec![Vec::new(); nv];
+ for &fi in &side_faces {
+ let f = &mesh.faces[fi];
+ let fnrm = mesh.face_normal(fi);
+ if fnrm.len_sq() < 1e-12 {
+ continue;
+ }
+ let k = f.verts.len();
+ for ci in 0..k {
+ let vi = f.verts[ci];
+ let p = mesh.verts[vi];
+ let prev = mesh.verts[f.verts[(ci + k - 1) % k]];
+ let next = mesh.verts[f.verts[(ci + 1) % k]];
+ let e1 = (prev - p).normalized();
+ let e2 = (next - p).normalized();
+ let ang = e1.dot(e2).clamp(-1.0, 1.0).acos().max(1e-4);
+ v_norm[vi] += fnrm * ang;
+ v_face_normals[vi].push(fnrm);
+ }
+ }
+ let mut v_disp_side = vec![Vec3::ZERO; nv];
+ for vi in 0..nv {
+ let n = v_norm[vi].normalized();
+ if n.len_sq() < 1e-12 {
+ continue;
+ }
+ let mut min_dot = 1.0f64;
+ for &fnrm in &v_face_normals[vi] {
+ let d = n.dot(fnrm);
+ if d > 0.1 {
+ min_dot = min_dot.min(d);
+ }
+ }
+ let miter = (1.0 / min_dot.max(0.45)).clamp(1.0, 2.2);
+ v_disp_side[vi] = n * (thickness * miter);
+ }
+
+ let mut wall = PolyMesh::new();
+ wall.materials = mesh.materials.clone();
+ let mut orig_to_wall: Vec<Option<usize>> = vec![None; nv];
+ let mut wall_orig_normals: Vec<Vec3> = Vec::with_capacity(side_faces.len() * 2);
+ for &fi in &side_faces {
+ let f = &mesh.faces[fi];
+ let mat_id = f.mat_id;
+ for [a, b, c] in mesh.triangulate_face(fi) {
+ let orig_n = (mesh.verts[b] - mesh.verts[a])
+ .cross(mesh.verts[c] - mesh.verts[a])
+ .normalized();
+ let mut tv = [0usize; 3];
+ for (slot, &vi) in [a, b, c].iter().enumerate() {
+ tv[slot] = match orig_to_wall[vi] {
+ Some(id) => id,
+ None => {
+ let p_in = mesh.verts[vi] + v_disp_side[vi] * inner_fac;
+ let id = wall.add_vert(p_in);
+ orig_to_wall[vi] = Some(id);
+ id
+ }
+ };
+ }
+ let nfi = wall.add_face(smallvec![tv[0], tv[1], tv[2]], op_id, None);
+ wall.faces[nfi].mat_id = mat_id;
+ wall_orig_normals.push(orig_n);
+ }
+ }
+
+ if let Some(zf) = z_floor {
+ let bot_mat = mesh.faces[bot_faces[0]].mat_id;
+ let (clipped, normals) =
+ clip_and_cap_wall_z(&wall, &wall_orig_normals, &mut orig_to_wall, zf, true, bot_mat, op_id)?;
+ wall = clipped;
+ wall_orig_normals = normals;
+ }
+ if let Some(zc) = z_ceil {
+ let top_mat = mesh.faces[top_faces[0]].mat_id;
+ let (clipped, normals) =
+ clip_and_cap_wall_z(&wall, &wall_orig_normals, &mut orig_to_wall, zc, false, top_mat, op_id)?;
+ wall = clipped;
+ let _ = normals;
+ }
+
+ let mut out = PolyMesh::new();
+ out.materials = mesh.materials.clone();
+ out.smooth_angle_deg = mesh.smooth_angle_deg;
+ out.weighted_normals = mesh.weighted_normals;
+
+ let mut outer_map: Vec<Option<usize>> = vec![None; nv];
+ let mut dir_count: std::collections::BTreeMap<(usize, usize), usize> = std::collections::BTreeMap::new();
+ for &fi in keep_faces {
+ let f = &mesh.faces[fi];
+ let k = f.verts.len();
+ let mut ov: SmallVec<[usize; 4]> = SmallVec::with_capacity(k);
+ for &vi in &f.verts {
+ let oid = match outer_map[vi] {
+ Some(id) => id,
+ None => {
+ let p_out = mesh.verts[vi] + outer_v_disp[vi] * outer_fac;
+ let id = out.add_vert(p_out);
+ outer_map[vi] = Some(id);
+ id
+ }
+ };
+ ov.push(oid);
+ }
+ let ofi = out.add_face(ov, op_id, Some("outer"));
+ out.faces[ofi].mat_id = f.mat_id;
+ for t in &f.tags {
+ out.faces[ofi].add_tag(t.clone());
+ }
+ let orig_n = mesh.face_normal(fi);
+ if orig_n.len_sq() > 1e-12 && out.face_normal(ofi).dot(orig_n) <= 1e-4 {
+ return None;
+ }
+ for ci in 0..k {
+ let a = f.verts[ci];
+ let b = f.verts[(ci + 1) % k];
+ *dir_count.entry((a, b)).or_insert(0) += 1;
+ }
+ }
+
+ let inner_base = out.verts.len();
+ for &v in &wall.verts {
+ out.add_vert(v);
+ }
+ for f in &wall.faces {
+ let mut iv: SmallVec<[usize; 4]> = f.verts.iter().map(|&vi| inner_base + vi).collect();
+ iv.reverse();
+ let ifi = out.add_face(iv, op_id, Some("cavity"));
+ out.faces[ifi].mat_id = f.mat_id;
+ }
+
+ for (&(a, b), &cnt) in &dir_count {
+ if cnt == 1 && !dir_count.contains_key(&(b, a)) {
+ let oa = outer_map[a]?;
+ let ob = outer_map[b]?;
+ let ia = inner_base + orig_to_wall[a]?;
+ let ib = inner_base + orig_to_wall[b]?;
+ out.add_face(smallvec![ob, oa, ia, ib], op_id, Some("rim"));
+ }
+ }
+
+ out.ensure_outward_winding();
+ let inv = crate::MeshInvariants::compute(&out);
+ if !inv.watertight
+ || !inv.consistent_winding
+ || inv.non_manifold_edges != 0
+ || inv.boundary_edges != 0
+ || inv.signed_volume <= 0.0
+ {
+ return None;
+ }
+ if crate::boolean::check_self_intersections(&out, 4_000_000) == crate::boolean::OverlapCheck::Overlap {
+ return None;
+ }
+ Some(out)
+}
+
/// Non-linear Simple Deform modifiers (`bend`, `twist`, `taper`) matching Blender's SimpleDeform math.
pub fn deform_simple(
mesh: &PolyMesh,
diff --git a/crates/forma-core/tests/kernel_tests.rs b/crates/forma-core/tests/kernel_tests.rs
index 5095959..212db12 100644
--- a/crates/forma-core/tests/kernel_tests.rs
+++ b/crates/forma-core/tests/kernel_tests.rs
@@ -1150,3 +1150,142 @@ fn test_deform_curve_on_3d_bezier_has_no_false_self_intersection() {
let inv = s.set_part("curved", curved).expect("smooth curved beam must pass strict manifold check");
assert!(inv.is_valid_solid());
}
+
+#[test]
+fn test_issue_78_high_res_twisted_loft_shell_and_cut() {
+ use forma_core::boolean::has_self_intersections;
+ use std::f64::consts::PI;
+
+ let side = 0.20_f64;
+ let r_corner = 0.03_f64;
+ let inr = side / (2.0 * 3.0_f64.sqrt());
+ let cd = 2.0 * (inr - r_corner);
+ let levels = [0.0_f64, 0.10, 0.20, 0.30];
+
+ // Exact rounded-equilateral-triangle polar radius sampler from issue #78
+ let polar_radii = |n: usize, flip: bool, rr: f64| -> Vec<f64> {
+ let samples = 240usize;
+ let mut boundary: Vec<(f64, f64)> = Vec::with_capacity(3 * samples);
+ for k in 0..3 {
+ let t = (90.0 + 120.0 * (k as f64) + if flip { 180.0 } else { 0.0 }).to_radians();
+ let (cx, cy) = (cd * t.cos(), cd * t.sin());
+ for j in 0..samples {
+ let a = t - 60.0_f64.to_radians() + 120.0_f64.to_radians() * (j as f64) / (samples as f64);
+ boundary.push((cx + rr * a.cos(), cy + rr * a.sin()));
+ }
+ }
+ let m = boundary.len();
+ (0..n)
+ .map(|i| {
+ let phi = 2.0 * PI * (i as f64) / (n as f64);
+ let (dx, dy) = (phi.cos(), phi.sin());
+ let mut best = f64::INFINITY;
+ for j in 0..m {
+ let (x1, y1) = boundary[j];
+ let (x2, y2) = boundary[(j + 1) % m];
+ let (ex, ey) = (x2 - x1, y2 - y1);
+ let den = dx * ey - dy * ex;
+ if den.abs() < 1e-15 {
+ continue;
+ }
+ let t = (x1 * ey - y1 * ex) / den;
+ let u = (x1 * dy - y1 * dx) / den;
+ if t > 0.0 && (-1e-9..=1.0 + 1e-9).contains(&u) && t < best {
+ best = t;
+ }
+ }
+ best
+ })
+ .collect()
+ };
+
+ let build_sections = |n: usize, sub: usize, rr: f64, z0: f64, ztop: f64| -> Vec<(f64, Vec<(f64, f64)>)> {
+ let ra = polar_radii(n, false, rr);
+ let rb = polar_radii(n, true, rr);
+ let mut raw: Vec<(f64, Vec<f64>)> = Vec::new();
+ for l in 0..3 {
+ let (a, b) = if l % 2 == 0 { (&ra, &rb) } else { (&rb, &ra) };
+ for s in 0..sub {
+ let f = (s as f64) / (sub as f64);
+ let w = 0.5 - 0.5 * (PI * f).cos();
+ let zl = (levels[l] + f * (levels[l + 1] - levels[l])).max(z0);
+ let rs: Vec<f64> = (0..n).map(|i| a[i] * (1.0 - w) + b[i] * w).collect();
+ raw.push((zl, rs));
+ }
+ }
+ raw.push((if ztop > levels[3] { ztop } else { levels[3] }, rb));
+ let mut dedup: Vec<(f64, Vec<f64>)> = Vec::new();
+ for (z, r) in raw {
+ if let Some(prev) = dedup.last_mut() {
+ if (prev.0 - z).abs() < 1e-9 {
+ *prev = (z, r);
+ continue;
+ }
+ }
+ dedup.push((z, r));
+ }
+ dedup
+ .into_iter()
+ .map(|(z, rs)| {
+ let z_r = (z * 1e5).round() * 1e-5;
+ let poly: Vec<(f64, f64)> = (0..n)
+ .map(|i| {
+ let phi = 2.0 * PI * (i as f64) / (n as f64);
+ let x = (rs[i] * phi.cos() * 1e5).round() * 1e-5;
+ let y = (rs[i] * phi.sin() * 1e5).round() * 1e-5;
+ (x, y)
+ })
+ .collect();
+ (z_r, poly)
+ })
+ .collect()
+ };
+
+ // Part 1: shell(0.01) must succeed even when vertical section spacing dz <= thickness (SUB >= 9..15)
+ for (n, sub) in [(48usize, 9usize), (48, 10), (48, 12), (48, 15), (96, 12)] {
+ let outer = forma_core::primitives::make_loft(&build_sections(n, sub, r_corner, 0.0, 0.30), n, 1).unwrap();
+ for open_top in [true, false] {
+ let shelled = forma_core::ops::shell_solid(&outer, 0.01, open_top, 2)
+ .unwrap_or_else(|e| panic!("shell(0.01, open_top={open_top}) failed at N={n} SUB={sub}: {e}"));
+ let inv = MeshInvariants::compute(&shelled);
+ assert!(
+ inv.is_valid_solid() && inv.genus == 0 && !has_self_intersections(&shelled),
+ "invalid shell(0.01, open_top={open_top}) at N={n} SUB={sub}: {inv:?}"
+ );
+ }
+ }
+ // Excessive thickness (> 30 mm corner radius) must still be cleanly rejected
+ let outer_48 = forma_core::primitives::make_loft(&build_sections(48, 12, r_corner, 0.0, 0.30), 48, 3).unwrap();
+ assert!(
+ forma_core::ops::shell_solid(&outer_48, 0.045, true, 4).is_err(),
+ "shell exceeding corner radius must still return Err"
+ );
+
+ // Part 2: outer_loft | cut(inner_loft) across previously failing (N, SUB) combinations
+ for (n, sub) in [
+ (32usize, 8usize),
+ (32, 12),
+ (48, 12),
+ (64, 6),
+ (64, 10),
+ (64, 12),
+ (96, 6),
+ (96, 8),
+ (96, 10),
+ (96, 11),
+ (96, 12),
+ (128, 6),
+ (128, 10),
+ (128, 12),
+ ] {
+ let outer = forma_core::primitives::make_loft(&build_sections(n, sub, r_corner, 0.0, 0.30), n, 10).unwrap();
+ let inner = forma_core::primitives::make_loft(&build_sections(n, sub, r_corner - 0.01, 0.01, 0.32), n, 11).unwrap();
+ let vase = forma_core::boolean::boolean_op(&outer, &inner, BoolOp::Difference, None, 12)
+ .unwrap_or_else(|e| panic!("loft cut failed at N={n} SUB={sub}: {e}"));
+ let inv = MeshInvariants::compute(&vase);
+ assert!(
+ inv.is_valid_solid() && inv.genus == 0 && !has_self_intersections(&vase),
+ "invalid loft cut at N={n} SUB={sub}: {inv:?}"
+ );
+ }
+}
diff --git a/crates/forma-lang/tests/audit_regressions.rs b/crates/forma-lang/tests/audit_regressions.rs
index fb09c58..17eb347 100644
--- a/crates/forma-lang/tests/audit_regressions.rs
+++ b/crates/forma-lang/tests/audit_regressions.rs
@@ -295,3 +295,40 @@ fn remove_part_keeps_last_modified_on_remaining_part_and_step_triangulates_nonpl
assert!(!step.contains("DIRECTION('',(0.00000000,0.00000000,0.00000000))"));
assert!(step.contains("CLOSED_SHELL"));
}
+
+#[test]
+fn issue_80_subsurfed_loft_add_cone_left_and_right_valid_solids() {
+ use forma_core::boolean::has_self_intersections;
+
+ let case_a = r#"
+def egg(cz, rz, ry, n=14) = [(-cz - rz * cos(2 * pi * i / n), ry * sin(2 * pi * i / n)) for i in range(n)]
+_s = loft([(-0.64, egg(0.58, 0.08, 0.07)), (-0.57, egg(0.57, 0.20, 0.17)), (-0.40, egg(0.57, 0.26, 0.23)), (-0.15, egg(0.58, 0.28, 0.26))], segs=14) | rot(0, 90, 0) | subsurf(1)
+left = _s | add(cone(0.05, 0.11, 0.44, segs=10, z0=0.08, at=(-0.43, -0.15, 0)))
+right = _s | add(cone(0.05, 0.11, 0.44, segs=10, z0=0.08, at=(-0.43, 0.15, 0)))
+"#;
+ let case_b = r#"
+def egg(cz, rz, ry, n=14) = [(-cz - rz * cos(2 * pi * i / n), ry * sin(2 * pi * i / n)) for i in range(n)]
+_s = loft([(-0.15, egg(0.55, 0.29, 0.26)), (0.08, egg(0.58, 0.32, 0.27)), (0.24, egg(0.60, 0.33, 0.26)), (0.38, egg(0.59, 0.29, 0.23)), (0.48, egg(0.56, 0.20, 0.17))], segs=14) | rot(0, 90, 0) | subsurf(1)
+left = _s | add(cone(0.045, 0.085, 0.40, segs=12, z0=0.08, at=(0.27, -0.13, 0)))
+right = _s | add(cone(0.045, 0.085, 0.40, segs=12, z0=0.08, at=(0.27, 0.13, 0)))
+"#;
+
+ for (label, script) in [("case_a_hole", case_a), ("case_b_flip", case_b)] {
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+ eval_script(&mut s, Dialect::Pipe, script)
+ .unwrap_or_else(|e| panic!("issue #80 {label} failed in strict mode: {e}"));
+ let left = s.get_part("left").expect("left part");
+ let right = s.get_part("right").expect("right part");
+ let inv_l = MeshInvariants::compute(left);
+ let inv_r = MeshInvariants::compute(right);
+ assert!(inv_l.is_valid_solid() && inv_l.genus == 0 && !has_self_intersections(left), "{label} left: {inv_l:?}");
+ assert!(inv_r.is_valid_solid() && inv_r.genus == 0 && !has_self_intersections(right), "{label} right: {inv_r:?}");
+ assert!(
+ (inv_l.volume - inv_r.volume).abs() < 1e-4,
+ "{label} mirror volumes diverged: left={} right={}",
+ inv_l.volume,
+ inv_r.volume
+ );
+ }
+}
diff --git a/wasm/forma.wasm b/wasm/forma.wasm
index ee1c701..2c858cd 100755
Binary files a/wasm/forma.wasm and b/wasm/forma.wasm differ