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

Carry the model length unit through 3MF/STEP/GLB export

Cursor Agentf5e28142f8dd
diff --git a/AGENTS.md b/AGENTS.md
index cf7db1c..cd8d162 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -94,4 +94,4 @@ forma spec --gbnf > forma_pipe.gbnf
- **Cutting through-holes cleanly:** Make cutting cylinders slightly taller than the target plate (e.g., `cyl(0.5, 1.0)` for a `0.4` thick plate) to avoid grazing coplanar caps.
- **Multi-hole patterns:** Pass `at=[(x1,y1,z1), (x2,y2,z2), ...]` in a single `| cut(...)` or `| add(...)` call—Forma automatically batches pairwise-disjoint booleans in one pass.
- **Sharp revolved/mechanical subsurf:** Use `subsurf(1, crease=true)` if you want smooth curvature without shrinking sharp rims.
-- **Exporting for downstream tools:** Use `.glb` for web/Blender/Three.js (glTF 2.0 Y-up, PBR materials + LSCM/triplanar UVs), faceted `.step` (watertight planar-face ISO 10303-21 solid; no analytic cylinders/NURBS) for reference/assembly import into SolidWorks/Fusion 360/FreeCAD, `.3mf`/`.stl` for 3D printing, `.svg` for dimensioned blueprints, and `.blend` via Blender bridge.
+- **Exporting for downstream tools:** Use `.glb` for web/Blender/Three.js (glTF 2.0 Y-up, PBR materials + LSCM/triplanar UVs), faceted `.step` (watertight planar-face ISO 10303-21 solid; no analytic cylinders/NURBS) for reference/assembly import into SolidWorks/Fusion 360/FreeCAD, `.3mf`/`.stl` for 3D printing (model in mm? start the script with `units("mm")` so `.3mf`/`.step` declare millimetres; `.stl`/`.obj` have no unit field and keep model units), `.svg` for dimensioned blueprints, and `.blend` via Blender bridge.
diff --git a/README.md b/README.md
index 4f6b5fb..115d8e1 100644
--- a/README.md
+++ b/README.md
@@ -25,7 +25,7 @@ Forma replaces headless Blender's 3D mesh modeling, boolean, and studio-preview
- **Fast, Watertight Pure-Rust Kernel:** Double-precision polyhedral mesh kernel (watertight manifold polygons/triangles), BVH-localized booleans with automatic batch chunking & fallback for multi-hole patterns, Link-Condition coplanar mesh simplification, ring-preserving bevels, shell/solidify, crease-aware Catmull-Clark subsurf, `pipe`, `loft` (`segs` 8..128), helical `thread`, `sweep`, `text3d`, and `pattern_linear`/`pattern_radial`.
- **Spatial Constraints & Queries:** Relational placement (`| on(base)`, `| align(axis, min|center|max, val)`), exact 3D `clearance(a, b)`, 2D `section(part, z)` loop/area queries, and Euler genus (`g`) diagnostics.
- **Zero-GPU Rendering & Blueprints:** Built-in 4-view (`Front / Right / Top / Iso`) studio PNG renderer with SSAO-lite + depth silhouettes + pure-Rust Deflate compression (`~20–75 KB` PNG in ~4 ms), plus dimensioned 1200×900 vector SVG technical blueprints (`forma draw`).
-- **Universal Import, Decimation & Export:** Pure-Rust `.glb` (glTF 2.0 Y-up), `.obj`, and `.stl` importers (`load("item.glb")`), topology-preserving QEM mesh decimation (`| decimate(0.5)`), native `.glb` (PBR + LSCM/triplanar UVs), faceted ISO 10303-21 `.step` (watertight planar-face solid; no analytic cylinders/NURBS), `.3mf`, `.stl`, `.obj`, `.svg`, `.png`, and `.blend` (via optional Blender bridge).
+- **Universal Import, Decimation & Export:** Pure-Rust `.glb` (glTF 2.0 Y-up), `.obj`, and `.stl` importers (`load("item.glb")`), topology-preserving QEM mesh decimation (`| decimate(0.5)`), native `.glb` (PBR + LSCM/triplanar UVs), faceted ISO 10303-21 `.step` (watertight planar-face solid; no analytic cylinders/NURBS), `.3mf`, `.stl`, `.obj`, `.svg`, `.png`, and `.blend` (via optional Blender bridge). Declare your model unit with `units("mm")` (or `forma eval --unit mm`; default metres) and `.3mf`/`.step` carry it, `.glb` is scaled to metres.
- **Optional Headless Server (`forma-server`):** Separate opt-in HTTP/1.1 worker crate (`cargo build --release -p forma-server`, compact static binary, `< 5 MB` scratch `Dockerfile`) with zero impact on the core `forma` CLI, `forma-mcp`, or `forma-3d` npm/WASM bundle.
---
diff --git a/SKILL.md b/SKILL.md
index f2d419e..462721a 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -44,7 +44,7 @@ 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).
+1. **Plan coordinates (Z-up) and unit.** Numbers are unit-agnostic and default to meters; if you model in another unit (e.g. a Pi case in mm) declare it with `units("mm")` (or `forma eval --unit mm`) so `.3mf`/`.step` exports open at the right size (`.glb` is scaled to metres; `.stl`/`.obj` keep model units). 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`.
diff --git a/crates/forma-cli/src/main.rs b/crates/forma-cli/src/main.rs
index 343ebc7..eded8d7 100644
--- a/crates/forma-cli/src/main.rs
+++ b/crates/forma-cli/src/main.rs
@@ -1,11 +1,11 @@
//! forma: Unix-composable headless 3D modeling CLI for LLM agents.
//!
//! Usage:
-//! forma eval [--dialect pipe|compact] [--strict] [--json] [--out FILE] [SCRIPT_FILE | -]
+//! forma eval [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--strict] [--json] [--out FILE] [SCRIPT_FILE | -]
//! forma spec [--dialect pipe|compact]
//! forma version
-use forma_core::Scene;
+use forma_core::{Scene, Unit};
use forma_lang::{eval_script, spec_topic, Dialect, SPEC_COMPACT, SPEC_PIPE, SPEC_PIPE_GBNF};
use std::io::{self, Read};
use std::path::PathBuf;
@@ -16,7 +16,7 @@ fn print_help() {
"forma 0.4.1 — ultra-fast, headless, watertight, LLM-native 3D modeling engine\n\
\n\
USAGE:\n\
- forma eval [--dialect pipe|compact] [--strict|--no-strict] [--json] [--out path.(glb|obj|stl|3mf|step|blend)] [--render preview.png] [--draw blueprint.svg] [file|-]\n\
+ forma eval [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--strict|--no-strict] [--json] [--out path.(glb|obj|stl|3mf|step|blend)] [--render preview.png] [--draw blueprint.svg] [file|-]\n\
forma render [--size 512] --out preview.png [file|-]\n\
forma draw --out blueprint.svg [file|-]\n\
forma spec [--dialect pipe|compact] [--gbnf]\n\
@@ -130,6 +130,7 @@ fn main() {
let is_render_cmd = args[0] == "render";
let is_draw_cmd = args[0] == "draw";
let mut dialect = Dialect::Pipe;
+ let mut unit: Option<Unit> = None;
let mut strict = true;
let mut as_json = false;
let mut export_scene = false;
@@ -153,6 +154,17 @@ fn main() {
});
i += 2;
}
+ "--unit" | "-u" => {
+ if i + 1 >= args.len() {
+ eprintln!("ERR: --unit requires value (m|cm|mm|um|in|ft)");
+ process::exit(2);
+ }
+ unit = Some(Unit::parse(&args[i + 1]).unwrap_or_else(|e| {
+ eprintln!("ERR: {e}");
+ process::exit(2);
+ }));
+ i += 2;
+ }
"--out" | "-o" => {
if i + 1 >= args.len() {
eprintln!("ERR: --out requires path");
@@ -234,6 +246,9 @@ fn main() {
let mut scene = Scene::new();
scene.strict_manifold = strict;
+ if let Some(u) = unit {
+ scene.unit = u;
+ }
match eval_script(&mut scene, dialect, &src) {
Ok(obs) => {
diff --git a/crates/forma-core/src/export.rs b/crates/forma-core/src/export.rs
index af4d6da..a504a8b 100644
--- a/crates/forma-core/src/export.rs
+++ b/crates/forma-core/src/export.rs
@@ -3,6 +3,7 @@
use crate::math::Vec3;
use crate::mesh::PolyMesh;
+use crate::units::Unit;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;
@@ -22,8 +23,16 @@ fn triplanar_uv(p: Vec3, n: Vec3) -> [f32; 2] {
}
}
-/// Serialize a PolyMesh to binary glTF 2.0 (.glb) bytes in memory (zero disk I/O).
+/// Serialize a PolyMesh to binary glTF 2.0 (.glb) bytes in memory (zero disk I/O),
+/// treating model coordinates as metres.
pub fn write_glb_bytes(mesh: &PolyMesh, yup: bool) -> Result<Vec<u8>, String> {
+ write_glb_bytes_with_unit(mesh, yup, Unit::Meter)
+}
+
+/// Serialize a PolyMesh to binary glTF 2.0 (.glb) bytes. glTF positions are defined in metres,
+/// so vertex positions are scaled from `unit` to metres (normals are unaffected).
+pub fn write_glb_bytes_with_unit(mesh: &PolyMesh, yup: bool, unit: Unit) -> Result<Vec<u8>, String> {
+ let k = unit.meters_per_unit();
let conv = |p: Vec3| -> [f32; 3] {
if yup {
[p.x as f32, p.z as f32, (-p.y) as f32]
@@ -64,7 +73,7 @@ pub fn write_glb_bytes(mesh: &PolyMesh, yup: bool) -> Result<Vec<u8>, String> {
for [ca, cb, cc] in mesh.triangulate_face_corners(fi) {
for ci in [ca, cb, cc] {
let vi = f.verts[ci];
- let v = mesh.verts[vi];
+ let v = mesh.verts[vi] * k;
let p = conv(v);
let n = conv(cn[ci]);
let uv = if has_face_uvs { f.uvs[ci] } else { triplanar_uv(v, raw_n) };
@@ -239,8 +248,18 @@ pub fn write_glb_bytes(mesh: &PolyMesh, yup: bool) -> Result<Vec<u8>, String> {
pub fn write_scene_glb_bytes(
nodes: &[(&str, &std::sync::Arc<PolyMesh>, [f64; 3])],
yup: bool,
+) -> Result<Vec<u8>, String> {
+ write_scene_glb_bytes_with_unit(nodes, yup, Unit::Meter)
+}
+
+/// Multi-node glTF export with positions and node translations scaled from `unit` to metres.
+pub fn write_scene_glb_bytes_with_unit(
+ nodes: &[(&str, &std::sync::Arc<PolyMesh>, [f64; 3])],
+ yup: bool,
+ unit: Unit,
) -> Result<Vec<u8>, String> {
use std::collections::HashMap;
+ let k = unit.meters_per_unit();
if nodes.is_empty() {
return Err("cannot export empty scene to GLB".into());
}
@@ -281,7 +300,7 @@ pub fn write_scene_glb_bytes(
for [ca, cb, cc] in mesh.triangulate_face_corners(fi) {
for ci in [ca, cb, cc] {
let vi = f.verts[ci];
- let v = mesh.verts[vi];
+ let v = mesh.verts[vi] * k;
let p = conv(v);
let n = conv(cn[ci]);
let uv = if has_uvs { f.uvs[ci] } else { triplanar_uv(v, raw_n) };
@@ -364,7 +383,7 @@ pub fn write_scene_glb_bytes(
let mut node_obj = serde_json::json!({"name": node_name, "mesh": mesh_idx});
if trans[0].abs() > 1e-9 || trans[1].abs() > 1e-9 || trans[2].abs() > 1e-9 {
- let tv = conv(Vec3::new(trans[0], trans[1], trans[2]));
+ let tv = conv(Vec3::new(trans[0] * k, trans[1] * k, trans[2] * k));
node_obj["translation"] = serde_json::json!(tv);
}
gltf_nodes.push(node_obj);
@@ -411,7 +430,12 @@ pub fn write_scene_glb_bytes(
/// automatic triplanar or unwrapped `TEXCOORD_0` UVs, and optional per-face PBR `materials`.
/// Note: `yup = true` emits glTF 2.0 spec-compliant Y-up coordinates (`(x,y,z) -> (x,z,-y)`).
pub fn write_glb(mesh: &PolyMesh, path: &Path, yup: bool) -> Result<(), String> {
- let bytes = write_glb_bytes(mesh, yup)?;
+ write_glb_with_unit(mesh, path, yup, Unit::Meter)
+}
+
+/// Write a `.glb` file, scaling positions from `unit` to glTF metres.
+pub fn write_glb_with_unit(mesh: &PolyMesh, path: &Path, yup: bool, unit: Unit) -> Result<(), String> {
+ let bytes = write_glb_bytes_with_unit(mesh, yup, unit)?;
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())?;
@@ -480,8 +504,15 @@ pub fn write_stl_binary(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
w.flush().map_err(|e| e.to_string())
}
-/// Export a PolyMesh to 3MF bytes (3D Manufacturing Format: pure-Rust OPC ZIP + XML, zero crates).
+/// Export a PolyMesh to 3MF bytes, declaring model coordinates as metres.
pub fn write_3mf_bytes(mesh: &PolyMesh) -> Result<Vec<u8>, String> {
+ write_3mf_bytes_with_unit(mesh, Unit::Meter)
+}
+
+/// Export a PolyMesh to 3MF bytes (3D Manufacturing Format: pure-Rust OPC ZIP + XML, zero crates).
+/// Vertices are written in model units and `model/@unit` declares `unit`, so slicers and CAD
+/// tools interpret the coordinates at the right physical size.
+pub fn write_3mf_bytes_with_unit(mesh: &PolyMesh, unit: Unit) -> Result<Vec<u8>, String> {
if mesh.faces.is_empty() || mesh.verts.is_empty() {
return Err("cannot export empty mesh to 3MF".into());
}
@@ -499,9 +530,10 @@ pub fn write_3mf_bytes(mesh: &PolyMesh) -> Result<Vec<u8>, String> {
r#"</Relationships>"#
);
let mut model = String::with_capacity(mesh.verts.len() * 48 + mesh.faces.len() * 40 + 512);
- model.push_str(
- r#"<?xml version="1.0" encoding="UTF-8"?><model unit="meter" xml:lang="en-US" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"><resources><object id="1" type="model"><mesh><vertices>"#,
- );
+ model.push_str(&format!(
+ r#"<?xml version="1.0" encoding="UTF-8"?><model unit="{}" xml:lang="en-US" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"><resources><object id="1" type="model"><mesh><vertices>"#,
+ unit.threemf_name()
+ ));
for v in &mesh.verts {
model.push_str(&format!(r#"<vertex x="{:.6}" y="{:.6}" z="{:.6}"/>"#, v.x, v.y, v.z));
}
@@ -580,7 +612,12 @@ pub fn write_3mf_bytes(mesh: &PolyMesh) -> Result<Vec<u8>, 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> {
- let zip = write_3mf_bytes(mesh)?;
+ write_3mf_with_unit(mesh, path, Unit::Meter)
+}
+
+/// Export a PolyMesh to a 3MF file declaring `unit`.
+pub fn write_3mf_with_unit(mesh: &PolyMesh, path: &Path, unit: Unit) -> Result<(), String> {
+ let zip = write_3mf_bytes_with_unit(mesh, unit)?;
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())?;
@@ -602,6 +639,36 @@ fn zip_crc32(data: &[u8]) -> u32 {
/// Export a PolyMesh to faceted ISO 10303-21 STEP (AP214) bytes (watertight planar-face solid;
/// no analytic cylindrical/NURBS surfaces).
pub fn write_step_bytes(mesh: &PolyMesh) -> Result<Vec<u8>, String> {
+ write_step_bytes_with_unit(mesh, Unit::Meter)
+}
+
+/// STEP `#9` LENGTH_UNIT entity (plus helper entities `#14..#17` for non-SI units such as inches).
+/// Metric units use `SI_UNIT` with an SI prefix; imperial units use `CONVERSION_BASED_UNIT`
+/// defined against millimetres.
+fn step_length_unit_entities(unit: Unit) -> String {
+ let si = |prefix: &str| format!("#9=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT({prefix},.METRE.));\n");
+ let imperial = |name: &str, mm: &str| {
+ format!(
+ "#9=(CONVERSION_BASED_UNIT('{name}',#14)LENGTH_UNIT()NAMED_UNIT(#15));\n\
+ #14=LENGTH_MEASURE_WITH_UNIT(LENGTH_MEASURE({mm}),#16);\n\
+ #15=DIMENSIONAL_EXPONENTS(1.,0.,0.,0.,0.,0.,0.);\n\
+ #16=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.));\n"
+ )
+ };
+ match unit {
+ Unit::Meter => si("$"),
+ Unit::Centimeter => si(".CENTI."),
+ Unit::Millimeter => si(".MILLI."),
+ Unit::Micrometer => si(".MICRO."),
+ Unit::Inch => imperial("INCH", "25.4"),
+ Unit::Foot => imperial("FOOT", "304.8"),
+ }
+}
+
+/// Export a PolyMesh to faceted STEP (AP214). Coordinates are written in model units and the
+/// geometric context declares `unit` as its length unit. The 1e-6 m distance accuracy is
+/// converted into model units so it stays physically constant.
+pub fn write_step_bytes_with_unit(mesh: &PolyMesh, unit: Unit) -> Result<Vec<u8>, String> {
if mesh.faces.is_empty() || mesh.verts.is_empty() {
return Err("cannot export empty mesh to STEP".into());
}
@@ -621,13 +688,16 @@ pub fn write_step_bytes(mesh: &PolyMesh) -> Result<Vec<u8>, String> {
#5=PRODUCT_DEFINITION_FORMATION('','',#4);\n\
#6=PRODUCT_DEFINITION_CONTEXT('part definition',#1,'design');\n\
#7=PRODUCT_DEFINITION('design','',#5,#6);\n\
- #8=PRODUCT_DEFINITION_SHAPE('','',#7);\n\
- #9=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT($,.METRE.));\n\
- #10=(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.));\n\
+ #8=PRODUCT_DEFINITION_SHAPE('','',#7);\n",
+ );
+ s.push_str(&step_length_unit_entities(unit));
+ s.push_str(&format!(
+ "#10=(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.));\n\
#11=(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT());\n\
- #12=UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-06),#9,'distance_accuracy_value','');\n\
+ #12=UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE({:.6E}),#9,'distance_accuracy_value','');\n\
#13=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#12))GLOBAL_UNIT_ASSIGNED_CONTEXT((#9,#10,#11))REPRESENTATION_CONTEXT('Context3D','3D Context'));\n",
- );
+ 1e-6 / unit.meters_per_unit()
+ ));
let mut next_id = 20usize;
let mut alloc = || {
@@ -738,40 +808,61 @@ pub fn write_step_bytes(mesh: &PolyMesh) -> Result<Vec<u8>, String> {
/// Export a PolyMesh to faceted ISO 10303-21 STEP (AP214) planar-face manifold solid (`.step` / `.stp`).
pub fn write_step(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
- let bytes = write_step_bytes(mesh)?;
+ write_step_with_unit(mesh, path, Unit::Meter)
+}
+
+/// Export a PolyMesh to a faceted STEP file declaring `unit`.
+pub fn write_step_with_unit(mesh: &PolyMesh, path: &Path, unit: Unit) -> Result<(), String> {
+ let bytes = write_step_bytes_with_unit(mesh, unit)?;
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 by extension string (`glb`, `obj`, `stl`, `3mf`, `step`, `stp`) into memory bytes.
+/// Export by extension string (`glb`, `obj`, `stl`, `3mf`, `step`, `stp`) into memory bytes,
+/// treating model coordinates as metres.
pub fn export_mesh_bytes(mesh: &PolyMesh, ext: &str) -> Result<Vec<u8>, String> {
+ export_mesh_bytes_with_unit(mesh, ext, Unit::Meter)
+}
+
+/// Export by extension string into memory bytes for a model authored in `unit`.
+///
+/// - `3mf` / `step` / `stp`: coordinates are kept in model units and the unit is declared in the file.
+/// - `glb`: glTF is defined in metres, so positions are scaled from `unit` to metres.
+/// - `obj` / `stl`: no unit field exists; coordinates are written in model units (slicers read STL as mm).
+pub fn export_mesh_bytes_with_unit(mesh: &PolyMesh, ext: &str, unit: Unit) -> Result<Vec<u8>, String> {
match ext.trim_start_matches('.').to_lowercase().as_str() {
- "glb" => write_glb_bytes(mesh, true),
+ "glb" => write_glb_bytes_with_unit(mesh, true, unit),
"obj" => write_obj_bytes(mesh),
"stl" => write_stl_binary_bytes(mesh),
- "3mf" => write_3mf_bytes(mesh),
- "step" | "stp" => write_step_bytes(mesh),
+ "3mf" => write_3mf_bytes_with_unit(mesh, unit),
+ "step" | "stp" => write_step_bytes_with_unit(mesh, unit),
other => Err(format!(
"unsupported export extension '.{other}' (supported: .glb, .obj, .stl, .3mf, .step)"
)),
}
}
-/// Export by extension (.glb, .obj, .stl, .3mf, .step, .stp).
+/// Export by extension (.glb, .obj, .stl, .3mf, .step, .stp), treating model coordinates as metres.
pub fn export_mesh(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
+ export_mesh_with_unit(mesh, path, Unit::Meter)
+}
+
+/// Export by extension (.glb, .obj, .stl, .3mf, .step, .stp) for a model authored in `unit`
+/// (see [`export_mesh_bytes_with_unit`] for per-format behaviour).
+pub fn export_mesh_with_unit(mesh: &PolyMesh, path: &Path, unit: Unit) -> Result<(), String> {
let ext = path
.extension()
.and_then(|s| s.to_str())
.map(|s| s.to_lowercase())
.unwrap_or_default();
match ext.as_str() {
- "glb" => write_glb(mesh, path, true),
+ "glb" => write_glb_with_unit(mesh, path, true, unit),
"obj" => write_obj(mesh, path),
"stl" => write_stl_binary(mesh, path),
- "3mf" => write_3mf(mesh, path),
- "step" | "stp" => write_step(mesh, path),
+ "3mf" => write_3mf_with_unit(mesh, path, unit),
+ "step" | "stp" => write_step_with_unit(mesh, path, unit),
_ => Err(format!("unsupported export extension '.{ext}' (supported: .glb, .obj, .stl, .3mf, .step)")),
}
}
diff --git a/crates/forma-core/src/lib.rs b/crates/forma-core/src/lib.rs
index 2079ae7..1384d38 100644
--- a/crates/forma-core/src/lib.rs
+++ b/crates/forma-core/src/lib.rs
@@ -8,6 +8,7 @@
//! - Copy-on-write (Arc) transactional snapshots/rollback and automatic topological invariants
//! - Compact (~100-token) spatial/topological observation & delta channel
//! - Native binary GLB (glTF 2.0 Y-up), faceted STEP AP214, 3MF, OBJ, and binary STL export
+//! - A scene-level model length unit (default metre) that unit-aware exporters (3MF, STEP, GLB) honour
pub mod boolean;
pub mod curves;
@@ -24,6 +25,7 @@ pub mod render;
pub mod scene;
pub mod selector;
pub mod spatial;
+pub mod units;
pub mod uv;
pub use invariants::MeshInvariants;
@@ -31,3 +33,4 @@ pub use mesh::{Face, LineageId, Material, PolyMesh};
pub use scene::{Observation, Scene, SceneError};
pub use selector::{EdgeSelector, FaceSelector};
pub use spatial::{ClearanceReport, SectionReport};
+pub use units::Unit;
diff --git a/crates/forma-core/src/scene.rs b/crates/forma-core/src/scene.rs
index f2cf2cb..505ba57 100644
--- a/crates/forma-core/src/scene.rs
+++ b/crates/forma-core/src/scene.rs
@@ -2,13 +2,14 @@
//! automatic topological invariant checks, and a compact (~100-token) LLM observation channel.
use crate::boolean::{boolean_op, BoolOp};
-use crate::export::export_mesh;
+use crate::export::export_mesh_with_unit;
use crate::invariants::MeshInvariants;
use crate::math::Vec3;
use crate::mesh::PolyMesh;
use crate::ops;
use crate::primitives;
use crate::selector::{EdgeSelector, FaceSelector};
+use crate::units::Unit;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::Path;
@@ -35,6 +36,7 @@ pub enum SceneError {
struct SceneSnapshot {
parts: BTreeMap<String, Arc<PolyMesh>>,
op_counter: u32,
+ unit: Unit,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -54,6 +56,8 @@ pub struct Scene {
snapshots: BTreeMap<String, SceneSnapshot>,
undo_stack: Vec<SceneSnapshot>,
op_counter: u32,
+ /// Length unit of model coordinates (default metre); declared/converted by unit-aware exporters.
+ pub unit: Unit,
pub strict_manifold: bool,
pub allow_fs_import: bool,
pub max_faces_per_part: usize,
@@ -77,6 +81,7 @@ impl Scene {
snapshots: BTreeMap::new(),
undo_stack: Vec::new(),
op_counter: 0,
+ unit: Unit::default(),
strict_manifold: false,
allow_fs_import: true,
max_faces_per_part: 200_000,
@@ -158,6 +163,12 @@ impl Scene {
crate::render::write_blueprint_svg(&mesh, title, path).map_err(SceneError::OpFailed)
}
+ /// Export `mesh` (typically from [`Scene::merged_mesh`]) to in-memory bytes by extension,
+ /// using this scene's model unit.
+ pub fn export_mesh_bytes(&self, mesh: &PolyMesh, ext: &str) -> Result<Vec<u8>, String> {
+ crate::export::export_mesh_bytes_with_unit(mesh, ext, self.unit)
+ }
+
/// Export ALL named scene parts as separate glTF 2.0 nodes (with shared `Arc<PolyMesh>` instancing).
pub fn export_scene_glb_bytes(&self, yup: bool) -> Result<Vec<u8>, SceneError> {
let nodes: Vec<(&str, &Arc<PolyMesh>, [f64; 3])> = self
@@ -165,7 +176,7 @@ impl Scene {
.iter()
.map(|(name, mesh)| (name.as_str(), mesh, [0.0, 0.0, 0.0]))
.collect();
- crate::export::write_scene_glb_bytes(&nodes, yup).map_err(SceneError::OpFailed)
+ crate::export::write_scene_glb_bytes_with_unit(&nodes, yup, self.unit).map_err(SceneError::OpFailed)
}
pub fn part_names(&self) -> Vec<String> {
@@ -190,6 +201,7 @@ impl Scene {
self.undo_stack.push(SceneSnapshot {
parts: self.parts.clone(),
op_counter: self.op_counter,
+ unit: self.unit,
});
if self.undo_stack.len() > 64 {
self.undo_stack.remove(0);
@@ -207,6 +219,7 @@ impl Scene {
SceneSnapshot {
parts: self.parts.clone(),
op_counter: self.op_counter,
+ unit: self.unit,
},
);
}
@@ -220,6 +233,7 @@ impl Scene {
self.push_undo();
self.parts = snap.parts;
self.op_counter = snap.op_counter;
+ self.unit = snap.unit;
Ok(())
}
@@ -227,6 +241,7 @@ impl Scene {
let snap = self.undo_stack.pop().ok_or(SceneError::NothingToUndo)?;
self.parts = snap.parts;
self.op_counter = snap.op_counter;
+ self.unit = snap.unit;
Ok(())
}
@@ -529,7 +544,7 @@ impl Scene {
pub fn export(&self, path: &Path, part_opt: Option<&str>) -> Result<MeshInvariants, SceneError> {
let mesh = self.merged_mesh(part_opt)?;
- export_mesh(&mesh, path).map_err(SceneError::OpFailed)?;
+ export_mesh_with_unit(&mesh, path, self.unit).map_err(SceneError::OpFailed)?;
Ok(MeshInvariants::compute(&mesh))
}
@@ -538,7 +553,11 @@ impl Scene {
let mut invs = BTreeMap::new();
let mut warnings = self.eval_warnings.clone();
let mut lines = Vec::new();
- lines.push(format!("OK [{elapsed_ms:.2}ms] parts={}", self.parts.len()));
+ if self.unit == Unit::default() {
+ lines.push(format!("OK [{elapsed_ms:.2}ms] parts={}", self.parts.len()));
+ } else {
+ lines.push(format!("OK [{elapsed_ms:.2}ms] parts={} unit={}", self.parts.len(), self.unit));
+ }
let mut all_manifold = true;
for (name, mesh) in &self.parts {
diff --git a/crates/forma-core/src/units.rs b/crates/forma-core/src/units.rs
new file mode 100644
index 0000000..031c53e
--- /dev/null
+++ b/crates/forma-core/src/units.rs
@@ -0,0 +1,101 @@
+//! Model length units.
+//!
+//! Forma geometry is unitless internally: a coordinate of `1.0` means "one model unit".
+//! The model unit defaults to the metre (historic behaviour) and can be set to anything
+//! the export formats can describe (e.g. millimetres for a 3D-printed case). Exporters that
+//! carry a unit (3MF, STEP) declare it; glTF (always metres by spec) is scaled from it;
+//! OBJ/STL have no unit field and are written in model units.
+
+use std::fmt;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum Unit {
+ Micrometer,
+ Millimeter,
+ Centimeter,
+ #[default]
+ Meter,
+ Inch,
+ Foot,
+}
+
+impl Unit {
+ /// Parse a unit name (`m`, `mm`, `cm`, `um`, `in`, `ft` and common long forms), case-insensitive.
+ pub fn parse(s: &str) -> Result<Self, String> {
+ match s.trim().to_lowercase().as_str() {
+ "m" | "meter" | "meters" | "metre" | "metres" => Ok(Self::Meter),
+ "mm" | "millimeter" | "millimeters" | "millimetre" | "millimetres" => Ok(Self::Millimeter),
+ "cm" | "centimeter" | "centimeters" | "centimetre" | "centimetres" => Ok(Self::Centimeter),
+ "um" | "micron" | "microns" | "micrometer" | "micrometers" | "micrometre" | "micrometres" => {
+ Ok(Self::Micrometer)
+ }
+ "in" | "inch" | "inches" => Ok(Self::Inch),
+ "ft" | "foot" | "feet" => Ok(Self::Foot),
+ other => Err(format!(
+ "unknown unit '{other}' (valid: m, cm, mm, um, in, ft)"
+ )),
+ }
+ }
+
+ /// Length of one model unit in metres.
+ pub fn meters_per_unit(self) -> f64 {
+ match self {
+ Self::Micrometer => 1e-6,
+ Self::Millimeter => 1e-3,
+ Self::Centimeter => 1e-2,
+ Self::Meter => 1.0,
+ Self::Inch => 0.0254,
+ Self::Foot => 0.3048,
+ }
+ }
+
+ /// Short symbol (`mm`, `m`, ...).
+ pub fn symbol(self) -> &'static str {
+ match self {
+ Self::Micrometer => "um",
+ Self::Millimeter => "mm",
+ Self::Centimeter => "cm",
+ Self::Meter => "m",
+ Self::Inch => "in",
+ Self::Foot => "ft",
+ }
+ }
+
+ /// Value of the 3MF core-spec `model/@unit` attribute.
+ pub fn threemf_name(self) -> &'static str {
+ match self {
+ Self::Micrometer => "micron",
+ Self::Millimeter => "millimeter",
+ Self::Centimeter => "centimeter",
+ Self::Meter => "meter",
+ Self::Inch => "inch",
+ Self::Foot => "foot",
+ }
+ }
+}
+
+impl fmt::Display for Unit {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(self.symbol())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parse_aliases() {
+ assert_eq!(Unit::parse("MM").unwrap(), Unit::Millimeter);
+ assert_eq!(Unit::parse("metres").unwrap(), Unit::Meter);
+ assert_eq!(Unit::parse("inches").unwrap(), Unit::Inch);
+ assert_eq!(Unit::parse("micron").unwrap(), Unit::Micrometer);
+ assert!(Unit::parse("parsec").is_err());
+ }
+
+ #[test]
+ fn default_is_meter() {
+ assert_eq!(Unit::default(), Unit::Meter);
+ assert_eq!(Unit::Meter.meters_per_unit(), 1.0);
+ }
+}
diff --git a/crates/forma-core/tests/units_export.rs b/crates/forma-core/tests/units_export.rs
new file mode 100644
index 0000000..a14279e
--- /dev/null
+++ b/crates/forma-core/tests/units_export.rs
@@ -0,0 +1,165 @@
+use forma_core::export::{
+ export_mesh_bytes, export_mesh_bytes_with_unit, write_3mf_bytes, write_3mf_bytes_with_unit, write_step_bytes,
+ write_step_bytes_with_unit,
+};
+use forma_core::math::Vec3;
+use forma_core::{PolyMesh, Scene, Unit};
+
+/// A 100 x 50 x 20 box centred on the origin, authored in whatever unit the caller declares.
+fn slab() -> PolyMesh {
+ forma_core::primitives::make_box(100.0, 50.0, 20.0, 1)
+}
+
+/// 3MF is written with stored (uncompressed) ZIP entries, so the model XML is searchable verbatim.
+fn model_xml(bytes: &[u8]) -> String {
+ String::from_utf8_lossy(bytes).into_owned()
+}
+
+fn max_3mf_coord(xml: &str, axis: char) -> f64 {
+ let key = format!("{axis}=\"");
+ xml.split("<vertex ")
+ .skip(1)
+ .map(|v| {
+ let start = v.find(&key).unwrap() + key.len();
+ let end = start + v[start..].find('"').unwrap();
+ v[start..end].parse::<f64>().unwrap()
+ })
+ .fold(f64::NEG_INFINITY, f64::max)
+}
+
+#[test]
+fn threemf_declares_unit_and_keeps_model_coordinates() {
+ let cases = [
+ (Unit::Millimeter, "millimeter"),
+ (Unit::Centimeter, "centimeter"),
+ (Unit::Meter, "meter"),
+ (Unit::Micrometer, "micron"),
+ (Unit::Inch, "inch"),
+ (Unit::Foot, "foot"),
+ ];
+ for (unit, name) in cases {
+ let xml = model_xml(&write_3mf_bytes_with_unit(&slab(), unit).unwrap());
+ assert!(xml.contains(&format!("<model unit=\"{name}\"")), "unit {unit:?} -> {name} missing");
+ // No hidden rescaling: a 100-wide box centred on 0 reaches x=50 whatever unit is declared.
+ assert!((max_3mf_coord(&xml, 'x') - 50.0).abs() < 1e-9);
+ assert!((max_3mf_coord(&xml, 'z') - 10.0).abs() < 1e-9);
+ }
+}
+
+#[test]
+fn step_declares_si_prefix_for_metric_units() {
+ let cases = [
+ (Unit::Millimeter, "SI_UNIT(.MILLI.,.METRE.)"),
+ (Unit::Centimeter, "SI_UNIT(.CENTI.,.METRE.)"),
+ (Unit::Micrometer, "SI_UNIT(.MICRO.,.METRE.)"),
+ (Unit::Meter, "SI_UNIT($,.METRE.)"),
+ ];
+ for (unit, needle) in cases {
+ let step = String::from_utf8(write_step_bytes_with_unit(&slab(), unit).unwrap()).unwrap();
+ let line = step.lines().find(|l| l.starts_with("#9=")).unwrap();
+ assert!(line.contains("LENGTH_UNIT()") && line.contains(needle), "unit {unit:?}: {line}");
+ // Coordinates are model units, unscaled.
+ assert!(step.contains("CARTESIAN_POINT('',(50.00000000,25.00000000,10.00000000))"));
+ }
+}
+
+#[test]
+fn step_declares_conversion_based_unit_for_imperial() {
+ for (unit, name, mm) in [(Unit::Inch, "INCH", "25.4"), (Unit::Foot, "FOOT", "304.8")] {
+ let step = String::from_utf8(write_step_bytes_with_unit(&slab(), unit).unwrap()).unwrap();
+ assert!(step.contains(&format!("#9=(CONVERSION_BASED_UNIT('{name}',#14)LENGTH_UNIT()NAMED_UNIT(#15));")));
+ assert!(step.contains(&format!("#14=LENGTH_MEASURE_WITH_UNIT(LENGTH_MEASURE({mm}),#16);")));
+ assert!(step.contains("#16=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.));"));
+ }
+}
+
+#[test]
+fn step_distance_accuracy_is_physically_constant() {
+ // 1e-6 m == 1e-3 mm
+ let mm = String::from_utf8(write_step_bytes_with_unit(&slab(), Unit::Millimeter).unwrap()).unwrap();
+ assert!(mm.contains("LENGTH_MEASURE(1.000000E-3),#9,'distance_accuracy_value'"), "{mm}");
+ let m = String::from_utf8(write_step_bytes_with_unit(&slab(), Unit::Meter).unwrap()).unwrap();
+ assert!(m.contains("LENGTH_MEASURE(1.000000E-6),#9,'distance_accuracy_value'"));
+}
+
+#[test]
+fn default_exports_stay_metres() {
+ let m = slab();
+ let three = model_xml(&write_3mf_bytes(&m).unwrap());
+ assert!(three.contains("<model unit=\"meter\""));
+ let step = String::from_utf8(write_step_bytes(&m).unwrap()).unwrap();
+ assert!(step.contains("#9=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT($,.METRE.));"));
+ assert_eq!(Scene::new().unit, Unit::Meter);
+ for ext in ["glb", "obj", "stl", "3mf", "step"] {
+ assert_eq!(
+ export_mesh_bytes(&m, ext).unwrap(),
+ export_mesh_bytes_with_unit(&m, ext, Unit::Meter).unwrap(),
+ "legacy `.{ext}` export must equal explicit metre export"
+ );
+ }
+}
+
+fn glb_position_extent(glb: &[u8]) -> [f64; 3] {
+ let jlen = u32::from_le_bytes([glb[12], glb[13], glb[14], glb[15]]) as usize;
+ let gltf: serde_json::Value = serde_json::from_slice(&glb[20..20 + jlen]).unwrap();
+ let min = gltf["accessors"][0]["min"].as_array().unwrap();
+ let max = gltf["accessors"][0]["max"].as_array().unwrap();
+ [0, 1, 2].map(|k| max[k].as_f64().unwrap() - min[k].as_f64().unwrap())
+}
+
+#[test]
+fn glb_is_scaled_to_metres_because_gltf_is_defined_in_metres() {
+ // 100 x 50 x 20 mm == 0.1 x 0.05 x 0.02 m. glTF is Y-up: extent = [x, z, y].
+ let mm = export_mesh_bytes_with_unit(&slab(), "glb", Unit::Millimeter).unwrap();
+ let e = glb_position_extent(&mm);
+ assert!((e[0] - 0.1).abs() < 1e-6 && (e[1] - 0.02).abs() < 1e-6 && (e[2] - 0.05).abs() < 1e-6, "{e:?}");
+
+ let inch = export_mesh_bytes_with_unit(&slab(), "glb", Unit::Inch).unwrap();
+ assert!((glb_position_extent(&inch)[0] - 2.54).abs() < 1e-5);
+
+ let m = export_mesh_bytes_with_unit(&slab(), "glb", Unit::Meter).unwrap();
+ assert!((glb_position_extent(&m)[0] - 100.0).abs() < 1e-4);
+}
+
+#[test]
+fn stl_and_obj_have_no_unit_field_and_keep_model_units() {
+ let mm_stl = export_mesh_bytes_with_unit(&slab(), "stl", Unit::Millimeter).unwrap();
+ assert_eq!(mm_stl, export_mesh_bytes(&slab(), "stl").unwrap());
+ let obj = String::from_utf8(export_mesh_bytes_with_unit(&slab(), "obj", Unit::Millimeter).unwrap()).unwrap();
+ assert!(obj.contains("v 50") || obj.contains("v -50"), "OBJ should keep raw model units: {obj}");
+}
+
+#[test]
+fn scene_unit_flows_through_export_and_snapshots() {
+ let mut s = Scene::new();
+ s.add_box("case", 100.0, 50.0, 20.0, Vec3::ZERO).unwrap();
+ s.unit = Unit::Millimeter;
+ s.checkpoint("mm");
+ assert!(s.observe(0.0, None).text.contains("unit=mm"));
+
+ let dir = std::env::temp_dir();
+ let p3 = dir.join("forma_units_scene.3mf");
+ let ps = dir.join("forma_units_scene.step");
+ s.export(&p3, None).unwrap();
+ s.export(&ps, None).unwrap();
+ assert!(model_xml(&std::fs::read(&p3).unwrap()).contains("<model unit=\"millimeter\""));
+ assert!(std::fs::read_to_string(&ps).unwrap().contains("SI_UNIT(.MILLI.,.METRE.)"));
+
+ let mesh = s.merged_mesh(None).unwrap();
+ assert_eq!(
+ s.export_mesh_bytes(&mesh, "3mf").unwrap(),
+ write_3mf_bytes_with_unit(&mesh, Unit::Millimeter).unwrap()
+ );
+
+ // Changing the unit is undoable / rolled back together with the geometry it describes.
+ s.push_undo();
+ s.unit = Unit::Inch;
+ s.undo().unwrap();
+ assert_eq!(s.unit, Unit::Millimeter);
+ s.unit = Unit::Meter;
+ s.rollback("mm").unwrap();
+ assert_eq!(s.unit, Unit::Millimeter);
+
+ let scene_glb = s.export_scene_glb_bytes(true).unwrap();
+ assert!((glb_position_extent(&scene_glb)[0] - 0.1).abs() < 1e-6);
+}
diff --git a/crates/forma-lang/src/compact.rs b/crates/forma-lang/src/compact.rs
index 990b314..1f82941 100644
--- a/crates/forma-lang/src/compact.rs
+++ b/crates/forma-lang/src/compact.rs
@@ -455,6 +455,12 @@ pub fn eval_compact(scene: &mut Scene, src: &str) -> Result<(), String> {
"undo" => {
scene.undo().map_err(|e| format!("line {line}: {e}"))?;
}
+ "units" => {
+ if tokens.len() < 2 {
+ return Err(format!("line {line}: units requires NAME (m, cm, mm, um, in, ft)"));
+ }
+ scene.unit = forma_core::Unit::parse(tokens[1]).map_err(|e| format!("line {line}: {e}"))?;
+ }
// Allow omitting 'new' shorthand: `box ID sx sy sz`
other if is_prim_kw(other) => {
if tokens.len() < 2 {
diff --git a/crates/forma-lang/src/lib.rs b/crates/forma-lang/src/lib.rs
index 4008188..bec2acb 100644
--- a/crates/forma-lang/src/lib.rs
+++ b/crates/forma-lang/src/lib.rs
@@ -70,7 +70,7 @@ pub const SPEC_PIPE_GBNF: &str = include_str!("../../../grammar/forma_pipe.gbnf"
/// Concise system prompt spec for Candidate A (Forma-Pipe), ~355 o200k tokens.
/// Keeps core MCP schema strictly <800 tokens; advanced Tier-1 domains load on-demand via `spec_topic`.
-pub const SPEC_PIPE: &str = r#"Forma-Pipe (Z-up meters, watertight 3D):
+pub const SPEC_PIPE: &str = r#"Forma-Pipe (Z-up, unit-agnostic numbers, default meters, watertight 3D):
`name = expr | op | op` (multi-line `|`, math `+ - * / sqrt sin cos pi`, last assigned part exports).
Primitives (`at=(x,y,z)` or `[(x,y,z),...]`; `z0=Z` sets bottom):
- `box(sx,sy,sz, at=, z0=)` | `cyl(r,h, segs=32, axis=z, at=, z0=)` (`segs=6`: verts k*60deg)
@@ -82,6 +82,7 @@ Ops (`|` or `op(m,...)`; `add`/`cut` take `at=(x,y,z)` or `[...]`):
- `bevel(edges, w, segs=1)` (vertical|top_rim|bottom_rim|outer_rim|sharp|all) | `extrude(faces, d)` | `inset(faces, amt, depth=0)`
- `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), metallic=0.1, roughness=0.5)` | `color(r,g,b)` | `clearance(a,b)` | `section(p,z)`
+- `units("mm")` (m|cm|mm|um|in|ft): declare the unit your numbers are in; .3mf/.step carry it, .glb is scaled to metres
More: `inspect(topic="deform|curves|uv|remesh|scene")`"#;
/// Progressive on-demand Tier-1 domain specs (paid 0 tokens unless requested!).
@@ -122,7 +123,7 @@ pub fn spec_topic(topic: &str) -> Result<&'static str, String> {
}
/// Concise system prompt spec + EBNF for Candidate B (Forma-DSL), ~330 o200k tokens.
-pub const SPEC_COMPACT: &str = r#"Forma-DSL (Z-up meters, watertight 3D line DSL; last modified part exports):
+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]
@@ -132,7 +133,7 @@ EBNF:
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'
+ 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)]
@@ -169,4 +170,41 @@ mod tests {
);
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="), "metre scenes keep the legacy observation text");
+
+ 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);
+ }
}
diff --git a/crates/forma-lang/src/pipeline.rs b/crates/forma-lang/src/pipeline.rs
index d1701fd..af596f5 100644
--- a/crates/forma-lang/src/pipeline.rs
+++ b/crates/forma-lang/src/pipeline.rs
@@ -295,6 +295,7 @@ fn allowed_call_kwargs(name: &str) -> Option<&'static [&'static str]> {
"clearance" => &["a", "b"],
"section" => &["part", "z"],
"checkpoint" | "rollback" | "del" | "remove" => &["name", "tag"],
+ "units" | "unit" => &["name", "unit"],
"undo" => &[],
"box" => &["sx", "x", "w", "width", "sy", "y", "d", "depth", "sz", "z", "h", "height", "rot", "rotate", "at", "center", "z0"],
"cyl" | "cylinder" | "prism" => &["r", "radius", "h", "height", "len", "length", "segs", "segments", "sides", "axis", "rot", "rotate", "at", "center", "z0"],
@@ -696,6 +697,11 @@ impl<'a> Parser<'a> {
self.scene.rollback(tag).map_err(|e| format!("{ctx}: {e}"))?;
return Ok(Val::Bool(true));
}
+ "units" | "unit" => {
+ let name = pos.first().or_else(|| kw.get("unit")).or_else(|| kw.get("name")).ok_or(format!("{ctx}: missing unit name (m, cm, mm, um, in, ft)"))?.as_str(&ctx)?;
+ self.scene.unit = forma_core::Unit::parse(name).map_err(|e| format!("{ctx}: {e}"))?;
+ return Ok(Val::Bool(true));
+ }
"undo" => {
self.scene.undo().map_err(|e| format!("{ctx}: {e}"))?;
return Ok(Val::Bool(true));
diff --git a/crates/forma-server/src/main.rs b/crates/forma-server/src/main.rs
index b92ba6d..6078592 100644
--- a/crates/forma-server/src/main.rs
+++ b/crates/forma-server/src/main.rs
@@ -7,8 +7,8 @@
//! Endpoints:
//! GET /health -> {"status":"ok","version":"0.4.1","workers":N}
//! GET /spec[?gbnf=1] -> Forma-Pipe language spec or GBNF grammar
-//! POST /v1/eval -> Evaluate Forma-Pipe with optional base64 in-memory `assets`
-//! POST /v1/process -> Direct asset processor (import -> decimate/scale/center_z0 -> export)
+//! POST /v1/eval -> Evaluate Forma-Pipe with optional base64 in-memory `assets` and model `unit` (default m)
+//! POST /v1/process -> Direct asset processor (import -> decimate/scale/center_z0 -> export; optional `unit`)
use forma_core::{MeshInvariants, Scene};
use forma_lang::{eval_script, Dialect, SPEC_COMPACT, SPEC_PIPE, SPEC_PIPE_GBNF};
@@ -185,6 +185,12 @@ fn handle_eval(body: &[u8]) -> HttpResponse {
let mut scene = Scene::new();
scene.strict_manifold = strict;
+ if let Some(u) = req.get("unit").and_then(|v| v.as_str()) {
+ match forma_core::Unit::parse(u) {
+ Ok(unit) => scene.unit = unit,
+ Err(e) => return HttpResponse::json(400, "Bad Request", json!({ "ok": false, "error": e })),
+ }
+ }
scene.allow_fs_import = false; // Zero host filesystem access in multi-tenant server!
scene.max_statements = 1_024;
@@ -231,7 +237,7 @@ fn handle_eval(body: &[u8]) -> HttpResponse {
let out_bytes = match format.as_str() {
"png" => forma_core::render::render_quad_png_bytes(&mesh, size),
"svg" => forma_core::render::render_blueprint_svg_string(&mesh, part.unwrap_or("FORMA PART")).map(|s| s.into_bytes()),
- other => forma_core::export::export_mesh_bytes(&mesh, other),
+ other => scene.export_mesh_bytes(&mesh, other),
};
match out_bytes {
Ok(bytes) => HttpResponse {
@@ -300,11 +306,18 @@ fn handle_process(body: &[u8]) -> HttpResponse {
};
}
+ let out_unit = match req.get("unit").and_then(|v| v.as_str()) {
+ Some(u) => match forma_core::Unit::parse(u) {
+ Ok(unit) => unit,
+ Err(e) => return HttpResponse::json(400, "Bad Request", json!({ "ok": false, "error": e })),
+ },
+ None => forma_core::Unit::default(),
+ };
let inv = MeshInvariants::compute(&mesh);
let out_bytes = match out_fmt.as_str() {
"png" => forma_core::render::render_quad_png_bytes(&mesh, size),
"svg" => forma_core::render::render_blueprint_svg_string(&mesh, "PROCESSED ITEM").map(|s| s.into_bytes()),
- other => forma_core::export::export_mesh_bytes(&mesh, other),
+ other => forma_core::export::export_mesh_bytes_with_unit(&mesh, other, out_unit),
};
match out_bytes {
Ok(bytes) => HttpResponse {
diff --git a/crates/forma-wasm/src/lib.rs b/crates/forma-wasm/src/lib.rs
index c378cb2..489fc88 100644
--- a/crates/forma-wasm/src/lib.rs
+++ b/crates/forma-wasm/src/lib.rs
@@ -254,7 +254,7 @@ pub extern "C" fn forma_session_export(
forma_core::render::render_blueprint_svg_string(&mesh, title)
.map(|svg| svg.into_bytes())
}
- other => forma_core::export::export_mesh_bytes(&mesh, other),
+ other => scene.export_mesh_bytes(&mesh, other),
};
match bytes_res {
Ok(bytes) => s.set_ok_bytes(bytes),
diff --git a/grammar/forma_pipe.gbnf b/grammar/forma_pipe.gbnf
index 4f69293..9a7e24e 100644
--- a/grammar/forma_pipe.gbnf
+++ b/grammar/forma_pipe.gbnf
@@ -30,7 +30,7 @@ func-name ::= "box" | "cyl" | "cylinder" | "prism" | "pipe" | "hollow_cyl"
| "cone" | "frustum" | "sphere" | "torus" | "revolve"
| "arc_tube" | "tube" | "extrude2d" | "loft" | "thread" | "helix"
| "sweep" | "text3d" | "text"
- | "clearance" | "section" | "checkpoint" | "rollback" | "undo" | "del"
+ | "clearance" | "section" | "checkpoint" | "rollback" | "undo" | "units" | "del"
| "sqrt" | "sin" | "cos" | "asin" | "acos" | "abs" | "deg" | "rad"
| pipe-op
diff --git a/llms.txt b/llms.txt
index 8533477..b5458d9 100644
--- a/llms.txt
+++ b/llms.txt
@@ -34,8 +34,9 @@ cargo build --release
./target/release/forma-mcp
```
-## Forma-Pipe Language Reference (Z-up, meters)
+## Forma-Pipe Language Reference (Z-up; numbers are in your model unit, default meters)
+- Units: `units("mm")` (`m|cm|mm|um|in|ft`, default `m`) declares the unit your numbers are in. `.3mf` (`unit=`) and `.step` (`SI_UNIT`/`CONVERSION_BASED_UNIT`) carry it; `.glb` is scaled to metres (glTF is metres); `.stl`/`.obj` have no unit field and keep model units. CLI: `forma eval --unit mm`.
- Assignment & chaining: `name = expr | op | op` (multi-line `|` supported, math `+ - * / sqrt sin cos asin acos abs pi`, last assigned part exports).
- Common placement kwargs on primitives: `at=(x,y,z)` or `at=[(x,y,z),...]`, `z0=Z` (rests bottom at Z), `rot=(rx,ry,rz)`.
- Primitives: