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

Add tested SKILL.md for LLMs and prepare zero-dependency forma-3d npm WASM package

wrong-nebula117adedfbdce
diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml
new file mode 100644
index 0000000..98aa970
--- /dev/null
+++ b/.github/workflows/npm-publish.yml
@@ -0,0 +1,23 @@
+name: Publish npm package
+
+on:
+ release:
+ types: [published]
+ workflow_dispatch:
+
+jobs:
+ publish:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ id-token: write
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ registry-url: https://registry.npmjs.org
+ - run: npm test
+ - run: npm publish --access public
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
diff --git a/.gitignore b/.gitignore
index 36f0722..3e5b52a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,3 +13,8 @@ __pycache__/
# Ephemeral benchmark scratch
bench/kernel_selfcheck/
+
+# npm secrets & packed tarballs
+.npmrc
+*.tgz
+node_modules/
diff --git a/AGENTS.md b/AGENTS.md
index 9955360..45486f8 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -13,18 +13,20 @@ Build the binary once:
cargo build --release
```
-Add to your MCP client config (Claude Code, Cursor, Codex, Antigravity, etc.):
+Add to your MCP client config (Claude Code, Cursor, Codex, Antigravity, etc.) — either zero-install via npm (`forma-3d`) or pointing directly at the compiled native binary:
```json
{
"mcpServers": {
"forma": {
- "command": "/path/to/forma/target/release/forma-mcp",
- "args": []
+ "command": "npx",
+ "args": ["-y", "forma-3d-mcp"]
}
}
}
```
+> Also see [`SKILL.md`](SKILL.md) for a compact, drop-in Agent Skill file ready for LLM skill loaders.
+
### Exposed Tools
| Tool | Purpose |
|---|---|
diff --git a/Cargo.lock b/Cargo.lock
index 743451a..1d19f89 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4,7 +4,7 @@ version = 4
[[package]]
name = "forma-cli"
-version = "0.1.0"
+version = "0.4.0"
dependencies = [
"forma-core",
"forma-lang",
@@ -13,7 +13,7 @@ dependencies = [
[[package]]
name = "forma-core"
-version = "0.1.0"
+version = "0.4.0"
dependencies = [
"serde",
"serde_json",
@@ -23,7 +23,7 @@ dependencies = [
[[package]]
name = "forma-lang"
-version = "0.1.0"
+version = "0.4.0"
dependencies = [
"forma-core",
"serde",
@@ -32,7 +32,7 @@ dependencies = [
[[package]]
name = "forma-mcp"
-version = "0.1.0"
+version = "0.4.0"
dependencies = [
"forma-core",
"forma-lang",
@@ -40,6 +40,15 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "forma-wasm"
+version = "0.4.0"
+dependencies = [
+ "forma-core",
+ "forma-lang",
+ "serde_json",
+]
+
[[package]]
name = "itoa"
version = "1.0.19"
diff --git a/Cargo.toml b/Cargo.toml
index 434ed5e..980c9b5 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -5,9 +5,17 @@ members = [
"crates/forma-lang",
"crates/forma-cli",
"crates/forma-mcp",
+ "crates/forma-wasm",
]
[workspace.package]
-version = "0.1.0"
+version = "0.4.0"
edition = "2021"
license = "MIT"
+
+[profile.wasm-release]
+inherits = "release"
+opt-level = "z"
+lto = true
+codegen-units = 1
+strip = true
diff --git a/README.md b/README.md
index 4806af8..469f56e 100644
--- a/README.md
+++ b/README.md
@@ -31,19 +31,10 @@ Forma rewrites headless Blender's 3D modeling, boolean, and studio-preview workf
## Quickstart
-```bash
-git clone https://github.com/wrong-nebula/forma.git
-cd forma
-cargo build --release
-```
-
-Model a brushed-steel 5-hole flange, inspect its 2D cross-section, export `.glb`, render a 4-view `.png`, and draw an engineering `.svg` blueprint in one command:
+### Option 1 — Zero-Install via npm (Cross-Platform WASM)
```bash
-./target/release/forma eval --strict \
- --out flange.glb \
- --render flange.png \
- --draw flange.svg <<'EOF'
+npx -y forma-3d eval --strict --out flange.glb --render flange.png --draw flange.svg <<'EOF'
flange = box(4, 2, 0.4)
| mat("brushed_steel", color=(0.55, 0.68, 0.85), metallic=0.9, roughness=0.25)
| cut(cyl(0.5, 1))
@@ -52,6 +43,15 @@ section(flange, 0.0)
EOF
```
+### Option 2 — Build Native 1.2 MB Rust Binary
+
+```bash
+git clone https://github.com/wrong-nebula/forma.git
+cd forma
+cargo build --release
+./target/release/forma eval --strict --out flange.glb --render flange.png --draw flange.svg script.forma
+```
+
<p align="center">
<img src="assets/readme_quad_views.png" alt="Built-In Pure-Rust 4-View Studio Renders" width="100%" />
</p>
@@ -60,22 +60,23 @@ EOF
## For AI Agents
-Forma is designed for drop-in agent use via **MCP**, **CLI**, or **GBNF constrained decoding**:
+Forma is designed for drop-in agent use via **MCP**, **CLI**, **Agent Skills**, or **GBNF constrained decoding**:
+- **LLM Agent Skill:** [`SKILL.md`](SKILL.md)
- **Machine-readable index:** [`llms.txt`](llms.txt)
- **Full agent integration guide:** [`AGENTS.md`](AGENTS.md)
- **Constrained-decoding grammar:** [`grammar/forma_pipe.gbnf`](grammar/forma_pipe.gbnf) (`forma spec --gbnf`)
-### MCP Server Setup (`forma-mcp`)
+### MCP Server Setup (`forma-mcp` / `npx forma-3d-mcp`)
-Add `forma-mcp` (4 tools: `eval`, `inspect`, `tx`, `export` — **789 `o200k` tokens** total) to any MCP client:
+Add Forma's MCP server (4 tools: `eval`, `inspect`, `tx`, `export` — **789 `o200k` tokens** total) to any MCP client:
```json
{
"mcpServers": {
"forma": {
- "command": "/path/to/forma/target/release/forma-mcp",
- "args": []
+ "command": "npx",
+ "args": ["-y", "forma-3d-mcp"]
}
}
}
diff --git a/SKILL.md b/SKILL.md
new file mode 100644
index 0000000..0a51f83
--- /dev/null
+++ b/SKILL.md
@@ -0,0 +1,138 @@
+---
+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.
+---
+
+# 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.
+
+## 1. Choose Your Interface
+
+### Option A — MCP Server (preferred for iterative modeling)
+Connect `forma-mcp` (native binary) or `npx -y forma-3d-mcp` (zero-install WASM via npm):
+```json
+{
+ "mcpServers": {
+ "forma": {
+ "command": "npx",
+ "args": ["-y", "forma-3d-mcp"]
+ }
+ }
+}
+```
+Exposed tools (4 tools, 789 `o200k` tokens total):
+- `eval` — Run transactional `Forma-Pipe` code (`strict: true` auto-rolls back any non-manifold result) and return a ~100-token spatial diff (`WT`, `NM`, `g`, `vol`, `bbox`, `size`, tags).
+- `inspect` — Read current scene invariants and bounding boxes without mutating state.
+- `tx` — Instant copy-on-write state control: `checkpoint`, `rollback`, `undo`, `reset`.
+- `export` — Export to `.glb`, `.step`, `.3mf`, `.stl`, `.obj`, `.svg`, `.png` (4-view studio), or `.blend` (via optional Blender bridge).
+
+### Option B — CLI (single-shot Unix pipes)
+Use either the compiled native binary (`forma`) or the cross-platform npm CLI (`npx -y forma-3d`):
+```bash
+forma spec # Print ~355-token language reference
+forma spec --gbnf # Print GBNF grammar for constrained decoding
+forma eval --strict \
+ --out part.glb \
+ --render preview.png \
+ --draw blueprint.svg <<'EOF'
+...Forma-Pipe script...
+EOF
+```
+
+---
+
+## 2. Standard 5-Step Modeling Workflow
+
+1. **Plan coordinates (Z-up, meters).** Primitives are centered at `(0, 0, 0)` unless placed with `at=(x,y,z)` or `z0=Z` (sets bottom Z; if both `at=` and `z0=` are given, `z0=` overrides the Z coordinate after `at=` positions X/Y).
+2. **Checkpoint before risky ops (MCP).** Call `tx(action="checkpoint", tag="base")` before complex cuts/bevels so you can roll back in O(1).
+3. **Write declarative `Forma-Pipe`.** Chain operations with `|`. Intermediate named parts still appear in the spatial diff (`parts=N`), while the **last assigned variable** is exported by default (or pass `part` in MCP `export` to pick a specific part).
+4. **Always evaluate with `--strict` / `strict: true`.** Verify the returned spatial diff reports `WT=ok` and `NM=0`, plus exact `bbox` / `size` / `section` / `clearance`.
+5. **Visually inspect & export.** Render a 4-view `.png` (`--render preview.png`) to confirm proportions visually, then export `.glb` (PBR + triplanar UVs), `.step`, `.3mf`, `.stl`, `.obj`, `.blend` (native CLI with Blender installed), or `.svg` blueprint (`--draw blueprint.svg`).
+
+---
+
+## 3. Forma-Pipe Language Reference
+
+- **Syntax:** `name = expr | op | op` (multi-line `|` supported; math `+ - * / sqrt sin cos asin acos abs pi`).
+- **Common primitive kwargs:** `at=(x,y,z)` or `at=[(x,y,z), ...]` (batch), `z0=Z`, `rot=(rx,ry,rz)`.
+
+### Primitives
+| Primitive | Notes |
+|---|---|
+| `box(sx, sy, sz, at=, z0=)` | Axis-aligned box |
+| `cyl(r, h, segs=32, axis=x\|y\|z, at=, z0=)` | Cylinder (`axis=x`, `y`, or `z` unquoted, default `z`; `segs=6` gives hex vertices at `k*60°`) |
+| `cone(r0, r1, h)` | Frustum / cone |
+| `sphere(r)` | UV sphere |
+| `torus(R, r)` | Major radius `R`, tube radius `r` |
+| `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 |
+| `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 |
+| `text3d("TEXT", height=0.3, depth=0.08)` | Watertight 3D extruded vector text |
+
+### Operations & Selectors
+- **Booleans:** `add(b, at=)`, `cut(b, at=)`, `intersect(b)` — `at=[...]` runs fast batch CSG.
+- **Features:**
+ - `bevel(edges, w, segs=1)` — semantic selectors: `vertical`, `top_rim`, `bottom_rim`, `outer_rim`, `sharp`, `all` (never guess integer edge indices).
+ - `shell(t, open_top=true)` — hollow solid with wall thickness `t`.
+ - `subsurf(levels=1, crease=false)` — Catmull-Clark subdivision (`crease=true` preserves sharp rims).
+ - `extrude(faces, d)` | `inset(faces, amt, depth=0)` — face selectors: `top`, `bottom`, `sides`, `all`.
+ - `mirror(x|y|z)` | `pattern_linear(n, step=(dx,dy,dz))` | `pattern_radial(n, r=)`
+- **Transforms & Relational Placement:**
+ - `move(x, y, z)` | `rot(rx, ry, rz)` (degrees) | `scale(sx, sy, sz)`
+ - `on(base)` (rests cleanly on top of `base`) | `align(x|y|z, min|center|max, val)` | `align_z0(z)`
+- **Materials & Spatial Queries:**
+ - `mat("name", color=(r,g,b), metallic=0.1, roughness=0.5)` | `color(r,g,b)`
+ - `section(part, z)` — returns 2D cross-section loop count & area at plane `Z`.
+ - `clearance(a, b)` — returns exact minimum 3D distance between parts `a` and `b`.
+
+---
+
+## 4. Verified Recipes
+
+### Brushed-Steel 5-Hole Mounting Flange
+```forma
+flange = box(4, 2, 0.4)
+ | mat("brushed_steel", color=(0.55, 0.68, 0.85), metallic=0.9, roughness=0.25)
+ | cut(cyl(0.5, 1.0))
+ | cut(cyl(0.25, 1.0), at=[(-1.4,-0.5,0), (-1.4,0.5,0), (1.4,-0.5,0), (1.4,0.5,0)])
+section(flange, 0.0)
+```
+
+### Beveled Hollow Enclosure
+```forma
+enclosure = box(3.0, 2.0, 1.0, z0=0)
+ | bevel(vertical, 0.2, segs=3)
+ | shell(0.15, open_top=true)
+ | mat("anodized_teal", color=(0.18, 0.56, 0.60), metallic=0.7, roughness=0.35)
+```
+
+### Helical Threaded Hex Bolt
+```forma
+head = cyl(0.7, 0.4, segs=6, z0=0)
+shank = thread(0.32, 0.42, 0.16, 6) | align_z0(0.38)
+bolt = head | add(shank)
+ | mat("titanium", color=(0.74, 0.78, 0.84), metallic=0.92, roughness=0.22)
+```
+
+### Ceramic Mug (Shell + Arc Handle)
+```forma
+body = cyl(0.5, 1.0, segs=32, z0=0) | shell(0.08, open_top=true)
+handle = arc_tube(center=(0.48, 0, 0.5), rx=0.26, rz=0.28, start=-85, end=85, r=0.065)
+mug = body | add(handle)
+ | mat("terracotta", color=(0.72, 0.36, 0.24), metallic=0.0, roughness=0.72)
+```
+
+---
+
+## 5. Troubleshooting & Best Practices
+
+- **Through-cuts:** Always make cutting cylinders/boxes taller than the target solid (e.g., cut a `0.4`-thick plate with a `1.0`-tall cylinder) to avoid grazing coplanar ambiguity.
+- **Overlapping joins:** When joining two solids with `add()` (like a bolt head + thread or mug body + handle), overlap them slightly (`0.02` units) rather than kissing at an exact zero-thickness plane.
+- **Bevel order:** Apply `bevel(vertical, w)` *before* `shell(t)` when hollowing an enclosure so inner and outer walls stay clean and uniform.
+- **Batch multi-hole cuts:** Pass a coordinate list `cut(cyl(r, h), at=[(x1,y1,0), ...])` instead of chaining separate `cut()` calls — it is faster and produces cleaner topology.
+- **Strict verification:** Never deliver a mesh that fails `--strict` (`WT=ok NM=0`). If a boolean fails, adjust cutter clearance/overlap or roll back with `tx(action="undo")`.
diff --git a/bin/forma-mcp.mjs b/bin/forma-mcp.mjs
new file mode 100755
index 0000000..c0dc600
--- /dev/null
+++ b/bin/forma-mcp.mjs
@@ -0,0 +1,182 @@
+#!/usr/bin/env node
+/**
+ * forma-3d-mcp — Thin, minimal-schema stdio JSON-RPC 2.0 MCP server (4 tools, 789 o200k tokens).
+ * Powered by Forma's bundled pure-Rust WebAssembly engine (zero external dependencies).
+ */
+
+import { createInterface } from "node:readline";
+import { writeFile } from "node:fs/promises";
+import { extname } from "node:path";
+import { performance } from "node:perf_hooks";
+import { loadForma } from "../lib/index.mjs";
+
+const VERSION = "0.4.0";
+
+function buildToolsSchema(specPipe) {
+ return [
+ {
+ name: "eval",
+ description: `Run transactional Forma-Pipe code (auto-rollback on error); returns compact bbox/vol/manifold diff.\n${specPipe}`,
+ inputSchema: {
+ type: "object",
+ properties: {
+ code: { type: "string" },
+ strict: { type: "boolean" },
+ },
+ required: ["code"],
+ },
+ },
+ {
+ name: "inspect",
+ description: "Compact bbox, volume, manifold invariants, and semantic face tags.",
+ inputSchema: { type: "object", properties: {} },
+ },
+ {
+ name: "tx",
+ description: "CoW snapshot control: checkpoint|rollback|undo|reset.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ action: { type: "string", enum: ["checkpoint", "rollback", "undo", "reset"] },
+ tag: { type: "string" },
+ },
+ required: ["action"],
+ },
+ },
+ {
+ name: "export",
+ description: "Export to .glb/.step/.3mf/.stl/.obj/.svg or 2x2 studio preview .png.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ path: { type: "string" },
+ part: { type: "string" },
+ size: { type: "integer" },
+ },
+ required: ["path"],
+ },
+ },
+ ];
+}
+
+async function handleToolCall(session, name, args) {
+ try {
+ if (name === "eval") {
+ if (typeof args?.code !== "string") {
+ return [true, "ERR: missing 'code' string"];
+ }
+ const t0 = performance.now();
+ const obs = session.eval(args.code, { strict: Boolean(args.strict) });
+ const ms = performance.now() - t0;
+ const text = obs.text.replace("[0.00ms]", `[${ms.toFixed(2)}ms]`);
+ return [false, text];
+ }
+ if (name === "inspect") {
+ const obs = session.inspect();
+ return [false, obs.text];
+ }
+ if (name === "tx") {
+ const action = typeof args?.action === "string" ? args.action : "";
+ const tag = typeof args?.tag === "string" ? args.tag : "default";
+ const msg = session.tx(action, tag);
+ return [false, msg];
+ }
+ if (name === "export") {
+ if (typeof args?.path !== "string") {
+ return [true, "ERR: missing 'path'"];
+ }
+ const p = args.path;
+ const part = typeof args.part === "string" ? args.part : "";
+ const ext = extname(p).replace(/^\./, "").toLowerCase();
+ const size = Number.isInteger(args.size) ? args.size : 512;
+ const t0 = performance.now();
+ const bytes = session.exportBytes(ext, { part, size });
+ await writeFile(p, bytes);
+ const ms = performance.now() - t0;
+ if (ext === "png") {
+ return [false, `OK rendered ${size}x${size} quad preview '${p}' [${ms.toFixed(2)}ms]`];
+ }
+ if (ext === "svg") {
+ return [false, `OK drew engineering blueprint '${p}' [${ms.toFixed(2)}ms]`];
+ }
+ const inv = session.invariants(part);
+ return [
+ false,
+ `OK exported '${p}' V=${inv.verts} F=${inv.faces} WT=${inv.watertight} NM=${inv.non_manifold_edges} vol=${Number(inv.volume).toFixed(3)}`,
+ ];
+ }
+ return [true, `ERR: unknown tool '${name}'`];
+ } catch (err) {
+ return [true, `ERR: ${err instanceof Error ? err.message : String(err)}`];
+ }
+}
+
+async function runServer() {
+ const engine = await loadForma();
+ const specPipe = engine.spec({ dialect: "pipe", gbnf: false });
+ const tools = buildToolsSchema(specPipe);
+ const session = engine.createSession();
+
+ const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
+ const send = (obj) => process.stdout.write(JSON.stringify(obj) + "\n");
+
+ for await (const line of rl) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+
+ let req;
+ try {
+ req = JSON.parse(trimmed);
+ } catch (err) {
+ send({
+ jsonrpc: "2.0",
+ id: null,
+ error: { code: -32700, message: `parse error: ${err.message}` },
+ });
+ continue;
+ }
+
+ if (req.id === undefined) continue;
+ const { id, method } = req;
+
+ if (method === "initialize") {
+ send({
+ jsonrpc: "2.0",
+ id,
+ result: {
+ protocolVersion: "2024-11-05",
+ capabilities: { tools: {} },
+ serverInfo: { name: "forma-mcp", version: VERSION },
+ },
+ });
+ } else if (method === "ping") {
+ send({ jsonrpc: "2.0", id, result: {} });
+ } else if (method === "tools/list") {
+ send({ jsonrpc: "2.0", id, result: { tools } });
+ } else if (method === "tools/call") {
+ const name = req.params?.name ?? "";
+ const args = req.params?.arguments ?? {};
+ const [isError, text] = await handleToolCall(session, name, args);
+ send({
+ jsonrpc: "2.0",
+ id,
+ result: {
+ content: [{ type: "text", text }],
+ isError,
+ },
+ });
+ } else {
+ send({
+ jsonrpc: "2.0",
+ id,
+ error: { code: -32601, message: `method not found: ${method}` },
+ });
+ }
+ }
+ session.free();
+}
+
+runServer().catch((err) => {
+ process.stderr.write(`ERR: ${err instanceof Error ? err.message : String(err)}\n`);
+ process.exit(1);
+});
diff --git a/bin/forma.mjs b/bin/forma.mjs
new file mode 100755
index 0000000..5fa66d5
--- /dev/null
+++ b/bin/forma.mjs
@@ -0,0 +1,154 @@
+#!/usr/bin/env node
+/**
+ * forma-3d CLI — cross-platform pure-WASM headless 3D B-rep modeling engine.
+ * Supports: eval, render, draw, spec, mcp, version, --help
+ */
+
+import { readFile, writeFile } from "node:fs/promises";
+import { extname } from "node:path";
+import { performance } from "node:perf_hooks";
+import { loadForma } from "../lib/index.mjs";
+
+const VERSION = "0.4.0";
+
+function printHelp() {
+ process.stdout.write(
+ `forma ${VERSION} (WASM) — 1.2 MB pure-Rust rewrite of headless Blender for AI agents\n\n` +
+ `USAGE:\n` +
+ ` forma-3d eval [--dialect pipe|compact] [--strict] [--json] [--out path.(glb|obj|stl|3mf|step)] [--render preview.png] [--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] [--gbnf]\n` +
+ ` forma-3d mcp\n` +
+ ` forma-3d --version\n`
+ );
+}
+
+async function readStdin() {
+ const chunks = [];
+ for await (const chunk of process.stdin) {
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
+ }
+ return Buffer.concat(chunks).toString("utf-8");
+}
+
+async function main() {
+ const args = process.argv.slice(2);
+ if (args.length === 0 || args[0] === "-h" || args[0] === "--help" || args[0] === "help") {
+ printHelp();
+ return;
+ }
+
+ const cmd = args[0];
+ if (cmd === "version" || cmd === "--version" || cmd === "-V") {
+ process.stdout.write(`forma ${VERSION}\n`);
+ return;
+ }
+
+ if (cmd === "mcp") {
+ await import("./forma-mcp.mjs");
+ return;
+ }
+
+ const engine = await loadForma();
+
+ if (cmd === "spec") {
+ let dialect = "pipe";
+ let gbnf = false;
+ 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] === "--gbnf") {
+ gbnf = true;
+ }
+ }
+ process.stdout.write(engine.spec({ dialect, gbnf }) + "\n");
+ return;
+ }
+
+ if (cmd !== "eval" && cmd !== "render" && cmd !== "draw") {
+ process.stderr.write(`ERR: unknown subcommand '${cmd}'. Run 'forma-3d --help'.\n`);
+ process.exit(2);
+ }
+
+ let dialect = "pipe";
+ let strict = false;
+ let asJson = false;
+ let outPath = null;
+ let renderPath = null;
+ let drawPath = null;
+ let renderSize = 512;
+ let inFile = null;
+
+ for (let i = 1; i < args.length; i++) {
+ const a = args[i];
+ if (a === "--dialect" || a === "-d") {
+ dialect = args[++i];
+ } else if (a === "--out" || a === "-o") {
+ const p = args[++i];
+ if (cmd === "render") renderPath = p;
+ else if (cmd === "draw") drawPath = p;
+ else outPath = p;
+ } else if (a === "--render") {
+ renderPath = args[++i];
+ } else if (a === "--draw") {
+ drawPath = args[++i];
+ } else if (a === "--size") {
+ renderSize = Number.parseInt(args[++i], 10) || 512;
+ } else if (a === "--strict") {
+ strict = true;
+ } else if (a === "--json") {
+ asJson = true;
+ } else {
+ inFile = a;
+ }
+ }
+
+ const src = !inFile || inFile === "-" ? await readStdin() : await readFile(inFile, "utf-8");
+ const session = engine.createSession();
+ const t0 = performance.now();
+ try {
+ 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 ext = extname(outPath).replace(/^\./, "").toLowerCase();
+ const bytes = session.exportBytes(ext);
+ await writeFile(outPath, bytes);
+ }
+ if (renderPath) {
+ const bytes = session.exportBytes("png", { size: renderSize });
+ await writeFile(renderPath, bytes);
+ }
+ if (drawPath) {
+ const bytes = session.exportBytes("svg");
+ await writeFile(drawPath, bytes);
+ }
+
+ if (asJson) {
+ process.stdout.write(JSON.stringify(obs) + "\n");
+ } else {
+ process.stdout.write(obs.text + "\n");
+ }
+ if (strict && !obs.ok) {
+ process.exit(3);
+ }
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ if (asJson) {
+ process.stdout.write(JSON.stringify({ ok: false, error: msg }) + "\n");
+ } else {
+ process.stderr.write(`ERR: ${msg}\n`);
+ }
+ process.exit(1);
+ } finally {
+ session.free();
+ }
+}
+
+main().catch((err) => {
+ process.stderr.write(`ERR: ${err instanceof Error ? err.message : String(err)}\n`);
+ process.exit(1);
+});
diff --git a/crates/forma-core/src/export.rs b/crates/forma-core/src/export.rs
index cb4ea0d..526c904 100644
--- a/crates/forma-core/src/export.rs
+++ b/crates/forma-core/src/export.rs
@@ -226,24 +226,31 @@ pub fn write_glb(mesh: &PolyMesh, path: &Path, yup: bool) -> Result<(), String>
w.flush().map_err(|e| e.to_string())
}
-pub fn write_obj(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
- let f = File::create(path).map_err(|e| format!("create {}: {e}", path.display()))?;
- let mut w = BufWriter::new(f);
- writeln!(w, "# Exported by forma-core 0.1").map_err(|e| e.to_string())?;
+pub fn write_obj_bytes(mesh: &PolyMesh) -> Result<Vec<u8>, String> {
+ let mut out = Vec::with_capacity(mesh.verts.len() * 32 + mesh.faces.len() * 20);
+ writeln!(out, "# Exported by forma-core 0.4").map_err(|e| e.to_string())?;
for v in &mesh.verts {
- writeln!(w, "v {:.6} {:.6} {:.6}", v.x, v.y, v.z).map_err(|e| e.to_string())?;
+ writeln!(out, "v {:.6} {:.6} {:.6}", v.x, v.y, v.z).map_err(|e| e.to_string())?;
}
for face in &mesh.faces {
- write!(w, "f").map_err(|e| e.to_string())?;
+ write!(out, "f").map_err(|e| e.to_string())?;
for &vi in &face.verts {
- write!(w, " {}", vi + 1).map_err(|e| e.to_string())?;
+ write!(out, " {}", vi + 1).map_err(|e| e.to_string())?;
}
- writeln!(w).map_err(|e| e.to_string())?;
+ writeln!(out).map_err(|e| e.to_string())?;
}
+ Ok(out)
+}
+
+pub fn write_obj(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
+ let bytes = write_obj_bytes(mesh)?;
+ let f = File::create(path).map_err(|e| format!("create {}: {e}", path.display()))?;
+ let mut w = BufWriter::new(f);
+ w.write_all(&bytes).map_err(|e| e.to_string())?;
w.flush().map_err(|e| e.to_string())
}
-pub fn write_stl_binary(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
+pub fn write_stl_binary_bytes(mesh: &PolyMesh) -> Result<Vec<u8>, String> {
let mut tris: Vec<([f32; 3], [f32; 3], [f32; 3], [f32; 3])> = Vec::new();
for fi in 0..mesh.faces.len() {
let n = mesh.face_normal(fi).to_f32_array();
@@ -256,26 +263,33 @@ pub fn write_stl_binary(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
));
}
}
- let f = File::create(path).map_err(|e| format!("create {}: {e}", path.display()))?;
- let mut w = BufWriter::new(f);
+ let mut out = Vec::with_capacity(84 + tris.len() * 50);
let mut header = [0u8; 80];
- let msg = b"forma-core 0.1 binary STL";
+ let msg = b"forma-core 0.4 binary STL";
header[..msg.len()].copy_from_slice(msg);
- w.write_all(&header).map_err(|e| e.to_string())?;
- w.write_all(&(tris.len() as u32).to_le_bytes()).map_err(|e| e.to_string())?;
+ out.extend_from_slice(&header);
+ out.extend_from_slice(&(tris.len() as u32).to_le_bytes());
for (n, a, b, c) in tris {
for v in [n, a, b, c] {
for x in v {
- w.write_all(&x.to_le_bytes()).map_err(|e| e.to_string())?;
+ out.extend_from_slice(&x.to_le_bytes());
}
}
- w.write_all(&0u16.to_le_bytes()).map_err(|e| e.to_string())?;
+ out.extend_from_slice(&0u16.to_le_bytes());
}
+ Ok(out)
+}
+
+pub fn write_stl_binary(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
+ let bytes = write_stl_binary_bytes(mesh)?;
+ let f = File::create(path).map_err(|e| format!("create {}: {e}", path.display()))?;
+ let mut w = BufWriter::new(f);
+ w.write_all(&bytes).map_err(|e| e.to_string())?;
w.flush().map_err(|e| e.to_string())
}
-/// Export a PolyMesh to 3MF (3D Manufacturing Format: pure-Rust OPC ZIP + XML, zero crates).
-pub fn write_3mf(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
+/// Export a PolyMesh to 3MF bytes (3D Manufacturing Format: pure-Rust OPC ZIP + XML, zero crates).
+pub fn write_3mf_bytes(mesh: &PolyMesh) -> Result<Vec<u8>, String> {
if mesh.faces.is_empty() || mesh.verts.is_empty() {
return Err("cannot export empty mesh to 3MF".into());
}
@@ -369,7 +383,12 @@ pub fn write_3mf(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
zip.extend_from_slice(&cd_len.to_le_bytes());
zip.extend_from_slice(&cd_off.to_le_bytes());
zip.extend_from_slice(&0u16.to_le_bytes());
+ Ok(zip)
+}
+/// Export a PolyMesh to 3MF (3D Manufacturing Format: pure-Rust OPC ZIP + XML, zero crates).
+pub fn write_3mf(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
+ let zip = write_3mf_bytes(mesh)?;
let f = File::create(path).map_err(|e| format!("create {}: {e}", path.display()))?;
let mut w = BufWriter::new(f);
w.write_all(&zip).map_err(|e| e.to_string())?;
@@ -388,9 +407,8 @@ fn zip_crc32(data: &[u8]) -> u32 {
!crc
}
-/// Export a PolyMesh to ISO 10303-21 STEP (AP214) manifold solid B-rep (`.step` / `.stp`).
-/// Deduplicates vertices & undirected edges so adjacent `ADVANCED_FACE`s share exact `EDGE_CURVE`s.
-pub fn write_step(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
+/// Export a PolyMesh to ISO 10303-21 STEP (AP214) bytes.
+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());
}
@@ -522,13 +540,32 @@ pub fn write_step(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
s.push_str(&format!("#{rep_id}=ADVANCED_BREP_SHAPE_REPRESENTATION('forma_part',(#{msb_id}),#13);\n"));
s.push_str(&format!("#{sdr_id}=SHAPE_DEFINITION_REPRESENTATION(#8,#{rep_id});\n"));
s.push_str("ENDSEC;\nEND-ISO-10303-21;\n");
+ Ok(s.into_bytes())
+}
+/// Export a PolyMesh to ISO 10303-21 STEP (AP214) manifold solid B-rep (`.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()))?;
let mut w = BufWriter::new(f);
- w.write_all(s.as_bytes()).map_err(|e| e.to_string())?;
+ w.write_all(&bytes).map_err(|e| e.to_string())?;
w.flush().map_err(|e| e.to_string())
}
+/// Export by extension string (`glb`, `obj`, `stl`, `3mf`, `step`, `stp`) into memory bytes.
+pub fn export_mesh_bytes(mesh: &PolyMesh, ext: &str) -> Result<Vec<u8>, String> {
+ match ext.trim_start_matches('.').to_lowercase().as_str() {
+ "glb" => write_glb_bytes(mesh, false),
+ "obj" => write_obj_bytes(mesh),
+ "stl" => write_stl_binary_bytes(mesh),
+ "3mf" => write_3mf_bytes(mesh),
+ "step" | "stp" => write_step_bytes(mesh),
+ other => Err(format!(
+ "unsupported export extension '.{other}' (supported: .glb, .obj, .stl, .3mf, .step)"
+ )),
+ }
+}
+
/// Export by extension (.glb, .obj, .stl, .3mf, .step, .stp).
pub fn export_mesh(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
let ext = path
diff --git a/crates/forma-core/src/render.rs b/crates/forma-core/src/render.rs
index 4386c9b..0976626 100644
--- a/crates/forma-core/src/render.rs
+++ b/crates/forma-core/src/render.rs
@@ -592,9 +592,8 @@ fn adler32(data: &[u8]) -> u32 {
(s2 << 16) | s1
}
-/// Export a crisp vector 1200x900 orthographic + isometric SVG technical blueprint
-/// with automatic dimension lines, sharp visible edges, and an ISO engineering title block.
-pub fn write_blueprint_svg(mesh: &PolyMesh, title: &str, path: &Path) -> Result<(), String> {
+/// Render a crisp vector 1200x900 orthographic + isometric SVG technical blueprint into a String.
+pub fn render_blueprint_svg_string(mesh: &PolyMesh, title: &str) -> Result<String, String> {
if mesh.faces.is_empty() || mesh.verts.is_empty() {
return Err("cannot draw blueprint of empty mesh".into());
}
@@ -728,7 +727,12 @@ pub fn write_blueprint_svg(mesh: &PolyMesh, title: &str, path: &Path) -> Result<
"##,
sz.x, sz.y, sz.z, inv.volume, inv.genus, inv.verts, inv.faces
));
+ Ok(svg)
+}
+/// Export a crisp vector 1200x900 orthographic + isometric SVG technical blueprint to disk.
+pub fn write_blueprint_svg(mesh: &PolyMesh, title: &str, path: &Path) -> Result<(), String> {
+ let svg = render_blueprint_svg_string(mesh, title)?;
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-lang/src/lib.rs b/crates/forma-lang/src/lib.rs
index 556cb29..096ddf2 100644
--- a/crates/forma-lang/src/lib.rs
+++ b/crates/forma-lang/src/lib.rs
@@ -10,6 +10,7 @@ pub mod pipeline;
use forma_core::{Observation, Scene};
use std::collections::BTreeMap;
+#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -31,6 +32,7 @@ impl Dialect {
/// Evaluate a script in the chosen dialect against a Scene, returning a compact Observation.
/// On any error, the Scene is automatically rolled back to its pre-eval state (transactional!).
pub fn eval_script(scene: &mut Scene, dialect: Dialect, src: &str) -> Result<Observation, String> {
+ #[cfg(not(target_arch = "wasm32"))]
let t0 = Instant::now();
let prev = {
let mut map = BTreeMap::new();
@@ -49,7 +51,10 @@ pub fn eval_script(scene: &mut Scene, dialect: Dialect, src: &str) -> Result<Obs
};
match res {
Ok(()) => {
+ #[cfg(not(target_arch = "wasm32"))]
let ms = t0.elapsed().as_secs_f64() * 1000.0;
+ #[cfg(target_arch = "wasm32")]
+ let ms = 0.0;
Ok(scene.observe(ms, Some(&prev)))
}
Err(err) => {
diff --git a/crates/forma-wasm/Cargo.toml b/crates/forma-wasm/Cargo.toml
index 79ed971..4a986e6 100644
--- a/crates/forma-wasm/Cargo.toml
+++ b/crates/forma-wasm/Cargo.toml
@@ -1,13 +1,14 @@
[package]
name = "forma-wasm"
-version = "0.3.0"
+version = "0.4.0"
edition = "2021"
-description = "Browser WebAssembly bindings for forma-core + forma-lang (compile with wasm-pack build --target web)"
+license = "MIT"
+description = "Zero-dependency WebAssembly core for Forma (Node.js, Deno, Bun, and browsers)"
[lib]
-crate-type = ["cdylib", "rlib"]
+crate-type = ["cdylib"]
[dependencies]
forma-core = { path = "../forma-core" }
forma-lang = { path = "../forma-lang" }
-wasm-bindgen = "0.2"
+serde_json = "1"
diff --git a/crates/forma-wasm/src/lib.rs b/crates/forma-wasm/src/lib.rs
index bca667d..c378cb2 100644
--- a/crates/forma-wasm/src/lib.rs
+++ b/crates/forma-wasm/src/lib.rs
@@ -1,25 +1,288 @@
-//! WebAssembly browser bindings for `forma` (build with `wasm-pack build --target web`).
-//! Runs 100% client-side in <15 ms with zero GPU required!
-
-use forma_core::Scene;
-use forma_lang::{eval_script, Dialect};
-use wasm_bindgen::prelude::*;
-
-/// Evaluate a Forma-Pipe script and return the compact spatial/topological observation text.
-#[wasm_bindgen]
-pub fn eval_pipe_text(code: &str, strict: bool) -> Result<String, JsValue> {
- let mut scene = Scene::new();
- scene.strict_manifold = strict;
- eval_script(&mut scene, Dialect::Pipe, code)
- .map(|obs| obs.text)
- .map_err(|e| JsValue::from_str(&e))
-}
-
-/// Evaluate a Forma-Pipe script and render a 4-view studio PNG (bytes) directly in WebAssembly!
-#[wasm_bindgen]
-pub fn eval_pipe_png(code: &str, size: usize) -> Result<Vec<u8>, JsValue> {
- let mut scene = Scene::new();
- eval_script(&mut scene, Dialect::Pipe, code).map_err(|e| JsValue::from_str(&e))?;
- let mesh = scene.merged_mesh(None).map_err(|e| JsValue::from_str(&e.to_string()))?;
- forma_core::render::render_quad_png_bytes(&mesh, size).map_err(|e| JsValue::from_str(&e))
+//! Zero-dependency WebAssembly C-ABI bridge for `forma` (runs in Node.js, Deno, Bun, and browsers).
+//! Build with:
+//! cargo build --release --target wasm32-unknown-unknown --manifest-path crates/forma-wasm/Cargo.toml
+
+use forma_core::{MeshInvariants, Scene};
+use forma_lang::{eval_script, Dialect, SPEC_COMPACT, SPEC_PIPE, SPEC_PIPE_GBNF};
+use serde_json::json;
+use std::cell::RefCell;
+use std::collections::BTreeMap;
+
+struct WasmState {
+ next_id: u32,
+ sessions: BTreeMap<u32, Scene>,
+ result_buf: Vec<u8>,
+ result_is_err: u32,
+}
+
+impl WasmState {
+ fn new() -> Self {
+ Self {
+ next_id: 1,
+ sessions: BTreeMap::new(),
+ result_buf: Vec::new(),
+ result_is_err: 0,
+ }
+ }
+
+ fn set_ok_bytes(&mut self, bytes: Vec<u8>) -> u32 {
+ self.result_buf = bytes;
+ self.result_is_err = 0;
+ self.result_buf.len() as u32
+ }
+
+ fn set_ok_str(&mut self, s: impl Into<String>) -> u32 {
+ self.set_ok_bytes(s.into().into_bytes())
+ }
+
+ fn set_err(&mut self, msg: impl Into<String>) -> u32 {
+ self.result_buf = msg.into().into_bytes();
+ self.result_is_err = 1;
+ self.result_buf.len() as u32
+ }
+}
+
+thread_local! {
+ static STATE: RefCell<WasmState> = RefCell::new(WasmState::new());
+}
+
+unsafe fn read_utf8(ptr: *const u8, len: usize) -> Result<String, String> {
+ if len == 0 {
+ return Ok(String::new());
+ }
+ let slice = std::slice::from_raw_parts(ptr, len);
+ std::str::from_utf8(slice)
+ .map(|s| s.to_string())
+ .map_err(|e| format!("invalid utf-8: {e}"))
+}
+
+#[no_mangle]
+pub extern "C" fn forma_alloc(len: usize) -> *mut u8 {
+ let mut buf = Vec::<u8>::with_capacity(len.max(1));
+ let ptr = buf.as_mut_ptr();
+ std::mem::forget(buf);
+ ptr
+}
+
+#[no_mangle]
+pub extern "C" fn forma_dealloc(ptr: *mut u8, len: usize) {
+ if !ptr.is_null() {
+ unsafe {
+ let _ = Vec::from_raw_parts(ptr, 0, len.max(1));
+ }
+ }
+}
+
+#[no_mangle]
+pub extern "C" fn forma_result_ptr() -> *const u8 {
+ STATE.with(|st| st.borrow().result_buf.as_ptr())
+}
+
+#[no_mangle]
+pub extern "C" fn forma_result_len() -> u32 {
+ STATE.with(|st| st.borrow().result_buf.len() as u32)
+}
+
+#[no_mangle]
+pub extern "C" fn forma_result_is_err() -> u32 {
+ STATE.with(|st| st.borrow().result_is_err)
+}
+
+/// Return language spec (dialect: 0=pipe, 1=compact) or GBNF grammar (gbnf != 0).
+#[no_mangle]
+pub extern "C" fn forma_spec(dialect: u32, gbnf: u32) -> u32 {
+ let text = if gbnf != 0 {
+ SPEC_PIPE_GBNF
+ } else if dialect == 1 {
+ SPEC_COMPACT
+ } else {
+ SPEC_PIPE
+ };
+ STATE.with(|st| st.borrow_mut().set_ok_str(text))
+}
+
+#[no_mangle]
+pub extern "C" fn forma_session_new() -> u32 {
+ STATE.with(|st| {
+ let mut s = st.borrow_mut();
+ let id = s.next_id;
+ s.next_id = s.next_id.wrapping_add(1).max(1);
+ s.sessions.insert(id, Scene::new());
+ id
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn forma_session_free(id: u32) {
+ STATE.with(|st| {
+ st.borrow_mut().sessions.remove(&id);
+ });
+}
+
+/// Evaluate script in session; sets result buffer to JSON Observation (or error string).
+/// dialect: 0 = pipe, 1 = compact.
+#[no_mangle]
+pub extern "C" fn forma_session_eval(
+ id: u32,
+ code_ptr: *const u8,
+ code_len: usize,
+ dialect: u32,
+ strict: u32,
+) -> u32 {
+ let code = match unsafe { read_utf8(code_ptr, code_len) } {
+ Ok(s) => s,
+ Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
+ };
+ let d = if dialect == 1 { Dialect::Compact } else { Dialect::Pipe };
+ STATE.with(|st| {
+ let mut s = st.borrow_mut();
+ let Some(scene) = s.sessions.get_mut(&id) else {
+ return s.set_err(format!("invalid session id {id}"));
+ };
+ scene.strict_manifold = strict != 0;
+ match eval_script(scene, d, &code) {
+ Ok(obs) => {
+ let payload = serde_json::to_string(&obs)
+ .unwrap_or_else(|e| json!({ "ok": false, "text": format!("ERR: {e}") }).to_string());
+ s.set_ok_str(payload)
+ }
+ Err(e) => s.set_err(e),
+ }
+ })
+}
+
+/// Inspect current scene state without mutating it.
+#[no_mangle]
+pub extern "C" fn forma_session_inspect(id: u32) -> u32 {
+ STATE.with(|st| {
+ let mut s = st.borrow_mut();
+ let Some(scene) = s.sessions.get(&id) else {
+ return s.set_err(format!("invalid session id {id}"));
+ };
+ let obs = scene.observe(0.0, None);
+ let payload = serde_json::to_string(&obs)
+ .unwrap_or_else(|e| json!({ "ok": false, "text": format!("ERR: {e}") }).to_string());
+ s.set_ok_str(payload)
+ })
+}
+
+/// Transactional control: action = checkpoint|rollback|undo|reset.
+#[no_mangle]
+pub extern "C" fn forma_session_tx(
+ id: u32,
+ action_ptr: *const u8,
+ action_len: usize,
+ tag_ptr: *const u8,
+ tag_len: usize,
+) -> u32 {
+ let action = match unsafe { read_utf8(action_ptr, action_len) } {
+ Ok(s) => s,
+ Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
+ };
+ let tag = match unsafe { read_utf8(tag_ptr, tag_len) } {
+ Ok(s) if !s.is_empty() => s,
+ Ok(_) => "default".to_string(),
+ Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
+ };
+ STATE.with(|st| {
+ let mut s = st.borrow_mut();
+ let Some(scene) = s.sessions.get_mut(&id) else {
+ return s.set_err(format!("invalid session id {id}"));
+ };
+ let res: Result<String, String> = match action.as_str() {
+ "checkpoint" => {
+ scene.checkpoint(&tag);
+ Ok(format!("OK checkpoint '{tag}' saved (parts={})", scene.part_names().len()))
+ }
+ "rollback" => scene
+ .rollback(&tag)
+ .map(|_| format!("OK rolled back to '{tag}'\n{}", scene.observe(0.0, None).text))
+ .map_err(|e| e.to_string()),
+ "undo" => scene
+ .undo()
+ .map(|_| format!("OK undo\n{}", scene.observe(0.0, None).text))
+ .map_err(|e| e.to_string()),
+ "reset" => {
+ *scene = Scene::new();
+ Ok("OK scene reset".into())
+ }
+ other => Err(format!("unknown tx action '{other}'")),
+ };
+ match res {
+ Ok(msg) => s.set_ok_str(msg),
+ Err(e) => s.set_err(e),
+ }
+ })
+}
+
+/// Export mesh bytes for format (`glb`, `obj`, `stl`, `3mf`, `step`, `stp`, `svg`, `png`).
+/// `part_len == 0` exports the default merged/latest part.
+#[no_mangle]
+pub extern "C" fn forma_session_export(
+ id: u32,
+ ext_ptr: *const u8,
+ ext_len: usize,
+ part_ptr: *const u8,
+ part_len: usize,
+ size: u32,
+) -> u32 {
+ let ext = match unsafe { read_utf8(ext_ptr, ext_len) } {
+ Ok(s) => s.trim_start_matches('.').to_lowercase(),
+ Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
+ };
+ let part_opt = match unsafe { read_utf8(part_ptr, part_len) } {
+ Ok(s) if !s.is_empty() => Some(s),
+ Ok(_) => None,
+ Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
+ };
+ STATE.with(|st| {
+ let mut s = st.borrow_mut();
+ let Some(scene) = s.sessions.get(&id) else {
+ return s.set_err(format!("invalid session id {id}"));
+ };
+ let mesh = match scene.merged_mesh(part_opt.as_deref()) {
+ Ok(m) => m,
+ Err(e) => return s.set_err(e.to_string()),
+ };
+ let bytes_res = match ext.as_str() {
+ "png" => {
+ let sz = if size == 0 { 512 } else { size as usize };
+ forma_core::render::render_quad_png_bytes(&mesh, sz)
+ }
+ "svg" => {
+ let title = part_opt.as_deref().unwrap_or("FORMA PART");
+ forma_core::render::render_blueprint_svg_string(&mesh, title)
+ .map(|svg| svg.into_bytes())
+ }
+ other => forma_core::export::export_mesh_bytes(&mesh, other),
+ };
+ match bytes_res {
+ Ok(bytes) => s.set_ok_bytes(bytes),
+ Err(e) => s.set_err(e),
+ }
+ })
+}
+
+/// Return JSON invariants for the current (or named) part — useful for MCP `export` summaries.
+#[no_mangle]
+pub extern "C" fn forma_session_invariants(id: u32, part_ptr: *const u8, part_len: usize) -> u32 {
+ let part_opt = match unsafe { read_utf8(part_ptr, part_len) } {
+ Ok(s) if !s.is_empty() => Some(s),
+ Ok(_) => None,
+ Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
+ };
+ STATE.with(|st| {
+ let mut s = st.borrow_mut();
+ let Some(scene) = s.sessions.get(&id) else {
+ return s.set_err(format!("invalid session id {id}"));
+ };
+ let mesh = match scene.merged_mesh(part_opt.as_deref()) {
+ Ok(m) => m,
+ Err(e) => return s.set_err(e.to_string()),
+ };
+ let inv = MeshInvariants::compute(&mesh);
+ let payload = serde_json::to_string(&inv)
+ .unwrap_or_else(|e| json!({ "error": e.to_string() }).to_string());
+ s.set_ok_str(payload)
+ })
}
diff --git a/lib/index.d.ts b/lib/index.d.ts
new file mode 100644
index 0000000..73b63a4
--- /dev/null
+++ b/lib/index.d.ts
@@ -0,0 +1,59 @@
+export interface FormaObservation {
+ ok: boolean;
+ elapsed_ms: number;
+ text: string;
+ parts: Record<string, unknown>;
+}
+
+export interface FormaInvariants {
+ verts: number;
+ faces: number;
+ watertight: boolean;
+ non_manifold_edges: number;
+ boundary_edges: number;
+ genus: number;
+ volume: number;
+}
+
+export interface EvalOptions {
+ dialect?: "pipe" | "compact";
+ strict?: boolean;
+}
+
+export interface ExportOptions extends EvalOptions {
+ part?: string;
+ size?: number;
+}
+
+export interface SpecOptions {
+ dialect?: "pipe" | "compact";
+ gbnf?: boolean;
+}
+
+export class FormaSession {
+ eval(code: string, opts?: EvalOptions): FormaObservation;
+ inspect(): FormaObservation;
+ tx(action: "checkpoint" | "rollback" | "undo" | "reset", tag?: string): string;
+ exportBytes(
+ format: "glb" | "step" | "stp" | "3mf" | "stl" | "obj" | "svg" | "png",
+ opts?: { part?: string; size?: number }
+ ): Uint8Array;
+ invariants(part?: string): FormaInvariants;
+ free(): void;
+}
+
+export interface FormaEngine {
+ spec(opts?: SpecOptions): string;
+ createSession(): FormaSession;
+}
+
+export function loadForma(wasmSource?: string | URL | Uint8Array | ArrayBuffer): Promise<FormaEngine>;
+export function evalPipe(code: string, opts?: EvalOptions): Promise<FormaObservation>;
+export function exportMesh(
+ code: string,
+ format?: "glb" | "step" | "stp" | "3mf" | "stl" | "obj" | "svg" | "png",
+ opts?: ExportOptions
+): Promise<Uint8Array>;
+export function renderPng(code: string, size?: number, opts?: EvalOptions): Promise<Uint8Array>;
+export function drawSvg(code: string, opts?: EvalOptions): Promise<string>;
+export function getSpec(opts?: SpecOptions): Promise<string>;
diff --git a/lib/index.mjs b/lib/index.mjs
new file mode 100644
index 0000000..ae2880a
--- /dev/null
+++ b/lib/index.mjs
@@ -0,0 +1,193 @@
+/**
+ * forma-3d — Zero-dependency pure-WASM JavaScript/Node.js API for Forma
+ * (a 1.2 MB pure-Rust rewrite of headless Blender built for AI agents).
+ */
+
+import { readFile } from "node:fs/promises";
+import { fileURLToPath } from "node:url";
+import { dirname, join } from "node:path";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const DEFAULT_WASM_PATH = join(__dirname, "..", "wasm", "forma.wasm");
+
+const encoder = new TextEncoder();
+const decoder = new TextDecoder("utf-8");
+
+let cachedEnginePromise = null;
+
+class FormaEngine {
+ constructor(instance) {
+ this.exports = instance.exports;
+ this.memory = instance.exports.memory;
+ }
+
+ _withUtf8(str, fn) {
+ const bytes = encoder.encode(str ?? "");
+ const ptr = this.exports.forma_alloc(bytes.length);
+ try {
+ if (bytes.length > 0) {
+ new Uint8Array(this.memory.buffer, ptr, bytes.length).set(bytes);
+ }
+ return fn(ptr, bytes.length);
+ } finally {
+ this.exports.forma_dealloc(ptr, bytes.length);
+ }
+ }
+
+ _readResultBytes() {
+ const ptr = this.exports.forma_result_ptr();
+ const len = this.exports.forma_result_len();
+ const isErr = this.exports.forma_result_is_err() !== 0;
+ const copy = new Uint8Array(this.memory.buffer, ptr, len).slice();
+ if (isErr) {
+ throw new Error(decoder.decode(copy));
+ }
+ return copy;
+ }
+
+ _readResultString() {
+ return decoder.decode(this._readResultBytes());
+ }
+
+ /** Return the compact language reference (~355 tokens) or formal GBNF grammar. */
+ spec({ dialect = "pipe", gbnf = false } = {}) {
+ const d = dialect === "compact" ? 1 : 0;
+ this.exports.forma_spec(d, gbnf ? 1 : 0);
+ return this._readResultString();
+ }
+
+ /** Create a stateful transactional 3D modeling session. */
+ createSession() {
+ const id = this.exports.forma_session_new();
+ return new FormaSession(this, id);
+ }
+}
+
+export class FormaSession {
+ constructor(engine, id) {
+ this._engine = engine;
+ this._id = id;
+ this._freed = false;
+ }
+
+ _checkOpen() {
+ if (this._freed) {
+ throw new Error("FormaSession has been freed");
+ }
+ }
+
+ /** Evaluate Forma-Pipe (or compact) code transactionally; returns parsed Observation. */
+ eval(code, { dialect = "pipe", strict = false } = {}) {
+ this._checkOpen();
+ const d = dialect === "compact" ? 1 : 0;
+ this._engine._withUtf8(code, (ptr, len) => {
+ this._engine.exports.forma_session_eval(this._id, ptr, len, d, strict ? 1 : 0);
+ });
+ return JSON.parse(this._engine._readResultString());
+ }
+
+ /** Inspect current scene state without mutating it. */
+ inspect() {
+ this._checkOpen();
+ this._engine.exports.forma_session_inspect(this._id);
+ return JSON.parse(this._engine._readResultString());
+ }
+
+ /** Copy-on-write state control: checkpoint | rollback | undo | reset. */
+ tx(action, tag = "default") {
+ this._checkOpen();
+ return this._engine._withUtf8(action, (ap, al) =>
+ this._engine._withUtf8(tag, (tp, tl) => {
+ this._engine.exports.forma_session_tx(this._id, ap, al, tp, tl);
+ return this._engine._readResultString();
+ })
+ );
+ }
+
+ /** Export bytes for .glb, .step, .3mf, .stl, .obj, .svg, or 4-view .png. */
+ exportBytes(format, { part = "", size = 512 } = {}) {
+ this._checkOpen();
+ return this._engine._withUtf8(format, (ep, el) =>
+ this._engine._withUtf8(part || "", (pp, pl) => {
+ this._engine.exports.forma_session_export(this._id, ep, el, pp, pl, size >>> 0);
+ return this._engine._readResultBytes();
+ })
+ );
+ }
+
+ /** Compute MeshInvariants JSON for the current or named part. */
+ invariants(part = "") {
+ this._checkOpen();
+ this._engine._withUtf8(part || "", (pp, pl) => {
+ this._engine.exports.forma_session_invariants(this._id, pp, pl);
+ });
+ return JSON.parse(this._engine._readResultString());
+ }
+
+ /** Free session memory in the WASM heap. */
+ free() {
+ if (!this._freed) {
+ this._freed = true;
+ this._engine.exports.forma_session_free(this._id);
+ }
+ }
+}
+
+/** Load and instantiate the Forma WASM engine (cached after first call). */
+export async function loadForma(wasmSource = DEFAULT_WASM_PATH) {
+ if (wasmSource === DEFAULT_WASM_PATH && cachedEnginePromise) {
+ return cachedEnginePromise;
+ }
+ const loader = (async () => {
+ const bytes =
+ wasmSource instanceof Uint8Array || wasmSource instanceof ArrayBuffer
+ ? wasmSource
+ : await readFile(wasmSource);
+ const { instance } = await WebAssembly.instantiate(bytes, {});
+ return new FormaEngine(instance);
+ })();
+ if (wasmSource === DEFAULT_WASM_PATH) {
+ cachedEnginePromise = loader;
+ }
+ return loader;
+}
+
+/** One-shot helper: evaluate Forma-Pipe script and return Observation. */
+export async function evalPipe(code, opts = {}) {
+ const engine = await loadForma();
+ const s = engine.createSession();
+ try {
+ return s.eval(code, opts);
+ } finally {
+ s.free();
+ }
+}
+
+/** One-shot helper: evaluate script and export binary bytes (.glb/.step/.3mf/.stl/.obj/.svg/.png). */
+export async function exportMesh(code, format = "glb", opts = {}) {
+ const engine = await loadForma();
+ const s = engine.createSession();
+ try {
+ s.eval(code, opts);
+ return s.exportBytes(format, opts);
+ } finally {
+ s.free();
+ }
+}
+
+/** One-shot helper: evaluate script and render a 4-view studio PNG (Uint8Array). */
+export async function renderPng(code, size = 512, opts = {}) {
+ return exportMesh(code, "png", { ...opts, size });
+}
+
+/** One-shot helper: evaluate script and render a 1200x900 engineering SVG blueprint string. */
+export async function drawSvg(code, opts = {}) {
+ const bytes = await exportMesh(code, "svg", opts);
+ return decoder.decode(bytes);
+}
+
+/** Return the compact language reference or formal GBNF grammar. */
+export async function getSpec(opts = {}) {
+ const engine = await loadForma();
+ return engine.spec(opts);
+}
diff --git a/llms.txt b/llms.txt
index 27d24c9..b69fc06 100644
--- a/llms.txt
+++ b/llms.txt
@@ -4,7 +4,8 @@
## Repository Map
-- [README.md](README.md): Overview, quickstart, CLI/MCP usage, and full 12-model / 10-lab benchmarks
+- [SKILL.md](SKILL.md): Ready-to-use Agent Skill (`name: forma`) with 5-step workflow, full syntax cheat sheet, verified recipes, and troubleshooting
+- [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
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..35a9990
--- /dev/null
+++ b/package.json
@@ -0,0 +1,66 @@
+{
+ "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.",
+ "license": "MIT",
+ "author": "wrong-nebula",
+ "type": "module",
+ "main": "./lib/index.mjs",
+ "types": "./lib/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./lib/index.d.ts",
+ "import": "./lib/index.mjs"
+ }
+ },
+ "bin": {
+ "forma": "bin/forma.mjs",
+ "forma-3d": "bin/forma.mjs",
+ "forma-mcp": "bin/forma-mcp.mjs",
+ "forma-3d-mcp": "bin/forma-mcp.mjs"
+ },
+ "files": [
+ "bin/",
+ "lib/",
+ "wasm/forma.wasm",
+ "grammar/forma_pipe.gbnf",
+ "SKILL.md",
+ "AGENTS.md",
+ "llms.txt",
+ "README.md",
+ "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",
+ "test": "node tests/npm_smoke.mjs"
+ },
+ "keywords": [
+ "3d",
+ "cad",
+ "brep",
+ "csg",
+ "blender",
+ "mcp",
+ "ai-agents",
+ "llm",
+ "glb",
+ "step",
+ "3mf",
+ "stl",
+ "wasm",
+ "rust",
+ "forma"
+ ],
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/wrong-nebula/forma.git"
+ },
+ "homepage": "https://github.com/wrong-nebula/forma#readme",
+ "bugs": {
+ "url": "https://github.com/wrong-nebula/forma/issues"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ },
+ "dependencies": {}
+}
diff --git a/tests/npm_smoke.mjs b/tests/npm_smoke.mjs
new file mode 100644
index 0000000..931d065
--- /dev/null
+++ b/tests/npm_smoke.mjs
@@ -0,0 +1,118 @@
+import assert from "node:assert/strict";
+import { execFileSync, spawn } from "node:child_process";
+import { mkdtempSync, readFileSync, statSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, dirname } from "node:path";
+import { fileURLToPath } from "node:url";
+import { loadForma, evalPipe, exportMesh, renderPng, drawSvg, getSpec } from "../lib/index.mjs";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const ROOT = join(__dirname, "..");
+const tmp = mkdtempSync(join(tmpdir(), "forma-npm-test-"));
+
+try {
+ // 1. JS / WASM ESM Library API
+ const specPipe = await getSpec();
+ assert.ok(specPipe.includes("Forma-Pipe"), "specPipe contains Forma-Pipe");
+ const gbnf = await getSpec({ gbnf: true });
+ assert.ok(/root\s+::=/.test(gbnf), "gbnf contains root rule");
+
+ const flangeCode = `
+flange = box(4, 2, 0.4)
+ | mat("brushed_steel", color=(0.55, 0.68, 0.85), metallic=0.9, roughness=0.25)
+ | cut(cyl(0.5, 1.0))
+ | cut(cyl(0.25, 1.0), at=[(-1.4,-0.5,0), (-1.4,0.5,0), (1.4,-0.5,0), (1.4,0.5,0)])
+section(flange, 0.0)
+`;
+ const obs = await evalPipe(flangeCode, { strict: true });
+ assert.equal(obs.ok, true);
+ assert.ok(obs.text.includes("WT=ok") && obs.text.includes("NM=0"), obs.text);
+
+ for (const fmt of ["glb", "step", "3mf", "stl", "obj"]) {
+ const bytes = await exportMesh(flangeCode, fmt, { strict: true });
+ assert.ok(bytes instanceof Uint8Array && bytes.length > 100, `export ${fmt} non-empty`);
+ }
+ const png = await renderPng(flangeCode, 256, { strict: true });
+ assert.equal(png[0], 0x89);
+ assert.equal(png[1], 0x50); // PNG signature
+ const svg = await drawSvg(flangeCode, { strict: true });
+ assert.ok(svg.includes("<svg") && svg.includes("FORMA"), "valid SVG blueprint");
+
+ // Stateful session + tx checkpoint/rollback
+ const engine = await loadForma();
+ const s = engine.createSession();
+ s.eval("a = box(2, 2, 2)", { strict: true });
+ assert.ok(s.tx("checkpoint", "v1").includes("OK checkpoint"));
+ s.eval("b = cyl(0.5, 4)", { strict: true });
+ assert.ok(s.inspect().text.includes("parts=2"));
+ assert.ok(s.tx("rollback", "v1").includes("parts=1"));
+ s.free();
+ console.log("PASS 1/4: JS/WASM ESM API (GLB/STEP/3MF/STL/OBJ/PNG/SVG + stateful tx)");
+
+ // 2. CLI bin/forma.mjs
+ 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);
+
+ const cliGlb = join(tmp, "cli.glb");
+ const cliPng = join(tmp, "cli.png");
+ const cliSvg = join(tmp, "cli.svg");
+ const cliOut = execFileSync(
+ process.execPath,
+ [cli, "eval", "--strict", "--out", cliGlb, "--render", cliPng, "--draw", cliSvg],
+ { input: flangeCode, encoding: "utf-8" }
+ );
+ 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 2/4: CLI bin/forma.mjs (eval --strict + .glb/.png/.svg)");
+
+ // 3. Test every recipe inside SKILL.md via npm WASM CLI
+ const skillMd = readFileSync(join(ROOT, "SKILL.md"), "utf-8");
+ const recipes = [...skillMd.matchAll(/```forma\n([\s\S]*?)\n```/g)].map((m) => m[1]);
+ assert.ok(recipes.length >= 4, "SKILL.md has >=4 recipes");
+ for (let i = 0; i < recipes.length; i++) {
+ const out = execFileSync(process.execPath, [cli, "eval", "--strict"], {
+ input: recipes[i],
+ encoding: "utf-8",
+ });
+ assert.ok(out.includes("WT=ok") && out.includes("NM=0"), `SKILL.md recipe ${i + 1} failed: ${out}`);
+ }
+ console.log(`PASS 3/4: SKILL.md (${recipes.length}/${recipes.length} recipes verified on WASM CLI)`);
+
+ // 4. MCP stdio server bin/forma-mcp.mjs
+ const mcpGlb = join(tmp, "mcp.glb");
+ const mcpPng = join(tmp, "mcp.png");
+ const requests = [
+ { jsonrpc: "2.0", id: 1, method: "initialize", params: {} },
+ { jsonrpc: "2.0", id: 2, method: "tools/list", params: {} },
+ { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "eval", arguments: { code: "p = box(2,2,1) | bevel(vertical, 0.2)", strict: true } } },
+ { jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "tx", arguments: { action: "checkpoint", tag: "base" } } },
+ { jsonrpc: "2.0", id: 5, method: "tools/call", params: { name: "export", arguments: { path: mcpGlb } } },
+ { jsonrpc: "2.0", id: 6, method: "tools/call", params: { name: "export", arguments: { path: mcpPng, size: 256 } } },
+ ];
+ const mcpResponses = await new Promise((resolve, reject) => {
+ const child = spawn(process.execPath, [join(ROOT, "bin", "forma-mcp.mjs")], {
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ let out = "";
+ let err = "";
+ child.stdout.on("data", (d) => (out += d.toString()));
+ child.stderr.on("data", (d) => (err += d.toString()));
+ child.on("error", reject);
+ child.on("close", (code) => {
+ if (code !== 0) return reject(new Error(`MCP exited ${code}: ${err}`));
+ resolve(out.trim().split("\n").map((l) => JSON.parse(l)));
+ });
+ child.stdin.write(requests.map((r) => JSON.stringify(r)).join("\n") + "\n");
+ child.stdin.end();
+ });
+
+ assert.equal(mcpResponses.length, 6);
+ assert.equal(mcpResponses[1].result.tools.length, 4);
+ assert.equal(mcpResponses[2].result.isError, false);
+ assert.ok(mcpResponses[2].result.content[0].text.includes("WT=ok"));
+ assert.ok(statSync(mcpGlb).size > 200 && statSync(mcpPng).size > 1000);
+ console.log("PASS 4/4: MCP stdio server bin/forma-mcp.mjs (4 tools + .glb/.png export)");
+} finally {
+ rmSync(tmp, { recursive: true, force: true });
+}
diff --git a/wasm/forma.wasm b/wasm/forma.wasm
new file mode 100755
index 0000000..01c2ac0
Binary files /dev/null and b/wasm/forma.wasm differ