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

7.4 KB
Raw Blame

Architecture

Forma is organized as a single pure-Rust geometry and language core surrounded by four thin runtime surfaces: a native CLI, a stdio MCP server, a universal WebAssembly npm package (forma-3d for Node, Cloudflare Workers, Edge, and browsers), and an opt-in HTTP microservice (forma-server). Every surface delegates parsing, execution, invariant verification, rendering, and export to the same underlying crates so a modeling script produces identical geometry regardless of where it runs.

Six crates, two membership tiers

The Cargo workspace splits six crates into two explicit tiers to protect compile times, binary size, and zero-dependency portability:

flowchart LR
  subgraph OptIn["Opt-In Workspace Crates (excluded from default-members)"]
    W["forma-wasm (wasm32 + wasm-opt)"]
    SRV["forma-server (HTTP/1.1)"]
    IMG["FROM scratch (< 5 MB musl)"]
    SRV --> IMG
  end
  subgraph Core["default-members (Core)"]
    CLI["forma-cli (forma)"]
    MCP["forma-mcp (stdio MCP)"]
    LANG["forma-lang (Pipe / DSL / GBNF)"]
    CORE["forma-core (f64 PolyMesh + Invariants)"]
    CLI --> LANG
    MCP --> LANG
    LANG --> CORE
  end
  W -. "wasm-release" .-> LANG
  SRV -. "static-release" .-> LANG

Default core (default-members)

  • forma-core: The double-precision (f64) polyhedral modeling kernel. It owns PolyMesh storage, semantic face/edge selectors, BVH-localized tolerance-guided CSG booleans with coplanar tie-breaking and perturbation retry, subdivision and bevel/shell/deform/curve/UV/remesh modifiers, the Scene transaction manager, MeshInvariants, the pure-Rust software PNG rasterizer and SVG orthographic drafter, the Unit model, and all native exporters/importers.
  • forma-lang: The language front end. It implements the Forma-Pipe pipeline dialect, the line-oriented Forma-DSL compact dialect, the embedded GBNF grammar (grammar/forma_pipe.gbnf), and the compiled core and on-demand topic specifications.
  • forma-cli: The native command-line binary (forma). It wires terminal flags and exit codes onto forma-lang and forma-core (including the .blend Blender bridge in forma-core::export).
  • forma-mcp: The native stdio JSON-RPC 2.0 MCP server (forma-mcp). It exposes exactly four tools (eval, inspect, tx, export) within the strict < 800 o200k token budget (723 tokens).

Opt-in surfaces (excluded from default-members)

  • forma-wasm: Compiles forma-lang and forma-core to wasm32-unknown-unknown using [profile.wasm-release] (opt-level = "z", full LTO, single codegen unit, stripped symbols, plus optional wasm-opt -Oz). The zero-dependency npm package forma-3d wraps this module across three conditional entry points: lib/workerd.mjs (zero-boilerplate Cloudflare Workers), lib/edge.mjs (pure Web-standard Edge/browser loader with automatic trap-recovery cache eviction), and lib/index.mjs (Node.js/Bun/Deno with lazy local file loading).
  • forma-server: A zero-dependency, multi-threaded HTTP/1.1 worker microservice built with [profile.static-release] (lto = true, codegen-units = 1, strip = "symbols", panic = "unwind" preserved for per-request catch_unwind). While Scene::new() defaults to allow_fs_import = true and max_statements = 4,096 for local CLI use, forma-server hardens every request with allow_fs_import = false, max_statements = 1,024, a 16 MiB request cap, a bounded worker queue (workers * 8), and 15-second socket timeouts.

Inside the transactional kernel

Every script evaluation flows through the same deterministic lifecycle inside forma-lang and forma-core:

flowchart LR
  P["Pipe / DSL Script"] --> PARSE["forma-lang Parser + GBNF"]
  PARSE --> SNAP["Scene: Push O(1) Arc CoW Snapshot"]
  SNAP --> EXEC["PolyMesh Ops & BVH CSG"]
  EXEC --> GATE{"MeshInvariants Gate (WT=ok, NM=0)"}
  GATE -- "strict fail / error" --> RB["Auto-Rollback (Restore Arc + Unit)"]
  RB --> SNAP
  GATE -- "pass" --> OBS["~100-tok Spatial Diff"]
  GATE -- "export" --> EXP["Unit-Aware GLB / STEP / 3MF / PNG / SVG"]
  1. Parsing: forma-lang parses either Forma-Pipe or Forma-DSL into operations against a Scene. Because the GBNF grammar is compiled directly into the crate, local LLM samplers and the parser stay aligned.
  2. Copy-on-write snapshotting: Before executing statements, Scene pushes a lightweight SceneSnapshot onto its undo stack. Because every named part is held in a BTreeMap<String, Arc<PolyMesh>>, snapshotting shares immutable mesh buffers in O(1) time without copying vertex or face arrays. The snapshot also records op_counter, last_modified, and the active Unit.
  3. Polyhedral execution: Operations create a new PolyMesh for the mutated part and replace only its Arc<PolyMesh> entry in the map while unmodified parts stay shared across snapshots, applying double-precision geometric transformations or BVH-localized booleans and propagating semantic face tags (top, bottom, hole, bevel, side).
  4. Post-evaluation invariant gate: MeshInvariants::compute performs a single-pass half-edge sort and Union-Find component analysis to verify watertightness, non-manifold edge count, boundary edges, winding consistency, finite vertices, degenerate face count, signed volume, surface area, and compactness.
  5. Commit or automatic rollback: If an operator errors or strict mode rejects any invariant, Scene pops the pre-evaluation snapshot and restores both geometry and unit state cleanly. Otherwise, it computes a concise delta against the previous state and returns the ~100-token observation text alongside structured invariants.

Progressive disclosure in the MCP agent loop

The MCP surface decouples everyday modeling from specialized geometry domains so coding agents do not pay prompt-token overhead for operators they rarely use:

flowchart LR
  AGENT["Coding Agent"] --> EVAL["eval(code, strict=true)"]
  AGENT --> INSP["inspect(topic?)"]
  AGENT --> TX["tx(checkpoint | rollback | undo | reset)"]
  INSP -. "0-tok preload" .-> TOPICS["Topic Specs (deform, curves, uv, remesh, scene)"]
  EVAL --> STATE["In-Memory Scene (Arc CoW)"]
  INSP --> STATE
  TX --> STATE
  STATE --> EXP["export(path, scene?) -> GLB / STEP / 3MF / BLEND / PNG / SVG"]
  • The base tool catalog (eval, inspect, tx, export) carries only the compact Forma-Pipe core grammar inside eval's description (723 o200k tokens total).
  • Specialized domain capabilities (deformers and solidify, Bezier/NURBS curves, LSCM UV unwrapping and QEM decimation, Surface Nets remeshing and bisect, and multi-object glTF/Blender scene graphs) remain compiled inside forma-lang at zero base-prompt cost and are fetched on demand through inspect(topic).
  • Explicit checkpoints (tx with checkpoint, rollback, undo, reset) complement per-evaluation auto-rollback, letting an agent branch a design safely before exporting meshes or 4-view visual renders.

Unit-agnostic core with unit-aware boundaries

Internally, forma-core treats all coordinates as unitless f64 model units in a right-handed Z-up frame. Scene.unit defaults to meters and travels alongside the geometry inside snapshots. Conversion happens strictly at export boundaries: .3mf and .step declare the active unit in file metadata, .glb scales vertices by meters_per_unit() and converts Z-up to glTF Y-up, and unitless formats (.stl, .obj) emit raw model coordinates.