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: harden boolean repair/batching, bevel/solidify guards, strict kwargs, clamp warnings, and honest STEP docs (Fixes #2, Fixes #5)

wrong-nebulaead121e73d28
diff --git a/AGENTS.md b/AGENTS.md
index cc45d12..f6fe56f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -33,7 +33,7 @@ Add to your MCP client config (Claude Code, Cursor, Codex, Antigravity, etc.)
| `eval` | Execute transactional `Forma-Pipe` code (`strict: true` auto-rolls back any non-manifold result); returns a ~100-token spatial diff (`WT`, `NM`, `g` genus, `vol`, `bbox`, `size`, tags). |
| `inspect` | Inspect current scene invariants and bounding boxes without mutating state. |
| `tx` | O(1) copy-on-write state control: `checkpoint`, `rollback`, `undo`, `reset`. |
-| `export` | Export to `.glb` (PBR + triplanar UVs), `.step`, `.3mf`, `.stl`, `.obj`, or render a zero-GPU 4-view studio `.png` preview (`~20–75 KB`). |
+| `export` | Export to `.glb` (glTF 2.0 Y-up, PBR + UVs), faceted `.step` (planar faces), `.3mf`, `.stl`, `.obj`, or render a zero-GPU 4-view studio `.png` preview (`~20–75 KB`). |
---
@@ -94,4 +94,4 @@ forma spec --gbnf > forma_pipe.gbnf
- **Cutting through-holes cleanly:** Make cutting cylinders slightly taller than the target plate (e.g., `cyl(0.5, 1.0)` for a `0.4` thick plate) to avoid grazing coplanar caps.
- **Multi-hole patterns:** Pass `at=[(x1,y1,z1), (x2,y2,z2), ...]` in a single `| cut(...)` or `| add(...)` call—Forma automatically batches pairwise-disjoint booleans in one pass.
- **Sharp revolved/mechanical subsurf:** Use `subsurf(1, crease=true)` if you want smooth curvature without shrinking sharp rims.
-- **Exporting for downstream tools:** Use `.glb` for web/Blender/Three.js (includes PBR materials + triplanar UVs), `.step` for SolidWorks/Fusion 360/FreeCAD, `.3mf`/`.stl` for 3D printing, `.svg` for dimensioned blueprints, and `.blend` via Blender bridge.
+- **Exporting for downstream tools:** Use `.glb` for web/Blender/Three.js (glTF 2.0 Y-up, PBR materials + LSCM/triplanar UVs), faceted `.step` (watertight planar-face ISO 10303-21 solid; no analytic cylinders/NURBS) for reference/assembly import into SolidWorks/Fusion 360/FreeCAD, `.3mf`/`.stl` for 3D printing, `.svg` for dimensioned blueprints, and `.blend` via Blender bridge.
diff --git a/README.md b/README.md
index 2e66bf5..be220d0 100644
--- a/README.md
+++ b/README.md
@@ -1,12 +1,12 @@
# Forma
-**A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server.**
+**A 1.2 MB pure-Rust headless 3D polyhedral modeling engine built for AI agents — CLI, WASM, and MCP server.**
<p align="center">
<img src="assets/readme_hero.png" alt="Forma — Pure-Rust Rewrite of Headless Blender for AI Agents" width="100%" />
</p>
-Forma rewrites headless Blender's 3D modeling, boolean, and studio-preview workflow from scratch in pure Rust—replacing the 953 MB desktop stack and brittle `bpy` scripting with a compact declarative pipe language (`Forma-Pipe`), semantic edge/face selectors, guaranteed-manifold CSG booleans, transactional snapshots, and a built-in zero-GPU studio renderer.
+Forma replaces headless Blender's 3D mesh modeling, boolean, and studio-preview workflow for AI agents with a single pure-Rust binary—trading the 953 MB desktop stack and brittle `bpy` scripting for a compact declarative pipe language (`Forma-Pipe`), semantic edge/face selectors, strict-by-default manifold CSG booleans, transactional snapshots, and a built-in zero-GPU studio renderer.
| Metric | Stock Headless Blender 5.3 (`bpy`) | **Forma** | Improvement |
|---|---:|---:|---:|
@@ -22,10 +22,10 @@ Forma rewrites headless Blender's 3D modeling, boolean, and studio-preview workf
## Features
- **Declarative `Forma-Pipe` Language:** Chain primitives and ops cleanly (`box | bevel | shell | cut`) with semantic selectors (`vertical`, `top_rim`, `bottom_rim`, `outer_rim`, `top`, `sides`)—zero fragile integer vertex indices.
-- **Fast, Watertight Pure-Rust Kernel:** Double-precision polyhedral B-rep, BVH-localized Möller-guarded booleans, automatic batch CSG for multi-hole patterns, zero-error Link-Condition coplanar mesh simplification, ring-preserving bevels, shell, crease-aware Catmull-Clark subsurf, `pipe`, `loft`, helical `thread`, `sweep`, `text3d`, and `pattern_linear`/`pattern_radial`.
+- **Fast, Watertight Pure-Rust Kernel:** Double-precision polyhedral mesh kernel (watertight manifold polygons/triangles), BVH-localized booleans with automatic batch chunking & fallback for multi-hole patterns, Link-Condition coplanar mesh simplification, ring-preserving bevels, shell/solidify, crease-aware Catmull-Clark subsurf, `pipe`, `loft` (`segs` 8..128), helical `thread`, `sweep`, `text3d`, and `pattern_linear`/`pattern_radial`.
- **Spatial Constraints & Queries:** Relational placement (`| on(base)`, `| align(axis, min|center|max, val)`), exact 3D `clearance(a, b)`, 2D `section(part, z)` loop/area queries, and Euler genus (`g`) diagnostics.
- **Zero-GPU Rendering & Blueprints:** Built-in 4-view (`Front / Right / Top / Iso`) studio PNG renderer with SSAO-lite + depth silhouettes + pure-Rust Deflate compression (`~20–75 KB` PNG in ~4 ms), plus dimensioned 1200×900 vector SVG technical blueprints (`forma draw`).
-- **Universal Import, Decimation & Export:** Pure-Rust `.glb`, `.obj`, and `.stl` importers (`load("item.glb")`), topology-preserving QEM mesh decimation (`| decimate(0.5)`), native `.glb` (PBR + triplanar UVs), ISO 10303-21 `.step`, `.3mf`, `.stl`, `.obj`, `.svg`, `.png`, and `.blend` (via optional Blender bridge).
+- **Universal Import, Decimation & Export:** Pure-Rust `.glb` (glTF 2.0 Y-up), `.obj`, and `.stl` importers (`load("item.glb")`), topology-preserving QEM mesh decimation (`| decimate(0.5)`), native `.glb` (PBR + LSCM/triplanar UVs), faceted ISO 10303-21 `.step` (watertight planar-face solid; no analytic cylinders/NURBS), `.3mf`, `.stl`, `.obj`, `.svg`, `.png`, and `.blend` (via optional Blender bridge).
- **Optional Headless Server (`forma-server`):** Separate opt-in HTTP/1.1 worker crate (`cargo build --release -p forma-server`, `1.4 MB` binary, `< 5 MB` scratch `Dockerfile`) with zero impact on the core `forma` CLI, `forma-mcp`, or `forma-3d` npm/WASM bundle.
---
diff --git a/SKILL.md b/SKILL.md
index ea2ccfb..b9d110e 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -1,11 +1,11 @@
---
name: forma
-description: Create, modify, inspect, render, and export watertight 3D B-rep models in milliseconds using Forma (a 1.2 MB pure-Rust rewrite of headless Blender). Use whenever a task involves 3D CAD/mesh generation, mechanical parts, enclosures, brackets, threads, lofts, pipes, booleans, .glb/.step/.3mf/.stl/.obj/.blend export, 4-view .png studio previews, or dimensioned .svg engineering blueprints.
+description: Create, modify, inspect, render, and export watertight 3D polyhedral models in milliseconds using Forma (a 1.2 MB pure-Rust headless 3D modeling engine). Use whenever a task involves 3D mesh/CAD generation, mechanical parts, enclosures, brackets, threads, lofts, pipes, booleans, .glb/faceted .step/.3mf/.stl/.obj/.blend export, 4-view .png studio previews, or dimensioned .svg engineering blueprints.
---
# Forma — Headless 3D Modeling Skill
-Forma is a 1.2 MB pure-Rust rewrite of headless Blender built for AI agents. It evaluates a compact declarative pipe language (`Forma-Pipe`) into guaranteed-manifold B-rep geometry in ~5–17 ms with zero GPU required.
+Forma is a 1.2 MB pure-Rust headless 3D modeling engine built for AI agents. It evaluates a compact declarative pipe language (`Forma-Pipe`) into strict, watertight polyhedral solid geometry in ~5–17 ms with zero GPU required.
## 1. Choose Your Interface
@@ -68,7 +68,7 @@ EOF
| `pipe(ro, ri, h)` | Hollow cylindrical tube |
| `extrude2d([(x,y), ...], z0, z1)` | Extrude closed 2D polygon |
| `revolve([(r,z), ...], segs=32)` | Lathe profile around Z (auto-closes at `r=0`) |
-| `loft([(z, [(x,y), ...]), ...])` | Multi-section smooth loft |
+| `loft([(z, [(x,y), ...]), ...], segs=24)` | Multi-section smooth loft (`segs` 8..128; warns if clamped) |
| `thread(r0, r1, pitch, turns)` | Watertight helical screw thread |
| `arc_tube(center=(x,y,z), rx=, rz=, start=-90, end=90, r=0.08)` | Curved handle / arc sweep |
| `tube([(x,y,z), ...], r=0.08)` | Polyline pipe sweep |
diff --git a/crates/forma-core/src/boolean.rs b/crates/forma-core/src/boolean.rs
index 482bb65..74cef6d 100644
--- a/crates/forma-core/src/boolean.rs
+++ b/crates/forma-core/src/boolean.rs
@@ -589,7 +589,7 @@ fn subdivide_tri_local(
let mut did_split = false;
for cut in cuts.iter() {
// Hard OOM guard on pathological/self-intersecting fuzzed meshes
- if scratch_a.len() >= 512 {
+ if scratch_a.len() >= 4096 {
break;
}
let prev_len = scratch_a.len();
@@ -1382,10 +1382,19 @@ fn eliminate_t_junctions(mesh: &mut PolyMesh, seg_tol: f64) {
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);
+ continue;
+ }
+ let min_dot = 1e-10 * orig_area2_sq;
+
let mut best_edge: Option<(usize, SmallVec<[(f64, usize); 4]>)> = None;
for ei in 0..3 {
let a = mesh.verts[tri[ei]];
let b = mesh.verts[tri[(ei + 1) % 3]];
+ let c_pt = mesh.verts[tri[(ei + 2) % 3]];
let ab = b - a;
let ab_len_sq = ab.len_sq();
if ab_len_sq < end_tol_sq * 4.0 {
@@ -1423,9 +1432,25 @@ fn eliminate_t_junctions(mesh: &mut PolyMesh, seg_tol: f64) {
filtered.push((t, bv));
}
}
+ // Orientation guard: reject any split that would invert or collapse a sub-triangle!
if !filtered.is_empty() {
- best_edge = Some((ei, filtered));
- break;
+ let mut valid_orient = true;
+ let mut prev_pt = a;
+ for &(_, bv) in &filtered {
+ let cur_pt = mesh.verts[bv];
+ if (cur_pt - prev_pt).cross(c_pt - prev_pt).dot(n_orig) <= min_dot {
+ valid_orient = false;
+ break;
+ }
+ prev_pt = cur_pt;
+ }
+ if valid_orient && (b - prev_pt).cross(c_pt - prev_pt).dot(n_orig) <= min_dot {
+ valid_orient = false;
+ }
+ if valid_orient {
+ best_edge = Some((ei, filtered));
+ break;
+ }
}
}
}
@@ -1494,9 +1519,9 @@ fn repair_seam_micro_edges(mesh: &mut PolyMesh) {
&& f.verts[2] != f.verts[0]
});
cancel_opposing_and_dup_tris(mesh);
- eliminate_t_junctions(mesh, snap_tol.max(1e-5));
+ eliminate_t_junctions(mesh, snap_tol.clamp(1e-5, 2e-5));
cancel_opposing_and_dup_tris(mesh);
- } else if snap_tol > 1e-5 {
+ } else if snap_tol > 1e-5 && snap_tol <= 2e-5 {
eliminate_t_junctions(mesh, snap_tol);
cancel_opposing_and_dup_tris(mesh);
}
@@ -1508,52 +1533,161 @@ fn prune_folded_flaps(mesh: &mut PolyMesh) {
if count_bad_edges(mesh) == 0 {
return;
}
- // Sort-based edge-count lookup (zero HashMap)
- let mut edges: Vec<u64> = Vec::with_capacity(mesh.faces.len() * 3);
- for f in &mesh.faces {
+ // Build edge -> incident faces lookup (zero HashMap via sort)
+ let nf = mesh.faces.len();
+ let mut edge_inc: Vec<(u64, usize)> = Vec::with_capacity(nf * 3);
+ for (fi, f) in mesh.faces.iter().enumerate() {
let n = f.verts.len();
for i in 0..n {
let u = f.verts[i];
let v = f.verts[(i + 1) % n];
if u != v {
let (a, b) = if u < v { (u, v) } else { (v, u) };
- edges.push(((a as u64) << 32) | (b as u64));
+ edge_inc.push((((a as u64) << 32) | (b as u64), fi));
}
}
}
- edges.sort_unstable();
- let mut counts: Vec<(u64, u32)> = Vec::with_capacity(edges.len() / 2 + 1);
+ edge_inc.sort_unstable();
+ let mut counts: Vec<(u64, u32, usize, usize)> = Vec::with_capacity(edge_inc.len() / 2 + 1);
let mut i = 0;
- while i < edges.len() {
- let k = edges[i];
+ while i < edge_inc.len() {
+ let k = edge_inc[i].0;
let mut j = i + 1;
- while j < edges.len() && edges[j] == k {
+ while j < edge_inc.len() && edge_inc[j].0 == k {
j += 1;
}
- counts.push((k, (j - i) as u32));
+ counts.push((k, (j - i) as u32, i, j));
i = j;
}
- let get_cnt = |u: usize, v: usize| -> u32 {
+ let edge_key_u64 = |u: usize, v: usize| -> u64 {
let (a, b) = if u < v { (u, v) } else { (v, u) };
- let k = ((a as u64) << 32) | (b as u64);
- counts.binary_search_by_key(&k, |&(ek, _)| ek).map_or(0, |idx| counts[idx].1)
+ ((a as u64) << 32) | (b as u64)
+ };
+ let lookup = |k: u64| -> (u32, usize, usize) {
+ counts
+ .binary_search_by_key(&k, |&(ek, _, _, _)| ek)
+ .map_or((0, 0, 0), |idx| (counts[idx].1, counts[idx].2, counts[idx].3))
};
- let mut to_remove: HashSet<usize> = HashSet::new();
- for (fi, f) in mesh.faces.iter().enumerate() {
+ let is_sliver = |fi: usize| -> bool {
+ let f = &mesh.faces[fi];
if f.verts.len() != 3 {
+ return false;
+ }
+ let pa = mesh.verts[f.verts[0]];
+ let pb = mesh.verts[f.verts[1]];
+ let pc = mesh.verts[f.verts[2]];
+ let area2 = (pb - pa).cross(pc - pa).len();
+ let max_e = (pb - pa).len().max((pc - pb).len()).max((pa - pc).len()).max(1e-12);
+ area2 / max_e < 2e-3
+ };
+
+ let mut to_remove: HashSet<usize> = HashSet::new();
+ let mut visited = vec![false; nf];
+ for seed in 0..nf {
+ if visited[seed] || !is_sliver(seed) {
+ continue;
+ }
+ let f = &mesh.faces[seed];
+ let es = [
+ edge_key_u64(f.verts[0], f.verts[1]),
+ edge_key_u64(f.verts[1], f.verts[2]),
+ edge_key_u64(f.verts[2], f.verts[0]),
+ ];
+ let cs = [lookup(es[0]).0, lookup(es[1]).0, lookup(es[2]).0];
+ // Seed must touch at least one boundary (1) edge
+ if !cs.iter().any(|&c| c == 1) {
+ continue;
+ }
+ // Fast path: classic single-triangle [1, >=3, >=3] flap
+ let mut cs_sorted = cs;
+ cs_sorted.sort_unstable();
+ if cs_sorted[0] == 1 && cs_sorted[1] >= 3 && cs_sorted[2] >= 3 {
+ visited[seed] = true;
+ to_remove.insert(seed);
+ continue;
+ }
+ // Generalized path: flood-fill small connected sliver-flap component (up to 16 tris)
+ // across internal count==2 edges. Valid to remove iff EVERY outer perimeter edge of
+ // the component has mesh count == 1 or >= 3 (leaves zero new host boundary edges!).
+ let mut comp: SmallVec<[usize; 16]> = SmallVec::new();
+ let mut queue: SmallVec<[usize; 16]> = SmallVec::new();
+ visited[seed] = true;
+ queue.push(seed);
+ let mut valid_comp = true;
+ while let Some(cur) = queue.pop() {
+ comp.push(cur);
+ if comp.len() > 16 {
+ valid_comp = false;
+ break;
+ }
+ let cf = &mesh.faces[cur];
+ for e_idx in 0..3 {
+ let ek = edge_key_u64(cf.verts[e_idx], cf.verts[(e_idx + 1) % 3]);
+ let (cnt, s, e) = lookup(ek);
+ if cnt == 2 {
+ let mut found_sliver_nbr = false;
+ for &(_, nbr) in &edge_inc[s..e] {
+ if nbr == cur {
+ continue;
+ }
+ if is_sliver(nbr) {
+ found_sliver_nbr = true;
+ if !visited[nbr] {
+ visited[nbr] = true;
+ queue.push(nbr);
+ }
+ }
+ }
+ if !found_sliver_nbr {
+ // Would expose a non-sliver host manifold edge!
+ valid_comp = false;
+ break;
+ }
+ }
+ }
+ if !valid_comp {
+ break;
+ }
+ }
+ if !valid_comp || comp.is_empty() {
continue;
}
- let [a, b, c] = [f.verts[0], f.verts[1], f.verts[2]];
- let mut cs = [get_cnt(a, b), get_cnt(b, c), get_cnt(c, a)];
- cs.sort_unstable();
- if cs[0] == 1 && cs[1] >= 3 && cs[2] >= 3 {
- let pa = mesh.verts[a];
- let pb = mesh.verts[b];
- let pc = mesh.verts[c];
- let area2 = (pb - pa).cross(pc - pa).len();
- let max_e = (pb - pa).len().max((pc - pb).len()).max((pa - pc).len()).max(1e-12);
- if area2 / max_e < 2e-3 {
+ // Verify external boundary of `comp`: must touch at least one count==1 and one count>=3 edge,
+ // and ZERO count==2 edges leaving `comp`.
+ let mut comp_edges: SmallVec<[u64; 32]> = SmallVec::new();
+ for &fi in &comp {
+ let cf = &mesh.faces[fi];
+ for e_idx in 0..3 {
+ comp_edges.push(edge_key_u64(cf.verts[e_idx], cf.verts[(e_idx + 1) % 3]));
+ }
+ }
+ comp_edges.sort_unstable();
+ let mut has_b = false;
+ let mut has_nm = false;
+ let mut touches_host_2 = false;
+ let mut ei = 0;
+ while ei < comp_edges.len() {
+ let ek = comp_edges[ei];
+ let mut ej = ei + 1;
+ while ej < comp_edges.len() && comp_edges[ej] == ek {
+ ej += 1;
+ }
+ if ej - ei == 1 {
+ let cnt = lookup(ek).0;
+ if cnt == 1 {
+ has_b = true;
+ } else if cnt >= 3 {
+ has_nm = true;
+ } else {
+ touches_host_2 = true;
+ break;
+ }
+ }
+ ei = ej;
+ }
+ if has_b && has_nm && !touches_host_2 {
+ for &fi in &comp {
to_remove.insert(fi);
}
}
@@ -1570,6 +1704,46 @@ fn prune_folded_flaps(mesh: &mut PolyMesh) {
}
}
+/// Fast manifold + consistent-winding check (returns number of bad undirected/unoriented edges).
+fn count_bad_or_unoriented_edges(mesh: &PolyMesh) -> usize {
+ if mesh.faces.is_empty() {
+ return 1;
+ }
+ let mut half_edges: Vec<(u64, i8)> = Vec::with_capacity(mesh.faces.len() * 3);
+ for f in &mesh.faces {
+ let n = f.verts.len();
+ for i in 0..n {
+ let u = f.verts[i];
+ let v = f.verts[(i + 1) % n];
+ if u == v {
+ continue;
+ }
+ if u < v {
+ half_edges.push((((u as u64) << 32) | (v as u64), 1));
+ } else {
+ half_edges.push((((v as u64) << 32) | (u as u64), -1));
+ }
+ }
+ }
+ half_edges.sort_unstable_by_key(|&(k, _)| k);
+ let mut bad = 0usize;
+ let mut i = 0;
+ while i < half_edges.len() {
+ let k = half_edges[i].0;
+ let mut j = i + 1;
+ let mut dir_sum = half_edges[i].1 as i32;
+ while j < half_edges.len() && half_edges[j].0 == k {
+ dir_sum += half_edges[j].1 as i32;
+ j += 1;
+ }
+ if (j - i) != 2 || dir_sum != 0 {
+ bad += 1;
+ }
+ i = j;
+ }
+ bad
+}
+
/// Execute a scale-invariant, tolerance-guided BVH-localized CSG boolean operation
/// between two closed solids, with post-assembly manifold repair and perturbation retries.
pub fn boolean_op(
@@ -1646,26 +1820,34 @@ pub fn boolean_op(
};
let tag_str = b_name.map(|n| format!("bool:{n}"));
- let (res, bad0) = run_bvh_csg(a_ref, b_ref, op, tag_str.as_deref(), op_id);
+ let (res, _) = run_bvh_csg(a_ref, b_ref, op, tag_str.as_deref(), op_id);
+ let bad0 = count_bad_or_unoriented_edges(&res);
if bad0 == 0 && !res.faces.is_empty() {
return Ok(unnormalize(res));
}
- // Deterministic perturbation retry on grazing curved seams
+ // Deterministic perturbation retry on grazing curved seams (only reached when exact pass has bad/unoriented edges)
let perturbations = [
- (Vec3::new(1.37e-5, -2.11e-5, 1.73e-5), 1.0 + 1.9e-5),
- (Vec3::new(-2.91e-5, 1.63e-5, -1.49e-5), 1.0 - 2.3e-5),
+ (Vec3::new(1.37e-5, -2.11e-5, 1.73e-5), 1.0 + 1.9e-5, (0.0, 0.0, 0.0)),
+ (Vec3::new(-2.91e-5, 1.63e-5, -1.49e-5), 1.0 - 2.3e-5, (0.0, 0.0, 0.0)),
+ (Vec3::new(3.13e-5, 2.71e-5, -2.29e-5), 1.0 + 3.7e-5, (0.013, -0.017, 0.011)),
+ (Vec3::new(-4.19e-5, -3.53e-5, 2.81e-5), 1.0 - 4.1e-5, (-0.019, 0.014, -0.016)),
];
let mut best = res;
let mut best_bad = bad0;
- for (shift, sc) in perturbations {
+ for (shift, sc, (rx, ry, rz)) in perturbations {
let mut bp = b_ref.clone();
let c = bp.aabb().center();
for v in &mut bp.verts {
- *v = c + (*v - c) * sc + shift;
+ let mut rel = (*v - c) * sc;
+ if rx != 0.0 || ry != 0.0 || rz != 0.0 {
+ rel = rel.rotate_euler_xyz_deg(rx, ry, rz);
+ }
+ *v = c + rel + shift;
}
- let (cand, bad) = run_bvh_csg(a_ref, &bp, op, tag_str.as_deref(), op_id);
+ let (cand, _) = run_bvh_csg(a_ref, &bp, op, tag_str.as_deref(), op_id);
+ let bad = count_bad_or_unoriented_edges(&cand);
if bad == 0 && !cand.faces.is_empty() {
return Ok(unnormalize(cand));
}
@@ -1678,9 +1860,38 @@ pub fn boolean_op(
Ok(unnormalize(best))
}
+/// Apply a pairwise-disjoint group of tools in one batch, automatically falling back to
+/// binary-split sub-batches (down to sequential cuts) if the combined batch yields any bad edges.
+fn apply_disjoint_group(
+ a: &PolyMesh,
+ group: &[&PolyMesh],
+ op: BoolOp,
+ b_name: Option<&str>,
+ op_id: u32,
+) -> Result<PolyMesh, String> {
+ if group.is_empty() {
+ return Ok(a.clone());
+ }
+ if group.len() == 1 {
+ return boolean_op(a, group[0], op, b_name, op_id);
+ }
+ let mut merged = group[0].clone();
+ for t in &group[1..] {
+ merged.append_mesh(t);
+ }
+ let cand = boolean_op(a, &merged, op, b_name, op_id)?;
+ if count_bad_or_unoriented_edges(&cand) == 0 && !cand.faces.is_empty() {
+ return Ok(cand);
+ }
+ // Automatic binary-split fallback so multi-hole batches never fail when sequential cuts pass!
+ let mid = group.len() / 2;
+ let left = apply_disjoint_group(a, &group[..mid], op, b_name, op_id)?;
+ apply_disjoint_group(&left, &group[mid..], op, b_name, op_id)
+}
+
/// Batch boolean of `a` with multiple tool meshes.
-/// Pairwise-disjoint tools are merged into a single BVH boolean pass (up to 4x faster for
-/// multi-hole patterns & multi-leg unions!), while overlapping tools fall back to sequential ops.
+/// Pairwise-disjoint tools are chunked (up to 4 tools / 256 faces per pass) into fast BVH boolean
+/// passes with automatic binary-split fallback on any grazing seam, while overlapping tools run sequentially.
pub fn boolean_batch(
a: &PolyMesh,
tools: &[PolyMesh],
@@ -1701,7 +1912,10 @@ pub fn boolean_batch(
}
return Ok(acc);
}
- // Partition tools into pairwise-disjoint batches
+ // Partition tools into bounded pairwise-disjoint batches (keeps 4-hole flanges in 1 pass
+ // while preventing 8-20+ hole rows from shattering 2 giant plate triangles with 500+ planes).
+ const MAX_BATCH_TOOLS: usize = 4;
+ const MAX_BATCH_FACES: usize = 256;
let bbs: Vec<Aabb> = tools.iter().map(|t| t.aabb()).collect();
let mut used = vec![false; tools.len()];
let mut acc = a.clone();
@@ -1710,19 +1924,24 @@ pub fn boolean_batch(
continue;
}
used[i] = true;
- let mut batch = tools[i].clone();
+ let mut group: Vec<&PolyMesh> = vec![&tools[i]];
+ let mut group_faces = tools[i].faces.len();
let mut batch_bbs = vec![bbs[i]];
for j in (i + 1)..tools.len() {
- if used[j] {
+ if used[j] || group.len() >= MAX_BATCH_TOOLS {
+ continue;
+ }
+ if group_faces + tools[j].faces.len() > MAX_BATCH_FACES {
continue;
}
if !batch_bbs.iter().any(|bb| bb.overlaps(&bbs[j], 1e-4)) {
- batch.append_mesh(&tools[j]);
+ group.push(&tools[j]);
+ group_faces += tools[j].faces.len();
batch_bbs.push(bbs[j]);
used[j] = true;
}
}
- acc = boolean_op(&acc, &batch, op, b_name, op_id)?;
+ acc = apply_disjoint_group(&acc, &group, op, b_name, op_id)?;
}
Ok(acc)
}
@@ -2024,3 +2243,77 @@ pub fn has_overlapping_components(mesh: &PolyMesh) -> bool {
false
}
+
+/// Fast BVH-accelerated geometric self-intersection detector for a single mesh.
+/// Checks every pair of non-adjacent triangles (sharing zero vertex indices and no coincident
+/// vertex coordinates) whose AABBs overlap, returning `true` if any pair crosses or overlaps in 3D.
+pub fn has_self_intersections(mesh: &PolyMesh) -> bool {
+ if mesh.faces.len() < 2 {
+ return false;
+ }
+ let bb = mesh.aabb();
+ if !bb.is_valid() {
+ return false;
+ }
+ let mesh_scale = bb.size().x.max(bb.size().y).max(bb.size().z).max(1e-9);
+ let aabb_eps = 1e-6 * mesh_scale;
+ let weld_sq = (1e-5 * mesh_scale).powi(2);
+
+ let mut tris: Vec<Tri> = Vec::with_capacity(mesh.faces.len() * 2);
+ let mut tri_v: Vec<[usize; 3]> = Vec::with_capacity(mesh.faces.len() * 2);
+ for fi in 0..mesh.faces.len() {
+ for [a, b, c] in mesh.triangulate_face(fi) {
+ if a == b || b == c || c == a {
+ continue;
+ }
+ if let Some(t) = Tri::from_verts(mesh.verts[a], mesh.verts[b], mesh.verts[c], 0, 0, 0) {
+ tris.push(t);
+ tri_v.push([a, b, c]);
+ }
+ }
+ }
+ let nt = tris.len();
+ if nt < 2 {
+ return false;
+ }
+ let bvh = TriBvh::build(&tris);
+ let mut hits: Vec<u32> = Vec::with_capacity(32);
+
+ for i in 0..nt {
+ let vi = tri_v[i];
+ let ti = &tris[i];
+ bvh.query_aabb(&ti.aabb, aabb_eps, &mut hits);
+ for &j_u32 in &hits {
+ let j = j_u32 as usize;
+ if j <= i {
+ continue;
+ }
+ let vj = tri_v[j];
+ // Skip topologically adjacent triangles sharing any vertex
+ if vi[0] == vj[0] || vi[0] == vj[1] || vi[0] == vj[2]
+ || vi[1] == vj[0] || vi[1] == vj[1] || vi[1] == vj[2]
+ || vi[2] == vj[0] || vi[2] == vj[1] || vi[2] == vj[2]
+ {
+ continue;
+ }
+ let tj = &tris[j];
+ // Skip triangles meeting at a coincident unwelded vertex
+ let mut shares_pos = false;
+ 'pos_chk: for p in &ti.v {
+ for q in &tj.v {
+ if (*p - *q).len_sq() <= weld_sq {
+ shares_pos = true;
+ break 'pos_chk;
+ }
+ }
+ }
+ if shares_pos {
+ continue;
+ }
+ if tris_overlap_3d(ti, tj, mesh_scale) {
+ return true;
+ }
+ }
+ }
+ false
+}
diff --git a/crates/forma-core/src/deform.rs b/crates/forma-core/src/deform.rs
index 75538be..50aeaa9 100644
--- a/crates/forma-core/src/deform.rs
+++ b/crates/forma-core/src/deform.rs
@@ -97,12 +97,13 @@ pub fn solidify_mesh(
}
let bb = mesh.aabb();
+ let z_tol = (1e-4 * bb.size().z).max(1e-9);
let mut keep_faces: Vec<usize> = Vec::with_capacity(mesh.faces.len());
for (fi, f) in mesh.faces.iter().enumerate() {
if open_top {
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);
- if n.z > 0.85 && (z_avg - bb.max.z).abs() < 1e-3 {
+ if n.z > 0.85 && (z_avg - bb.max.z).abs() < z_tol {
continue;
}
}
@@ -198,6 +199,18 @@ pub fn solidify_mesh(
let ifi = out.add_face(iv, op_id, Some("cavity"));
out.faces[ifi].mat_id = f.mat_id;
+ // Guard against excessive thickness folding/inverting outer or inner offset faces
+ let orig_n = mesh.face_normal(fi);
+ if orig_n.len_sq() > 1e-12 {
+ let out_n = out.face_normal(ofi);
+ let in_n = out.face_normal(ifi);
+ if out_n.dot(orig_n) <= 1e-4 || (-in_n).dot(orig_n) <= 1e-4 {
+ return Err(format!(
+ "solidify thickness ({thickness}) inverts offset faces / self-intersects; reduce thickness"
+ ));
+ }
+ }
+
for ci in 0..k {
let a = f.verts[ci];
let b = f.verts[(ci + 1) % k];
@@ -218,6 +231,11 @@ pub fn solidify_mesh(
}
out.ensure_outward_winding();
+ if out.faces.len() <= 8_000 && crate::boolean::has_self_intersections(&out) {
+ return Err(format!(
+ "solidify thickness ({thickness}) produces a self-intersecting shell; reduce thickness"
+ ));
+ }
Ok(out)
}
diff --git a/crates/forma-core/src/export.rs b/crates/forma-core/src/export.rs
index e3e0f47..af4d6da 100644
--- a/crates/forma-core/src/export.rs
+++ b/crates/forma-core/src/export.rs
@@ -599,7 +599,8 @@ fn zip_crc32(data: &[u8]) -> u32 {
!crc
}
-/// Export a PolyMesh to ISO 10303-21 STEP (AP214) bytes.
+/// Export a PolyMesh to faceted ISO 10303-21 STEP (AP214) bytes (watertight planar-face solid;
+/// no analytic cylindrical/NURBS surfaces).
pub fn write_step_bytes(mesh: &PolyMesh) -> Result<Vec<u8>, String> {
if mesh.faces.is_empty() || mesh.verts.is_empty() {
return Err("cannot export empty mesh to STEP".into());
@@ -608,7 +609,7 @@ pub fn write_step_bytes(mesh: &PolyMesh) -> Result<Vec<u8>, String> {
s.push_str(
"ISO-10303-21;\n\
HEADER;\n\
- FILE_DESCRIPTION(('Forma Pure-Rust Manifold B-Rep'),'2;1');\n\
+ FILE_DESCRIPTION(('Forma Pure-Rust Faceted Manifold Solid (Planar Faces)'),'2;1');\n\
FILE_NAME('forma_part.step','2026-12-03T00:00:00',('forma'),('forma-core 0.4'),'forma-core','forma','');\n\
FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }'));\n\
ENDSEC;\n\
@@ -735,7 +736,7 @@ pub fn write_step_bytes(mesh: &PolyMesh) -> Result<Vec<u8>, String> {
Ok(s.into_bytes())
}
-/// Export a PolyMesh to ISO 10303-21 STEP (AP214) manifold solid B-rep (`.step` / `.stp`).
+/// Export a PolyMesh to faceted ISO 10303-21 STEP (AP214) planar-face manifold solid (`.step` / `.stp`).
pub fn write_step(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
let bytes = write_step_bytes(mesh)?;
let f = File::create(path).map_err(|e| format!("create {}: {e}", path.display()))?;
diff --git a/crates/forma-core/src/lib.rs b/crates/forma-core/src/lib.rs
index c2f5eb1..2079ae7 100644
--- a/crates/forma-core/src/lib.rs
+++ b/crates/forma-core/src/lib.rs
@@ -1,13 +1,13 @@
-//! forma-core: Headless, transactional, agent-native 3D B-rep modeling kernel.
+//! forma-core: Headless, transactional, agent-native 3D polyhedral modeling kernel.
//!
//! Designed around:
-//! - Polyhedral B-rep with double-precision coordinates and persistent topological lineage/tags
+//! - Double-precision polyhedral meshes with persistent topological lineage/tags
//! - Semantic & geometric selectors (zero reliance on fragile integer indices)
-//! - Guaranteed-manifold CSG booleans with coplanar tie-breaking & T-junction elimination
-//! - Exact Catmull-Clark subdivision, polyhedral bevel, extrude, inset, revolve, sweep, shell
+//! - Tolerance-guided BVH-localized CSG booleans with coplanar tie-breaking, repair, and perturbation retry
+//! - Catmull-Clark subdivision, polyhedral bevel, extrude, inset, revolve, sweep, shell, solidify, deformers
//! - Copy-on-write (Arc) transactional snapshots/rollback and automatic topological invariants
//! - Compact (~100-token) spatial/topological observation & delta channel
-//! - Native binary GLB (glTF 2.0), OBJ, and binary STL export
+//! - Native binary GLB (glTF 2.0 Y-up), faceted STEP AP214, 3MF, OBJ, and binary STL export
pub mod boolean;
pub mod curves;
diff --git a/crates/forma-core/src/ops.rs b/crates/forma-core/src/ops.rs
index 92d1c9f..cd3e35c 100644
--- a/crates/forma-core/src/ops.rs
+++ b/crates/forma-core/src/ops.rs
@@ -202,12 +202,14 @@ fn try_bevel_vertical_prism(
let bb = mesh.aabb();
let z0 = bb.min.z;
let z1 = bb.max.z;
- if z1 - z0 < 1e-6 {
+ let h = z1 - z0;
+ if h < 1e-9 {
return None;
}
+ let z_tol = (1e-4 * h).max(1e-9);
// Find top face polygon
let top_faces: Vec<usize> = (0..mesh.faces.len())
- .filter(|&fi| mesh.face_normal(fi).z > 0.99 && (mesh.face_centroid(fi).z - z1).abs() < 1e-3)
+ .filter(|&fi| mesh.face_normal(fi).z > 0.99 && (mesh.face_centroid(fi).z - z1).abs() < z_tol)
.collect();
if top_faces.len() != 1 {
return None;
@@ -280,7 +282,7 @@ fn try_bevel_vertical_prism(
/// Extract ordered horizontal rings `(poly_xy, z)` from bottom face to top face on a Z-prism
/// (including prisms that already have a top or bottom bevel!). Returns `None` if mesh is not a layered Z-prism.
-fn extract_z_prism_rings(mesh: &PolyMesh, bot_fi: usize, top_fi: usize) -> Option<Vec<(Vec<(f64, f64)>, f64)>> {
+fn extract_z_prism_rings(mesh: &PolyMesh, bot_fi: usize, top_fi: usize, z_tol: f64) -> Option<Vec<(Vec<(f64, f64)>, f64)>> {
let bot_raw = &mesh.faces[bot_fi].verts;
let top_raw = &mesh.faces[top_fi].verts;
let n = bot_raw.len();
@@ -301,7 +303,7 @@ fn extract_z_prism_rings(mesh: &PolyMesh, bot_fi: usize, top_fi: usize) -> Optio
let mut pts = Vec::with_capacity(ring.len());
for &vi in ring {
let p = mesh.verts[vi];
- if (p.z - z).abs() > 1e-3 {
+ if (p.z - z).abs() > z_tol {
return None;
}
pts.push((p.x, p.y));
@@ -407,6 +409,118 @@ fn inset_ccw_poly(poly: &[(f64, f64)], inset_d: f64) -> Vec<(f64, f64)> {
out
}
+/// Compute a conservative upper bound on inward 2D polygon inset distance so opposite edges
+/// cannot cross and no edge can invert during `try_bevel_z_rims`.
+fn max_safe_poly_inset(poly: &[(f64, f64)]) -> f64 {
+ let n = poly.len();
+ if n < 3 {
+ return 0.0;
+ }
+ // Precompute miter directions matching `inset_ccw_poly`
+ let mut cx = 0.0;
+ let mut cy = 0.0;
+ for &(x, y) in poly {
+ cx += x;
+ cy += y;
+ }
+ cx /= n as f64;
+ cy /= n as f64;
+
+ let mut miters = Vec::with_capacity(n);
+ for i in 0..n {
+ let prev = poly[(i + n - 1) % n];
+ let curr = poly[i];
+ let next = poly[(i + 1) % n];
+ let e1 = (curr.0 - prev.0, curr.1 - prev.1);
+ let e2 = (next.0 - curr.0, next.1 - curr.1);
+ let l1 = e1.0.hypot(e1.1).max(1e-9);
+ let l2 = e2.0.hypot(e2.1).max(1e-9);
+ let n1 = (-e1.1 / l1, e1.0 / l1);
+ let n2 = (-e2.1 / l2, e2.0 / l2);
+ let denom = 1.0 + n1.0 * n2.0 + n1.1 * n2.1;
+ if denom > 0.1 {
+ miters.push(((n1.0 + n2.0) / denom, (n1.1 + n2.1) / denom));
+ } else {
+ let dx = cx - curr.0;
+ let dy = cy - curr.1;
+ let dl = dx.hypot(dy).max(1e-9);
+ miters.push((dx / dl, dy / dl));
+ }
+ }
+
+ let mut max_d = f64::INFINITY;
+ // 1. Edge-collapse bound: keep every edge >= 10% of its original length
+ for i in 0..n {
+ let j = (i + 1) % n;
+ let ex = poly[j].0 - poly[i].0;
+ let ey = poly[j].1 - poly[i].1;
+ let elen = ex.hypot(ey);
+ if elen < 1e-12 {
+ continue;
+ }
+ let tx = ex / elen;
+ let ty = ey / elen;
+ let shrink_rate = (miters[i].0 * tx + miters[i].1 * ty) - (miters[j].0 * tx + miters[j].1 * ty);
+ if shrink_rate > 1e-9 {
+ max_d = max_d.min(0.9 * elen / shrink_rate);
+ }
+ }
+
+ // 2. Opposite-edge clearance bound: prevent vertex/edge collisions across thin walls & rods
+ let point_seg_dist = |p: (f64, f64), a: (f64, f64), b: (f64, f64)| -> f64 {
+ let dx = b.0 - a.0;
+ let dy = b.1 - a.1;
+ let l2 = dx * dx + dy * dy;
+ if l2 < 1e-18 {
+ return (p.0 - a.0).hypot(p.1 - a.1);
+ }
+ let t = (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / l2).clamp(0.0, 1.0);
+ let qx = a.0 + dx * t;
+ let qy = a.1 + dy * t;
+ (p.0 - qx).hypot(p.1 - qy)
+ };
+ if n <= 128 {
+ for i in 0..n {
+ let p = poly[i];
+ let mi = miters[i];
+ let prev_edge = (i + n - 1) % n;
+ for e in 0..n {
+ if e == i || e == prev_edge {
+ continue;
+ }
+ let a = poly[e];
+ let b = poly[(e + 1) % n];
+ let ex = b.0 - a.0;
+ let ey = b.1 - a.1;
+ let el = ex.hypot(ey);
+ if el < 1e-12 {
+ continue;
+ }
+ // Only check opposing walls (whose inward normal faces opposite to vertex miter)
+ let ne = (-ey / el, ex / el);
+ if mi.0 * ne.0 + mi.1 * ne.1 >= -0.1 {
+ continue;
+ }
+ let dist = point_seg_dist(p, a, b);
+ // Two opposite walls approach each other at speed ~2*d, so clamp at 0.45 * clearance
+ max_d = max_d.min(0.45 * dist);
+ }
+ }
+ } else {
+ // O(n) fallback for very dense polygons: distance from centroid to each edge
+ for e in 0..n {
+ let dist = point_seg_dist((cx, cy), poly[e], poly[(e + 1) % n]);
+ max_d = max_d.min(0.9 * dist);
+ }
+ }
+
+ if max_d.is_finite() {
+ max_d.max(0.0)
+ } else {
+ 0.0
+ }
+}
+
/// Exact top and/or bottom perimeter bevel on a Z-prism (box, hex prism, cylinder, etc.).
/// Preserves any existing bevel on the opposite rim so chained `bevel(top_rim) | bevel(bottom_rim)`
/// produces exact, non-shrinking geometry identical to `bevel(outer_rim)`.
@@ -422,44 +536,48 @@ fn try_bevel_z_rims(
let z0 = bb.min.z;
let z1 = bb.max.z;
let h = z1 - z0;
- if h < 1e-6 {
+ if h < 1e-9 {
return None;
}
+ let z_tol = (1e-4 * h).max(1e-9);
+ let xy_tol = (1e-5 * bb.size().x.max(bb.size().y)).max(1e-9);
let top_faces: Vec<usize> = (0..mesh.faces.len())
- .filter(|&fi| mesh.face_normal(fi).z > 0.99 && (mesh.face_centroid(fi).z - z1).abs() < 1e-3)
+ .filter(|&fi| mesh.face_normal(fi).z > 0.99 && (mesh.face_centroid(fi).z - z1).abs() < z_tol)
.collect();
let bot_faces: Vec<usize> = (0..mesh.faces.len())
- .filter(|&fi| mesh.face_normal(fi).z < -0.99 && (mesh.face_centroid(fi).z - z0).abs() < 1e-3)
+ .filter(|&fi| mesh.face_normal(fi).z < -0.99 && (mesh.face_centroid(fi).z - z0).abs() < z_tol)
.collect();
if top_faces.len() != 1 || bot_faces.len() != 1 {
return None;
}
- let existing = extract_z_prism_rings(mesh, bot_faces[0], top_faces[0])?;
+ let existing = extract_z_prism_rings(mesh, bot_faces[0], top_faces[0], z_tol)?;
let n = existing[0].0.len();
let k = existing.len();
// Helper: check if two consecutive rings have identical XY (i.e. a vertical side wall)
let is_same_xy = |a: &[(f64, f64)], b: &[(f64, f64)]| -> bool {
- a.iter().zip(b.iter()).all(|(p, q)| (p.0 - q.0).hypot(p.1 - q.1) < 1e-4)
+ a.iter().zip(b.iter()).all(|(p, q)| (p.0 - q.0).hypot(p.1 - q.1) < xy_tol)
};
// Build final ring stack `(poly_xy, z, tag_from_prev)` preserving untouched ends!
let mut final_rings: Vec<(Vec<(f64, f64)>, f64, &str)> = Vec::new();
- // Determine vertical span available at bottom & top
+ // Determine vertical span available at bottom & top, AND clamp against 2D cap XY inradius!
let bot_avail = existing[1].1 - existing[0].1;
let top_avail = existing[k - 1].1 - existing[k - 2].1;
let bot_is_vert = is_same_xy(&existing[0].0, &existing[1].0);
let top_is_vert = is_same_xy(&existing[k - 2].0, &existing[k - 1].0);
+ let bot_xy_max = max_safe_poly_inset(&existing[0].0);
+ let top_xy_max = max_safe_poly_inset(&existing[k - 1].0);
// If k == 2 and both ends requested, share available height symmetrically
let (w_bot, w_top) = if k == 2 && do_top && do_bot {
- let w = width.min(h * 0.45);
+ let w = width.min(h * 0.45).min(bot_xy_max).min(top_xy_max);
(w, w)
} else {
- let wb = width.min(bot_avail * 0.9);
- let wt = width.min(top_avail * 0.9);
+ let wb = width.min(bot_avail * 0.9).min(bot_xy_max);
+ let wt = width.min(top_avail * 0.9).min(top_xy_max);
(wb, wt)
};
@@ -901,30 +1019,36 @@ pub fn shell_solid(
open_top: bool,
op_id: u32,
) -> Result<PolyMesh, String> {
- if thickness <= 1e-6 {
+ if !thickness.is_finite() || thickness <= 1e-9 {
return Err("shell thickness must be positive".into());
}
let bb = mesh.aabb();
let sz = bb.size();
let c = bb.center();
- let sx = (sz.x - 2.0 * thickness).max(1e-4) / sz.x.max(1e-6);
- let sy = (sz.y - 2.0 * thickness).max(1e-4) / sz.y.max(1e-6);
+ let sx = (sz.x - 2.0 * thickness) / sz.x.max(1e-9);
+ let sy = (sz.y - 2.0 * thickness) / sz.y.max(1e-9);
if sx <= 0.01 || sy <= 0.01 {
return Err("shell thickness exceeds part dimensions".into());
}
let mut inner = mesh.clone();
if open_top {
+ if thickness >= sz.z * 0.99 {
+ return Err("shell thickness exceeds part height".into());
+ }
// Keep floor thickness = `thickness` at bottom, extend cavity above top to cut open cleanly
let z_floor = bb.min.z + thickness;
- let z_top_ext = bb.max.z + thickness.max(0.1);
+ let z_top_ext = bb.max.z + thickness.max(0.05 * sz.z.max(1e-6));
for v in &mut inner.verts {
v.x = c.x + (v.x - c.x) * sx;
v.y = c.y + (v.y - c.y) * sy;
- let tz = ((v.z - bb.min.z) / sz.z.max(1e-6)).clamp(0.0, 1.0);
+ let tz = ((v.z - bb.min.z) / sz.z.max(1e-9)).clamp(0.0, 1.0);
v.z = z_floor + tz * (z_top_ext - z_floor);
}
} else {
- let sz_s = (sz.z - 2.0 * thickness).max(1e-4) / sz.z.max(1e-6);
+ let sz_s = (sz.z - 2.0 * thickness) / sz.z.max(1e-9);
+ if sz_s <= 0.01 {
+ return Err("shell thickness exceeds part height".into());
+ }
for v in &mut inner.verts {
v.x = c.x + (v.x - c.x) * sx;
v.y = c.y + (v.y - c.y) * sy;
diff --git a/crates/forma-core/src/scene.rs b/crates/forma-core/src/scene.rs
index c9b584f..aa33a43 100644
--- a/crates/forma-core/src/scene.rs
+++ b/crates/forma-core/src/scene.rs
@@ -60,6 +60,7 @@ pub struct Scene {
pub max_statements: usize,
pub assets: BTreeMap<String, Vec<u8>>,
pub query_notes: Vec<String>,
+ pub eval_warnings: Vec<String>,
}
impl Default for Scene {
@@ -82,6 +83,7 @@ impl Scene {
max_statements: 4_096,
assets: BTreeMap::new(),
query_notes: Vec::new(),
+ eval_warnings: Vec::new(),
}
}
@@ -126,6 +128,14 @@ impl Scene {
std::mem::take(&mut self.query_notes)
}
+ pub fn push_warning(&mut self, warn: impl Into<String>) {
+ self.eval_warnings.push(warn.into());
+ }
+
+ pub fn take_warnings(&mut self) -> Vec<String> {
+ std::mem::take(&mut self.eval_warnings)
+ }
+
pub fn clearance(&self, a: &str, b: &str) -> Result<crate::spatial::ClearanceReport, SceneError> {
let ma = self.get_part(a)?;
let mb = self.get_part(b)?;
@@ -526,7 +536,7 @@ impl Scene {
/// Build a compact (~80-150 token) spatial & topological observation of the scene.
pub fn observe(&self, elapsed_ms: f64, prev: Option<&BTreeMap<String, MeshInvariants>>) -> Observation {
let mut invs = BTreeMap::new();
- let mut warnings = Vec::new();
+ let mut warnings = self.eval_warnings.clone();
let mut lines = Vec::new();
lines.push(format!("OK [{elapsed_ms:.2}ms] parts={}", self.parts.len()));
diff --git a/crates/forma-core/tests/fuzz_invariants.rs b/crates/forma-core/tests/fuzz_invariants.rs
index be34aba..d0b2d25 100644
--- a/crates/forma-core/tests/fuzz_invariants.rs
+++ b/crates/forma-core/tests/fuzz_invariants.rs
@@ -36,19 +36,61 @@ impl Rng {
}
}
+fn add_random_tool(s: &mut Scene, name: &str, rng: &mut Rng) {
+ let at = Vec3::new(rng.range(-0.5, 0.5), rng.range(-0.5, 0.5), rng.range(-0.5, 0.5));
+ let _ = match rng.usize(6) {
+ 0 => s.add_box(name, rng.range(0.3, 1.2), rng.range(0.3, 1.2), rng.range(0.3, 1.2), at),
+ 1 => s.add_cyl(
+ name,
+ rng.range(0.2, 0.7),
+ rng.range(0.4, 1.6),
+ [8, 12, 16, 20][rng.usize(4)],
+ at,
+ ['x', 'y', 'z'][rng.usize(3)],
+ ),
+ 2 => s.add_cone(
+ name,
+ rng.range(0.25, 0.7),
+ rng.range(0.0, 0.5),
+ rng.range(0.4, 1.5),
+ 12,
+ at,
+ ['x', 'y', 'z'][rng.usize(3)],
+ ),
+ 3 => s.add_sphere(name, rng.range(0.25, 0.75), 12, 8, at),
+ 4 => {
+ let maj = rng.range(0.35, 0.7);
+ let min = rng.range(0.1, maj * 0.45);
+ s.add_torus(name, maj, min, 14, 8, at)
+ }
+ _ => {
+ let prof = [
+ (rng.range(0.25, 0.6), 0.0),
+ (rng.range(0.15, 0.55), rng.range(0.2, 0.5)),
+ (rng.range(0.15, 0.5), rng.range(0.6, 1.1)),
+ ];
+ s.add_revolve(name, &prof, 12, at)
+ }
+ };
+}
+
#[test]
fn test_10000_fuzzed_modeling_operations_zero_crashes_zero_nans() {
let mut rng = Rng(0xDEAD_BEEF_CAFE_BABE);
let mut total_ops = 0usize;
let mut total_ok_ops = 0usize;
- let mut total_solid_checks = 0usize;
- let mut valid_solids = 0usize;
+ let mut mutating_solid_checks = 0usize;
+ let mut valid_mutating_solids = 0usize;
+ let mut boolean_checks = 0usize;
+ let mut valid_booleans = 0usize;
let t0 = Instant::now();
// 1,000 independent episodes x 10-12 operations = >10,500 fuzzed operations!
+ // Uses curved tools (box/cyl/cone/sphere/torus/revolve), 1,500-face boolean ceiling,
+ // and excludes skipped no-ops from the watertightness denominator for honest reporting.
for ep in 0..1000 {
let mut s = Scene::new();
- // Seed scene with 1-2 valid watertight primitives
+ // Seed scene with 1 valid watertight primitive
let kind = rng.usize(5);
let init_res = match kind {
0 => s.add_box("p0", rng.range(0.5, 3.0), rng.range(0.5, 3.0), rng.range(0.5, 3.0), Vec3::ZERO),
@@ -72,6 +114,8 @@ fn test_10000_fuzzed_modeling_operations_zero_crashes_zero_nans() {
for step in 0..10 {
total_ops += 1;
let op_pick = rng.usize(13);
+ let mut is_boolean = false;
+ let mut executed_mutating = true;
let res = match op_pick {
0 => s.transform(
"p0",
@@ -103,60 +147,62 @@ fn test_10000_fuzzed_modeling_operations_zero_crashes_zero_nans() {
s.bevel("p0", &es, rng.range(0.02, 0.12), [1, 2][rng.usize(2)])
}
4 => {
- // Only subsurf if face count is small so fuzzing stays ultra-fast
- let fc = s.get_part("p0").map(|m| m.faces.len()).unwrap_or(999);
- if fc < 80 {
+ let fc = s.get_part("p0").map(|m| m.faces.len()).unwrap_or(9999);
+ if fc < 160 {
s.subsurf("p0", 1)
} else {
+ executed_mutating = false;
Ok(MeshInvariants::compute(s.get_part("p0").unwrap()))
}
}
5 => {
- let fc = s.get_part("p0").map(|m| m.faces.len()).unwrap_or(999);
- if fc < 120 {
+ let fc = s.get_part("p0").map(|m| m.faces.len()).unwrap_or(9999);
+ if fc < 400 {
s.shell("p0", rng.range(0.05, 0.15), rng.usize(2) == 0)
} else {
+ executed_mutating = false;
Ok(MeshInvariants::compute(s.get_part("p0").unwrap()))
}
}
6 => {
- let fc = s.get_part("p0").map(|m| m.faces.len()).unwrap_or(999);
- if fc < 150 {
- let _ = s.add_box(
- "tool",
- rng.range(0.3, 1.2),
- rng.range(0.3, 1.2),
- rng.range(0.3, 1.2),
- Vec3::new(rng.range(-0.5, 0.5), rng.range(-0.5, 0.5), rng.range(-0.5, 0.5)),
- );
+ let fc = s.get_part("p0").map(|m| m.faces.len()).unwrap_or(9999);
+ if fc < 1500 {
+ is_boolean = true;
+ add_random_tool(&mut s, "tool", &mut rng);
let bop = [BoolOp::Union, BoolOp::Difference, BoolOp::Intersect][rng.usize(3)];
s.boolean_parts("p0", "tool", bop, false)
} else {
+ executed_mutating = false;
Ok(MeshInvariants::compute(s.get_part("p0").unwrap()))
}
}
7 => s.align_bottom_z("p0", rng.range(-1.0, 1.0)),
8 => {
+ executed_mutating = false;
s.checkpoint("mid");
Ok(MeshInvariants::compute(s.get_part("p0").unwrap()))
}
9 => {
+ executed_mutating = false;
let _ = s.rollback("start");
Ok(MeshInvariants::compute(s.get_part("p0").unwrap()))
}
10 => {
+ executed_mutating = false;
let _ = s.undo();
Ok(MeshInvariants::compute(s.get_part("p0").unwrap()))
}
11 => {
- let fc = s.get_part("p0").map(|m| m.faces.len()).unwrap_or(999);
- if fc < 120 {
+ let fc = s.get_part("p0").map(|m| m.faces.len()).unwrap_or(9999);
+ if fc < 400 {
s.mirror("p0", ['x', 'y', 'z'][rng.usize(3)], false)
} else {
+ executed_mutating = false;
Ok(MeshInvariants::compute(s.get_part("p0").unwrap()))
}
}
_ => {
+ executed_mutating = false;
let obs = s.observe(0.1, None);
assert!(!obs.text.is_empty());
Ok(MeshInvariants::compute(s.get_part("p0").unwrap()))
@@ -166,23 +212,32 @@ fn test_10000_fuzzed_modeling_operations_zero_crashes_zero_nans() {
if let Ok(inv) = res {
total_ok_ops += 1;
assert_eq!(inv.nan_verts, 0, "NaN vertex at ep={ep} step={step}");
- if inv.faces > 0 {
- total_solid_checks += 1;
- if inv.watertight && inv.non_manifold_edges == 0 {
- valid_solids += 1;
+ if executed_mutating && inv.faces > 0 {
+ mutating_solid_checks += 1;
+ let ok_wt = inv.watertight && inv.consistent_winding && inv.non_manifold_edges == 0;
+ if ok_wt {
+ valid_mutating_solids += 1;
+ }
+ if is_boolean {
+ boolean_checks += 1;
+ if ok_wt {
+ valid_booleans += 1;
+ }
}
}
}
}
}
let ms = t0.elapsed().as_secs_f64() * 1000.0;
- let wt_pct = 100.0 * (valid_solids as f64) / (total_solid_checks.max(1) as f64);
+ let wt_pct = 100.0 * (valid_mutating_solids as f64) / (mutating_solid_checks.max(1) as f64);
+ let bool_pct = 100.0 * (valid_booleans as f64) / (boolean_checks.max(1) as f64);
println!(
- "FUZZ PASS: {total_ops} ops ({total_ok_ops} ok), 0 panics, 0 NaNs, {valid_solids}/{total_solid_checks} ({wt_pct:.1}%) watertight solids in {ms:.1}ms ({:.3}ms/op)",
+ "HONEST CURVED-TOOL FUZZ PASS: {total_ops} ops ({total_ok_ops} ok), 0 panics, 0 NaNs | mutating: {valid_mutating_solids}/{mutating_solid_checks} ({wt_pct:.1}% WT) | curved booleans: {valid_booleans}/{boolean_checks} ({bool_pct:.1}% WT) in {ms:.1}ms ({:.3}ms/op)",
ms / (total_ops as f64)
);
assert!(total_ops >= 10_000);
- assert!(wt_pct > 90.0, "expected >90% watertight under unconstrained random fuzzing, got {wt_pct:.1}%");
+ assert!(boolean_checks >= 300, "expected >=300 real curved-tool boolean checks, got {boolean_checks}");
+ assert!(wt_pct > 80.0, "expected >80% honest watertight under unconstrained curved-tool fuzzing, got {wt_pct:.1}%");
}
#[test]
@@ -191,15 +246,14 @@ fn test_strict_transactional_fuzz_100_percent_watertight() {
let mut s = Scene::new();
s.strict_manifold = true;
s.add_box("p0", 2.0, 2.0, 2.0, Vec3::ZERO).unwrap();
- for _ in 0..500 {
+ for _ in 0..400 {
s.push_undo();
let res = match rng.usize(5) {
0 => s.extrude("p0", &FaceSelector::Top, rng.range(0.05, 0.3), None),
1 => s.inset("p0", &FaceSelector::Top, rng.range(0.03, 0.15), rng.range(-0.05, 0.05)),
2 => s.bevel("p0", &EdgeSelector::Vertical, rng.range(0.02, 0.1), 1),
3 => {
- let _ = s.add_box("t", rng.range(0.3, 0.9), rng.range(0.3, 0.9), rng.range(0.3, 0.9),
- Vec3::new(rng.range(-0.4, 0.4), rng.range(-0.4, 0.4), rng.range(-0.4, 0.4)));
+ add_random_tool(&mut s, "t", &mut rng);
s.boolean_parts("p0", "t", [BoolOp::Union, BoolOp::Difference][rng.usize(2)], false)
}
_ => s.transform("p0", Vec3::new(0.05, -0.05, 0.0), Vec3::ZERO, Vec3::new(1.0, 1.0, 1.0)),
@@ -208,8 +262,8 @@ fn test_strict_transactional_fuzz_100_percent_watertight() {
let _ = s.undo();
}
let inv = MeshInvariants::compute(s.get_part("p0").unwrap());
- assert!(inv.watertight && inv.non_manifold_edges == 0 && inv.nan_verts == 0, "strict invariant broken: {inv:?}");
- if inv.faces > 400 {
+ assert!(inv.is_valid_solid(), "strict invariant broken: {inv:?}");
+ if inv.faces > 500 {
s = Scene::new();
s.strict_manifold = true;
s.add_box("p0", 2.0, 2.0, 2.0, Vec3::ZERO).unwrap();
diff --git a/crates/forma-core/tests/kernel_tests.rs b/crates/forma-core/tests/kernel_tests.rs
index af57d86..cbcb74e 100644
--- a/crates/forma-core/tests/kernel_tests.rs
+++ b/crates/forma-core/tests/kernel_tests.rs
@@ -622,3 +622,153 @@ fn test_ergonomics_radial_axis_disjoint_array_caps_and_high_segs() {
let dinv = MeshInvariants::compute(&deck);
assert!(dinv.is_valid_solid() && dinv.components == 100, "deck={dinv:?}");
}
+
+#[test]
+fn test_bevel_xy_clamping_solidify_guard_and_bvh_self_intersection() {
+ use forma_core::boolean::has_self_intersections;
+
+ // 1. Wide top_rim bevel on a thin bar (0.2 x 4.0 x 4.0) MUST clamp in XY without self-intersection
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+ s.add_box("bar", 0.2, 4.0, 4.0, Vec3::ZERO).unwrap();
+ let binv = s.bevel("bar", &EdgeSelector::TopRim, 0.5, 3).unwrap();
+ assert!(binv.is_valid_solid(), "clamped bar bevel must be valid solid: {binv:?}");
+ assert!(!has_self_intersections(s.get_part("bar").unwrap()), "clamped bar bevel must not self-intersect");
+
+ // 2. Wide outer_rim bevel on a narrow cylinder (r=0.5, h=4.0) MUST clamp safely in XY
+ s.add_cyl("rod", 0.5, 4.0, 24, Vec3::ZERO, 'z').unwrap();
+ let rinv = s.bevel("rod", &EdgeSelector::OuterRim, 0.9, 3).unwrap();
+ assert!(rinv.is_valid_solid());
+ assert!(!has_self_intersections(s.get_part("rod").unwrap()));
+
+ // 3. Micro-scale (mm) bevel + shell work cleanly with scale-relative Z tolerances
+ let mut sm = Scene::new();
+ sm.strict_manifold = true;
+ sm.add_box("tiny", 0.002, 0.002, 0.001, Vec3::ZERO).unwrap();
+ let tinv = sm.bevel("tiny", &EdgeSelector::OuterRim, 0.0002, 2).unwrap();
+ assert!(tinv.is_valid_solid(), "micro-scale bevel failed: {tinv:?}");
+ let shinv = sm.shell("tiny", 0.0002, true).unwrap();
+ assert!(shinv.is_valid_solid(), "micro-scale shell failed: {shinv:?}");
+
+ // 4. Excessive shell height (closed & open) and excessive solidify thickness are rejected
+ let mut sg = Scene::new();
+ sg.add_box("flat", 2.0, 2.0, 0.4, Vec3::ZERO).unwrap();
+ assert!(sg.shell("flat", 0.25, false).is_err(), "closed shell exceeding half height must err");
+ assert!(sg.shell("flat", 0.45, true).is_err(), "open shell exceeding full height must err");
+
+ let thin_box = forma_core::primitives::make_box(0.4, 0.4, 1.0, 1);
+ assert!(
+ forma_core::deform::solidify_mesh(&thin_box, 0.35, -1.0, true, 2).is_err(),
+ "excessive solidify thickness inverting inner wall must err"
+ );
+
+ // 5. BVH self-intersection detector: false on clean box, true when top cap plunges through bottom cap
+ let clean = forma_core::primitives::make_box(2.0, 2.0, 2.0, 3);
+ assert!(!has_self_intersections(&clean));
+ // Extrude top face up by 1.0, then plunge those top vertices down to z = -2.0 through the bottom face!
+ let mut plunged = forma_core::ops::extrude_faces(&clean, &FaceSelector::Top, 1.0, None, 4).unwrap();
+ assert!(!has_self_intersections(&plunged));
+ for v in &mut plunged.verts {
+ if v.z > 1.5 {
+ v.z = -2.0;
+ }
+ }
+ assert!(has_self_intersections(&plunged), "plunged self-intersecting mesh must be flagged");
+}
+
+#[test]
+fn test_issue_5_rim_breaking_scallop_cuts() {
+ use forma_core::boolean::boolean_batch;
+ use forma_core::primitives::make_cylinder;
+
+ // Exact Issue #5 base: cyl(0.6, 0.5, segs=48) | cut(cyl(0.25, 1))
+ let mut base_s = Scene::new();
+ base_s.strict_manifold = true;
+ base_s.add_cyl("ring", 0.6, 0.5, 48, Vec3::ZERO, 'z').unwrap();
+ base_s.add_cyl("bore", 0.25, 1.0, 32, Vec3::ZERO, 'z').unwrap();
+ base_s.boolean_parts("ring", "bore", BoolOp::Difference, false).unwrap();
+ let base = (**base_s.get_part("ring").unwrap()).clone();
+
+ let pts = [
+ Vec3::new(0.58, 0.0, 0.0),
+ Vec3::new(0.29, 0.502, 0.0),
+ Vec3::new(-0.29, 0.502, 0.0),
+ Vec3::new(-0.58, 0.0, 0.0),
+ Vec3::new(-0.29, -0.502, 0.0),
+ Vec3::new(0.29, -0.502, 0.0),
+ ];
+
+ // 1. Single failing 120-deg cut alone
+ let mut c120 = make_cylinder(0.05, 0.7, 32, 10);
+ c120.translate(pts[2]);
+ let single = forma_core::boolean::boolean_op(&base, &c120, BoolOp::Difference, None, 11).unwrap();
+ let sinv = MeshInvariants::compute(&single);
+ assert!(sinv.is_valid_solid() && sinv.genus == 1, "Issue #5 single 120-deg cut failed: {sinv:?}");
+
+ // 2. All 6 batched cuts
+ let tools: Vec<_> = pts
+ .iter()
+ .map(|&p| {
+ let mut c = make_cylinder(0.05, 0.7, 32, 12);
+ c.translate(p);
+ c
+ })
+ .collect();
+ let batched = boolean_batch(&base, &tools, BoolOp::Difference, None, 13).unwrap();
+ let binv = MeshInvariants::compute(&batched);
+ assert!(binv.is_valid_solid() && binv.genus == 1, "Issue #5 batched 6 cuts failed: {binv:?}");
+
+ // 3. All 6 sequential cuts
+ let mut seq = base.clone();
+ for (i, t) in tools.iter().enumerate() {
+ seq = forma_core::boolean::boolean_op(&seq, t, BoolOp::Difference, None, 20 + i as u32).unwrap();
+ }
+ let qinv = MeshInvariants::compute(&seq);
+ assert!(qinv.is_valid_solid() && qinv.genus == 1, "Issue #5 sequential 6 cuts failed: {qinv:?}");
+}
+
+#[test]
+fn test_batch_hole_rows_8_to_20_holes_all_scales() {
+ use forma_core::boolean::boolean_batch;
+ use forma_core::primitives::{make_box, make_cylinder};
+
+ for &n in &[8usize, 12, 20] {
+ let len = (n + 1) as f64;
+ let plate = make_box(len, 2.0, 0.5, 1);
+ let tools: Vec<_> = (0..n)
+ .map(|i| {
+ let x = -0.5 * ((n - 1) as f64) + (i as f64);
+ let mut c = make_cylinder(0.2, 1.0, 32, 2);
+ c.translate(Vec3::new(x, 0.0, 0.0));
+ c
+ })
+ .collect();
+ let res = boolean_batch(&plate, &tools, BoolOp::Difference, None, 3).unwrap();
+ let inv = MeshInvariants::compute(&res);
+ assert!(
+ inv.is_valid_solid() && inv.genus == n as i64,
+ "batch {n}-hole row failed (expected g={n}): {inv:?}"
+ );
+ }
+
+ // Also verify high-scale L=20 and compact L=2 8-hole rows
+ for &scale in &[2.0_f64, 20.0_f64] {
+ let n = 8usize;
+ let plate = make_box(scale, 0.2 * scale, 0.05 * scale, 10);
+ let r = 0.02 * scale;
+ let tools: Vec<_> = (0..n)
+ .map(|i| {
+ let x = (-0.42 + 0.84 * (i as f64) / ((n - 1) as f64)) * scale;
+ let mut c = make_cylinder(r, 0.2 * scale, 32, 11);
+ c.translate(Vec3::new(x, 0.0, 0.0));
+ c
+ })
+ .collect();
+ let res = boolean_batch(&plate, &tools, BoolOp::Difference, None, 12).unwrap();
+ let inv = MeshInvariants::compute(&res);
+ assert!(
+ inv.is_valid_solid() && inv.genus == n as i64,
+ "scaled L={scale} batch 8-hole row failed: {inv:?}"
+ );
+ }
+}
diff --git a/crates/forma-lang/src/lib.rs b/crates/forma-lang/src/lib.rs
index 66b46fa..4008188 100644
--- a/crates/forma-lang/src/lib.rs
+++ b/crates/forma-lang/src/lib.rs
@@ -44,6 +44,7 @@ pub fn eval_script(scene: &mut Scene, dialect: Dialect, src: &str) -> Result<Obs
map
};
scene.take_notes();
+ scene.take_warnings();
scene.push_undo();
let res = match dialect {
Dialect::Pipe => pipeline::eval_pipe(scene, src),
@@ -133,3 +134,39 @@ EBNF:
| 'subdiv' ID n | 'mov'|'rot'|'scl' ID a b c | 'z0' ID z | 'mir' ID x|y|z
tx := 'ckpt' ID | 'rb' ID | 'undo'
Notes: centered unless `@ x y z` or `z0 z`. `cyl` 6 segs vertices at k*60deg. `rev` auto-closes to r=0. `arc` is XZ ellipse (deg)."#;
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_issue_2_unknown_kwargs_and_clamp_warnings() {
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+ // Unknown kwarg rejected
+ let err = eval_script(&mut s, Dialect::Pipe, "p = box(1, 1, 1, foo=3)").unwrap_err();
+ assert!(err.contains("unknown keyword argument 'foo'"), "err={err}");
+
+ // Typo triggers "did you mean" suggestion
+ let err2 = eval_script(&mut s, Dialect::Pipe, "p = box(1, 1, 1, widht=2)").unwrap_err();
+ assert!(err2.contains("did you mean 'width'"), "err2={err2}");
+
+ let err3 = eval_script(&mut s, Dialect::Pipe, "p = box(1, 1, 1) | bevel(vertical, 0.1, wdth=0.2)").unwrap_err();
+ assert!(err3.contains("did you mean 'width'"), "err3={err3}");
+
+ // Clamped segs emits WARN without failing valid geometry
+ let obs = eval_script(
+ &mut s,
+ Dialect::Pipe,
+ "p = loft([(0, [(-1,-1),(1,-1),(1,1),(-1,1)]), (2, [(-0.5,-0.5),(0.5,-0.5),(0.5,0.5),(-0.5,0.5)])], segs=200)",
+ )
+ .unwrap();
+ assert!(obs.ok);
+ assert!(
+ obs.warnings.iter().any(|w| w.contains("loft: segs=200 clamped to 128")),
+ "expected clamp warning, got {:?}",
+ obs.warnings
+ );
+ assert!(obs.text.contains("WARN:"));
+ }
+}
diff --git a/crates/forma-lang/src/pipeline.rs b/crates/forma-lang/src/pipeline.rs
index 22283a5..d1701fd 100644
--- a/crates/forma-lang/src/pipeline.rs
+++ b/crates/forma-lang/src/pipeline.rs
@@ -231,6 +231,116 @@ fn check_finite(v: f64, ctx: &str) -> Result<f64, String> {
}
}
+fn edit_distance(a: &str, b: &str) -> usize {
+ let ab: Vec<char> = a.chars().collect();
+ let bb: Vec<char> = b.chars().collect();
+ let mut prev: Vec<usize> = (0..=bb.len()).collect();
+ let mut curr = vec![0usize; bb.len() + 1];
+ for (i, &ca) in ab.iter().enumerate() {
+ curr[0] = i + 1;
+ for (j, &cb) in bb.iter().enumerate() {
+ let cost = usize::from(ca != cb);
+ curr[j + 1] = (prev[j + 1] + 1).min(curr[j] + 1).min(prev[j] + cost);
+ }
+ std::mem::swap(&mut prev, &mut curr);
+ }
+ prev[bb.len()]
+}
+
+fn check_allowed_kwargs(kw: &HashMap<String, Val>, allowed: &[&str], ctx: &str) -> Result<(), String> {
+ if kw.is_empty() {
+ return Ok(());
+ }
+ let mut unknown: Vec<&str> = kw
+ .keys()
+ .map(|k| k.as_str())
+ .filter(|k| !allowed.contains(k))
+ .collect();
+ if unknown.is_empty() {
+ return Ok(());
+ }
+ unknown.sort_unstable();
+ let first = unknown[0];
+ let suggestion = allowed
+ .iter()
+ .map(|&cand| (edit_distance(first, cand), cand))
+ .filter(|&(d, _)| d <= 2)
+ .min_by_key(|&(d, _)| d)
+ .map(|(_, cand)| format!(" — did you mean '{cand}'?"))
+ .unwrap_or_default();
+ if allowed.is_empty() {
+ Err(format!("{ctx}: unknown keyword argument '{first}' (accepts positional arguments only)"))
+ } else {
+ Err(format!(
+ "{ctx}: unknown keyword argument '{first}'{suggestion} (valid: {})",
+ allowed.join(", ")
+ ))
+ }
+}
+
+fn warn_if_clamped(scene: &mut Scene, op: &str, param: &str, requested: usize, lo: usize, hi: usize) {
+ if requested < lo || requested > hi {
+ let clamped = requested.clamp(lo, hi);
+ scene.push_warning(format!(
+ "{op}: {param}={requested} clamped to {clamped} (supported range {lo}..={hi})"
+ ));
+ }
+}
+
+fn allowed_call_kwargs(name: &str) -> Option<&'static [&'static str]> {
+ Some(match name {
+ "sqrt" | "sin" | "cos" | "asin" | "acos" | "abs" | "deg" | "rad" => &["x"],
+ "bezier" => &["points", "pts", "segs", "segments"],
+ "nurbs" | "bspline" => &["points", "pts", "degree", "deg", "segs", "segments", "weights"],
+ "clearance" => &["a", "b"],
+ "section" => &["part", "z"],
+ "checkpoint" | "rollback" | "del" | "remove" => &["name", "tag"],
+ "undo" => &[],
+ "box" => &["sx", "x", "w", "width", "sy", "y", "d", "depth", "sz", "z", "h", "height", "rot", "rotate", "at", "center", "z0"],
+ "cyl" | "cylinder" | "prism" => &["r", "radius", "h", "height", "len", "length", "segs", "segments", "sides", "axis", "rot", "rotate", "at", "center", "z0"],
+ "cone" | "frustum" => &["r0", "r_bot", "r_bottom", "r1", "r_top", "h", "height", "segs", "segments", "axis", "rot", "rotate", "at", "center", "z0"],
+ "sphere" => &["r", "radius", "segs", "segments", "rot", "rotate", "at", "center", "z0"],
+ "torus" => &["R", "major", "r", "minor", "segs", "segments", "rot", "rotate", "at", "center", "z0"],
+ "revolve" => &["profile", "points", "pts", "segs", "segments", "rot", "rotate", "at", "center", "z0"],
+ "arc_tube" => &["center", "at", "rx", "r_x", "rz", "r_z", "start", "start_deg", "a0", "end", "end_deg", "a1", "r", "tube_r", "radius", "segs", "segments", "arc_segs", "rot", "rotate", "z0"],
+ "tube" => &["points", "pts", "r", "radius", "segs", "segments", "closed", "rot", "rotate", "at", "center", "z0"],
+ "extrude2d" => &["points", "pts", "z0", "z1", "holes", "rot", "rotate", "at", "center"],
+ "pipe" | "hollow_cyl" => &["r_out", "ro", "outer", "r", "r_in", "ri", "inner", "h", "height", "len", "length", "segs", "segments", "axis", "rot", "rotate", "at", "center", "z0"],
+ "loft" => &["sections", "profiles", "segs", "segments", "rot", "rotate", "at", "center", "z0"],
+ "thread" | "helix" => &["r_minor", "r_min", "r_in", "r", "r_major", "r_maj", "r_out", "pitch", "p", "turns", "n", "segs", "segments", "rot", "rotate", "at", "center", "z0"],
+ "sweep" => &["profile", "path", "closed", "scale_end", "taper", "twist", "twist_deg", "rot", "rotate", "at", "center", "z0"],
+ "text3d" | "text" => &["text", "size", "h", "height", "depth", "d", "t", "rot", "rotate", "at", "center", "z0"],
+ "load" | "import" => &["path", "file", "yup", "rot", "rotate", "at", "center", "z0"],
+ _ => return None,
+ })
+}
+
+fn allowed_pipe_kwargs(op_name: &str) -> Option<&'static [&'static str]> {
+ Some(match op_name {
+ "add" | "union" | "cut" | "sub" | "diff" | "intersect" => &["other", "at"],
+ "bevel" => &["edges", "w", "width", "r", "radius", "segs", "segments"],
+ "shell" => &["t", "thickness", "wall", "open_top"],
+ "extrude" => &["faces", "dist", "d"],
+ "inset" => &["faces", "amt", "amount", "depth"],
+ "subsurf" | "subdiv" => &["levels", "level", "n", "crease"],
+ "move" | "translate" | "rot" | "rotate" | "scale" | "align_z0" | "color" | "flat" => &[],
+ "align" => &["axis", "mode", "val", "to"],
+ "on" | "place_on" => &["base", "gap"],
+ "mat" | "material" => &["name", "color", "metallic", "m", "roughness", "r", "faces", "tag"],
+ "mirror" => &["axis", "union"],
+ "pattern_linear" | "array" => &["count", "n", "step", "union"],
+ "pattern_radial" | "radial" => &["count", "n", "r", "radius", "axis", "union"],
+ "decimate" | "lod" => &["ratio", "faces", "target_faces"],
+ "smooth" => &["angle", "weighted"],
+ "solidify" => &["t", "thickness", "offset", "open_top"],
+ "deform" => &["mode", "axis", "path", "corners", "angle", "factor", "subdivs"],
+ "unwrap" | "uv" => &["angle", "margin"],
+ "remesh" => &["voxel_size", "size"],
+ "bisect" => &["normal", "offset", "clear_inner"],
+ _ => return None,
+ })
+}
+
struct Parser<'a> {
toks: Vec<(Tok, usize)>,
pos: usize,
@@ -509,6 +619,9 @@ impl<'a> Parser<'a> {
line: usize,
) -> Result<Val, String> {
let ctx = format!("line {line}: {name}()");
+ if let Some(allowed) = allowed_call_kwargs(name) {
+ check_allowed_kwargs(&kw, allowed, &ctx)?;
+ }
let get_num_any = |idx: usize, keys: &[&str], def: Option<f64>| -> Result<f64, String> {
for &k in keys {
if let Some(v) = kw.get(k) {
@@ -541,6 +654,7 @@ impl<'a> Parser<'a> {
let ctrl = kw.get("points").or_else(|| kw.get("pts")).or_else(|| pos.first())
.ok_or(format!("{ctx}: missing control points"))?.as_vec3_list(&ctx)?;
let segs = get_num_any(1, &["segs", "segments"], Some(24.0))? as usize;
+ warn_if_clamped(self.scene, "bezier", "segs", segs, 4, 128);
let pts = forma_core::curves::eval_bezier_3d(&ctrl, segs).map_err(|e| format!("{ctx}: {e}"))?;
return Ok(Val::List(pts.into_iter().map(|p| Val::List(vec![Val::Num(p.x), Val::Num(p.y), Val::Num(p.z)])).collect()));
}
@@ -549,6 +663,7 @@ impl<'a> Parser<'a> {
.ok_or(format!("{ctx}: missing control points"))?.as_vec3_list(&ctx)?;
let degree = get_num_any(1, &["degree", "deg"], Some(3.0))? as usize;
let segs = get_num_any(2, &["segs", "segments"], Some(32.0))? as usize;
+ warn_if_clamped(self.scene, "nurbs", "segs", segs, 4, 128);
let weights: Option<Vec<f64>> = kw.get("weights").map(|v| match v {
Val::List(items) => items.iter().map(|it| it.as_num(&ctx)).collect::<Result<Vec<_>, _>>(),
_ => Err(format!("{ctx}: weights must be list of numbers")),
@@ -572,12 +687,12 @@ impl<'a> Parser<'a> {
return Ok(Val::Num(rep.area));
}
"checkpoint" => {
- let tag = pos.first().or_else(|| kw.get("name")).ok_or(format!("{ctx}: missing tag"))?.as_str(&ctx)?;
+ let tag = pos.first().or_else(|| kw.get("name")).or_else(|| kw.get("tag")).ok_or(format!("{ctx}: missing tag"))?.as_str(&ctx)?;
self.scene.checkpoint(tag);
return Ok(Val::Bool(true));
}
"rollback" => {
- let tag = pos.first().or_else(|| kw.get("name")).ok_or(format!("{ctx}: missing tag"))?.as_str(&ctx)?;
+ let tag = pos.first().or_else(|| kw.get("name")).or_else(|| kw.get("tag")).ok_or(format!("{ctx}: missing tag"))?.as_str(&ctx)?;
self.scene.rollback(tag).map_err(|e| format!("{ctx}: {e}"))?;
return Ok(Val::Bool(true));
}
@@ -625,6 +740,7 @@ impl<'a> Parser<'a> {
return Err(format!("{ctx}: cyl requires positive radius and height (r={r}, h={h})"));
}
let segs = get_num_any(2, &["segs", "segments", "sides"], Some(32.0))? as usize;
+ warn_if_clamped(self.scene, "cyl", "segs", segs, 3, 128);
let mut m = forma_core::primitives::make_cylinder(r, h, segs, op_id);
let axis = kw
.get("axis")
@@ -646,6 +762,7 @@ impl<'a> Parser<'a> {
return Err(format!("{ctx}: cone requires positive height and at least one positive radius (r0={r0}, r1={r1}, h={h})"));
}
let segs = get_num_any(3, &["segs", "segments"], Some(32.0))? as usize;
+ warn_if_clamped(self.scene, "cone", "segs", segs, 3, 128);
let mut m = forma_core::primitives::make_cone(r0, r1, h, segs, op_id);
if let Some(ax) = kw.get("axis").and_then(|v| v.as_str(&ctx).ok()) {
match ax.to_lowercase().as_str() {
@@ -662,6 +779,7 @@ impl<'a> Parser<'a> {
return Err(format!("{ctx}: sphere requires positive radius (r={r})"));
}
let segs = get_num_any(1, &["segs", "segments"], Some(32.0))? as usize;
+ warn_if_clamped(self.scene, "sphere", "segs", segs, 4, 96);
forma_core::primitives::make_sphere(r, segs, (segs / 2).max(12), op_id)
}
"torus" => {
@@ -671,6 +789,7 @@ impl<'a> Parser<'a> {
return Err(format!("{ctx}: torus requires positive major and minor radii (R={maj}, r={min})"));
}
let segs = get_num_any(2, &["segs", "segments"], Some(32.0))? as usize;
+ warn_if_clamped(self.scene, "torus", "segs", segs, 6, 96);
forma_core::primitives::make_torus(maj, min, segs, (segs / 2).max(12), op_id)
}
"revolve" => {
@@ -682,6 +801,7 @@ impl<'a> Parser<'a> {
.ok_or(format!("{ctx}: missing profile list"))?;
let prof = prof_val.as_vec2_list(&ctx)?;
let segs = get_num_any(1, &["segs", "segments"], Some(32.0))? as usize;
+ warn_if_clamped(self.scene, "revolve", "segs", segs, 6, 128);
forma_core::primitives::make_revolve(&prof, segs, op_id).map_err(|e| format!("{ctx}: {e}"))?
}
"arc_tube" => {
@@ -696,6 +816,7 @@ impl<'a> Parser<'a> {
let end = get_num_any(4, &["end", "end_deg", "a1"], Some(90.0))?;
let r = get_num_any(5, &["r", "tube_r", "radius"], Some(0.08))?;
let segs = get_num_any(6, &["segs", "segments", "arc_segs"], Some(16.0))? as usize;
+ warn_if_clamped(self.scene, "arc_tube", "segs", segs, 4, 128);
forma_core::primitives::make_arc_tube(center, rx, rz, start, end, r, segs, 12, op_id)
.map_err(|e| format!("{ctx}: {e}"))?
}
@@ -708,6 +829,7 @@ impl<'a> Parser<'a> {
.as_vec3_list(&ctx)?;
let r = get_num_any(1, &["r", "radius"], Some(0.08))?;
let segs = get_num_any(2, &["segs", "segments"], Some(12.0))? as usize;
+ warn_if_clamped(self.scene, "tube", "segs", segs, 6, 64);
let closed = kw.get("closed").map(|v| v.as_bool(&ctx)).transpose()?.unwrap_or(false);
forma_core::primitives::make_tube(&pts, r, segs, closed, op_id).map_err(|e| format!("{ctx}: {e}"))?
}
@@ -741,6 +863,7 @@ impl<'a> Parser<'a> {
let r_in = get_num_any(1, &["r_in", "ri", "inner"], None)?;
let h = get_num_any(2, &["h", "height", "len", "length"], None)?;
let segs = get_num_any(3, &["segs", "segments"], Some(32.0))? as usize;
+ warn_if_clamped(self.scene, "pipe", "segs", segs, 6, 128);
let mut m = forma_core::primitives::make_pipe(r_out, r_in, h, segs, op_id)
.map_err(|e| format!("{ctx}: {e}"))?;
let axis = kw
@@ -778,6 +901,7 @@ impl<'a> Parser<'a> {
return Err(format!("{ctx}: sections must be a list"));
}
let segs = get_num_any(1, &["segs", "segments"], Some(24.0))? as usize;
+ warn_if_clamped(self.scene, "loft", "segs", segs, 8, 128);
forma_core::primitives::make_loft(&sections, segs, op_id).map_err(|e| format!("{ctx}: {e}"))?
}
"thread" | "helix" => {
@@ -786,6 +910,7 @@ impl<'a> Parser<'a> {
let pitch = get_num_any(2, &["pitch", "p"], Some(r_min * 0.3))?;
let turns = get_num_any(3, &["turns", "n"], Some(4.0))?;
let segs = get_num_any(4, &["segs", "segments"], Some(28.0))? as usize;
+ warn_if_clamped(self.scene, "thread", "segs", segs, 12, 96);
forma_core::primitives::make_thread(r_min, r_maj, pitch, turns, segs, op_id)
.map_err(|e| format!("{ctx}: {e}"))?
}
@@ -892,6 +1017,9 @@ impl<'a> Parser<'a> {
line: usize,
) -> Result<PolyMesh, String> {
let ctx = format!("line {line}: | {op_name}()");
+ if let Some(allowed) = allowed_pipe_kwargs(op_name) {
+ check_allowed_kwargs(&kw, allowed, &ctx)?;
+ }
let op_id = self.scene.next_op();
match op_name {
"add" | "union" | "cut" | "sub" | "diff" | "intersect" => {
diff --git a/llms.txt b/llms.txt
index 7820737..b7d8c60 100644
--- a/llms.txt
+++ b/llms.txt
@@ -1,6 +1,6 @@
# Forma
-> A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, Unix CLI, and minimal-schema MCP server. Single static binary, zero GPU required, guaranteed-manifold geometry, ~16.9 ms cold-start eval + export.
+> A 1.2 MB pure-Rust headless 3D polyhedral modeling engine built for AI agents — Unix CLI, WASM library, and minimal-schema MCP server. Single static binary, zero GPU required, strict watertight solid verification, ~16.9 ms cold-start eval + export.
## Repository Map
@@ -8,7 +8,7 @@
- [README.md](README.md): Overview, quickstart, npm/CLI/MCP usage, and full 12-model / 10-lab benchmarks
- [AGENTS.md](AGENTS.md): Step-by-step integration guide for AI agents (MCP, CLI, constrained decoding, feedback loop)
- [grammar/forma_pipe.gbnf](grammar/forma_pipe.gbnf): Formal GBNF grammar for zero-syntax-error constrained decoding (llama.cpp, vLLM, XGrammar)
-- [crates/forma-core](crates/forma-core): Pure-Rust double-precision B-rep kernel, BVH booleans, bevel, shell, subsurf, loft, thread, sweep, text3d, spatial queries, pure-Rust PNG/SVG renderer, GLB/STEP/3MF/STL/OBJ exporters
+- [crates/forma-core](crates/forma-core): Pure-Rust double-precision polyhedral mesh kernel, BVH booleans, bevel, shell, subsurf, loft, thread, sweep, text3d, spatial queries, pure-Rust PNG/SVG renderer, GLB/faceted STEP/3MF/STL/OBJ exporters
- [crates/forma-lang](crates/forma-lang): `Forma-Pipe` declarative modeling language evaluator
- [crates/forma-cli](crates/forma-cli): `forma` CLI (`eval`, `render`, `draw`, `spec`)
- [crates/forma-mcp](crates/forma-mcp): `forma-mcp` stdio JSON-RPC 2.0 MCP server (4 tools, 789 o200k tokens)
@@ -48,13 +48,13 @@ cargo build --release
- `arc_tube(center=(x,y,z), rx=, rz=, start=-90, end=90, r=0.08)` (XZ elliptical arc)
- `tube([(x,y,z), ...], r=0.08, closed=false)`
- `extrude2d([(x,y), ...], z0=0, z1=1)`
- - `loft([(z, [(x,y), ...]), ...], segs=24)`
- - `thread(r_minor, r_major, pitch, turns, segs=28)`
+ - `loft([(z, [(x,y), ...]), ...], segs=24)` (`segs` 8..128)
+ - `thread(r_minor, r_major, pitch, turns, segs=28)` (`segs` 12..96)
- `sweep([(x,y), ...], [(x,y,z), ...], closed=false)`
- `text3d("TEXT", size=0.5, depth=0.1)`
- Pipeline Ops (`mesh | op(...)` or `op(mesh, ...)`):
- Booleans: `add(b, at=)`, `cut(b, at=)`, `intersect(b)` (batch-accelerated when `at=[...]`)
- - Modeling: `bevel(edges, w, segs=1)` (`vertical|top_rim|bottom_rim|outer_rim|sharp|all`), `shell(t, open_top=true)`, `extrude(faces, d)`, `inset(faces, amt, depth=0)` (`top|bottom|sides`), `subsurf(levels=1, crease=false)`, `mirror(x|y|z)`, `pattern_linear(n, step)`, `pattern_radial(n)`
+ - Modeling: `bevel(edges, w, segs=1)` (`vertical|top_rim|bottom_rim|outer_rim|sharp|all`), `shell(t, open_top=true)`, `extrude(faces, d)`, `inset(faces, amt, depth=0)` (`top|bottom|sides`), `subsurf(levels=1, crease=false)`, `mirror(x|y|z)`, `pattern_linear(n, step)` / `array(n, step)`, `pattern_radial(n, r=, axis=z)` / `radial(n, r=, axis=z)`
- Placement: `move(x,y,z)`, `rot(rx,ry,rz)`, `scale(sx,sy,sz)`, `align(x|y|z, min|center|max, val)`, `on(base, gap=0)`, `align_z0(z)`
- Materials: `mat(name, color=(r,g,b), metallic=0.1, roughness=0.5, faces=)`, `color(r,g,b)`
- Spatial Queries (emitted in compact observation output):
diff --git a/package.json b/package.json
index 35a9990..226bc9e 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "forma-3d",
"version": "0.4.0",
- "description": "A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, WASM library, and MCP server.",
+ "description": "A 1.2 MB pure-Rust headless 3D polyhedral modeling engine built for AI agents — CLI, WASM library, and MCP server.",
"license": "MIT",
"author": "wrong-nebula",
"type": "module",
@@ -31,7 +31,7 @@
"LICENSE"
],
"scripts": {
- "build:wasm": "RUSTFLAGS=\"--remap-path-prefix=$HOME=/home\" cargo build --profile wasm-release --target wasm32-unknown-unknown -p forma-wasm && mkdir -p wasm && cp target/wasm32-unknown-unknown/wasm-release/forma_wasm.wasm wasm/forma.wasm",
+ "build:wasm": "RUSTFLAGS=\"--remap-path-prefix=$HOME=/home\" cargo build --locked --profile wasm-release --target wasm32-unknown-unknown -p forma-wasm && mkdir -p wasm && cp target/wasm32-unknown-unknown/wasm-release/forma_wasm.wasm wasm/forma.wasm",
"test": "node tests/npm_smoke.mjs"
},
"keywords": [
diff --git a/wasm/forma.wasm b/wasm/forma.wasm
index e512b0c..e052d19 100755
Binary files a/wasm/forma.wasm and b/wasm/forma.wasm differ