A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server
//! forma-lang: Parsers and transactional evaluators for Forma's modeling languages.
//!
//! - `pipeline` (`Forma-Pipe`, default): Declarative pipe notation
//! (`name = prim(...) | op(...)`) with named keyword arguments and semantic selectors.
//! - `compact` (`Forma-DSL`): Positional line-oriented notation
//! (`new f box 4 2 .4` / `sub f cyl .5 1 @ ...`).
pub mod compact;
pub mod pipeline;
use forma_core::{Observation, Scene};
#[cfg(not(target_arch = "wasm32"))]
use std::time::Instant;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Dialect {
Pipe,
Compact,
}
impl Dialect {
pub fn parse_name(s: &str) -> Result<Self, String> {
match s.to_lowercase().as_str() {
"pipe" | "forma-pipe" | "a" | "default" => Ok(Self::Pipe),
"compact" | "dsl" | "forma-dsl" | "b" => Ok(Self::Compact),
_ => Err(format!("unknown dialect '{s}' (use 'pipe' or 'compact')")),
}
}
}
/// 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 = scene.invariants_map();
let tx = scene.begin_transaction();
scene.take_notes();
scene.take_warnings();
let res = match dialect {
Dialect::Pipe => pipeline::eval_pipe(scene, src),
Dialect::Compact => compact::eval_compact(scene, src),
};
match res {
Ok(()) => {
scene.commit_transaction(tx);
#[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) => {
scene.abort_transaction(tx);
Err(err)
}
}
}
/// Returns true when an `eval_script` error string originated from a strict manifold/invariant
/// violation (`SceneError::InvariantViolation`), so CLIs can exit with the documented code `3`.
pub fn is_invariant_violation_err(err: &str) -> bool {
err.contains("invariant violation on '")
}
/// Formal GBNF grammar for zero-syntax-error constrained decoding (llama.cpp / XGrammar / vLLM).
pub const SPEC_PIPE_GBNF: &str = include_str!("../../../grammar/forma_pipe.gbnf");
/// Concise reference for Forma-Pipe (~485 o200k tokens).
/// Keeps core MCP tool schemas strictly under 800 tokens; advanced topics load on demand via `spec_topic`.
pub const SPEC_PIPE: &str = r#"Forma-Pipe (Z-up, watertight, default m; scalars persist):
name = expr | op (multi-line |; _tmp local; del("name"); def f(a=1)=expr; [e for i in range(n)]; math +-*/ sqrt sin cos tan asin acos atan atan2 abs pi; last exports; pass --scene (CLI) or scene=true (MCP) to export/render ALL parts).
Prims (at=(x,y,z)|[...], z0=Z, rot=(rx,ry,rz)):
box(sx,sy,sz) cyl(r,h,segs=32,axis=z) [6:k*60deg] cone(r0,r1,h) sphere(r) torus(R,r) pipe(ro,ri,h)
revolve([(r,z),...],segs=32) extrude2d([(x,y),...],z0,z1,holes=) loft([(z,[(x,y),...]),...],t=0) sheet([[(x,y,z),...],...],t=0.02,closed=false) gear(z,m=,h=,bore=)
arc_tube(center=,rx=,rz=,start=-90,end=90,r=) tube([(x,y,z),...],r=) thread(r0,r1,pitch,turns) text3d("T",height=,depth=)
Ops (| or op(m,...); add/cut take at=):
add(b,at=) cut(b,at=) intersect(b) mirror(x|y|z) array(n,step) radial(n,r=,axis=z) shell(t,open_top=true) subsurf(levels=1,crease=false)
bevel(edges,w,segs=1) [vertical|top_rim|bottom_rim|outer_rim|sharp|all] extrude(faces,d) inset(faces,amt,depth=0) [top|bottom|sides|all]
move(x,y,z) rot(rx,ry,rz) scale(sx,sy,sz) align(x|y|z,min|center|max,val) on(base) align_z0(z)
mat(name,color=(r,g,b[,a]),metallic=0,roughness=0.5,alpha=1,emissive=(r,g,b),transmission=0,double_sided=false) color(r,g,b[,a]) smooth(angle=35) flat() group(path) inst(p,at=,rot=,group=) units("mm") [m|cm|mm|um|in|ft] clearance(a,b) section(part,z) features(part)
Topics (inspect): deform(solidify,deform) curves(bezier,nurbs,sweep) uv(unwrap,decimate) remesh(remesh,bisect,load) scene(group,inst)"#;
/// Compact 1-line usage signature for progressive-topic ops, attached inline on errors to save an `inspect(topic=...)` turn.
pub fn op_usage_hint(name: &str) -> Option<&'static str> {
match name {
"solidify" => Some("solidify(t, offset=-1.0, open_top=false)"),
"deform" => Some("deform(\"bend\"|\"twist\"|\"taper\", axis=x|y|z, angle=45, factor=0.5, subdivs=0) | deform(\"curve\", path=[(x,y,z),...], axis=x|y|z) | deform(\"lattice\", corners=[8 pts])"),
"bezier" => Some("bezier([(x,y,z),...], segs=24)"),
"nurbs" | "bspline" => Some("nurbs([(x,y,z),...], degree=3, segs=32, weights=)"),
"sweep" => Some("sweep(profile2d, path3d, scale_end=1.0, twist=0.0, closed=false)"),
"unwrap" | "uv" => Some("unwrap(angle=45, margin=0.01)"),
"decimate" | "lod" => Some("decimate(ratio=0.5, faces=)"),
"remesh" => Some("remesh(voxel_size=0.0)"),
"bisect" => Some("bisect(normal=(0,0,1), offset=0.0, clear_inner=false)"),
"load" | "import" => Some("load(\"path.glb|obj|stl\", yup=)"),
"group" => Some("group(\"parent/child\") or group(\"parent/child\", [\"a\", \"b\"])"),
"inst" | "instance" => Some("inst(proto, at=[(x,y,z),...], rot=[(rx,ry,rz),...], scale=, group=, name=)"),
_ => None,
}
}
/// Progressive on-demand domain specs (loaded only when requested).
pub fn spec_topic(topic: &str) -> Result<&'static str, String> {
match topic.trim().to_lowercase().as_str() {
"deform" => Ok(
"Forma-Pipe // Deform & Solidify:\n\
- `solidify(t, offset=-1.0, open_top=false)` — true vertex-normal offset shell (safe on concave/curved shapes)\n\
- `deform(\"bend\"|\"twist\"|\"taper\", axis=x|y|z, angle=45, factor=0.5, subdivs=0)` — auto-subdivides & deforms\n\
- `deform(\"curve\", path=[(x,y,z),...], axis=x|y|z)` — parallel-transport curve warp (accepts `bezier()`/`nurbs()`)\n\
- `deform(\"lattice\", corners=[8 Vec3 points in (x,y,z) bit order: 000,100,010,110,001,101,011,111])` — trilinear 3D FFD cage"
),
"curves" => Ok(
"Forma-Pipe // Curves & Sketch Holes:\n\
- `bezier([(x,y,z),...], segs=24)` -> returns 3D path list for `tube()`, `sweep()`, `deform(\"curve\")`\n\
- `nurbs([(x,y,z),...], degree=3, segs=32, weights=)` -> clamped Cox-de Boor NURBS 3D path\n\
- `extrude2d(outer, z0, z1, holes=[[(x,y),...], ...])` -> watertight extrusion with inner holes (no booleans)\n\
- `sweep(profile2d, path3d, scale_end=1.0, twist=0.0, closed=false)` -> tapered/twisted 3D rail sweep"
),
"uv" | "normals" => Ok(
"Forma-Pipe // Smooth Normals & LSCM UVs:\n\
- `smooth(angle=35, weighted=true)` / `flat()` — auto-smooth & area/angle-weighted normals in GLB\n\
- `unwrap(angle=45, margin=0.01)` — pure-Rust LSCM conformal UV unwrap + MaxRects atlas pack into [0,1]^2\n\
- `decimate(ratio=0.5, faces=)` — Link-Condition QEM LOD reduction keeping WT=ok NM=0"
),
"remesh" => Ok(
"Forma-Pipe // Remesh, Bisect & Import:\n\
- `remesh(voxel_size=0.0)` — Surface Nets voxel remesh (0 = auto diag/28; heals dirty/multi-shell meshes to watertight)\n\
- `bisect(normal=(0,0,1), offset=0.0, clear_inner=false)` — exact watertight half-space plane cut + planar cap\n\
- `load(\"path.glb|obj|stl\")` — import external 3D asset (or uploaded key in forma-server)\n\
- `features(part)` — compile & cache compact CAD facts (planes, bores/bosses, symmetry, wall thickness)"
),
"scene" => Ok(
"Forma-Pipe // Multi-Object Scene Graph, Hierarchy & Instancing:\n\
- `part = expr | group(\"pavilion/drum\")` or `group(\"pavilion/drum\", [\"a\", \"b\"])` — build nested glTF parent/child node hierarchies with zero booleans.\n\
- `inst(proto, at=[(x,y,z),...], rot=[(rx,ry,rz),...], scale=..., group=\"pavilion/grille\", name=\"bar\")` — spawn lightweight instances sharing 1 `Arc<PolyMesh>` prototype (O(1) RAM, 1-line observe summary, shared glTF mesh).\n\
- Automatic O(V) GLB deduplication also collapses identical/translated/rotated/scaled parts into 1 shared glTF mesh automatically.\n\
- Pass `scene: true` to MCP `export` (or `--scene` in `forma eval` / `forma render` / `forma draw`) to export ALL named parts & instances together (`.glb`/`.blend` hierarchy, `.obj` `o <name>` groups, multi-`<object>` `.3mf`, multi-solid `.step`, combined `.stl`, and full-scene `.png`/`.svg` previews). Without `--scene`, only the last-modified part exports.\n\
- Prefix temporary/helper meshes with `_` (e.g. `_bar = ...`) so they stay local and do not appear in `scene.parts` or `scene: true` exports; remove an existing named part or instance set with `del(\"name\")`."
),
other => Err(format!("unknown spec topic '{other}' (valid: deform, curves, uv, remesh, scene)")),
}
}
/// Concise reference and EBNF for Forma-DSL (compact positional notation).
pub const SPEC_COMPACT: &str = r#"Forma-DSL (Z-up, default meters, watertight 3D line DSL; last modified part exports):
EBNF:
stmt := 'new' ID prim | ('add'|'sub'|'int') ID (ID|prim) ['@' x y z (',' x y z)*] | mod | tx
prim := 'box' sx sy sz [opts] | 'cyl' r h [segs] [ax] [opts] | 'cone' r0 r1 h [segs] [ax] [opts]
| 'sph' r [opts] | 'tor' R r [opts] | 'rev' segs r0,z0 r1,z1 ...
| 'arc' cx cy cz rx rz a0 a1 r [segs] | 'tube' r x0,y0,z0 ... | 'ext2' z0 z1 x0,y0 ...
opts := ('@' x y z | 'z0' z | 'ax' x|y|z | 'rot' rx ry rz)*
mod := 'bev' ID vertical|top_rim|bottom_rim|outer_rim|sharp|all w [segs]
| 'shl' ID t [open|closed] | 'ext' ID top|bottom|sides d | 'ins' ID top|bottom a [d]
| 'subdiv' ID n | 'mov'|'rot'|'scl' ID a b c | 'z0' ID z | 'mir' ID x|y|z
tx := 'ckpt' ID | 'rb' ID | 'undo' | 'units' m|cm|mm|um|in|ft
Notes: centered unless `@ x y z` or `z0 z`. `cyl` 6 segs vertices at k*60deg. `rev` auto-closes to r=0. `arc` is XZ ellipse (deg)."#;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_unknown_kwargs_and_clamp_warnings() {
let mut s = Scene::new();
s.strict_manifold = true;
// Unknown kwarg rejected
let err = eval_script(&mut s, Dialect::Pipe, "p = box(1, 1, 1, foo=3)").unwrap_err();
assert!(err.contains("unknown keyword argument 'foo'"), "err={err}");
// Typo triggers "did you mean" suggestion
let err2 = eval_script(&mut s, Dialect::Pipe, "p = box(1, 1, 1, widht=2)").unwrap_err();
assert!(err2.contains("did you mean 'width'"), "err2={err2}");
let err3 = eval_script(&mut s, Dialect::Pipe, "p = box(1, 1, 1) | bevel(vertical, 0.1, wdth=0.2)").unwrap_err();
assert!(err3.contains("did you mean 'width'"), "err3={err3}");
// Clamped segs emits WARN without failing valid geometry
let obs = eval_script(
&mut s,
Dialect::Pipe,
"p = loft([(0, [(-1,-1),(1,-1),(1,1),(-1,1)]), (2, [(-0.5,-0.5),(0.5,-0.5),(0.5,0.5),(-0.5,0.5)])], segs=200)",
)
.unwrap();
assert!(obs.ok);
assert!(
obs.warnings.iter().any(|w| w.contains("loft: segs=200 clamped to 128")),
"expected clamp warning, got {:?}",
obs.warnings
);
assert!(obs.text.contains("WARN:"));
}
#[test]
fn test_units_statement_sets_scene_unit_and_exports() {
for (dialect, script) in [
(Dialect::Pipe, "units(\"mm\")\ncase = box(100, 50, 20)"),
(Dialect::Pipe, "case = box(100, 50, 20)\nunits(unit=\"MM\")"),
(Dialect::Compact, "units mm\nnew case box 100 50 20"),
] {
let mut s = Scene::new();
s.strict_manifold = true;
let obs = eval_script(&mut s, dialect, script).unwrap();
assert_eq!(s.unit, forma_core::Unit::Millimeter, "script: {script}");
assert!(obs.text.contains("unit=mm"), "obs={}", obs.text);
let mesh = s.merged_mesh(None).unwrap();
let step = String::from_utf8(s.export_mesh_bytes(&mesh, "step").unwrap()).unwrap();
assert!(step.contains("SI_UNIT(.MILLI.,.METRE.)"));
let zip = s.export_mesh_bytes(&mesh, "3mf").unwrap();
assert!(String::from_utf8_lossy(&zip).contains("<model unit=\"millimeter\""));
}
}
#[test]
fn test_units_default_and_errors_roll_back() {
let mut s = Scene::new();
let obs = eval_script(&mut s, Dialect::Pipe, "p = box(1, 1, 1)").unwrap();
assert_eq!(s.unit, forma_core::Unit::Meter);
assert!(!obs.text.contains("unit="), "default metre scenes omit the unit= suffix");
let err = eval_script(&mut s, Dialect::Pipe, "units(\"parsec\")").unwrap_err();
assert!(err.contains("unknown unit 'parsec'"), "err={err}");
assert!(eval_script(&mut s, Dialect::Pipe, "units()").is_err());
assert!(eval_script(&mut s, Dialect::Compact, "units").is_err());
// A later failure in the same script undoes the unit change too.
assert!(eval_script(&mut s, Dialect::Pipe, "units(\"in\")\nq = box(1, 1, nope=2)").is_err());
assert_eq!(s.unit, forma_core::Unit::Meter);
}
#[test]
fn test_fallback_bevel_segs_warning() {
let mut s = Scene::new();
s.strict_manifold = true;
let obs = eval_script(&mut s, Dialect::Pipe, "a = box(2, 2, 2) | bevel(all, 0.3, segs=4)").unwrap();
assert!(obs.ok);
assert!(
obs.warnings.iter().any(|w| w.contains("fell back to 1-segment chamfer")),
"expected fallback warning, got {:?}",
obs.warnings
);
}
#[test]
fn test_deform_curve_positional_axis() {
let mut s = Scene::new();
s.strict_manifold = true;
let obs = eval_script(
&mut s,
Dialect::Pipe,
"p = box(2, 0.4, 0.4) | deform(\"curve\", [(0,0,0), (1,0.3,0), (2,0,0)], \"x\")",
)
.unwrap();
assert!(obs.ok, "{}", obs.text);
let p = s.get_part("p").unwrap();
let bb = p.aabb();
assert!(bb.max.y > 0.35, "expected X-axis curve warp to displace in Y, got bbox={bb:?}");
}
#[test]
fn test_features_query_in_pipe() {
let mut s = Scene::new();
s.strict_manifold = true;
let obs = eval_script(
&mut s,
Dialect::Pipe,
"units(\"mm\")\n\
plate = box(40, 20, 4) | cut(cyl(5, 10))\n\
n = features(plate)\n",
)
.unwrap();
assert!(obs.ok, "{}", obs.text);
assert!(obs.text.contains("features(plate):"), "{}", obs.text);
assert!(obs.text.contains("planes(6):"), "{}", obs.text);
assert!(obs.text.contains("cylinders(1):"), "{}", obs.text);
assert!(obs.text.contains("bore axis=+z r=5.000"), "{}", obs.text);
assert!(obs.text.contains("unit=mm"), "{}", obs.text);
assert_eq!(s.get_scalar("n"), Some(7.0));
}
#[test]
fn test_topic_usage_hints_on_error_and_spec_discovery() {
for op in ["solidify", "deform", "bezier", "nurbs", "sweep", "unwrap", "decimate", "remesh", "bisect", "load"] {
assert!(SPEC_PIPE.contains(op), "SPEC_PIPE should advertise topic op '{op}'");
}
let mut s = Scene::new();
s.strict_manifold = true;
let e_solidify = eval_script(&mut s, Dialect::Pipe, "a = box(1,1,1) | solidify()").unwrap_err();
assert!(e_solidify.contains("(usage: solidify(t, offset=-1.0, open_top=false))"), "{e_solidify}");
let e_deform = eval_script(&mut s, Dialect::Pipe, "a = box(1,1,1) | deform()").unwrap_err();
assert!(e_deform.contains("(usage: deform("), "{e_deform}");
let e_sweep = eval_script(&mut s, Dialect::Pipe, "a = sweep()").unwrap_err();
assert!(e_sweep.contains("(usage: sweep(profile2d, path3d"), "{e_sweep}");
let e_bisect = eval_script(&mut s, Dialect::Pipe, "a = box(1,1,1) | bisect(normal=123)").unwrap_err();
assert!(e_bisect.contains("(usage: bisect(normal=(0,0,1), offset=0.0, clear_inner=false))"), "{e_bisect}");
let e_load = eval_script(&mut s, Dialect::Pipe, "a = load()").unwrap_err();
assert!(e_load.contains("(usage: load(\"path.glb|obj|stl\", yup=))"), "{e_load}");
}
}