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 kernel, export, server, CLI/WASM parity, and build manifests

wrong-nebula764dfa4fa73d
diff --git a/.gitignore b/.gitignore
index ca42752..e39510c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -23,3 +23,6 @@ node_modules/
# Local working research, audit, and roadmap notes
notes/
+
+# Local experimental workspace (independent Cargo workspace & git repo)
+caulker/
diff --git a/Cargo.lock b/Cargo.lock
index 384796e..a30cd25 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -26,8 +26,6 @@ name = "forma-lang"
version = "0.4.2"
dependencies = [
"forma-core",
- "serde",
- "serde_json",
]
[[package]]
@@ -36,7 +34,6 @@ version = "0.4.2"
dependencies = [
"forma-core",
"forma-lang",
- "serde",
"serde_json",
]
diff --git a/Dockerfile b/Dockerfile
index 73e145d..732696b 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,9 +1,10 @@
-# Multi-stage minimal headless Forma HTTP microservice (~2 MB final scratch image)
+# Multi-stage minimal headless Forma HTTP microservice (< 5 MB final scratch image)
FROM rust:1.83-alpine AS builder
RUN apk add --no-cache musl-dev
WORKDIR /src
COPY Cargo.toml Cargo.lock ./
COPY crates ./crates
+COPY grammar ./grammar
RUN RUSTFLAGS="--remap-path-prefix=/root=/home -C target-feature=+crt-static" \
cargo build --locked --profile static-release -p forma-server -p forma-cli
diff --git a/bin/blend-bridge.mjs b/bin/blend-bridge.mjs
new file mode 100644
index 0000000..f754b63
--- /dev/null
+++ b/bin/blend-bridge.mjs
@@ -0,0 +1,57 @@
+/**
+ * Node.js Blender CLI bridge for exporting `.blend` files from glTF 2.0 (`.glb`) bytes.
+ * Used only by CLI/MCP entrypoints in `bin/`; never imported by edge/browser bundles in `lib/`.
+ */
+
+import { execFile } from "node:child_process";
+import { mkdir, unlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { promisify } from "node:util";
+
+const execFileAsync = promisify(execFile);
+let seq = 0;
+
+/** Convert `.glb` bytes into a `.blend` file using a local Blender executable. */
+export async function writeBlendFromGlbBytes(glbBytes, outPath) {
+ const absOut = resolve(outPath);
+ await mkdir(dirname(absOut), { recursive: true });
+
+ const tmpGlb = join(tmpdir(), `forma_blend_bridge_${process.pid}_${++seq}.glb`);
+ await writeFile(tmpGlb, glbBytes);
+
+ const py =
+ `import bpy; bpy.ops.wm.read_factory_settings(use_empty=True); ` +
+ `bpy.ops.import_scene.gltf(filepath=${JSON.stringify(tmpGlb)}); ` +
+ `bpy.ops.wm.save_as_mainfile(filepath=${JSON.stringify(absOut)})`;
+
+ const envBin = process.env.BLENDER_BIN?.trim();
+ const candidates = envBin
+ ? [envBin]
+ : process.platform === "darwin"
+ ? ["blender", "/Applications/Blender.app/Contents/MacOS/Blender"]
+ : ["blender"];
+
+ try {
+ let lastErr = null;
+ for (const bin of candidates) {
+ try {
+ await execFileAsync(bin, ["--background", "--factory-startup", "--python-expr", py]);
+ return;
+ } catch (err) {
+ if (err && err.code === "ENOENT") {
+ lastErr = err;
+ continue;
+ }
+ const detail = (err?.stderr || err?.stdout || err?.message || String(err)).trim();
+ throw new Error(`Blender .blend export failed (${bin}): ${detail}`);
+ }
+ }
+ throw new Error(
+ `Blender executable not found for .blend export (tried: ${candidates.join(", ")}; ` +
+ `install Blender or set BLENDER_BIN=/path/to/blender)`
+ );
+ } finally {
+ await unlink(tmpGlb).catch(() => {});
+ }
+}
diff --git a/bin/forma.mjs b/bin/forma.mjs
index 062d075..c2f582b 100755
--- a/bin/forma.mjs
+++ b/bin/forma.mjs
@@ -4,26 +4,46 @@
* Supports: eval, render, draw, spec, mcp, version, --help
*/
+import { readFileSync } from "node:fs";
import { readFile, writeFile } from "node:fs/promises";
import { extname } from "node:path";
-import { performance } from "node:perf_hooks";
import { loadForma } from "../lib/index.mjs";
+import { writeBlendFromGlbBytes } from "./blend-bridge.mjs";
-const VERSION = "0.4.2";
+const VERSION = JSON.parse(
+ readFileSync(new URL("../package.json", import.meta.url), "utf-8")
+).version;
function printHelp() {
process.stdout.write(
`forma ${VERSION} (WASM) — pure-Rust headless 3D polyhedral modeling engine for AI agents\n\n` +
`USAGE:\n` +
- ` forma-3d eval [--dialect pipe|compact] [--strict|--no-strict] [--json] [--scene] [--out path.(glb|obj|stl|3mf|step)] [--render preview.png] [--draw blueprint.svg] [file|-]\n` +
+ ` forma-3d eval [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--strict|--no-strict] [--json] [--scene] [--out path.(glb|obj|stl|3mf|step|blend)] [--render preview.png] [--size 512] [--draw blueprint.svg] [file|-]\n` +
` forma-3d render [--size 512] --out preview.png [file|-]\n` +
` forma-3d draw --out blueprint.svg [file|-]\n` +
` forma-3d spec [--dialect pipe|compact] [--topic TOPIC] [--gbnf]\n` +
` forma-3d mcp\n` +
- ` forma-3d --version\n`
+ ` forma-3d version | --version | -V\n\n` +
+ `EXIT CODES:\n` +
+ ` 0 Success\n` +
+ ` 1 Script, I/O, or export error\n` +
+ ` 2 Invalid CLI usage or flag\n` +
+ ` 3 Strict manifold/invariant check failed\n`
);
}
+function usageErr(msg) {
+ process.stderr.write(`ERR: ${msg}\n`);
+ process.exit(2);
+}
+
+function requireVal(args, i, flag, hint) {
+ if (i + 1 >= args.length) {
+ usageErr(`${flag} requires ${hint}`);
+ }
+ return args[i + 1];
+}
+
async function readStdin() {
const chunks = [];
for await (const chunk of process.stdin) {
@@ -57,27 +77,36 @@ async function main() {
let gbnf = false;
let topic = null;
for (let i = 1; i < args.length; i++) {
- if ((args[i] === "--dialect" || args[i] === "-d") && i + 1 < args.length) {
- dialect = args[++i];
- } else if ((args[i] === "--topic" || args[i] === "-t") && i + 1 < args.length) {
- topic = args[++i];
- } else if (args[i] === "--gbnf") {
+ const a = args[i];
+ if (a === "--dialect" || a === "-d") {
+ dialect = requireVal(args, i++, a, "value (pipe|compact)");
+ } else if (a === "--topic" || a === "-t") {
+ topic = requireVal(args, i++, a, "value (deform|curves|uv|remesh|scene)");
+ } else if (a === "--gbnf") {
gbnf = true;
- } else if (!args[i].startsWith("-") && topic === null) {
- topic = args[i];
+ } else if (a.startsWith("-")) {
+ usageErr(`unknown flag '${a}' for 'forma-3d spec'. Run 'forma-3d --help'.`);
+ } else if (topic === null) {
+ topic = a;
+ } else {
+ usageErr(`unexpected argument '${a}' for 'forma-3d spec'. Run 'forma-3d --help'.`);
}
}
- const out = topic !== null ? engine.specTopic(topic) : engine.spec({ dialect, gbnf });
- process.stdout.write(out + "\n");
- return;
+ try {
+ const out = topic !== null ? engine.specTopic(topic) : engine.spec({ dialect, gbnf });
+ process.stdout.write(out + "\n");
+ return;
+ } catch (err) {
+ usageErr(err instanceof Error ? err.message : String(err));
+ }
}
if (cmd !== "eval" && cmd !== "render" && cmd !== "draw") {
- process.stderr.write(`ERR: unknown subcommand '${cmd}'. Run 'forma-3d --help'.\n`);
- process.exit(2);
+ usageErr(`unknown subcommand '${cmd}'. Run 'forma-3d --help'.`);
}
let dialect = "pipe";
+ let unit = null;
let strict = true;
let asJson = false;
let exportScene = false;
@@ -90,21 +119,23 @@ async function main() {
for (let i = 1; i < args.length; i++) {
const a = args[i];
if (a === "--dialect" || a === "-d") {
- dialect = args[++i];
+ dialect = requireVal(args, i++, a, "value (pipe|compact)");
+ } else if (a === "--unit" || a === "-u") {
+ unit = requireVal(args, i++, a, "value (m|cm|mm|um|in|ft)");
} else if (a === "--out" || a === "-o") {
- const p = args[++i];
+ const p = requireVal(args, i++, a, "output path");
if (cmd === "render") renderPath = p;
else if (cmd === "draw") drawPath = p;
else outPath = p;
} else if (a === "--render") {
- renderPath = args[++i];
+ renderPath = requireVal(args, i++, a, "PNG path");
} else if (a === "--draw") {
- drawPath = args[++i];
+ drawPath = requireVal(args, i++, a, "SVG path");
} else if (a === "--size") {
- const parsed = Number.parseInt(args[++i], 10);
- if (!Number.isFinite(parsed) || parsed <= 0) {
- process.stderr.write("ERR: --size requires a positive integer\n");
- process.exit(2);
+ const raw = requireVal(args, i++, a, "positive pixel integer");
+ const parsed = Number.parseInt(raw, 10);
+ if (!Number.isFinite(parsed) || parsed <= 0 || String(parsed) !== raw.trim()) {
+ usageErr(`invalid --size '${raw}': expected positive integer`);
}
renderSize = parsed;
} else if (a === "--strict") {
@@ -115,33 +146,55 @@ async function main() {
asJson = true;
} else if (a === "--scene") {
exportScene = true;
+ } else if (a.startsWith("-") && a !== "-") {
+ usageErr(`unknown flag '${a}'. Run 'forma-3d --help'.`);
+ } else if (inFile !== null) {
+ usageErr(`unexpected extra input file '${a}' (only one script file is accepted)`);
} else {
inFile = a;
}
}
+ if (cmd === "render" && !renderPath) {
+ usageErr("'forma-3d render' requires '--out preview.png'");
+ }
+ if (cmd === "draw" && !drawPath) {
+ usageErr("'forma-3d draw' requires '--out blueprint.svg'");
+ }
+
const src = !inFile || inFile === "-" ? await readStdin() : await readFile(inFile, "utf-8");
const session = engine.createSession();
- const t0 = performance.now();
try {
+ if (unit !== null) {
+ try {
+ session.setUnit(unit);
+ } catch (err) {
+ usageErr(err instanceof Error ? err.message : String(err));
+ }
+ }
const obs = session.eval(src, { dialect, strict });
- const ms = performance.now() - t0;
- obs.elapsed_ms = Number(ms.toFixed(2));
- obs.text = obs.text.replace("[0.00ms]", `[${ms.toFixed(2)}ms]`);
if (outPath) {
- const bytes = exportScene
- ? session.exportSceneBytes()
- : session.exportBytes(extname(outPath).replace(/^\./, "").toLowerCase());
- await writeFile(outPath, bytes);
+ const ext = extname(outPath).replace(/^\./, "").toLowerCase();
+ if (exportScene) {
+ if (ext === "blend") {
+ await writeBlendFromGlbBytes(session.exportSceneBytes(), outPath);
+ } else if (ext === "glb") {
+ await writeFile(outPath, session.exportSceneBytes());
+ } else {
+ throw new Error(`multi-node scene export requires .glb or .blend (got '.${ext}')`);
+ }
+ } else if (ext === "blend") {
+ await writeBlendFromGlbBytes(session.exportBytes("glb"), outPath);
+ } else {
+ await writeFile(outPath, session.exportBytes(ext));
+ }
}
if (renderPath) {
- const bytes = session.exportBytes("png", { size: renderSize });
- await writeFile(renderPath, bytes);
+ await writeFile(renderPath, session.exportBytes("png", { size: renderSize }));
}
if (drawPath) {
- const bytes = session.exportBytes("svg");
- await writeFile(drawPath, bytes);
+ await writeFile(drawPath, session.exportBytes("svg"));
}
if (asJson) {
diff --git a/crates/forma-core/examples/perf_bench.rs b/crates/forma-core/examples/perf_bench.rs
index b1076c1..2da1997 100644
--- a/crates/forma-core/examples/perf_bench.rs
+++ b/crates/forma-core/examples/perf_bench.rs
@@ -1,5 +1,5 @@
-//! Microsecond-precision kernel benchmark & invariant gate for autoresearch hill-climbing.
-//! Run with: cargo run --release --offline -p forma-core --example perf_bench
+//! Microsecond-precision kernel benchmark & manifold invariant check.
+//! Run with: cargo run --release -p forma-core --example perf_bench
use forma_core::boolean::BoolOp;
use forma_core::export::write_glb_bytes;
@@ -25,7 +25,7 @@ fn bench_us<F: FnMut()>(iters: usize, mut f: F) -> f64 {
}
fn main() {
- let mut total_12_ms = 0.0;
+ let mut total_suite_ms = 0.0;
// --- Microbenchmarks of individual primitives & ops ---
let us_box = bench_us(200, || { let _ = make_box(2.0, 2.0, 2.0, 1); });
@@ -74,7 +74,7 @@ fn main() {
println!(" write_glb: {:8.1} us", us_glb);
println!(" render_512px: {:8.1} us", us_png);
- // --- Full end-to-end macro benchmarks (the 6 hardest modeling tasks + invariant assertions) ---
+ // --- Full end-to-end macro benchmarks (8 canonical modeling tasks + invariant assertions) ---
println!("\n=== FULL MODELING PIPELINE LATENCY (ms, median of 3, strict WT=true NM=0) ===");
let run_case = |name: &str, exp_vol: f64, f: &dyn Fn() -> Scene| -> f64 {
let mut times = Vec::new();
@@ -93,7 +93,7 @@ fn main() {
let inv = last_inv.unwrap();
assert!(
inv.watertight && inv.non_manifold_edges == 0 && (inv.volume - exp_vol).abs() < 0.03,
- "INVARIANT REGRESSION on {name}: WT={} NM={} B={} vol={:.4} (exp {:.4})",
+ "INVARIANT FAILURE on {name}: WT={} NM={} B={} vol={:.4} (exp {:.4})",
inv.watertight, inv.non_manifold_edges, inv.boundary_edges, inv.volume, exp_vol
);
println!(" {:18} {:8.2} ms V={:5} F={:5} vol={:.4} WT=ok", name, med, inv.verts, inv.faces, inv.volume);
@@ -113,9 +113,9 @@ fn main() {
}
s
});
- total_12_ms += flange_seq;
+ total_suite_ms += flange_seq;
- total_12_ms += run_case("l_bracket", 1.2847, &|| {
+ total_suite_ms += run_case("l_bracket", 1.2847, &|| {
let mut s = Scene::new();
s.add_box("h", 2.0, 1.0, 0.4, Vec3::new(0.0, 0.0, -0.8)).unwrap();
s.add_box("v", 0.4, 1.0, 2.0, Vec3::new(-0.8, 0.0, 0.0)).unwrap();
@@ -127,7 +127,7 @@ fn main() {
s
});
- total_12_ms += run_case("pipe_tee", 3.1074, &|| {
+ total_suite_ms += run_case("pipe_tee", 3.1074, &|| {
let mut s = Scene::new();
s.add_cyl("h", 0.6, 4.0, 28, Vec3::ZERO, 'x').unwrap();
s.add_cyl("v", 0.5, 2.0, 28, Vec3::new(0.0, 0.0, 1.0), 'z').unwrap();
@@ -139,7 +139,7 @@ fn main() {
s
});
- total_12_ms += run_case("beveled_enclosure", 1.5106, &|| {
+ total_suite_ms += run_case("beveled_enclosure", 1.5106, &|| {
let mut s = Scene::new();
s.add_box("enc", 2.4, 1.6, 1.0, Vec3::new(0.0, 0.0, 0.5)).unwrap();
s.bevel("enc", &EdgeSelector::Vertical, 0.15, 3).unwrap();
@@ -147,7 +147,7 @@ fn main() {
s
});
- total_12_ms += run_case("hex_nut", 1.3965, &|| {
+ total_suite_ms += run_case("hex_nut", 1.3965, &|| {
let mut s = Scene::new();
s.add_cyl("nut", 1.0, 0.8, 6, Vec3::ZERO, 'z').unwrap();
s.bevel("nut", &EdgeSelector::OuterRim, 0.1, 1).unwrap();
@@ -156,7 +156,7 @@ fn main() {
s
});
- total_12_ms += run_case("subdiv_mug", 0.6884, &|| {
+ total_suite_ms += run_case("subdiv_mug", 0.6884, &|| {
let mut s = Scene::new();
s.add_cyl("cup", 0.6, 1.4, 32, Vec3::new(0.0, 0.0, 0.7), 'z').unwrap();
s.add_arc_tube("handle", Vec3::new(0.55, 0.0, 0.70), 0.42, 0.35, -90.0, 90.0, 0.08, 16, 12).unwrap();
@@ -166,7 +166,7 @@ fn main() {
s
});
- total_12_ms += run_case("arched_bridge", 5.3759, &|| {
+ total_suite_ms += run_case("arched_bridge", 5.3759, &|| {
let mut s = Scene::new();
s.add_box("blk", 4.0, 1.2, 1.6, Vec3::new(0.0, 0.0, 0.8)).unwrap();
s.bevel("blk", &EdgeSelector::TopRim, 0.1, 2).unwrap();
@@ -175,7 +175,7 @@ fn main() {
s
});
- total_12_ms += run_case("table_frame", 0.4539, &|| {
+ total_suite_ms += run_case("table_frame", 0.4539, &|| {
let mut s = Scene::new();
s.add_box("top", 2.4, 1.4, 0.12, Vec3::new(0.0, 0.0, 0.94)).unwrap();
for &sx in &[-1.04, 1.04] {
@@ -188,7 +188,7 @@ fn main() {
});
println!("--------------------------------------------------------");
- println!("TOTAL SUITE SCORE (lower is better): {:.2} ms", total_12_ms);
+ println!("TOTAL SUITE SCORE (lower is better): {:.2} ms", total_suite_ms);
// Also benchmark batch CSG on flange_plate (5 disjoint holes in 1 BVH pass!)
let batch_flange = run_case("flange_batch_5h", 2.5773, &|| {
diff --git a/crates/forma-core/src/boolean.rs b/crates/forma-core/src/boolean.rs
index da4a790..acd5f3f 100644
--- a/crates/forma-core/src/boolean.rs
+++ b/crates/forma-core/src/boolean.rs
@@ -2379,7 +2379,8 @@ fn tri_plane_overlap_interval(tri: &[Vec3; 3], dists: [f64; 3], line_dir: Vec3,
}
fn tris_overlap_3d(a: &Tri, b: &Tri, scale: f64) -> bool {
- let plane_eps = 1e-7 * scale.max(1e-9);
+ let s = scale.max(1e-9);
+ let plane_eps = 1e-7 * s;
let da = [
b.normal.dot(a.v[0]) - b.w,
b.normal.dot(a.v[1]) - b.w,
@@ -2401,19 +2402,33 @@ fn tris_overlap_3d(a: &Tri, b: &Tri, scale: f64) -> bool {
return false;
}
let line_dir = a.normal.cross(b.normal);
- if line_dir.len_sq() < 1e-10 {
+ if line_dir.len_sq() < 1e-6 {
+ // Parallel or nearly parallel planes: only count as overlapping if genuinely coplanar
+ // and their 2D projections share positive area.
+ if da.iter().any(|d| d.abs() > plane_eps) || db.iter().any(|d| d.abs() > plane_eps) {
+ return false;
+ }
let area = coplanar_tris_overlap_area(&a.v, &b.v, a.normal);
- let area_eps = 1e-10 * scale * scale;
+ let area_eps = 1e-10 * s * s;
return area > area_eps;
}
+ // Non-parallel planes: a triangle strictly on one side of the other's plane cannot intersect it.
+ if (da[0] > 0.0 && da[1] > 0.0 && da[2] > 0.0)
+ || (da[0] < 0.0 && da[1] < 0.0 && da[2] < 0.0)
+ || (db[0] > 0.0 && db[1] > 0.0 && db[2] > 0.0)
+ || (db[0] < 0.0 && db[1] < 0.0 && db[2] < 0.0)
+ {
+ return false;
+ }
let d = line_dir.normalized();
- let Some((ta0, ta1)) = tri_plane_overlap_interval(&a.v, da, d, plane_eps) else {
+ let exact_eps = 1e-12 * s;
+ let Some((ta0, ta1)) = tri_plane_overlap_interval(&a.v, da, d, exact_eps) else {
return false;
};
- let Some((tb0, tb1)) = tri_plane_overlap_interval(&b.v, db, d, plane_eps) else {
+ let Some((tb0, tb1)) = tri_plane_overlap_interval(&b.v, db, d, exact_eps) else {
return false;
};
- ta0.max(tb0) < ta1.min(tb1) - 1e-7 * scale.max(1e-9)
+ ta0.max(tb0) < ta1.min(tb1) - plane_eps
}
/// Fast per-component AABB + BVH inter-shell overlap check for multi-component meshes.
diff --git a/crates/forma-core/src/curves.rs b/crates/forma-core/src/curves.rs
index a496cc5..9e31d93 100644
--- a/crates/forma-core/src/curves.rs
+++ b/crates/forma-core/src/curves.rs
@@ -1,4 +1,4 @@
-//! Tier 1 Curves & 2D Sketch Extrusion with Holes:
+//! Curves & 2D Sketch Extrusion with Holes:
//! - Bezier & clamped uniform B-Spline / NURBS 3D curve evaluators (Cox-de Boor)
//! - 2D polygon extrusion with arbitrary inner holes (mutual-visibility bridge + ear-clipping)
//! - Variable-scale & twist 3D rail sweep (`make_sweep_advanced`)
@@ -419,8 +419,8 @@ pub fn make_sweep_advanced(
tangents.push(tn);
}
- let mut normal = if tangents[0].y.abs() < 0.9 {
- tangents[0].cross(Vec3::Y).normalized()
+ let mut normal = if tangents[0].z.abs() < 0.9 {
+ tangents[0].cross(Vec3::Z).normalized()
} else {
tangents[0].cross(Vec3::X).normalized()
};
diff --git a/crates/forma-core/src/deform.rs b/crates/forma-core/src/deform.rs
index fc8ecee..d81e963 100644
--- a/crates/forma-core/src/deform.rs
+++ b/crates/forma-core/src/deform.rs
@@ -1,4 +1,4 @@
-//! Tier 1 Pure-Rust Modifiers:
+//! Pure-Rust Mesh Modifiers:
//! - True normal-offset `solidify_mesh` (angle-weighted vertex pseudonormals + miter clamping)
//! - Non-linear deformers: `deform_simple` (bend, twist, taper), `deform_curve`, `deform_lattice`
//! with automatic edge pre-subdivision so coarse primitives deform smoothly!
@@ -355,7 +355,7 @@ pub fn deform_simple(
}
}
}
- other => return Err(format!("deform: unknown mode '{other}' (expected bend|twist|taper)")),
+ other => return Err(format!("deform: unknown mode '{other}' (expected bend|twist|taper|curve|lattice)")),
}
out.ensure_outward_winding();
diff --git a/crates/forma-core/src/export.rs b/crates/forma-core/src/export.rs
index 70b6932..ff72b1e 100644
--- a/crates/forma-core/src/export.rs
+++ b/crates/forma-core/src/export.rs
@@ -1,5 +1,5 @@
-//! Fast native exporters: Binary glTF 2.0 (.glb), Wavefront (.obj), Binary (.stl),
-//! and optional stock-Blender .blend bridge.
+//! Native exporters: Binary glTF 2.0 (.glb), Wavefront (.obj), Binary (.stl),
+//! 3MF (.3mf), faceted STEP (.step/.stp), and Blender (.blend via optional Blender CLI bridge).
use crate::math::Vec3;
use crate::mesh::PolyMesh;
@@ -936,13 +936,117 @@ pub fn export_mesh_bytes_with_unit(mesh: &PolyMesh, ext: &str, unit: Unit) -> Re
}
}
-/// Export by extension (.glb, .obj, .stl, .3mf, .step, .stp), treating model coordinates as metres.
+/// Convert glTF 2.0 binary (`.glb`) bytes into a native Blender `.blend` file via Blender CLI.
+///
+/// Locates Blender via `BLENDER_BIN`, then `blender` on `PATH`, and on macOS falls back to
+/// `/Applications/Blender.app/Contents/MacOS/Blender`.
+#[cfg(not(target_arch = "wasm32"))]
+pub fn write_blend_from_glb_bytes(glb_bytes: &[u8], out: &Path) -> Result<(), String> {
+ use std::process::Command;
+ use std::sync::atomic::{AtomicU64, Ordering};
+
+ static COUNTER: AtomicU64 = AtomicU64::new(0);
+
+ let abs_out = if out.is_absolute() {
+ out.to_path_buf()
+ } else {
+ std::env::current_dir()
+ .map_err(|e| format!("resolve current dir: {e}"))?
+ .join(out)
+ };
+ if let Some(parent) = abs_out.parent() {
+ if !parent.as_os_str().is_empty() {
+ std::fs::create_dir_all(parent)
+ .map_err(|e| format!("create output dir {}: {e}", parent.display()))?;
+ }
+ }
+
+ let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
+ let tmp_glb = std::env::temp_dir().join(format!(
+ "forma_blend_bridge_{}_{}.glb",
+ std::process::id(),
+ seq
+ ));
+ std::fs::write(&tmp_glb, glb_bytes)
+ .map_err(|e| format!("write temp glb {}: {e}", tmp_glb.display()))?;
+
+ let py = format!(
+ "import bpy; bpy.ops.wm.read_factory_settings(use_empty=True); \
+ bpy.ops.import_scene.gltf(filepath={:?}); \
+ bpy.ops.wm.save_as_mainfile(filepath={:?})",
+ tmp_glb.to_string_lossy(),
+ abs_out.to_string_lossy()
+ );
+
+ let candidates: Vec<String> = match std::env::var("BLENDER_BIN") {
+ Ok(v) if !v.trim().is_empty() => vec![v],
+ _ => {
+ let mut list = vec!["blender".to_string()];
+ #[cfg(target_os = "macos")]
+ list.push("/Applications/Blender.app/Contents/MacOS/Blender".to_string());
+ list
+ }
+ };
+
+ let mut last_not_found = false;
+ let mut result = None;
+ for bin in &candidates {
+ match Command::new(bin)
+ .args(["--background", "--factory-startup", "--python-expr", &py])
+ .output()
+ {
+ Ok(output) => {
+ result = Some((bin.as_str(), output));
+ break;
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+ last_not_found = true;
+ continue;
+ }
+ Err(e) => {
+ let _ = std::fs::remove_file(&tmp_glb);
+ return Err(format!("failed to invoke Blender bridge ({bin}): {e}"));
+ }
+ }
+ }
+ let _ = std::fs::remove_file(&tmp_glb);
+
+ let Some((bin, output)) = result else {
+ let tried = candidates.join(", ");
+ let hint = if last_not_found {
+ "install Blender or set BLENDER_BIN=/path/to/blender"
+ } else {
+ "set BLENDER_BIN=/path/to/blender"
+ };
+ return Err(format!(
+ "Blender executable not found for .blend export (tried: {tried}; {hint})"
+ ));
+ };
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
+ return Err(format!("Blender .blend export failed ({bin}): {detail}"));
+ }
+ Ok(())
+}
+
+/// Export a PolyMesh to a Blender `.blend` file via the optional Blender CLI bridge.
+#[cfg(not(target_arch = "wasm32"))]
+pub fn write_blend_with_unit(mesh: &PolyMesh, path: &Path, unit: Unit) -> Result<(), String> {
+ let glb_bytes = write_glb_bytes_with_unit(mesh, true, unit)?;
+ write_blend_from_glb_bytes(&glb_bytes, path)
+}
+
+/// Export by extension (.glb, .obj, .stl, .3mf, .step, .stp, and .blend on native),
+/// treating model coordinates as metres.
pub fn export_mesh(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
export_mesh_with_unit(mesh, path, Unit::Meter)
}
-/// Export by extension (.glb, .obj, .stl, .3mf, .step, .stp) for a model authored in `unit`
-/// (see [`export_mesh_bytes_with_unit`] for per-format behaviour).
+/// Export by extension (.glb, .obj, .stl, .3mf, .step, .stp, and .blend on native)
+/// for a model authored in `unit` (see [`export_mesh_bytes_with_unit`] for per-format behaviour).
pub fn export_mesh_with_unit(mesh: &PolyMesh, path: &Path, unit: Unit) -> Result<(), String> {
let ext = path
.extension()
@@ -955,6 +1059,14 @@ pub fn export_mesh_with_unit(mesh: &PolyMesh, path: &Path, unit: Unit) -> Result
"stl" => write_stl_binary(mesh, path),
"3mf" => write_3mf_with_unit(mesh, path, unit),
"step" | "stp" => write_step_with_unit(mesh, path, unit),
- _ => Err(format!("unsupported export extension '.{ext}' (supported: .glb, .obj, .stl, .3mf, .step)")),
+ #[cfg(not(target_arch = "wasm32"))]
+ "blend" => write_blend_with_unit(mesh, path, unit),
+ _ => {
+ #[cfg(not(target_arch = "wasm32"))]
+ let supported = ".glb, .obj, .stl, .3mf, .step, .blend";
+ #[cfg(target_arch = "wasm32")]
+ let supported = ".glb, .obj, .stl, .3mf, .step";
+ Err(format!("unsupported export extension '.{ext}' (supported: {supported})"))
+ }
}
}
diff --git a/crates/forma-core/src/invariants.rs b/crates/forma-core/src/invariants.rs
index 4d72d63..4ac01a7 100644
--- a/crates/forma-core/src/invariants.rs
+++ b/crates/forma-core/src/invariants.rs
@@ -207,10 +207,10 @@ impl MeshInvariants {
self.signed_volume / self.surface_area.powf(1.5)
}
- /// True for a part with no volume to build on: empty, inside out, or a sheet whose thickness is about
- /// a billionth of its width (`compactness() <= MIN_COMPACTNESS`). A 0.1 mm cube passes where an absolute
- /// floor such as `1e-12` cubic units would refuse it, and so do a long thin bar and copies far apart,
- /// which a floor on the bounding box would refuse.
+ /// True for a part with negligible solid volume: empty, inverted, or a sheet thinner than
+ /// `MIN_COMPACTNESS` (`signed_volume / surface_area^1.5`). Using dimensionless compactness
+ /// makes the check scale-invariant across model sizes (from sub-millimetre parts to multi-metre
+ /// assemblies and thin beams).
pub fn has_negligible_volume(&self) -> bool {
let c = self.compactness();
!(self.signed_volume.is_finite()
diff --git a/crates/forma-core/src/remesh.rs b/crates/forma-core/src/remesh.rs
index 75e7d7b..65015d5 100644
--- a/crates/forma-core/src/remesh.rs
+++ b/crates/forma-core/src/remesh.rs
@@ -315,7 +315,7 @@ pub fn remesh_voxel(mesh: &PolyMesh, voxel_size: f64, op_id: u32) -> Result<Poly
}
out.ensure_outward_winding();
- // Exact 1-step surface-normal volume calibration (matches input volume with 0 topology change!)
+ // Two-pass damped surface-normal volume calibration to match input volume with zero topology change.
let target_vol = mesh.signed_volume().abs();
let vol_cal_gain: f64 = 0.9641;
let vol_cal_gain2: f64 = 0.9641;
diff --git a/crates/forma-core/src/render.rs b/crates/forma-core/src/render.rs
index 4391d23..cff04d4 100644
--- a/crates/forma-core/src/render.rs
+++ b/crates/forma-core/src/render.rs
@@ -737,8 +737,20 @@ fn adler32(data: &[u8]) -> u32 {
(s2 << 16) | s1
}
-/// Render a crisp vector 1200x900 orthographic + isometric SVG technical blueprint into a String.
+/// Render a crisp vector 1200x900 orthographic + isometric SVG technical blueprint into a String
+/// (using metres for dimension labels).
pub fn render_blueprint_svg_string(mesh: &PolyMesh, title: &str) -> Result<String, String> {
+ render_blueprint_svg_string_with_unit(mesh, title, crate::units::Unit::Meter)
+}
+
+/// Render a crisp vector 1200x900 orthographic + isometric SVG technical blueprint into a String,
+/// labeling dimensions and volume with `unit`.
+pub fn render_blueprint_svg_string_with_unit(
+ mesh: &PolyMesh,
+ title: &str,
+ unit: crate::units::Unit,
+) -> Result<String, String> {
+ let unit_sym = unit.symbol();
if mesh.faces.is_empty() || mesh.verts.is_empty() {
return Err("cannot draw blueprint of empty mesh".into());
}
@@ -746,9 +758,9 @@ pub fn render_blueprint_svg_string(mesh: &PolyMesh, title: &str) -> Result<Strin
let bb = mesh.aabb();
let sz = bb.size();
- // Collect crisp feature edges (dihedral > 22 deg or boundary)
+ // Collect crisp feature edges in deterministic order (dihedral > 22 deg or boundary)
let face_normals: Vec<Vec3> = (0..mesh.faces.len()).map(|fi| mesh.face_normal(fi)).collect();
- let mut edge_map: HashMap<(usize, usize), Vec<usize>> = HashMap::with_capacity(mesh.faces.len() * 2);
+ let mut edge_map: std::collections::BTreeMap<(usize, usize), Vec<usize>> = std::collections::BTreeMap::new();
for (fi, f) in mesh.faces.iter().enumerate() {
let n = f.verts.len();
for i in 0..n {
@@ -838,7 +850,7 @@ pub fn render_blueprint_svg_string(mesh: &PolyMesh, title: &str) -> Result<Strin
<line x1="{min_x:.1}" y1="{max_y:.1}" x2="{min_x:.1}" y2="{:.1}" stroke-opacity="0.45"/>
<line x1="{max_x:.1}" y1="{max_y:.1}" x2="{max_x:.1}" y2="{:.1}" stroke-opacity="0.45"/>
<line x1="{min_x:.1}" y1="{dy:.1}" x2="{max_x:.1}" y2="{dy:.1}" marker-start="url(#arr)" marker-end="url(#arr)"/>
-<text x="{:.1}" y="{:.1}" text-anchor="middle" stroke="none">{dim_h:.3} m</text>
+<text x="{:.1}" y="{:.1}" text-anchor="middle" stroke="none">{dim_h:.3} {unit_sym}</text>
"##,
dy + 5.0, dy + 5.0, 0.5 * (min_x + max_x), dy + 16.0
));
@@ -847,7 +859,7 @@ pub fn render_blueprint_svg_string(mesh: &PolyMesh, title: &str) -> Result<Strin
r##"<line x1="{max_x:.1}" y1="{min_y:.1}" x2="{:.1}" y2="{min_y:.1}" stroke-opacity="0.45"/>
<line x1="{max_x:.1}" y1="{max_y:.1}" x2="{:.1}" y2="{max_y:.1}" stroke-opacity="0.45"/>
<line x1="{dx:.1}" y1="{min_y:.1}" x2="{dx:.1}" y2="{max_y:.1}" marker-start="url(#arr)" marker-end="url(#arr)"/>
-<text x="{:.1}" y="{:.1}" stroke="none">{dim_v:.3} m</text>
+<text x="{:.1}" y="{:.1}" stroke="none">{dim_v:.3} {unit_sym}</text>
</g>
"##,
dx + 5.0, dx + 5.0, dx + 8.0, 0.5 * (min_y + max_y) + 4.0
@@ -859,15 +871,16 @@ pub fn render_blueprint_svg_string(mesh: &PolyMesh, title: &str) -> Result<Strin
// ISO Engineering Title Block
let wt_str = if inv.watertight && inv.non_manifold_edges == 0 { "WATERTIGHT (NM=0)" } else { "NON-MANIFOLD" };
let esc_title = title.replace('&', "&amp;").replace('<', "&lt;");
+ let version = env!("CARGO_PKG_VERSION");
svg.push_str(&format!(
r##"<g font-family="ui-monospace, Menlo, monospace">
<rect x="615" y="795" width="555" height="75" fill="#ffffff" stroke="#1e293b" stroke-width="1.5"/>
<line x1="615" y1="825" x2="1170" y2="825" stroke="#1e293b" stroke-width="1"/>
<line x1="900" y1="825" x2="900" y2="870" stroke="#1e293b" stroke-width="1"/>
<text x="628" y="815" font-size="14" font-weight="700" fill="#0f172a">PART: {esc_title}</text>
-<text x="1158" y="815" text-anchor="end" font-size="12" font-weight="700" fill="#2563eb">FORMA v0.4 CAD</text>
-<text x="628" y="844" font-size="11" fill="#334155">SIZE: {:.3} x {:.3} x {:.3} m</text>
-<text x="628" y="861" font-size="11" fill="#334155">VOL: {:.4} m^3 | GENUS: {}</text>
+<text x="1158" y="815" text-anchor="end" font-size="12" font-weight="700" fill="#2563eb">FORMA v{version} CAD</text>
+<text x="628" y="844" font-size="11" fill="#334155">SIZE: {:.3} x {:.3} x {:.3} {unit_sym}</text>
+<text x="628" y="861" font-size="11" fill="#334155">VOL: {:.4} {unit_sym}^3 | GENUS: {}</text>
<text x="912" y="844" font-size="11" fill="#334155">MESH: V={} F={}</text>
<text x="912" y="861" font-size="11" font-weight="700" fill="#059669">{wt_str}</text>
</g>
@@ -878,9 +891,20 @@ pub fn render_blueprint_svg_string(mesh: &PolyMesh, title: &str) -> Result<Strin
Ok(svg)
}
-/// Export a crisp vector 1200x900 orthographic + isometric SVG technical blueprint to disk.
+/// Export a crisp vector 1200x900 orthographic + isometric SVG technical blueprint to disk (in metres).
pub fn write_blueprint_svg(mesh: &PolyMesh, title: &str, path: &Path) -> Result<(), String> {
- let svg = render_blueprint_svg_string(mesh, title)?;
+ write_blueprint_svg_with_unit(mesh, title, path, crate::units::Unit::Meter)
+}
+
+/// Export a crisp vector 1200x900 orthographic + isometric SVG technical blueprint to disk,
+/// labeling dimensions and volume with `unit`.
+pub fn write_blueprint_svg_with_unit(
+ mesh: &PolyMesh,
+ title: &str,
+ path: &Path,
+ unit: crate::units::Unit,
+) -> Result<(), String> {
+ let svg = render_blueprint_svg_string_with_unit(mesh, title, unit)?;
let f = File::create(path).map_err(|e| format!("create {}: {e}", path.display()))?;
let mut bw = BufWriter::new(f);
bw.write_all(svg.as_bytes()).map_err(|e| e.to_string())?;
diff --git a/crates/forma-core/src/spatial.rs b/crates/forma-core/src/spatial.rs
index f585c1d..cca7595 100644
--- a/crates/forma-core/src/spatial.rs
+++ b/crates/forma-core/src/spatial.rs
@@ -337,8 +337,8 @@ pub fn clearance(a: &PolyMesh, b: &PolyMesh) -> ClearanceReport {
/// Exact 2D horizontal cross-section query at elevation `Z = z`.
pub fn section_z(mesh: &PolyMesh, z: f64) -> SectionReport {
- // Slightly nudge z by 1e-7 if needed? No — use exact half-open [z, +inf) classification
- // so horizontal triangles at exact z don't double-count edges!
+ // Use exact half-open [z, +inf) vertex classification so horizontal faces at exact z
+ // do not double-count cross-section edges.
let mut segs: Vec<((f64, f64), (f64, f64))> = Vec::new();
let mut min_x = f64::INFINITY;
let mut min_y = f64::INFINITY;
diff --git a/crates/forma-core/src/units.rs b/crates/forma-core/src/units.rs
index 031c53e..e0dabea 100644
--- a/crates/forma-core/src/units.rs
+++ b/crates/forma-core/src/units.rs
@@ -1,7 +1,7 @@
//! Model length units.
//!
//! Forma geometry is unitless internally: a coordinate of `1.0` means "one model unit".
-//! The model unit defaults to the metre (historic behaviour) and can be set to anything
+//! The model unit defaults to the metre and can be set to anything
//! the export formats can describe (e.g. millimetres for a 3D-printed case). Exporters that
//! carry a unit (3MF, STEP) declare it; glTF (always metres by spec) is scaled from it;
//! OBJ/STL have no unit field and are written in model units.
diff --git a/crates/forma-core/src/uv.rs b/crates/forma-core/src/uv.rs
index 005ef83..8db2a7a 100644
--- a/crates/forma-core/src/uv.rs
+++ b/crates/forma-core/src/uv.rs
@@ -725,8 +725,8 @@ fn try_pack_single(
Some(placed)
}
-/// Multi-strategy MaxRects packer: evaluates 3 sort orders (MaxSide, Area, Perimeter) x
-/// 3 heuristics (BSSF, BAF, BL), returning the first feasible packing at target bin size!
+/// Multi-strategy MaxRects packer: evaluates 6 sort orders across 4 heuristics (BSSF, BAF, BL, CP)
+/// plus deterministic 2-opt swaps, returning the first feasible packing at the target bin size.
fn try_pack_maxrects(sizes: &[(f64, f64)], bin: f64, pad: f64) -> Option<Vec<(f64, f64, bool)>> {
let n = sizes.len();
let mut ord_max: Vec<usize> = (0..n).collect();
diff --git a/crates/forma-core/tests/issue_regressions.rs b/crates/forma-core/tests/issue_regressions.rs
index fe4bb6b..aa951c4 100644
--- a/crates/forma-core/tests/issue_regressions.rs
+++ b/crates/forma-core/tests/issue_regressions.rs
@@ -1,4 +1,5 @@
-//! Regression tests for upstream issues (one or more tests per issue number).
+//! Kernel invariant tests for multi-shell overlap checks, extreme-ratio CSG,
+//! self-intersection guards, exact inset geometry, text3d glyph validation, and revolve bounds.
use forma_core::boolean::{check_overlapping_components, has_overlapping_components, OverlapCheck};
use forma_core::invariants::MeshInvariants;
use forma_core::math::Vec3;
@@ -20,8 +21,8 @@ fn add_tet(m: &mut PolyMesh, a: Vec3, b: Vec3, c: Vec3, d: Vec3) {
}
}
-/// Issue #17 repro: N long thin parallel tetrahedra along (1,1,0). No two intersect,
-/// but every pair of axis-aligned shell boxes overlaps.
+/// N long thin parallel tetrahedra along (1,1,0): no two intersect, though every pair of
+/// axis-aligned shell bounding boxes overlaps.
fn sliver_mesh(n: usize) -> PolyMesh {
let mut m = PolyMesh::new();
let l = 10.0;
@@ -65,9 +66,8 @@ fn loose_shell_mesh(n: usize) -> PolyMesh {
}
#[test]
-fn issue17_overlap_check_is_near_linear_on_thousands_of_shells() {
- // 8,000 diagonal slivers took 35 s in the shell-pair loop; 6,000 loose shells are the
- // shape of an imported mesh made of many small pieces. Both must clear in well under a second each.
+fn overlap_check_is_near_linear_on_thousands_of_shells() {
+ // Parallel diagonal slivers (overlapping AABBs) and jittered loose shells must both clear rapidly.
let slivers = sliver_mesh(8000);
let t0 = Instant::now();
let r = check_overlapping_components(&slivers);
@@ -80,15 +80,15 @@ fn issue17_overlap_check_is_near_linear_on_thousands_of_shells() {
let dt_loose = t1.elapsed().as_secs_f64();
assert_eq!(r2, OverlapCheck::Clear, "jittered grid shells do not overlap");
- println!("issue17: 8000 slivers {dt_sliver:.3}s, 6000 loose shells {dt_loose:.3}s");
+ println!("overlap_check: 8000 slivers {dt_sliver:.3}s, 6000 loose shells {dt_loose:.3}s");
let sliver_limit = if cfg!(debug_assertions) { 5.0 } else { 1.0 };
let loose_limit = if cfg!(debug_assertions) { 5.0 } else { 1.0 };
- assert!(dt_sliver < sliver_limit, "8000 slivers took {dt_sliver:.2}s (was ~35 s)");
- assert!(dt_loose < loose_limit, "6000 loose shells took {dt_loose:.2}s");
+ assert!(dt_sliver < sliver_limit, "8000 slivers took {dt_sliver:.2}s (limit {sliver_limit:.1}s)");
+ assert!(dt_loose < loose_limit, "6000 loose shells took {dt_loose:.2}s (limit {loose_limit:.1}s)");
}
#[test]
-fn issue17_strict_eval_path_on_slivers_is_fast_and_ok() {
+fn strict_eval_path_on_slivers_is_fast_and_ok() {
let mut s = Scene::new();
s.strict_manifold = true;
let t0 = Instant::now();
@@ -98,11 +98,11 @@ fn issue17_strict_eval_path_on_slivers_is_fast_and_ok() {
assert_eq!(inv.components, 4000);
assert!(obs.warnings.iter().all(|w| !w.contains("overlap")), "{:?}", obs.warnings);
let eval_limit = if cfg!(debug_assertions) { 15.0 } else { 2.0 };
- assert!(dt < eval_limit, "strict set_part + observe on 4000 slivers took {dt:.2}s (was ~7 s)");
+ assert!(dt < eval_limit, "strict set_part + observe on 4000 slivers took {dt:.2}s (limit {eval_limit:.1}s)");
}
#[test]
-fn issue17_overlap_check_still_detects_crossing_contained_and_coplanar_shells() {
+fn overlap_check_detects_crossing_contained_and_coplanar_shells() {
// Crossing shells among thousands of clean ones.
let mut m = loose_shell_mesh(3000);
let o = Vec3::new(0.05, 0.05, 0.05);
@@ -136,11 +136,11 @@ fn issue17_overlap_check_still_detects_crossing_contained_and_coplanar_shells()
}
// ---------------------------------------------------------------------------------------------
-// Issue #23: `cut` silently did nothing at large part/cutter size ratios.
+// Extreme part-to-cutter size ratios in boolean difference
// ---------------------------------------------------------------------------------------------
#[test]
-fn issue23_cut_resolves_small_cutter_in_large_part() {
+fn cut_resolves_small_cutter_in_large_part() {
use forma_core::boolean::BoolOp;
// 32-gon prism area for r = 1.
let ngon_area = 0.5 * 32.0 * (2.0 * std::f64::consts::PI / 32.0).sin();
@@ -164,7 +164,7 @@ fn issue23_cut_resolves_small_cutter_in_large_part() {
}
#[test]
-fn issue23_millimetre_plate_small_hole_is_clean() {
+fn millimetre_plate_small_hole_is_clean() {
use forma_core::boolean::{has_self_intersections, BoolOp};
let mut s = Scene::new();
s.strict_manifold = true;
@@ -177,7 +177,7 @@ fn issue23_millimetre_plate_small_hole_is_clean() {
}
#[test]
-fn issue23_unresolvable_ratio_fails_loudly_never_silently() {
+fn unresolvable_ratio_fails_loudly_never_silently() {
use forma_core::boolean::BoolOp;
// Far past f64-resolvable ratios the cut must either work or say why: never return the box.
for size in [1.0e9, 1.0e12, 1.0e15] {
@@ -199,11 +199,11 @@ fn issue23_unresolvable_ratio_fails_loudly_never_silently() {
}
// ---------------------------------------------------------------------------------------------
-// Issue #24: strict missed single-shell self-intersection (negative extrude, tube paths).
+// Single-shell self-intersection guards (deformed meshes, negative extrude, tube paths, empty CSG)
// ---------------------------------------------------------------------------------------------
#[test]
-fn issue24_strict_rejects_single_shell_self_intersection() {
+fn strict_rejects_single_shell_self_intersection() {
use forma_core::boolean::has_self_intersections;
// One closed, consistently wound shell whose corner is dragged through the opposite faces.
let mut m = forma_core::primitives::make_box(2.0, 2.0, 2.0, 1);
@@ -231,7 +231,7 @@ fn issue24_strict_rejects_single_shell_self_intersection() {
}
#[test]
-fn issue24_negative_extrude_cuts_a_pocket_instead_of_folding_walls() {
+fn negative_extrude_cuts_a_pocket_instead_of_folding_walls() {
use forma_core::boolean::has_self_intersections;
use forma_core::selector::FaceSelector;
let mut s = Scene::new();
@@ -259,7 +259,7 @@ fn issue24_negative_extrude_cuts_a_pocket_instead_of_folding_walls() {
}
#[test]
-fn issue24_tube_repeated_closing_and_foldback_paths() {
+fn tube_repeated_closing_and_foldback_paths() {
use forma_core::boolean::has_self_intersections;
use forma_core::primitives::make_tube;
let p = |x: f64, y: f64| Vec3::new(x, y, 0.0);
@@ -289,10 +289,10 @@ fn issue24_tube_repeated_closing_and_foldback_paths() {
}
}
-// New bug found while fixing #24: a cut or intersect whose true result is empty returned the
-// perturbation skin (a watertight zero-thickness shell) and strict accepted it.
+/// A cut or intersect whose true result is empty must return an empty mesh rather than a
+/// zero-thickness perturbation skin.
#[test]
-fn hunt_cut_or_intersect_with_empty_true_result_never_returns_a_skin() {
+fn cut_or_intersect_with_empty_result_never_returns_a_skin() {
use forma_core::boolean::{boolean_op, BoolOp};
let a = forma_core::primitives::make_box(2.0, 2.0, 2.0, 1);
let same = boolean_op(&a, &a.clone(), BoolOp::Difference, None, 2).unwrap();
@@ -313,11 +313,11 @@ fn hunt_cut_or_intersect_with_empty_true_result_never_returns_a_skin() {
}
// ---------------------------------------------------------------------------------------------
-// Issue #25: inset(amt) moved vertices by a clamped centroid fraction.
+// Exact edge-offset inset geometry and bounds validation
// ---------------------------------------------------------------------------------------------
#[test]
-fn issue25_inset_border_is_exactly_amount_wide_on_every_side() {
+fn inset_border_is_exactly_amount_wide_on_every_side() {
use forma_core::selector::FaceSelector;
// 4 x 1 top face, border 0.3, floor 0.5 down: the floor is exactly 3.4 x 0.4 and the rim
// slopes from the face outline to it, so the pocket is a prismatoid.
@@ -328,7 +328,7 @@ fn issue25_inset_border_is_exactly_amount_wide_on_every_side() {
let expect_vol = 4.0 - 0.5 / 6.0 * (4.0 * 1.0 + 4.0 * (3.7 * 0.7) + 3.4 * 0.4);
assert!((inv.volume - expect_vol).abs() < 1e-9, "vol {} expected {expect_vol}", inv.volume);
let sec = s.section_z("p", 0.75).unwrap();
- // Half way down the opening is 3.7 x 0.7: wall area 1.41 (the issue measured 0.56).
+ // Halfway down the opening is 3.7 x 0.7 (wall area = 1.41).
assert!((sec.area - (4.0 - 3.7 * 0.7)).abs() < 1e-6, "wall area {} expected {}", sec.area, 4.0 - 3.7 * 0.7);
// The inner face corners sit exactly 0.3 from both adjacent edges.
@@ -344,7 +344,7 @@ fn issue25_inset_border_is_exactly_amount_wide_on_every_side() {
assert!((p.x.abs() - 1.7).abs() < 1e-12 && (p.y.abs() - 0.2).abs() < 1e-12, "{p:?}");
}
- // A tiny amount stays tiny (it used to be raised to 2% of the face).
+ // Small positive inset amounts are preserved verbatim without silent clamping.
let b = forma_core::primitives::make_box(2.0, 2.0, 2.0, 1);
let tiny = forma_core::ops::inset_faces(&b, &FaceSelector::Top, 1e-4, 0.0, 2).unwrap();
let max_x = tiny.faces.iter().filter(|f| f.has_tag("inner")).flat_map(|f| f.verts.iter().map(|&v| tiny.verts[v].x)).fold(0.0, f64::max);
@@ -352,10 +352,10 @@ fn issue25_inset_border_is_exactly_amount_wide_on_every_side() {
}
#[test]
-fn issue25_inset_that_cannot_fit_or_is_not_positive_is_an_error() {
+fn inset_that_cannot_fit_or_is_not_positive_is_an_error() {
use forma_core::selector::FaceSelector;
let b = forma_core::primitives::make_box(4.0, 1.0, 1.0, 1);
- // 0.5 would close the 1-wide face completely; it used to be clamped silently.
+ // 0.5 collapses the 1-wide face completely and must return an error.
let err = forma_core::ops::inset_faces(&b, &FaceSelector::Top, 0.5, 0.0, 2).unwrap_err();
assert!(err.starts_with("inset:") && err.contains("does not fit") && err.contains("0.5"), "{err}");
assert!(forma_core::ops::inset_faces(&b, &FaceSelector::Top, 0.49, 0.0, 2).is_ok());
@@ -367,11 +367,11 @@ fn issue25_inset_that_cannot_fit_or_is_not_positive_is_an_error() {
}
// ---------------------------------------------------------------------------------------------
-// Issue #26: text3d blanked unsupported glyphs; revolve accepted negative radii.
+// Input validation for text3d glyphs and revolve radii
// ---------------------------------------------------------------------------------------------
#[test]
-fn issue26_text3d_names_unsupported_characters() {
+fn text3d_names_unsupported_characters() {
use forma_core::primitives::make_text_3d;
assert!(make_text_3d("Acao 12-3.4_5:6", 0.5, 0.1, 1).is_ok());
let err = make_text_3d("A\u{e7}\u{e3}o \u{f1} \u{20ac}", 0.5, 0.1, 1).unwrap_err();
@@ -385,7 +385,7 @@ fn issue26_text3d_names_unsupported_characters() {
}
#[test]
-fn issue26_revolve_rejects_negative_and_non_finite_radii() {
+fn revolve_rejects_negative_and_non_finite_radii() {
use forma_core::primitives::make_revolve;
let err = make_revolve(&[(0.0, 0.0), (1.0, 0.0), (-0.5, 1.0), (0.0, 1.0)], 32, 1).unwrap_err();
assert!(err.starts_with("revolve:") && err.contains("negative radius") && err.contains("point 2"), "{err}");
diff --git a/crates/forma-core/tests/kernel_tests.rs b/crates/forma-core/tests/kernel_tests.rs
index 8e32ccd..5095959 100644
--- a/crates/forma-core/tests/kernel_tests.rs
+++ b/crates/forma-core/tests/kernel_tests.rs
@@ -7,7 +7,7 @@ use std::time::Instant;
#[test]
fn test_coplanar_union_exact_watertight() {
- // Classic failure case where Blender 5.3 FLOAT boolean fails (vol=8, NM=22)
+ // Coplanar-face union of two touching cubes must merge cleanly with zero non-manifold edges.
let mut s = Scene::new();
s.strict_manifold = true;
s.add_box("a", 2.0, 2.0, 2.0, Vec3::ZERO).unwrap();
@@ -242,7 +242,7 @@ fn test_all_12_benchmark_geometries_and_export() {
#[test]
fn test_chained_top_and_bottom_rim_bevel_matches_outer_rim() {
- // Regression test for the #1 empirical LLM Pass@1 failure (hex_nut bevel shrinkage bug)
+ // Chaining bevel(top_rim) then bevel(bottom_rim) must preserve rim dimensions identically to bevel(outer_rim).
let build = |mode: u8| -> MeshInvariants {
let mut s = Scene::new();
s.strict_manifold = true;
@@ -348,7 +348,7 @@ fn test_pbr_materials_spatial_queries_and_headless_png_renderer() {
}
#[test]
-fn test_v03_pipe_loft_thread_creased_subsurf_and_3mf_export() {
+fn test_pipe_loft_thread_creased_subsurf_and_3mf_export() {
// 1. Pipe primitive: exact genus=1, watertight, 0 non-manifold edges
let pipe = forma_core::primitives::make_pipe(0.6, 0.4, 2.0, 32, 1).unwrap();
let pinv = MeshInvariants::compute(&pipe);
@@ -388,7 +388,7 @@ fn test_v03_pipe_loft_thread_creased_subsurf_and_3mf_export() {
}
#[test]
-fn test_v04_step_blueprint_svg_sweep_and_text3d() {
+fn test_step_blueprint_svg_sweep_and_text3d() {
// 1. Arbitrary 2D profile sweep along 3D L-rail
let prof = [(-0.1, -0.05), (0.1, -0.05), (0.1, 0.05), (-0.1, 0.05)];
let path = [Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 0.0)];
@@ -416,7 +416,7 @@ fn test_v04_step_blueprint_svg_sweep_and_text3d() {
}
#[test]
-fn test_issue_1_strict_patterns_zero_vol_and_scale_invariant_csg() {
+fn test_strict_patterns_zero_vol_and_scale_invariant_csg() {
// 1. Overlapping linear pattern: union=true merges cleanly; union=false rejected under strict
let mut s = Scene::new();
s.strict_manifold = true;
@@ -533,9 +533,7 @@ fn test_glb_yup_roundtrip_legacy_compat_and_import_fixes() {
assert!((rt_zup.aabb().min - orig_bb.min).len() < 1e-4);
assert!((rt_zup.aabb().max - orig_bb.max).len() < 1e-4);
- // Legacy forma-core 0.2 GLB (without extras.forma_yup) stays Z-up by default
- let mut legacy_json = gltf.clone();
- legacy_json["asset"] = serde_json::json!({"version": "2.0", "generator": "forma-core 0.2"});
+ // Older forma-core GLBs without extras.forma_yup stay Z-up on import
let glb_raw_z = write_glb_bytes(&orig, false).unwrap();
let ljlen = u32::from_le_bytes([glb_raw_z[12], glb_raw_z[13], glb_raw_z[14], glb_raw_z[15]]) as usize;
let bin_part = &glb_raw_z[20 + ljlen..];
@@ -600,7 +598,7 @@ fn test_glb_yup_roundtrip_legacy_compat_and_import_fixes() {
#[test]
fn test_ergonomics_radial_axis_disjoint_array_caps_and_high_segs() {
- // 1. High-resolution wheel rim (segs=96, previously clamped at 48)
+ // 1. High-resolution wheel rim (segs=96)
let rim = forma_core::primitives::make_pipe(1.0, 0.88, 0.14, 96, 1).unwrap();
let rinv = MeshInvariants::compute(&rim);
assert!(rinv.is_valid_solid() && rinv.genus == 1 && rinv.faces == 96 * 4, "rim={rinv:?}");
@@ -619,7 +617,7 @@ fn test_ergonomics_radial_axis_disjoint_array_caps_and_high_segs() {
let ybb = ring_y.aabb();
assert!((ybb.size().y - 0.04).abs() < 1e-4 && ybb.size().x > 1.8 && ybb.size().z > 1.8, "axis=y ring should lie in XZ plane: {ybb:?}");
- // 3. 100-instance disjoint linear array passes via O(1) AABB fast-path (previously capped at 32)
+ // 3. 100-instance disjoint linear array passes via O(1) AABB fast-path
let plank = forma_core::primitives::make_box(0.05, 1.0, 0.02, 5);
let deck = forma_core::ops::array_linear(&plank, 100, Vec3::new(0.1, 0.0, 0.0), true, 6).unwrap();
let dinv = MeshInvariants::compute(&deck);
@@ -680,11 +678,11 @@ fn test_bevel_xy_clamping_solidify_guard_and_bvh_self_intersection() {
}
#[test]
-fn test_issue_5_rim_breaking_scallop_cuts() {
+fn test_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))
+ // Hollow ring 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();
@@ -706,7 +704,7 @@ fn test_issue_5_rim_breaking_scallop_cuts() {
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:?}");
+ assert!(sinv.is_valid_solid() && sinv.genus == 1, "single 120-deg scallop cut failed: {sinv:?}");
// 2. All 6 batched cuts
let tools: Vec<_> = pts
@@ -719,7 +717,7 @@ fn test_issue_5_rim_breaking_scallop_cuts() {
.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:?}");
+ assert!(binv.is_valid_solid() && binv.genus == 1, "batched 6 scallop cuts failed: {binv:?}");
// 3. All 6 sequential cuts
let mut seq = base.clone();
@@ -727,7 +725,7 @@ fn test_issue_5_rim_breaking_scallop_cuts() {
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:?}");
+ assert!(qinv.is_valid_solid() && qinv.genus == 1, "sequential 6 scallop cuts failed: {qinv:?}");
}
#[test]
@@ -777,7 +775,7 @@ fn test_batch_hole_rows_8_to_20_holes_all_scales() {
}
#[test]
-fn test_issues_10_11_twisted_loft_shell_cut_and_scale_invariant_vol() {
+fn test_twisted_loft_shell_cut_and_scale_invariant_vol() {
use std::f64::consts::PI;
// 1. Scale-invariant negligible-volume check: tiny 1e-4 cube passes, giant pancake fails
@@ -840,25 +838,25 @@ fn test_issues_10_11_twisted_loft_shell_cut_and_scale_invariant_vol() {
.collect()
};
- // Issue #10: shell(0.01, open_top=true) and solidify on SUB=1, 2 twisted loft -> g=0
+ // shell(0.01, open_top=true) and solidify on twisted loft at SUB=1, 2 -> g=0
for sub in [1usize, 2] {
let outer = forma_core::primitives::make_loft(&build_sections(0.065, 0.0, 0.30, sub), n, 10).unwrap();
let shelled = forma_core::ops::shell_solid(&outer, 0.01, true, 11).unwrap();
let sh_inv = MeshInvariants::compute(&shelled);
- assert!(sh_inv.is_valid_solid() && sh_inv.genus == 0, "Issue #10 shell SUB={sub}: {sh_inv:?}");
+ assert!(sh_inv.is_valid_solid() && sh_inv.genus == 0, "twisted loft shell SUB={sub}: {sh_inv:?}");
let solidified = forma_core::deform::solidify_mesh(&outer, 0.01, -1.0, true, 12).unwrap();
let so_inv = MeshInvariants::compute(&solidified);
- assert!(so_inv.is_valid_solid() && so_inv.genus == 0, "Issue #10 solidify SUB={sub}: {so_inv:?}");
+ assert!(so_inv.is_valid_solid() && so_inv.genus == 0, "twisted loft solidify SUB={sub}: {so_inv:?}");
}
- // Issue #11: outer_loft | cut(inner_loft) at SUB=7, 8 -> WT=ok NM=0 g=0
+ // outer_loft | cut(inner_loft) at SUB=7, 8 -> WT=ok NM=0 g=0
for sub in [7usize, 8] {
let outer = forma_core::primitives::make_loft(&build_sections(0.065, 0.0, 0.30, sub), n, 20).unwrap();
let inner = forma_core::primitives::make_loft(&build_sections(0.055, 0.01, 0.32, sub), n, 21).unwrap();
let cut = forma_core::boolean::boolean_op(&outer, &inner, BoolOp::Difference, None, 22).unwrap();
let cinv = MeshInvariants::compute(&cut);
- assert!(cinv.is_valid_solid() && cinv.genus == 0, "Issue #11 loft cut SUB={sub}: {cinv:?}");
+ assert!(cinv.is_valid_solid() && cinv.genus == 0, "twisted loft cut SUB={sub}: {cinv:?}");
}
}
@@ -930,7 +928,7 @@ fn test_strict_volume_floor_is_relative_to_the_part() {
}
#[test]
-fn test_issue_34_shell_preserves_walls_on_notches_and_holes() {
+fn test_shell_preserves_walls_on_notches_and_holes() {
// 1. L-shaped tray: outline area=5, inward 0.1 offset area=3.84 -> wall section=1.16, vol=1.544
let mut s = Scene::new();
s.strict_manifold = true;
@@ -948,8 +946,7 @@ fn test_issue_34_shell_preserves_walls_on_notches_and_holes() {
assert_eq!(l_sec.loops, 2, "l_tray section at z=0.5 should have outer+inner loop, got {:?}", l_sec);
assert!((l_sec.area - 1.16).abs() < 1e-3, "l_tray section area={}, expected 1.16", l_sec.area);
- // 2. U-shaped tray: outline area=8, inward 0.1 offset area=5.8 -> wall section=2.2, vol=2.384 (Wait: 8*0.1 + (8-5.8)*0.9 = 2.78? Let's verify U-tray area!)
- // U-shape [(0,0),(4,0),(4,3),(3,3),(3,1),(1,1),(1,3),(0,3)] has area = 4*3 - 2*2 = 8; inward 0.1 offset has exact volume 2.384!
+ // 2. U-shaped tray: outline area = 8 (4*3 - 2*2); inward 0.1 shell has exact volume 2.384.
s.add_extrude_2d(
"u_tray",
&[
@@ -988,7 +985,7 @@ fn test_issue_34_shell_preserves_walls_on_notches_and_holes() {
}
#[test]
-fn test_issue_35_bevel_vertical_after_hole_cut_and_curved_wall_guard() {
+fn test_bevel_vertical_after_hole_cut_and_curved_wall_guard() {
// 1. Cut hole first, then bevel(vertical, 0.2, segs=3) -> must match bevel-first cut-second
let mut s_after = Scene::new();
s_after.strict_manifold = true;
@@ -1094,7 +1091,7 @@ fn test_snapshot_restores_last_modified_and_mesh_materials() {
}
#[test]
-fn test_audit_hardening_unit_scale_tiny_hole_and_close_shell_holes() {
+fn test_unit_scale_tiny_hole_and_close_shell_holes() {
// 1. Unit-scale box (scale=5.0 inside 0.25..8.0) with a 0.0005 radius cutter must normalize to feature scale
let mut s = Scene::new();
s.strict_manifold = true;
@@ -1118,3 +1115,38 @@ fn test_audit_hardening_unit_scale_tiny_hole_and_close_shell_holes() {
"expected adjacent-hole clearance error, got {err}"
);
}
+
+#[test]
+fn test_sweep_and_sweep_advanced_share_initial_frame() {
+ // Non-square profile along +X so a 90-degree frame flip would swap Y and Z extents.
+ let prof = [(-0.4, -0.1), (0.4, -0.1), (0.4, 0.1), (-0.4, 0.1)];
+ let path = [Vec3::new(0.0, 0.0, 0.0), Vec3::new(2.0, 0.0, 0.0)];
+ let plain = forma_core::primitives::make_sweep(&prof, &path, false, 1).unwrap();
+ let adv = forma_core::curves::make_sweep_advanced(&prof, &path, 1.0, 0.0, false, 2).unwrap();
+ let sz_plain = plain.aabb().size();
+ let sz_adv = adv.aabb().size();
+ assert!(
+ (sz_plain - sz_adv).len() < 1e-9,
+ "make_sweep ({sz_plain:?}) and make_sweep_advanced ({sz_adv:?}) must agree on frame orientation"
+ );
+}
+
+#[test]
+fn test_deform_curve_on_3d_bezier_has_no_false_self_intersection() {
+ let path = forma_core::curves::eval_bezier_3d(
+ &[
+ Vec3::new(0.0, 0.0, 0.0),
+ Vec3::new(1.0, 0.0, 1.2),
+ Vec3::new(2.5, 0.8, 1.2),
+ Vec3::new(3.5, 0.0, 0.0),
+ ],
+ 24,
+ )
+ .unwrap();
+ let beam = forma_core::primitives::make_box(3.5, 0.3, 0.3, 1);
+ let curved = forma_core::deform::deform_curve(&beam, &path, 'x', 2).unwrap();
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+ let inv = s.set_part("curved", curved).expect("smooth curved beam must pass strict manifold check");
+ assert!(inv.is_valid_solid());
+}
diff --git a/crates/forma-core/tests/regression_fixes.rs b/crates/forma-core/tests/regression_fixes.rs
index 6e0a989..0927acd 100644
--- a/crates/forma-core/tests/regression_fixes.rs
+++ b/crates/forma-core/tests/regression_fixes.rs
@@ -219,8 +219,8 @@ fn test_renderer_per_view_tight_framing_on_elongated_prop() {
}
#[test]
-fn test_issue_17_sweep_and_prune_many_disjoint_shells_fast_and_accurate() {
- // 10 x 10 x 10 = 1,000 disjoint shells (previously O(S^2) = 500k AABB pairs)
+fn test_sweep_and_prune_many_disjoint_shells_fast_and_accurate() {
+ // 10 x 10 x 10 = 1,000 disjoint shells verified via sweep-and-prune broadphase.
let mut grid = PolyMesh::new();
let unit = make_box(0.5, 0.5, 0.5, 1);
for ix in 0..10 {
diff --git a/crates/forma-core/tests/units_export.rs b/crates/forma-core/tests/units_export.rs
index a14279e..8704701 100644
--- a/crates/forma-core/tests/units_export.rs
+++ b/crates/forma-core/tests/units_export.rs
@@ -94,9 +94,13 @@ fn default_exports_stay_metres() {
assert_eq!(
export_mesh_bytes(&m, ext).unwrap(),
export_mesh_bytes_with_unit(&m, ext, Unit::Meter).unwrap(),
- "legacy `.{ext}` export must equal explicit metre export"
+ "default `.{ext}` export must equal explicit metre export"
);
}
+ let svg_mm = forma_core::render::render_blueprint_svg_string_with_unit(&m, "slab", Unit::Millimeter).unwrap();
+ assert!(svg_mm.contains("100.000 mm"), "expected mm dimensions in blueprint SVG");
+ assert!(svg_mm.contains("mm^3"), "expected mm^3 volume in blueprint SVG");
+ assert!(!svg_mm.contains("100.000 m<"), "blueprint SVG must not label mm dimensions as metres");
}
fn glb_position_extent(glb: &[u8]) -> [f64; 3] {
diff --git a/crates/forma-lang/Cargo.toml b/crates/forma-lang/Cargo.toml
index b67e2f0..746cc26 100644
--- a/crates/forma-lang/Cargo.toml
+++ b/crates/forma-lang/Cargo.toml
@@ -6,5 +6,3 @@ license.workspace = true
[dependencies]
forma-core = { path = "../forma-core" }
-serde = { version = "1.0", features = ["derive"] }
-serde_json = "1.0"
diff --git a/crates/forma-lang/src/compact.rs b/crates/forma-lang/src/compact.rs
index 115b34a..60262eb 100644
--- a/crates/forma-lang/src/compact.rs
+++ b/crates/forma-lang/src/compact.rs
@@ -1,4 +1,4 @@
-//! Candidate B (Forma-DSL): Compact EBNF-specified positional line-oriented DSL.
+//! Forma-DSL: Compact EBNF-specified positional line-oriented modeling dialect.
use forma_core::boolean::BoolOp;
use forma_core::math::Vec3;
@@ -6,7 +6,7 @@ use forma_core::selector::{EdgeSelector, FaceSelector};
use forma_core::{PolyMesh, Scene};
fn parse_f(s: &str, line: usize) -> Result<f64, String> {
- // Support simple +/-/*// expressions like `2.0/3` or `1.4-0.2`
+ // Support simple literal ratios and products like `2.0/3` or `0.5*2`.
if let Ok(v) = s.parse::<f64>() {
return Ok(v);
}
@@ -317,7 +317,7 @@ pub fn eval_compact(scene: &mut Scene, src: &str) -> Result<(), String> {
continue;
}
let cmd = tokens[0];
- // Trailing tokens on fixed-arity commands used to be dropped silently.
+ // Enforce exact arity on fixed-argument commands so stray trailing tokens error explicitly.
let fixed_arity: Option<(usize, &str)> = match cmd {
"bev" => Some((5, "bev ID edge_sel w [segs]")),
"shl" => Some((4, "shl ID t [open|closed]")),
diff --git a/crates/forma-lang/tests/validation.rs b/crates/forma-lang/tests/validation.rs
index e6f668a..ef50016 100644
--- a/crates/forma-lang/tests/validation.rs
+++ b/crates/forma-lang/tests/validation.rs
@@ -46,7 +46,7 @@ fn pipe_rejects_extra_positional_arguments() {
}
#[test]
-fn pipe_valid_forms_from_the_spec_still_evaluate() {
+fn pipe_valid_forms_from_the_spec_evaluate() {
for src in [
"p = box(1,2,3)",
"p = box(2)",
@@ -154,3 +154,31 @@ fn pipe_count_arguments_must_be_whole_and_non_negative() {
assert!(e.contains("whole numbers"), "{src} -> {e}");
}
}
+
+#[test]
+fn pipe_spec_kwargs_extrude2d_z0_and_readable_syntax_errors() {
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+ // SPEC_PIPE short kwarg aliases must evaluate cleanly.
+ eval_script(
+ &mut s,
+ Dialect::Pipe,
+ "b = thread(r0=0.3, r1=0.4, pitch=0.15, turns=4)\nsection(p=b, z=0.0)\ndel(tag=\"b\")",
+ )
+ .unwrap();
+ assert!(s.part_names().is_empty());
+
+ // extrude2d(z0=..., z1=...) respects extrusion bounds without double-shifting Z.
+ eval_script(
+ &mut s,
+ Dialect::Pipe,
+ "e = extrude2d([(0,0),(1,0),(1,1),(0,1)], z0=5, z1=2)",
+ )
+ .unwrap();
+ let bb = s.get_part("e").unwrap().aabb();
+ assert!((bb.min.z - 2.0).abs() < 1e-9 && (bb.max.z - 5.0).abs() < 1e-9, "bbox={bb:?}");
+
+ // Parser syntax errors use readable token descriptions, not internal enum names.
+ let err = pipe_err("a = box(1, 1");
+ assert!(err.contains("expected ')'") && err.contains("end of input"), "err={err}");
+}
diff --git a/crates/forma-mcp/Cargo.toml b/crates/forma-mcp/Cargo.toml
index 6471fba..7e26cc2 100644
--- a/crates/forma-mcp/Cargo.toml
+++ b/crates/forma-mcp/Cargo.toml
@@ -11,5 +11,4 @@ path = "src/main.rs"
[dependencies]
forma-core = { path = "../forma-core" }
forma-lang = { path = "../forma-lang" }
-serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
diff --git a/crates/forma-server/Cargo.toml b/crates/forma-server/Cargo.toml
index 893b660..2fb2344 100644
--- a/crates/forma-server/Cargo.toml
+++ b/crates/forma-server/Cargo.toml
@@ -1,8 +1,8 @@
[package]
name = "forma-server"
-version = "0.4.2"
-edition = "2021"
-license = "GPL-3.0-or-later"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
description = "Zero-dependency headless multi-threaded HTTP microservice for Forma 3D synthesis & runtime asset processing"
[[bin]]
diff --git a/crates/forma-server/src/main.rs b/crates/forma-server/src/main.rs
index 4f2954e..b303ac2 100644
--- a/crates/forma-server/src/main.rs
+++ b/crates/forma-server/src/main.rs
@@ -5,13 +5,13 @@
//! asset processing (import .glb/.obj/.stl -> decimate/transform/boolean -> export).
//!
//! Endpoints:
-//! GET /health -> {"status":"ok","version":"0.4.2","workers":N}
-//! GET /spec[?gbnf=1] -> Forma-Pipe language spec or GBNF grammar
-//! POST /v1/eval -> Evaluate Forma-Pipe with optional base64 in-memory `assets` and model `unit` (default m)
-//! POST /v1/process -> Direct asset processor (import -> decimate/scale/center_z0 -> export; optional `unit`)
+//! GET /health -> {"status":"ok","version":"...","workers":N}
+//! GET /spec[?dialect=compact|gbnf=1|topic=] -> Forma-Pipe/DSL spec, topic spec, or GBNF grammar
+//! POST /v1/eval -> Evaluate Forma-Pipe with optional base64 `assets` and `unit` (default m)
+//! POST /v1/process -> Direct asset processor (import -> scale/center_z0/decimate -> export; optional `unit`)
use forma_core::{MeshInvariants, Scene};
-use forma_lang::{eval_script, Dialect, SPEC_COMPACT, SPEC_PIPE, SPEC_PIPE_GBNF};
+use forma_lang::{eval_script, spec_topic, Dialect, SPEC_COMPACT, SPEC_PIPE, SPEC_PIPE_GBNF};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::io::{BufRead, BufReader, Read, Write};
@@ -21,7 +21,7 @@ use std::sync::{mpsc, Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
-const VERSION: &str = "0.4.2";
+const VERSION: &str = env!("CARGO_PKG_VERSION");
const MAX_BODY_BYTES: usize = 16 * 1024 * 1024; // 16 MB request cap
const MAX_HEADER_LINE_BYTES: usize = 16 * 1024; // 16 KB per HTTP request/header line
@@ -84,7 +84,7 @@ fn parse_args() -> Config {
USAGE: forma-server [--bind 127.0.0.1:8080] [--workers 4]\n\
ENDPOINTS:\n\
GET /health\n\
- GET /spec[?gbnf=1]\n\
+ GET /spec[?dialect=compact|gbnf=1|topic=deform|curves|uv|remesh|scene]\n\
POST /v1/eval\n\
POST /v1/process"
);
@@ -245,12 +245,19 @@ fn handle_eval(body: &[u8]) -> HttpResponse {
};
let ms = t0.elapsed().as_secs_f64() * 1000.0;
- if format == "json" || format == "text" {
+ if format == "text" {
+ let mut resp = HttpResponse::text(200, "OK", obs.text);
+ resp.headers.push(("X-Forma-Exec-Ms".into(), format!("{ms:.2}")));
+ return resp;
+ }
+ if format == "json" {
let mut resp = HttpResponse::json(200, "OK", json!({
"ok": obs.ok,
"elapsed_ms": (ms * 100.0).round() / 100.0,
"text": obs.text,
"parts": obs.parts,
+ "diff": obs.diff,
+ "warnings": obs.warnings,
}));
resp.headers.push(("X-Forma-Exec-Ms".into(), format!("{ms:.2}")));
return resp;
@@ -263,7 +270,8 @@ fn handle_eval(body: &[u8]) -> HttpResponse {
let inv = MeshInvariants::compute(&mesh);
let out_bytes = match format.as_str() {
"png" => forma_core::render::render_quad_png_bytes(&mesh, size),
- "svg" => forma_core::render::render_blueprint_svg_string(&mesh, part.unwrap_or("FORMA PART")).map(|s| s.into_bytes()),
+ "svg" => forma_core::render::render_blueprint_svg_string_with_unit(&mesh, part.unwrap_or("FORMA PART"), scene.unit)
+ .map(|s| s.into_bytes()),
other => scene.export_mesh_bytes(&mesh, other),
};
match out_bytes {
@@ -312,21 +320,42 @@ fn handle_process(body: &[u8]) -> HttpResponse {
Err(e) => return HttpResponse::json(422, "Unprocessable Entity", json!({ "ok": false, "error": e })),
};
- if let Some(arr) = req.get("scale").and_then(|v| v.as_array()).filter(|a| a.len() == 3) {
- let sx = arr[0].as_f64().unwrap_or(1.0);
- let sy = arr[1].as_f64().unwrap_or(1.0);
- let sz = arr[2].as_f64().unwrap_or(1.0);
- if sx.is_finite() && sy.is_finite() && sz.is_finite() && sx.abs() > 1e-6 && sy.abs() > 1e-6 && sz.abs() > 1e-6 {
- mesh.scale(forma_core::math::Vec3::new(sx, sy, sz));
+ if let Some(scale_val) = req.get("scale") {
+ let scale_vec = if let Some(s) = scale_val.as_f64() {
+ Some((s, s, s))
+ } else if let Some(arr) = scale_val.as_array().filter(|a| a.len() == 3) {
+ match (arr[0].as_f64(), arr[1].as_f64(), arr[2].as_f64()) {
+ (Some(sx), Some(sy), Some(sz)) => Some((sx, sy, sz)),
+ _ => None,
+ }
+ } else {
+ None
+ };
+ let Some((sx, sy, sz)) = scale_vec else {
+ return HttpResponse::json(
+ 400,
+ "Bad Request",
+ json!({ "ok": false, "error": "'scale' must be a non-zero number or 3-element array [sx, sy, sz]" }),
+ );
+ };
+ if !sx.is_finite() || !sy.is_finite() || !sz.is_finite() || sx.abs() <= 1e-6 || sy.abs() <= 1e-6 || sz.abs() <= 1e-6 {
+ return HttpResponse::json(
+ 400,
+ "Bad Request",
+ json!({ "ok": false, "error": "'scale' values must be finite and non-zero" }),
+ );
}
+ mesh.scale(forma_core::math::Vec3::new(sx, sy, sz));
}
if req.get("center_z0").and_then(|v| v.as_bool()).unwrap_or(false) {
let bb = mesh.aabb();
let c = bb.center();
mesh.translate(forma_core::math::Vec3::new(-c.x, -c.y, -bb.min.z));
}
- if let Some(ratio) = req.get("decimate").and_then(|v| v.as_f64()) {
- let target_faces = req.get("target_faces").and_then(|v| v.as_u64()).map(|n| n as usize);
+ let decimate_ratio = req.get("decimate").and_then(|v| v.as_f64());
+ let target_faces = req.get("target_faces").and_then(|v| v.as_u64()).map(|n| n as usize);
+ if decimate_ratio.is_some() || target_faces.is_some() {
+ let ratio = decimate_ratio.unwrap_or(1.0);
mesh = match forma_core::ops::decimate_mesh(&mesh, ratio, target_faces, 1) {
Ok(m) => m,
Err(e) => return HttpResponse::json(422, "Unprocessable Entity", json!({ "ok": false, "error": e })),
@@ -343,7 +372,8 @@ fn handle_process(body: &[u8]) -> HttpResponse {
let inv = MeshInvariants::compute(&mesh);
let out_bytes = match out_fmt.as_str() {
"png" => forma_core::render::render_quad_png_bytes(&mesh, size),
- "svg" => forma_core::render::render_blueprint_svg_string(&mesh, "PROCESSED ITEM").map(|s| s.into_bytes()),
+ "svg" => forma_core::render::render_blueprint_svg_string_with_unit(&mesh, "PROCESSED ITEM", out_unit)
+ .map(|s| s.into_bytes()),
other => forma_core::export::export_mesh_bytes_with_unit(&mesh, other, out_unit),
};
match out_bytes {
@@ -450,9 +480,16 @@ fn handle_connection(mut stream: TcpStream, workers: usize) {
"workers": workers,
})),
("GET", "/spec") => {
- if target.contains("gbnf=1") {
+ let query = target.split_once('?').map(|(_, q)| q).unwrap_or("");
+ let topic_val = query.split('&').find_map(|kv| kv.strip_prefix("topic="));
+ if let Some(topic) = topic_val.filter(|s| !s.is_empty()) {
+ match spec_topic(topic) {
+ Ok(s) => HttpResponse::text(200, "OK", s.to_string()),
+ Err(e) => HttpResponse::json(400, "Bad Request", json!({ "ok": false, "error": e })),
+ }
+ } else if query.split('&').any(|kv| kv == "gbnf=1") {
HttpResponse::text(200, "OK", SPEC_PIPE_GBNF.to_string())
- } else if target.contains("dialect=compact") {
+ } else if query.split('&').any(|kv| kv == "dialect=compact") {
HttpResponse::text(200, "OK", SPEC_COMPACT.to_string())
} else {
HttpResponse::text(200, "OK", SPEC_PIPE.to_string())
diff --git a/crates/forma-wasm/Cargo.toml b/crates/forma-wasm/Cargo.toml
index 1fb8737..bd4b16a 100644
--- a/crates/forma-wasm/Cargo.toml
+++ b/crates/forma-wasm/Cargo.toml
@@ -1,8 +1,8 @@
[package]
name = "forma-wasm"
-version = "0.4.2"
-edition = "2021"
-license = "GPL-3.0-or-later"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
description = "Zero-dependency WebAssembly core for Forma (Node.js, Deno, Bun, and browsers)"
[lib]
diff --git a/tests/npm_smoke.mjs b/tests/npm_smoke.mjs
index 912bcd1..fd5768f 100644
--- a/tests/npm_smoke.mjs
+++ b/tests/npm_smoke.mjs
@@ -131,9 +131,10 @@ section(flange, 0.0)
console.log("PASS 2/5: Edge / Cloudflare Workers / Browser API (WebAssembly.Module, Response, trap recovery, zero node:*)");
// 2. CLI bin/forma.mjs
+ const pkgVersion = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf-8")).version;
const cli = join(ROOT, "bin", "forma.mjs");
const ver = execFileSync(process.execPath, [cli, "--version"], { encoding: "utf-8" }).trim();
- assert.ok(ver.startsWith("forma 0.4"), ver);
+ assert.equal(ver, `forma ${pkgVersion}`, ver);
const cliGlb = join(tmp, "cli.glb");
const cliPng = join(tmp, "cli.png");
@@ -145,7 +146,27 @@ section(flange, 0.0)
);
assert.ok(cliOut.includes("WT=ok") && cliOut.includes("NM=0"), cliOut);
assert.ok(statSync(cliGlb).size > 500 && statSync(cliPng).size > 1000 && statSync(cliSvg).size > 500);
- console.log("PASS 3/5: CLI bin/forma.mjs (eval --strict + .glb/.png/.svg)");
+
+ // CLI --unit flag and unit-labeled SVG blueprints
+ const mmSvg = join(tmp, "mm.svg");
+ const mmOut = execFileSync(
+ process.execPath,
+ [cli, "eval", "--strict", "--unit", "mm", "--draw", mmSvg],
+ { input: "p = box(100, 50, 20)\n", encoding: "utf-8" }
+ );
+ assert.ok(mmOut.includes("unit=mm"), mmOut);
+ const mmSvgText = readFileSync(mmSvg, "utf-8");
+ assert.ok(mmSvgText.includes("100.000 mm") && mmSvgText.includes("mm^3"), "SVG labels reflect --unit mm");
+
+ // Unknown CLI flags exit with status 2 (usage error)
+ let badFlagCode = 0;
+ try {
+ execFileSync(process.execPath, [cli, "eval", "--bogus-flag"], { input: "p = box(1,1,1)\n", stdio: "pipe" });
+ } catch (err) {
+ badFlagCode = err.status;
+ }
+ assert.equal(badFlagCode, 2, "unknown flag must exit with code 2");
+ console.log("PASS 3/5: CLI bin/forma.mjs (eval --strict, --unit mm, exit codes, .glb/.png/.svg)");
// 3. Test every recipe inside SKILL.md via npm WASM CLI
const skillMd = readFileSync(join(ROOT, "SKILL.md"), "utf-8");