A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server
fix(cli,core): npm --scene/--view parity, GLB sRGB->linear, clamp warnings, and strict exit code 3
Captain Coconutb6b25bc02d9a
diff --git a/bin/forma.mjs b/bin/forma.mjsindex c2f582b..44b643a 100755--- a/bin/forma.mjs+++ b/bin/forma.mjs@@ -18,9 +18,9 @@ function printHelp() {process.stdout.write(`forma ${VERSION} (WASM) — pure-Rust headless 3D polyhedral modeling engine for AI agents\n\n` +`USAGE:\n` +- ` forma-3d eval [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--strict|--no-strict] [--json] [--scene] [--out path.(glb|obj|stl|3mf|step|blend)] [--render preview.png] [--size 512] [--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 eval [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--strict|--no-strict] [--json] [--scene] [--out path.(glb|obj|stl|3mf|step|blend)] [--render preview.png] [--size 512] [--view quad|front|back|right|left|top|iso] [--draw blueprint.svg] [file|-]\n` ++ ` forma-3d render [--scene] [--size 512] [--view quad|front|back|right|left|top|iso] --out preview.png [file|-]\n` ++ ` forma-3d draw [--scene] --out blueprint.svg [file|-]\n` +` forma-3d spec [--dialect pipe|compact] [--topic TOPIC] [--gbnf]\n` +` forma-3d mcp\n` +` forma-3d version | --version | -V\n\n` +@@ -114,6 +114,7 @@ async function main() {let renderPath = null;let drawPath = null;let renderSize = 512;+ let renderView = "quad";let inFile = null;for (let i = 1; i < args.length; i++) {@@ -138,6 +139,8 @@ async function main() {usageErr(`invalid --size '${raw}': expected positive integer`);}renderSize = parsed;+ } else if (a === "--view") {+ renderView = requireVal(args, i++, a, "value (quad|front|back|right|left|top|iso)");} else if (a === "--strict") {strict = true;} else if (a === "--no-strict") {@@ -191,10 +194,14 @@ async function main() {}}if (renderPath) {- await writeFile(renderPath, session.exportBytes("png", { size: renderSize }));+ const pngBytes = exportScene+ ? session.exportScenePngBytes(renderSize, renderView)+ : session.exportBytes("png", { size: renderSize, view: renderView });+ await writeFile(renderPath, pngBytes);}if (drawPath) {- await writeFile(drawPath, session.exportBytes("svg"));+ const svgData = exportScene ? session.exportSceneSvg() : session.exportBytes("svg");+ await writeFile(drawPath, svgData);}if (asJson) {@@ -212,6 +219,9 @@ async function main() {} else {process.stderr.write(`ERR: ${msg}\n`);}+ if (strict && msg.includes("invariant violation on '")) {+ process.exit(3);+ }process.exit(1);} finally {session.free();diff --git a/crates/forma-cli/src/main.rs b/crates/forma-cli/src/main.rsindex 9fe2554..7638947 100644--- a/crates/forma-cli/src/main.rs+++ b/crates/forma-cli/src/main.rs@@ -8,7 +8,10 @@//! forma version | --version | -Vuse forma_core::{Scene, Unit};-use forma_lang::{eval_script, spec_topic, Dialect, SPEC_COMPACT, SPEC_PIPE, SPEC_PIPE_GBNF};+use forma_lang::{+ eval_script, is_invariant_violation_err, spec_topic, Dialect, SPEC_COMPACT, SPEC_PIPE,+ SPEC_PIPE_GBNF,+};use std::io::{self, Read};use std::path::PathBuf;use std::process;@@ -324,6 +327,9 @@ fn main() {} else {eprintln!("ERR: {e}");}+ if strict && is_invariant_violation_err(&e) {+ process::exit(3);+ }process::exit(1);}}diff --git a/crates/forma-cli/tests/cli_exit_codes.rs b/crates/forma-cli/tests/cli_exit_codes.rsnew file mode 100644index 0000000..fcbe902--- /dev/null+++ b/crates/forma-cli/tests/cli_exit_codes.rs@@ -0,0 +1,59 @@+use std::io::Write;+use std::process::{Command, Stdio};++fn run_forma(args: &[&str], stdin_data: &str) -> (i32, String, String) {+ let bin = env!("CARGO_BIN_EXE_forma");+ let mut child = Command::new(bin)+ .args(args)+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .expect("spawn forma binary");+ child+ .stdin+ .as_mut()+ .unwrap()+ .write_all(stdin_data.as_bytes())+ .unwrap();+ let out = child.wait_with_output().unwrap();+ let code = out.status.code().unwrap_or(-1);+ (+ code,+ String::from_utf8_lossy(&out.stdout).into_owned(),+ String::from_utf8_lossy(&out.stderr).into_owned(),+ )+}++#[test]+fn issue_84_strict_invariant_failure_exits_with_code_3() {+ // 1. Self-intersecting torus in --strict mode exits 3+ let (code, _, stderr) = run_forma(&["eval", "--strict", "-"], "a = torus(0.5, 1)\n");+ assert_eq!(code, 3, "expected exit code 3 for strict self-intersection, stderr={stderr}");+ assert!(stderr.contains("invariant violation"), "stderr={stderr}");++ // 2. Overlapping multi-shell array in --strict mode exits 3+ let (code2, _, stderr2) = run_forma(+ &["eval", "--strict", "-"],+ "a = box(1, 1, 1) | array(2, step=(0.5, 0, 0), union=false)\n",+ );+ assert_eq!(code2, 3, "expected exit code 3 for overlapping shells, stderr={stderr2}");++ // 3. JSON mode still exits 3 on strict invariant failure+ let (code3, stdout3, _) = run_forma(&["eval", "--strict", "--json", "-"], "a = torus(0.5, 1)\n");+ assert_eq!(code3, 3, "expected exit code 3 in --json mode, stdout={stdout3}");+ assert!(stdout3.contains("\"ok\":false"), "stdout={stdout3}");++ // 4. Syntax/script error still exits 1+ let (code_syn, _, _) = run_forma(&["eval", "--strict", "-"], "a = box(1,\n");+ assert_eq!(code_syn, 1, "syntax error must still exit 1");++ // 5. Unknown flag still exits 2+ let (code_flag, _, _) = run_forma(&["eval", "--bogus-flag"], "a = box(1,1,1)\n");+ assert_eq!(code_flag, 2, "unknown flag must still exit 2");++ // 6. Valid solid exits 0+ let (code_ok, stdout_ok, _) = run_forma(&["eval", "--strict", "-"], "a = box(1,1,1)\n");+ assert_eq!(code_ok, 0);+ assert!(stdout_ok.contains("WT=ok"));+}diff --git a/crates/forma-core/src/export.rs b/crates/forma-core/src/export.rsindex 198c409..137ae85 100644--- a/crates/forma-core/src/export.rs+++ b/crates/forma-core/src/export.rs@@ -8,6 +8,50 @@ use std::fs::File;use std::io::{BufWriter, Write};use std::path::Path;+/// Convert a single sRGB channel `[0, 1]` to linear light (IEC 61966-2-1) for glTF 2.0 `baseColorFactor`.+#[inline]+pub(crate) fn srgb_to_linear(c: f32) -> f32 {+ let c = c.clamp(0.0, 1.0);+ if c <= 0.04045 {+ c / 12.92+ } else {+ ((c + 0.055) / 1.055).powf(2.4)+ }+}++/// Convert a single linear channel `[0, 1]` back to sRGB (IEC 61966-2-1) when importing glTF 2.0 colors.+#[inline]+pub(crate) fn linear_to_srgb(c: f32) -> f32 {+ let c = c.clamp(0.0, 1.0);+ if c <= 0.0031308 {+ c * 12.92+ } else {+ 1.055 * c.powf(1.0 / 2.4) - 0.055+ }+}++/// Convert sRGB `[r, g, b, a]` (alpha stays linear per glTF 2.0) to linear `[r, g, b, a]`.+#[inline]+pub(crate) fn srgb_rgba_to_linear(rgba: [f32; 4]) -> [f32; 4] {+ [+ srgb_to_linear(rgba[0]),+ srgb_to_linear(rgba[1]),+ srgb_to_linear(rgba[2]),+ rgba[3].clamp(0.0, 1.0),+ ]+}++/// Convert linear `[r, g, b, a]` (alpha stays linear per glTF 2.0) to sRGB `[r, g, b, a]`.+#[inline]+pub(crate) fn linear_rgba_to_srgb(rgba: [f32; 4]) -> [f32; 4] {+ [+ linear_to_srgb(rgba[0]),+ linear_to_srgb(rgba[1]),+ linear_to_srgb(rgba[2]),+ rgba[3].clamp(0.0, 1.0),+ ]+}+/// Compute deterministic triplanar box UV coordinates for vertex `p` on a face with normal `n`.#[inline]fn triplanar_uv(p: Vec3, n: Vec3) -> [f32; 2] {@@ -302,10 +346,11 @@ pub fn write_glb_bytes_with_unit(mesh: &PolyMesh, yup: bool, unit: Unit) -> Resus.push(',');}let name_json = serde_json::to_string(&mat.name).unwrap_or_else(|_| "\"mat\"".to_string());+ let lin = srgb_rgba_to_linear(mat.color);s.push_str(&format!(r#"{{"name":{},"pbrMetallicRoughness":{{"baseColorFactor":[{},{},{},{}],"metallicFactor":{},"roughnessFactor":{}}}}}"#,name_json,- mat.color[0], mat.color[1], mat.color[2], mat.color[3],+ lin[0], lin[1], lin[2], lin[3],mat.metallic, mat.roughness));}@@ -441,10 +486,11 @@ pub fn write_scene_glb_bytes_with_unit(let key = format!("{}:{:?}:{}:{}", mat.name, mat.color, mat.metallic, mat.roughness);let mslot = *mat_dedup.entry(key).or_insert_with(|| {let idx = gltf_materials.len();+ let lin = srgb_rgba_to_linear(mat.color);gltf_materials.push(serde_json::json!({"name": mat.name,"pbrMetallicRoughness": {- "baseColorFactor": mat.color,+ "baseColorFactor": lin,"metallicFactor": mat.metallic,"roughnessFactor": mat.roughness}diff --git a/crates/forma-core/src/import.rs b/crates/forma-core/src/import.rsindex 7684c9d..46b6980 100644--- a/crates/forma-core/src/import.rs+++ b/crates/forma-core/src/import.rs@@ -483,12 +483,14 @@ pub fn read_glb_bytes_with_opts(bytes: &[u8], yup_override: Option<bool>) -> Res.and_then(|p| p.get("baseColorFactor")).and_then(|v| v.as_array()).filter(|a| a.len() >= 3)- .map(|a| [- a[0].as_f64().unwrap_or(0.7) as f32,- a[1].as_f64().unwrap_or(0.7) as f32,- a[2].as_f64().unwrap_or(0.7) as f32,- a.get(3).and_then(|x| x.as_f64()).unwrap_or(1.0) as f32,- ])+ .map(|a| {+ crate::export::linear_rgba_to_srgb([+ a[0].as_f64().unwrap_or(0.7) as f32,+ a[1].as_f64().unwrap_or(0.7) as f32,+ a[2].as_f64().unwrap_or(0.7) as f32,+ a.get(3).and_then(|x| x.as_f64()).unwrap_or(1.0) as f32,+ ])+ }).unwrap_or([0.72, 0.75, 0.80, 1.0]);let metallic = pbr.and_then(|p| p.get("metallicFactor")).and_then(|v| v.as_f64()).unwrap_or(0.1) as f32;let roughness = pbr.and_then(|p| p.get("roughnessFactor")).and_then(|v| v.as_f64()).unwrap_or(0.5) as f32;diff --git a/crates/forma-core/src/ops.rs b/crates/forma-core/src/ops.rsindex fc17653..8d63cfd 100644--- a/crates/forma-core/src/ops.rs+++ b/crates/forma-core/src/ops.rs@@ -293,16 +293,36 @@ pub fn bevel_edges_with_warning(if width <= 1e-7 {return Ok((mesh.clone(), None));}- let segments = segments.clamp(1, 8);+ let mut warnings: Vec<String> = Vec::new();+ let clamped_segs = segments.clamp(1, 8);+ if segments != clamped_segs {+ warnings.push(format!(+ "bevel: segs={segments} clamped to {clamped_segs} (supported range 1..=8)"+ ));+ }+ let segments = clamped_segs;let edges = sel.select(mesh);if edges.is_empty() {return Err("bevel: edge selector matched 0 edges".into());}+ let join_warnings = |ws: Vec<String>| -> Option<String> {+ if ws.is_empty() {+ None+ } else {+ Some(ws.join("; "))+ }+ };+// Specialized exact path 1: Vertical edges of a Z-prism/box (with or without holes)if matches!(sel, EdgeSelector::Vertical) {- if let Some(filleted) = try_bevel_vertical_prism(mesh, width, segments, op_id) {- return Ok((filleted, None));+ if let Some((filleted, clamped_w)) = try_bevel_vertical_prism(mesh, width, segments, op_id) {+ if let Some(w_used) = clamped_w {+ warnings.push(format!(+ "bevel: width={width} clamped to {w_used:.4} to fit edge geometry"+ ));+ }+ return Ok((filleted, join_warnings(warnings)));}}@@ -313,21 +333,29 @@ pub fn bevel_edges_with_warning() {let do_top = matches!(sel, EdgeSelector::TopRim | EdgeSelector::OuterRim);let do_bot = matches!(sel, EdgeSelector::BottomRim | EdgeSelector::OuterRim);- if let Some(beveled) = try_bevel_z_rims(mesh, width, segments, do_top, do_bot, op_id) {- return Ok((beveled, None));+ if let Some((beveled, clamped_w)) = try_bevel_z_rims(mesh, width, segments, do_top, do_bot, op_id) {+ if let Some(w_used) = clamped_w {+ warnings.push(format!(+ "bevel: width={width} clamped to {w_used:.4} to fit edge geometry"+ ));+ }+ return Ok((beveled, join_warnings(warnings)));}}// General path: chamfer/bevel arbitrary selected edges via vertex-split & corner bridging- let warn = if segments > 1 {- Some(format!(+ if segments > 1 {+ warnings.push(format!("bevel: segs={segments} is only supported on prism/rim edges; fell back to 1-segment chamfer"- ))- } else {- None- };- let out = bevel_general_polyhedron(mesh, &edges, width, op_id)?;- Ok((out, warn))+ ));+ }+ let (out, clamped_w) = bevel_general_polyhedron(mesh, &edges, width, op_id)?;+ if let Some(w_used) = clamped_w {+ warnings.push(format!(+ "bevel: width={width} clamped to {w_used:.4} to fit edge geometry"+ ));+ }+ Ok((out, join_warnings(warnings)))}fn simplify_collinear_2d(pts: &[(f64, f64)], rel_eps: f64) -> Vec<(f64, f64)> {@@ -641,12 +669,13 @@ fn try_bevel_vertical_prism(radius: f64,segments: usize,op_id: u32,-) -> Option<PolyMesh> {+) -> Option<(PolyMesh, Option<f64>)> {let ZPrismFootprint { z0, z1, outer: poly, holes } = extract_z_prism_footprint(mesh)?;let n = poly.len();let mut rounded: Vec<(f64, f64)> = Vec::with_capacity(n * (segments + 1));let cos_sharp_thresh = 20.0_f64.to_radians().cos();let mut beveled_any = false;+ let mut min_clamped_d: Option<f64> = None;for i in 0..n {let prev = poly[(i + n - 1) % n];@@ -670,6 +699,9 @@ fn try_bevel_vertical_prism(beveled_any = true;let d = radius.min(l1 * 0.45).min(l2 * 0.45);+ if d < radius - 1e-9 {+ min_clamped_d = Some(min_clamped_d.map_or(d, |m| m.min(d)));+ }let p_start = (curr.0 + u1.0 * d, curr.1 + u1.1 * d);let p_end = (curr.0 + u2.0 * d, curr.1 + u2.1 * d);@@ -732,7 +764,7 @@ fn try_bevel_vertical_prism(}res.smooth_angle_deg = mesh.smooth_angle_deg;res.weighted_normals = mesh.weighted_normals;- Some(res)+ Some((res, min_clamped_d))}/// Extract ordered horizontal rings `(poly_xy, z)` from bottom face to top face on a Z-prism@@ -986,7 +1018,7 @@ fn try_bevel_z_rims(do_top: bool,do_bot: bool,op_id: u32,-) -> Option<PolyMesh> {+) -> Option<(PolyMesh, Option<f64>)> {let bb = mesh.aabb();let z0 = bb.min.z;let z1 = bb.max.z;@@ -1036,6 +1068,14 @@ fn try_bevel_z_rims((wb, wt)};+ let mut clamped_w: Option<f64> = None;+ if do_bot && bot_is_vert && w_bot < width - 1e-9 {+ clamped_w = Some(clamped_w.map_or(w_bot, |m| m.min(w_bot)));+ }+ if do_top && top_is_vert && w_top < width - 1e-9 {+ clamped_w = Some(clamped_w.map_or(w_top, |m| m.min(w_top)));+ }+// Bottom endif do_bot && bot_is_vert && w_bot > 1e-7 {let base_poly = &existing[0].0;@@ -1135,7 +1175,7 @@ fn try_bevel_z_rims(}}m.ensure_outward_winding();- Some(m)+ Some((m, clamped_w))}/// General polyhedral chamfer for arbitrary selected edges via per-face corner shrinking.@@ -1144,7 +1184,7 @@ fn bevel_general_polyhedron(selected_edges: &[(usize, usize)],width: f64,op_id: u32,-) -> Result<PolyMesh, String> {+) -> Result<(PolyMesh, Option<f64>), String> {let sel_set: HashSet<(usize, usize)> = selected_edges.iter().copied().collect();let mut out = PolyMesh::new();out.materials = mesh.materials.clone();@@ -1166,6 +1206,8 @@ fn bevel_general_polyhedron(}}+ let mut min_clamped_w: Option<f64> = None;+for (fi, f) in mesh.faces.iter().enumerate() {let c = mesh.face_centroid(fi);let n = f.verts.len();@@ -1188,10 +1230,18 @@ fn bevel_general_polyhedron(let l_next = (mesh.verts[next] - p).len();let mut shift = Vec3::ZERO;if e_prev_sel {- shift = shift + d_prev * width.min(l_prev * 0.35);+ let eff = width.min(l_prev * 0.35);+ if eff < width - 1e-9 {+ min_clamped_w = Some(min_clamped_w.map_or(eff, |m| m.min(eff)));+ }+ shift = shift + d_prev * eff;}if e_next_sel {- shift = shift + d_next * width.min(l_next * 0.35);+ let eff = width.min(l_next * 0.35);+ if eff < width - 1e-9 {+ min_clamped_w = Some(min_clamped_w.map_or(eff, |m| m.min(eff)));+ }+ shift = shift + d_next * eff;}if shift.len_sq() < 1e-12 {p.lerp(c, 0.1)@@ -1199,7 +1249,12 @@ fn bevel_general_polyhedron(p + shift}} else {- p.lerp(c, (width / (p - c).len().max(1e-6)).min(0.35))+ let dist = (p - c).len().max(1e-6);+ let max_eff = dist * 0.35;+ if max_eff < width - 1e-9 {+ min_clamped_w = Some(min_clamped_w.map_or(max_eff, |m| m.min(max_eff)));+ }+ p.lerp(c, (width / dist).min(0.35))};let nvi = out.add_vert(np);face_corner_map.insert((fi, v), nvi);@@ -1293,7 +1348,7 @@ fn bevel_general_polyhedron(out.weld_and_clean(1e-6);out.ensure_outward_winding();- Ok(out)+ Ok((out, min_clamped_w))}/// Exact Catmull-Clark subdivision (`levels` iterations) on closed manifold polyhedral meshes.diff --git a/crates/forma-core/src/scene.rs b/crates/forma-core/src/scene.rsindex fc232f0..772d67c 100644--- a/crates/forma-core/src/scene.rs+++ b/crates/forma-core/src/scene.rs@@ -271,6 +271,12 @@ impl Scene {crate::render::render_quad_png_bytes(&mesh, size).map_err(SceneError::OpFailed)}+ /// Render a named view (`quad|front|back|right|left|top|iso`) of ALL named parts in the scene directly to PNG bytes.+ pub fn render_preview_scene_view_bytes(&self, size: usize, view: &str) -> Result<Vec<u8>, SceneError> {+ let mesh = self.merged_scene_mesh()?;+ crate::render::render_view_png_bytes(&mesh, size, view).map_err(SceneError::OpFailed)+ }+pub fn export_blueprint_svg(&self, path: &Path, part_opt: Option<&str>) -> Result<(), SceneError> {let mesh = self.merged_mesh(part_opt)?;let title = part_opt.or_else(|| self.last_part_name()).unwrap_or("forma_part");@@ -722,13 +728,21 @@ impl Scene {pub fn bevel(&mut self, target: &str, sel: &EdgeSelector, width: f64, segments: usize) -> Result<MeshInvariants, SceneError> {let m = Arc::clone(self.get_part(target)?);let op = self.next_op();- let res = ops::bevel_edges(&m, sel, width, segments, op).map_err(SceneError::OpFailed)?;+ let (res, warn) = ops::bevel_edges_with_warning(&m, sel, width, segments, op).map_err(SceneError::OpFailed)?;+ if let Some(msg) = warn {+ self.push_warning(msg);+ }self.set_part(target, res)}pub fn subsurf(&mut self, target: &str, levels: usize) -> Result<MeshInvariants, SceneError> {let m = Arc::clone(self.get_part(target)?);let op = self.next_op();+ if levels > 4 {+ self.push_warning(format!(+ "subsurf: levels={levels} clamped to 4 (supported range 0..=4)"+ ));+ }let res = ops::subsurf_catmull_clark(&m, levels, op);self.set_part(target, res)}diff --git a/crates/forma-core/tests/kernel_tests.rs b/crates/forma-core/tests/kernel_tests.rsindex 5095959..30bc5b0 100644--- a/crates/forma-core/tests/kernel_tests.rs+++ b/crates/forma-core/tests/kernel_tests.rs@@ -1150,3 +1150,73 @@ fn test_deform_curve_on_3d_bezier_has_no_false_self_intersection() {let inv = s.set_part("curved", curved).expect("smooth curved beam must pass strict manifold check");assert!(inv.is_valid_solid());}++#[test]+fn test_issue_82_glb_base_color_srgb_to_linear_roundtrip() {+ let mut b = forma_core::primitives::make_box(1.0, 1.0, 1.0, 1);+ let srgb = [0.5_f32, 0.2, 0.8, 0.75];+ b.assign_material(+ forma_core::Material {+ name: "swatch".into(),+ color: srgb,+ metallic: 0.2,+ roughness: 0.7,+ },+ None,+ );++ let parse_glb_base_color = |glb: &[u8]| -> [f64; 4] {+ let json_len = u32::from_le_bytes([glb[12], glb[13], glb[14], glb[15]]) as usize;+ let v: serde_json::Value = serde_json::from_slice(&glb[20..20 + json_len]).unwrap();+ let arr = v["materials"][0]["pbrMetallicRoughness"]["baseColorFactor"]+ .as_array()+ .unwrap();+ [+ arr[0].as_f64().unwrap(),+ arr[1].as_f64().unwrap(),+ arr[2].as_f64().unwrap(),+ arr[3].as_f64().unwrap(),+ ]+ };++ // Expected IEC 61966-2-1 linear RGB values (alpha stays linear)+ let expected_lin = [0.21404114_f64, 0.03310477, 0.60382734, 0.75];++ // Single-mesh GLB export+ let single_glb = forma_core::export::write_glb_bytes(&b, true).unwrap();+ let single_bc = parse_glb_base_color(&single_glb);+ for i in 0..4 {+ assert!(+ (single_bc[i] - expected_lin[i]).abs() < 1e-4,+ "single GLB baseColorFactor[{i}]={} != expected {}",+ single_bc[i],+ expected_lin[i]+ );+ }++ // Multi-part scene GLB export+ let mut scene = Scene::new();+ scene.set_part("swatch", b).unwrap();+ let scene_glb = scene.export_scene_glb_bytes(true).unwrap();+ let scene_bc = parse_glb_base_color(&scene_glb);+ for i in 0..4 {+ assert!(+ (scene_bc[i] - expected_lin[i]).abs() < 1e-4,+ "scene GLB baseColorFactor[{i}]={} != expected {}",+ scene_bc[i],+ expected_lin[i]+ );+ }++ // Importing the GLB back converts linear -> sRGB losslessly+ let reimported = forma_core::import::read_glb_bytes_with_opts(&single_glb, None).unwrap();+ assert_eq!(reimported.materials.len(), 1);+ for i in 0..4 {+ assert!(+ (reimported.materials[0].color[i] - srgb[i]).abs() < 1e-4,+ "round-trip sRGB color[{i}]={} != {}",+ reimported.materials[0].color[i],+ srgb[i]+ );+ }+}diff --git a/crates/forma-lang/src/lib.rs b/crates/forma-lang/src/lib.rsindex ef5781d..78d9b62 100644--- a/crates/forma-lang/src/lib.rs+++ b/crates/forma-lang/src/lib.rs@@ -57,6 +57,12 @@ pub fn eval_script(scene: &mut Scene, dialect: Dialect, src: &str) -> Result<Obs}}+/// 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");diff --git a/crates/forma-lang/src/pipeline.rs b/crates/forma-lang/src/pipeline.rsindex 71e4cff..01a0596 100644--- a/crates/forma-lang/src/pipeline.rs+++ b/crates/forma-lang/src/pipeline.rs@@ -1811,6 +1811,7 @@ impl<'a> Parser<'a> {.transpose()?.unwrap_or(1.0);let lv = whole_count(lv, &ctx)?;+ warn_if_clamped(self.scene, "subsurf", "levels", lv, 0, 4);let crease_deg = if let Some(cv) = kw.get("crease").or_else(|| pos.get(1)) {match cv {Val::Bool(true) => Some(55.0),diff --git a/crates/forma-lang/tests/audit_regressions.rs b/crates/forma-lang/tests/audit_regressions.rsindex fb09c58..017cf5a 100644--- a/crates/forma-lang/tests/audit_regressions.rs+++ b/crates/forma-lang/tests/audit_regressions.rs@@ -295,3 +295,76 @@ fn remove_part_keeps_last_modified_on_remaining_part_and_step_triangulates_nonplassert!(!step.contains("DIRECTION('',(0.00000000,0.00000000,0.00000000))"));assert!(step.contains("CLOSED_SHELL"));}++#[test]+fn issue_83_subsurf_levels_and_bevel_width_emit_clamp_warnings() {+ // 1. subsurf(levels > 4) warns; levels <= 4 does not+ let mut s_ok = Scene::new();+ s_ok.strict_manifold = true;+ let obs_ok = eval_script(&mut s_ok, Dialect::Pipe, "s4 = box(1, 1, 1) | subsurf(4)").unwrap();+ assert!(obs_ok.warnings.is_empty(), "subsurf(4) should not warn: {:?}", obs_ok.warnings);++ let mut s_hi = Scene::new();+ s_hi.strict_manifold = true;+ let obs_hi = eval_script(&mut s_hi, Dialect::Pipe, "s9 = box(1, 1, 1) | subsurf(9)").unwrap();+ assert!(+ obs_hi.warnings.iter().any(|w| w.contains("subsurf: levels=9 clamped to 4")),+ "expected subsurf clamp warning, got {:?}",+ obs_hi.warnings+ );++ // 2. bevel(all, w) oversized width on unit cube warns+ let mut b_all = Scene::new();+ b_all.strict_manifold = true;+ let obs_all = eval_script(&mut b_all, Dialect::Pipe, "b8 = box(1, 1, 1) | bevel(all, 0.8)").unwrap();+ assert!(+ obs_all.warnings.iter().any(|w| w.contains("bevel: width=0.8 clamped to")),+ "expected bevel(all) width clamp warning, got {:?}",+ obs_all.warnings+ );++ // 3. bevel(top_rim, w) warns when clamped, clean when within range+ let mut c_ok = Scene::new();+ c_ok.strict_manifold = true;+ let obs_c_ok = eval_script(&mut c_ok, Dialect::Pipe, "c05 = cyl(1, 2) | bevel(top_rim, 0.5, segs=3)").unwrap();+ assert!(obs_c_ok.warnings.is_empty(), "bevel(top_rim, 0.5) should not warn: {:?}", obs_c_ok.warnings);++ let mut c_hi = Scene::new();+ c_hi.strict_manifold = true;+ let obs_c_hi = eval_script(&mut c_hi, Dialect::Pipe, "c15 = cyl(1, 2) | bevel(top_rim, 1.5, segs=3)").unwrap();+ assert!(+ obs_c_hi.warnings.iter().any(|w| w.contains("bevel: width=1.5 clamped to")),+ "expected bevel(top_rim) width clamp warning, got {:?}",+ obs_c_hi.warnings+ );++ // 4. bevel(vertical, w) warns when clamped, clean when within range+ let mut v_ok = Scene::new();+ v_ok.strict_manifold = true;+ let obs_v_ok = eval_script(&mut v_ok, Dialect::Pipe, "v = box(1, 1, 1) | bevel(vertical, 0.2, segs=2)").unwrap();+ assert!(obs_v_ok.warnings.is_empty(), "bevel(vertical, 0.2) should not warn: {:?}", obs_v_ok.warnings);++ let mut v_hi = Scene::new();+ v_hi.strict_manifold = true;+ let obs_v_hi = eval_script(&mut v_hi, Dialect::Pipe, "v = box(1, 1, 1) | bevel(vertical, 0.8, segs=2)").unwrap();+ assert!(+ obs_v_hi.warnings.iter().any(|w| w.contains("bevel: width=0.8 clamped to")),+ "expected bevel(vertical) width clamp warning, got {:?}",+ obs_v_hi.warnings+ );++ // 5. Compact DSL subdiv & bev propagate warnings too+ let mut sc = Scene::new();+ sc.strict_manifold = true;+ let obs_c = eval_script(&mut sc, Dialect::Compact, "new p box 1 1 1\nbev p all 0.8\nsubdiv p 6").unwrap();+ assert!(+ obs_c.warnings.iter().any(|w| w.contains("bevel: width=0.8 clamped to")),+ "compact bev should warn: {:?}",+ obs_c.warnings+ );+ assert!(+ obs_c.warnings.iter().any(|w| w.contains("subsurf: levels=6 clamped to 4")),+ "compact subdiv should warn: {:?}",+ obs_c.warnings+ );+}diff --git a/crates/forma-wasm/src/lib.rs b/crates/forma-wasm/src/lib.rsindex bf22aee..dc1c358 100644--- a/crates/forma-wasm/src/lib.rs+++ b/crates/forma-wasm/src/lib.rs@@ -320,6 +320,43 @@ pub extern "C" fn forma_session_export_scene(id: u32) -> u32 {})}+/// Render a named view (`quad|front|back|right|left|top|iso`) of a part directly to PNG bytes.+#[no_mangle]+pub extern "C" fn forma_session_export_png_view(+ id: u32,+ part_ptr: *const u8,+ part_len: usize,+ view_ptr: *const u8,+ view_len: usize,+ size: u32,+) -> 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)),+ };+ let view = match unsafe { read_utf8(view_ptr, view_len) } {+ Ok(s) if !s.is_empty() => s,+ Ok(_) => "quad".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(&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 sz = if size == 0 { 512 } else { size as usize };+ match forma_core::render::render_view_png_bytes(&mesh, sz, &view) {+ Ok(bytes) => s.set_ok_bytes(bytes),+ Err(e) => s.set_err(e),+ }+ })+}+/// Render a 2x2 studio quad preview PNG of all named scene parts combined.#[no_mangle]pub extern "C" fn forma_session_export_scene_png(id: u32, size: u32) -> u32 {@@ -336,6 +373,32 @@ pub extern "C" fn forma_session_export_scene_png(id: u32, size: u32) -> u32 {})}+/// Render a named view (`quad|front|back|right|left|top|iso`) of all named scene parts combined.+#[no_mangle]+pub extern "C" fn forma_session_export_scene_png_view(+ id: u32,+ view_ptr: *const u8,+ view_len: usize,+ size: u32,+) -> u32 {+ let view = match unsafe { read_utf8(view_ptr, view_len) } {+ Ok(s) if !s.is_empty() => s,+ Ok(_) => "quad".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(&id) else {+ return s.set_err(format!("invalid session id {id}"));+ };+ let sz = if size == 0 { 512 } else { size as usize };+ match scene.render_preview_scene_view_bytes(sz, &view) {+ Ok(bytes) => s.set_ok_bytes(bytes),+ Err(e) => s.set_err(e.to_string()),+ }+ })+}+/// Render a 1200x900 dimensioned engineering SVG blueprint of all named scene parts combined.#[no_mangle]pub extern "C" fn forma_session_export_scene_svg(id: u32) -> u32 {diff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex 5bdb12b..6bba5e5 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -26,11 +26,11 @@ Forma ships two command-line executables backed by the same `forma-lang` and `fo| `--strict` | Enabled | Yes | Yes | Enforce watertightness, zero non-manifold edges, finite vertices, and non-degenerate volume. || `--no-strict` | Disabled | Yes | Yes | Disable strict invariant rejection and exit code `3`. || `--json` | Disabled | Yes | Yes | Print full `Observation` JSON to stdout instead of compact text. |-| `--scene` | Disabled | Yes | Yes | Export all named parts as separate glTF 2.0 / Blender nodes when `--out` targets `.glb` or `.blend`. |+| `--scene` | Disabled | Yes | Yes | Export/render/draw all named parts together (`.glb`, `.blend`, `.png`, `.svg`) instead of only the last assigned part. || `--out`, `-o <path>` | None | Yes | Yes | Export mesh (`.glb`, `.obj`, `.stl`, `.3mf`, `.step`, `.blend` via Blender bridge). || `--render <path.png>` | None | Yes | Yes | Render PNG preview alongside `eval`. |-| `--view <view>` | `quad` | Yes | No | Camera view for native `--render` / `render`: `quad`, `front`, `back`, `right`, `left`, `top`, `iso`. |-| `--size <px>` | `512` | Yes | Yes | Output PNG dimension in pixels (WASM `quad` renders 4-view preview at `size`). |+| `--view <view>` | `quad` | Yes | Yes | Camera view for `--render` / `render`: `quad`, `front`, `back`, `right`, `left`, `top`, `iso`. |+| `--size <px>` | `512` | Yes | Yes | Output PNG dimension in pixels (`quad` renders 4-view preview at `size`). || `--draw <path.svg>` | None | Yes | Yes | Emit 3-view orthographic SVG engineering drawing. || `[file\|-]` | stdin | Yes | Yes | Script file path; reads stdin when omitted or `-`. |@@ -38,13 +38,13 @@ Forma ships two command-line executables backed by the same `forma-lang` and `fo### `render`-- Native: `forma render [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--view quad|front|back|right|left|top|iso] [--size 512] --out preview.png [file|-]`-- WASM: `forma-3d render [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--size 512] --out preview.png [file|-]`+- Native: `forma render [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--scene] [--view quad|front|back|right|left|top|iso] [--size 512] --out preview.png [file|-]`+- WASM: `forma-3d render [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--scene] [--view quad|front|back|right|left|top|iso] [--size 512] --out preview.png [file|-]`### `draw`-- Native: `forma draw [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] --out blueprint.svg [file|-]`-- WASM: `forma-3d draw [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] --out blueprint.svg [file|-]`+- Native: `forma draw [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--scene] --out blueprint.svg [file|-]`+- WASM: `forma-3d draw [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--scene] --out blueprint.svg [file|-]`### `spec`@@ -55,9 +55,9 @@ Forma ships two command-line executables backed by the same `forma-lang` and `fo| Code | Meaning || --- | --- || `0` | Evaluation and all requested exports/renders succeeded. |-| `1` | Script evaluation error, invariant rollback error, or file I/O error. |+| `1` | Script syntax/evaluation error, export error, or file I/O error. || `2` | Invalid CLI argument, missing required flag value, or unknown subcommand. |-| `3` | Evaluation finished in `--strict` mode with `obs.ok == false` (for example `WT!=ok` or `NM>0`). |+| `3` | Strict manifold/invariant check failed (`--strict` auto-rollback or `obs.ok == false`, e.g. `WT!=ok`, `NM>0`, self-intersection). |## Environment variables@@ -73,7 +73,7 @@ Forma ships two command-line executables backed by the same `forma-lang` and `fo| `Forma-Pipe` and `Forma-DSL` evaluation | Yes | Yes | Identical `forma-lang` and `forma-core` code. || In-script `units("mm")` declaration | Yes | Yes | Portable across every runtime surface. || CLI `--unit` / `-u` flag | Yes | Yes | Sets initial unit before evaluating the script. |-| CLI `--view` single-angle PNG flag | Yes | No | WASM always renders the 4-view `quad` PNG. |+| CLI `--view` single-angle PNG flag | Yes | Yes | Both CLIs support `quad`, `front`, `back`, `right`, `left`, `top`, `iso`. || `.glb`, `.step`, `.3mf`, `.stl`, `.obj`, `.png`, `.svg` | Yes | Yes | Identical exporters and software rasterizer. || `.blend` stock-Blender bridge export | Yes | Yes (Node CLI/MCP) | Uses local Blender (`BLENDER_BIN` or `blender` on `PATH`). || Built-in `mcp` subcommand | Separate binary (`forma-mcp`) | Yes (`forma-3d mcp`) | Native builds separate `forma` and `forma-mcp` binaries. |diff --git a/lib/edge.mjs b/lib/edge.mjsindex a5f1091..cc759d5 100644--- a/lib/edge.mjs+++ b/lib/edge.mjs@@ -224,9 +224,23 @@ export class FormaSession {return res;}- /** Export bytes for .glb, .step, .3mf, .stl, .obj, .svg, or 4-view .png. */- exportBytes(format, { part = "", size = 512 } = {}) {+ /** Export bytes for .glb, .step, .3mf, .stl, .obj, .svg, or .png (quad|front|back|right|left|top|iso). */+ exportBytes(format, { part = "", size = 512, view = "quad" } = {}) {this._checkOpen();+ const normFmt = String(format ?? "").replace(/^\./, "").toLowerCase();+ const normView = String(view ?? "quad").trim();+ if (+ normFmt === "png" &&+ normView.toLowerCase() !== "quad" &&+ typeof this._engine.exports.forma_session_export_png_view === "function"+ ) {+ return this._engine._withUtf8(part || "", (pp, pl) =>+ this._engine._withUtf8(normView, (vp, vl) => {+ this._engine.exports.forma_session_export_png_view(this._id, pp, pl, vp, vl, size >>> 0);+ return this._engine._readResultBytes();+ })+ );+ }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);@@ -242,9 +256,19 @@ export class FormaSession {return this._engine._readResultBytes();}- /** Render a 4-view studio PNG preview of all named scene parts combined. */- exportScenePngBytes(size = 512) {+ /** Render a studio PNG preview (`quad|front|back|right|left|top|iso`) of all named scene parts combined. */+ exportScenePngBytes(size = 512, view = "quad") {this._checkOpen();+ const normView = String(view ?? "quad").trim();+ if (+ normView.toLowerCase() !== "quad" &&+ typeof this._engine.exports.forma_session_export_scene_png_view === "function"+ ) {+ return this._engine._withUtf8(normView, (vp, vl) => {+ this._engine.exports.forma_session_export_scene_png_view(this._id, vp, vl, size >>> 0);+ return this._engine._readResultBytes();+ });+ }this._engine._run(() =>this._engine.exports.forma_session_export_scene_png(this._id, size >>> 0));@@ -456,7 +480,7 @@ export async function exportMesh(code, format = "glb", opts = {}) {s.eval(code, opts);if (opts.scene) {const ext = String(format ?? "glb").replace(/^\./, "").toLowerCase();- if (ext === "png") return s.exportScenePngBytes(opts.size ?? 512);+ if (ext === "png") return s.exportScenePngBytes(opts.size ?? 512, opts.view ?? "quad");if (ext === "svg") return encoder.encode(s.exportSceneSvg());if (ext === "glb") return s.exportSceneBytes();throw new Error(`scene export requires .glb, .png, or .svg (got '.${ext}')`);diff --git a/lib/index.d.ts b/lib/index.d.tsindex d993f94..8775c48 100644--- a/lib/index.d.ts+++ b/lib/index.d.ts@@ -21,6 +21,7 @@ export type WasmSource =export type FormaDialect = "pipe" | "forma-pipe" | "a" | "default" | "compact" | "dsl" | "forma-dsl" | "b";export type FormaUnit = "m" | "cm" | "mm" | "um" | "in" | "ft";export type FormaExportFormat = "glb" | "step" | "stp" | "3mf" | "stl" | "obj" | "svg" | "png";+export type FormaRenderView = "quad" | "front" | "back" | "right" | "left" | "top" | "iso";export interface FormaInvariants {verts: number;@@ -80,6 +81,8 @@ export interface ExportOptions extends EvalOptions {scene?: boolean;/** Render resolution in pixels for PNG exports (default `512`). */size?: number;+ /** Camera view for PNG renders (`quad|front|back|right|left|top|iso`, default `"quad"`). */+ view?: FormaRenderView | string;}export interface EngineSpecOptions {@@ -107,12 +110,12 @@ export class FormaSession {inspect(): FormaObservation;/** Copy-on-write snapshot control: `checkpoint`, `rollback`, `undo`, or `reset`. */tx(action: "checkpoint" | "rollback" | "undo" | "reset", tag?: string): string;- /** Export a part to `.glb`, `.step`, `.3mf`, `.stl`, `.obj`, `.svg`, or 4-view `.png` bytes. */- exportBytes(format: FormaExportFormat, opts?: { part?: string; size?: number }): Uint8Array;+ /** Export a part to `.glb`, `.step`, `.3mf`, `.stl`, `.obj`, `.svg`, or `.png` bytes. */+ exportBytes(format: FormaExportFormat, opts?: { part?: string; size?: number; view?: FormaRenderView | string }): Uint8Array;/** Export all named parts as a multi-node binary glTF 2.0 (`.glb`) scene graph. */exportSceneBytes(): Uint8Array;- /** Render a 4-view studio PNG preview of all named scene parts combined. */- exportScenePngBytes(size?: number): Uint8Array;+ /** Render a studio PNG preview (`quad|front|back|right|left|top|iso`) of all named scene parts combined. */+ exportScenePngBytes(size?: number, view?: FormaRenderView | string): Uint8Array;/** Render a 1200x900 dimensioned SVG blueprint of all named scene parts combined. */exportSceneSvg(): string;/** Compute topological & spatial invariants for the current or named part. */diff --git a/tests/npm_smoke.mjs b/tests/npm_smoke.mjsindex 3238651..7ddb50a 100644--- a/tests/npm_smoke.mjs+++ b/tests/npm_smoke.mjs@@ -166,11 +166,64 @@ section(flange, 0.0)badFlagCode = err.status;}assert.equal(badFlagCode, 2, "unknown flag must exit with code 2");- console.log("PASS 3/5: CLI bin/forma.mjs (eval --strict, --unit mm, exit codes, .glb/.png/.svg)");++ // Issue #84: strict invariant violation exits with status 3 (while syntax error exits 1)+ let strictFailCode = 0;+ try {+ execFileSync(process.execPath, [cli, "eval", "--strict", "-"], { input: "a = torus(0.5, 1)\n", stdio: "pipe" });+ } catch (err) {+ strictFailCode = err.status;+ }+ assert.equal(strictFailCode, 3, "strict invariant violation must exit with code 3");++ let syntaxErrCode = 0;+ try {+ execFileSync(process.execPath, [cli, "eval", "--strict", "-"], { input: "a = box(1,\n", stdio: "pipe" });+ } catch (err) {+ syntaxErrCode = err.status;+ }+ assert.equal(syntaxErrCode, 1, "syntax error must exit with code 1");++ // Issue #58: --scene renders & draws all named parts, and --view selects single-angle camera+ const twoPartCode = "a = box(1, 1, 1)\nb = sphere(0.5) | move(3, 0, 0)\n";+ const singlePng = join(tmp, "single.png");+ const singleSvg = join(tmp, "single.svg");+ const scenePng = join(tmp, "scene.png");+ const sceneIsoPng = join(tmp, "scene-iso.png");+ const sceneSvg = join(tmp, "scene.svg");+ execFileSync(+ process.execPath,+ [cli, "eval", "--strict", "--render", singlePng, "--draw", singleSvg],+ { input: twoPartCode, encoding: "utf-8" }+ );+ execFileSync(+ process.execPath,+ [cli, "eval", "--strict", "--scene", "--render", scenePng, "--draw", sceneSvg],+ { input: twoPartCode, encoding: "utf-8" }+ );+ execFileSync(+ process.execPath,+ [cli, "render", "--scene", "--size", "256", "--view", "iso", "--out", sceneIsoPng],+ { input: twoPartCode, encoding: "utf-8" }+ );+ const singleSvgText = readFileSync(singleSvg, "utf-8");+ const sceneSvgText = readFileSync(sceneSvg, "utf-8");+ assert.ok(singleSvgText.includes("1.000 m"), "single-part SVG should span only sphere (1.000 m)");+ assert.ok(sceneSvgText.includes("4.000 m"), "scene SVG must span both box and shifted sphere (4.000 m)");+ const singlePngBytes = readFileSync(singlePng);+ const scenePngBytes = readFileSync(scenePng);+ const sceneIsoBytes = readFileSync(sceneIsoPng);+ assert.ok(!singlePngBytes.equals(scenePngBytes), "--scene --render PNG must differ from single-part PNG");+ assert.equal(sceneIsoBytes[0], 0x89);+ assert.equal(sceneIsoBytes[1], 0x50);+ const topViewBytes = await renderPng(twoPartCode, 128, { scene: true, view: "top", strict: true });+ assert.equal(topViewBytes[0], 0x89);+ assert.equal(topViewBytes[1], 0x50);+ console.log("PASS 3/5: CLI bin/forma.mjs (eval --strict, --unit mm, --scene, --view, exit codes, .glb/.png/.svg)");// 3. Test every recipe inside SKILL.md via npm WASM CLIconst skillMd = readFileSync(join(ROOT, "SKILL.md"), "utf-8");- const recipes = [...skillMd.matchAll(/```forma\n([\s\S]*?)\n```/g)].map((m) => m[1]);+ const recipes = [...skillMd.matchAll(/```forma\r?\n([\s\S]*?)\r?\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"], {