--- name: forma description: Create, modify, inspect, render, and export watertight 3D polyhedral models in milliseconds using Forma (a ~1.7 MB native / ~0.8 MB WASM pure-Rust headless 3D modeling engine). Use whenever a task involves 3D mesh/CAD generation, mechanical parts, gears, enclosures, brackets, threads, lofts, pipes, booleans, .glb/faceted .step/.3mf/.stl/.obj/.blend export, 4-view .png studio previews, or dimensioned .svg engineering blueprints. --- # Forma — Headless 3D Modeling Skill Forma is a lightweight pure-Rust headless 3D modeling engine (~1.7 MB native / ~0.8 MB WASM) built for AI agents. It evaluates a compact declarative pipe language (`Forma-Pipe`) into strict, watertight polyhedral solid geometry in ~5–17 ms with zero GPU required. ## 1. Choose Your Interface ### Option A — MCP Server (preferred for iterative modeling) Connect `forma-mcp` (native binary) or `npx -y -p forma-3d forma-3d-mcp` (zero-install WASM via npm): ```json { "mcpServers": { "forma": { "command": "npx", "args": ["-y", "-p", "forma-3d", "forma-3d-mcp"] } } } ``` Exposed tools (4 tools, 900 `o200k` tokens total, Native = WASM parity; optional `--log ` JSONL session journal): - `eval` — Run transactional `Forma-Pipe` code (`strict: true` auto-rolls back any non-manifold result) and return a delta-first spatial diff (`WT`, `NM`, `g`, `vol`, `bbox`, `size`, tags; collapses unchanged healthy parts on >2-part edits and reports `sync:` staleness when prior renders/exports are outdated). Pass `out: ["preview.png", "scene.glb"]` (plus `scene`, `size`, `view`) to build, render, and export in **1 turn**. - `inspect` — Read scene invariants without mutating state, drill into one part (`part: "name"`), run deterministic craftsmanship lint + pairwise contact graph (`lint: true`), or load domain specs (`topic: "deform"|"curves"|"uv"|"remesh"|"scene"`). - `tx` — Instant copy-on-write state control: `checkpoint`, `rollback`, `undo`, `reset`. - `export` — Export to `.glb`, `.step`, `.3mf`, `.stl`, `.obj`, `.svg`, `.png` (~2.8 ms studio render), or `.blend` (via local Blender bridge); supports `paths: [...]` batching, `scene: true` multi-part export/render, and `view: "quad|front|back|right|left|top|iso"`. ### 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 ~485-token core language reference forma spec --topic deform # Load advanced topic: deform | curves | uv | remesh | scene forma spec --gbnf # Print GBNF grammar for constrained decoding forma lint --json script.forma # Deterministic Layer A lint + contact graph # Multi-part export/render: ALWAYS pass --scene to include ALL named parts! # (Omitting --scene exports ONLY the last-modified part.) forma eval --strict --critique --scene \ --out scene.glb \ # .glb, .blend, .obj, .3mf, .stl, or .step --render preview.png \ # --view quad|front|back|right|left|top|iso --draw blueprint.svg <<'EOF' ...Forma-Pipe script... EOF ``` --- ## 2. Token-Efficient Modeling Workflow Minimize round-trips and output tokens by treating `Forma-Pipe` as a parametric script rather than stepping one primitive per turn: 1. **Batch the whole part or assembly into 1–2 `eval` calls.** Define shared parameters as scalars (which persist across MCP `eval` calls), reuse geometry with `def name(p1, p2=default) = expr` macros and `[expr for i in range(n)]` comprehensions, and prefix temporary cutters/helpers with `_` (`_tmp = ...`) so they stay local and never pollute `scene.parts` or `scene: true` exports. 2. **Set coordinates (Z-up) and unit upfront.** Numbers default to meters; for mm/in parts, start with `units("mm")` (or `forma eval --unit mm`) so `.3mf`/`.step` open at the right size (`.glb` scales to metres; `.stl`/`.obj` keep model units). Primitives center at `(0, 0, 0)` unless placed with `at=(x,y,z)` or `z0=Z` (`z0=` overrides Z if both are given). 3. **Skip routine checkpoints.** `eval` with `strict: true` (default) already auto-rolls back on any error or watertightness failure (`WT!=ok`, `NM>0`). Only call `tx(action="checkpoint", tag="...")` before genuinely risky or exploratory edits you may want to discard even if they succeed. 4. **Verify from the returned diff, then preview once.** Check `WT=ok NM=0`, `bbox`/`size`, `vol`, `genus`, and geometric queries (`clearance(a, b)`, `section(part, z)`) directly in the `eval` output. Preview the full assembly with `export({ path: "preview.png", scene: true })` (MCP) or `forma eval --scene --render preview.png ...` (CLI) — **never boolean-merge (`add`) separate scene parts just to export or preview them together**; `--scene` / `scene: true` exports all named parts with their materials intact. 5. **Clean up & export.** Remove unwanted parts with `del("name")`, then export with `--scene` (CLI) or `scene: true` (MCP) for multi-part assemblies (`.glb`, `.blend`, `.obj`, `.3mf`, `.stl`, `.step`, `.png`, `.svg`). Without `--scene` / `scene: true`, only the last-modified part exports. --- ## 3. Forma-Pipe Language Reference - **Syntax:** `name = expr | op | op` (multi-line `|` supported). - **Parametric helpers:** - Persistent scalars across MCP `eval` calls (`m = 2.0`, `h = 8.0`; rolled back by `tx`). - Macros: `def name(p1, p2=default) = expr` - List comprehensions: `[expr for i in range(n)]` (`range(stop)`, `range(start, stop)`, `range(start, stop, step)`). - Local mesh helpers: `_tmp = ...` stays local to the script and is excluded from `scene.parts` and `scene: true` exports. - Delete named part: `del("name")`. - **Math:** `+ - * / sqrt sin cos tan asin acos atan atan2 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 | | `gear(teeth, module=1.0, h=1.0, pressure_angle=20, bore=0)` | Involute spur gear (tooth 0 on `+X`; mesh pair at center distance `m*(z1+z2)/2` with gear 2 rotated `180/z2` deg if `z2` is even, `0` deg if `z2` is odd) | | `extrude2d([(x,y), ...], z0, z1, holes=)` | Extrude closed 2D polygon with optional inner holes | | `revolve([(r,z), ...], segs=32)` | Lathe profile around Z (auto-closes at `r=0`) | | `loft([(z, [(x,y), ...]), ...], segs=24)` | Multi-section smooth loft (`segs` 8..128; warns if clamped) | | `thread(r0, r1, pitch, turns)` | Watertight helical screw thread | | `arc_tube(center=(x,y,z), rx=, rz=, start=-90, end=90, r=0.08)` | Curved handle / arc sweep | | `tube([(x,y,z), ...], r=0.08)` | Polyline pipe sweep | | `text3d("TEXT", height=0.3, depth=0.08)` | Watertight 3D extruded vector text | | `load("path.glb\|obj\|stl")` | Import existing `.glb`, `.obj`, or `.stl` mesh (or uploaded asset key in `forma-server`) | ### 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))` / `array(n, step=)` | `pattern_radial(n, r=, axis=z)` / `radial(n, r=, axis=z)` | `decimate(ratio=0.5, faces=)` (QEM LOD reduction preserving watertightness) - **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, State & Spatial Queries:** - `mat("name", color=(r,g,b[,a]), metallic=0.0, roughness=0.5, alpha=1.0, emissive=(r,g,b), emissive_strength=1.0, transmission=0.0, ior=1.5, double_sided=false, faces=)` | `color(r,g,b[,a], alpha=)` - Colors are display **sRGB** (`0..1`) and automatically converted to linear RGB in glTF `.glb` export (matching Forma's PNG preview). - Use `alpha=0.25` (or `opacity=0.25` / 4-tuple `color=(1,1,1,0.25)`) for translucent steam/smoke/tinted glass (`alphaMode: "BLEND"` in `.glb`), `transmission=0.85, ior=1.33` for refractive water/glass (`KHR_materials_transmission`), and `emissive=(1.0, 0.78, 0.45), emissive_strength=2.0` for glowing lamps/shoji/screens. - `del("name")` — remove a named part from the scene. - `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`. - **Advanced Topics (load via `forma spec --topic ` or MCP `inspect({ topic })`):** - `deform`: `solidify(t, offset=-1.0, open_top=false)`, `deform("bend"|"twist"|"taper"|"curve"|"lattice", ...)` - `curves`: `bezier([...])`, `nurbs([...])`, `sweep(profile2d, path3d, scale_end=, twist=)` - `uv`: `smooth(angle=35)`, `flat()`, `unwrap()`, `decimate(ratio=)` - `remesh`: `remesh(voxel_size=)`, `bisect(normal=, offset=)` - `scene`: multi-part `--scene` / `scene: true` exports across `.glb`, `.blend`, `.obj`, `.3mf`, `.stl`, `.step`, `.png`, `.svg` --- ## 4. Verified Recipes ### Meshing Spur Gears (Single-Call Parametric Assembly) ```forma units("mm") m = 2.0 z1 = 12 z2 = 24 h = 8.0 cd = m * (z1 + z2) / 2 def ring(n, r, z=0) = [(r * cos(2 * pi * i / n), r * sin(2 * pi * i / n), z) for i in range(n)] _hole = cyl(2.5, h + 4) pinion = gear(z1, module=m, h=h, bore=3, z0=0) | mat("steel", color=(0.62, 0.68, 0.76), metallic=0.9, roughness=0.25) wheel = gear(z2, module=m, h=h, bore=4, z0=0) | cut(_hole, at=ring(6, 13, h / 2)) | rot(0, 0, 180 / z2) | move(cd, 0, 0) | mat("brass", color=(0.82, 0.66, 0.28), metallic=0.88, roughness=0.28) ``` Then render/export both gears together in one call — MCP: `export({ paths: ["gears.png", "gears.glb"], scene: true })`, or CLI: `forma eval --scene --out gears.glb --render gears.png gears.forma`. `_hole` stays local and does not appear in the exported scene. ### 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 (or comprehension `[... for i in range(n)]`) to `cut(cyl(r, h), at=...)` instead of chaining separate `cut()` calls — it is faster and produces cleaner topology. - **Keep scenes clean:** Prefix intermediate meshes with `_` (`_cut`, `_body`) so only final parts enter `scene.parts`, or remove stale parts with `del("name")`. - **3D-print readiness:** Decide `render-only` vs. `print` upfront—for printable parts, start with `units("mm")`, use higher segment counts (`segs=64`) on measured bores/cylinders, and model functional mating faces/holes before aesthetic bevels. - **Strict verification:** Never deliver a mesh that fails `--strict` (`WT=ok NM=0`). `eval(strict=true)` auto-rolls back failures cleanly; use `tx(action="undo")` if a valid edit needs reverting.