A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server
fix: harden GLB export, deterministic LSCM UVs, per-view framing, and sweep-and-prune overlap
Andrew Ryan Carpenterba9d4bdaae92
diff --git a/crates/forma-cli/src/main.rs b/crates/forma-cli/src/main.rsindex 31a69f8..bbd8ec2 100644--- a/crates/forma-cli/src/main.rs+++ b/crates/forma-cli/src/main.rs@@ -16,8 +16,8 @@ fn print_help() {"forma 0.4.2 — 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 render [--size 512] --out preview.png [file|-]\n\+ forma eval [--dialect pipe|compact] [--strict|--no-strict] [--json] [--out path.(glb|obj|stl|3mf|step|blend)] [--render preview.png] [--view quad|front|back|right|left|top|iso] [--draw blueprint.svg] [file|-]\n\+ forma render [--size 512] [--view quad|front|back|right|left|top|iso] --out preview.png [file|-]\n\forma draw --out blueprint.svg [file|-]\n\forma spec [--dialect pipe|compact] [--gbnf]\n\forma --help\n\@@ -137,6 +137,7 @@ fn main() {let mut render_path: Option<PathBuf> = None;let mut draw_path: Option<PathBuf> = None;let mut render_size: usize = 512;+ let mut render_view: String = "quad".into();let mut in_file: Option<String> = None;let mut i = 1;@@ -191,6 +192,14 @@ fn main() {render_size = args[i + 1].parse().unwrap_or(512);i += 2;}+ "--view" => {+ if i + 1 >= args.len() {+ eprintln!("ERR: --view requires value (quad|front|back|right|left|top|iso)");+ process::exit(2);+ }+ render_view = args[i + 1].clone();+ i += 2;+ }"--strict" => {strict = true;i += 1;@@ -257,7 +266,7 @@ fn main() {}}if let Some(ref png) = render_path {- if let Err(e) = scene.render_preview(png, None, render_size) {+ if let Err(e) = scene.render_preview_view(png, None, render_size, &render_view) {eprintln!("ERR: render failed: {e}");process::exit(1);}diff --git a/crates/forma-core/src/boolean.rs b/crates/forma-core/src/boolean.rsindex 74cef6d..235e857 100644--- a/crates/forma-core/src/boolean.rs+++ b/crates/forma-core/src/boolean.rs@@ -2186,7 +2186,39 @@ pub fn has_overlapping_components(mesh: &PolyMesh) -> bool {let mesh_scale = global_bb.size().x.max(global_bb.size().y).max(global_bb.size().z).max(1e-9);let aabb_eps = 1e-6 * mesh_scale;- // 3. Lazy per-component triangle + BVH build ONLY for components with an AABB overlap+ // 3. Axis-sorted 1D Sweep-and-Prune over component AABBs (O(S log S + K) instead of O(S^2))+ let mut sum_c = Vec3::ZERO;+ let mut sum_c2 = Vec3::ZERO;+ for bb in &comp_bbs {+ let c = bb.center();+ sum_c += c;+ sum_c2 += Vec3::new(c.x * c.x, c.y * c.y, c.z * c.z);+ }+ let inv_nc = 1.0 / (nc as f64);+ let mean_c = sum_c * inv_nc;+ let var_x = (sum_c2.x * inv_nc) - mean_c.x * mean_c.x;+ let var_y = (sum_c2.y * inv_nc) - mean_c.y * mean_c.y;+ let var_z = (sum_c2.z * inv_nc) - mean_c.z * mean_c.z;+ let sweep_axis = if var_x >= var_y && var_x >= var_z {+ 0usize+ } else if var_y >= var_z {+ 1usize+ } else {+ 2usize+ };+ let axis_val = |v: Vec3, ax: usize| -> f64 {+ match ax {+ 0 => v.x,+ 1 => v.y,+ _ => v.z,+ }+ };+ let mut order: Vec<usize> = (0..nc).collect();+ order.sort_unstable_by(|&a, &b| {+ axis_val(comp_bbs[a].min, sweep_axis).total_cmp(&axis_val(comp_bbs[b].min, sweep_axis))+ });++ // 4. Lazy per-component triangle + BVH build ONLY for components with an AABB overlaplet mut comp_data: Vec<Option<(Vec<Tri>, TriBvh)>> = (0..nc).map(|_| None).collect();let ensure_comp = |cid: usize, comp_data: &mut [Option<(Vec<Tri>, TriBvh)>]| {if comp_data[cid].is_some() {@@ -2205,8 +2237,13 @@ pub fn has_overlapping_components(mesh: &PolyMesh) -> bool {};let mut hits: Vec<u32> = Vec::with_capacity(32);- for ci in 0..nc {- for cj in (ci + 1)..nc {+ for a in 0..nc {+ let ci = order[a];+ let max_sweep = axis_val(comp_bbs[ci].max, sweep_axis) + aabb_eps;+ for &cj in &order[(a + 1)..] {+ if axis_val(comp_bbs[cj].min, sweep_axis) > max_sweep {+ break;+ }if !comp_bbs[ci].overlaps(&comp_bbs[cj], aabb_eps) {continue;}@@ -2215,11 +2252,20 @@ pub fn has_overlapping_components(mesh: &PolyMesh) -> bool {let (tris_i, bvh_i) = comp_data[ci].as_ref().unwrap();let (tris_j, bvh_j) = comp_data[cj].as_ref().unwrap();- // Check triangle-triangle crossing or coplanar face overlap- for ta in tris_i {- bvh_j.query_aabb(&ta.aabb, aabb_eps, &mut hits);+ // Iterate smaller component's triangles against larger component's BVH,+ // pre-filtering triangles against the partner component's AABB.+ let (small_tris, big_tris, big_bvh, big_bb) = if tris_i.len() <= tris_j.len() {+ (tris_i, tris_j, bvh_j, &comp_bbs[cj])+ } else {+ (tris_j, tris_i, bvh_i, &comp_bbs[ci])+ };+ for ta in small_tris {+ if !ta.aabb.overlaps(big_bb, aabb_eps) {+ continue;+ }+ big_bvh.query_aabb(&ta.aabb, aabb_eps, &mut hits);for &tb_idx in &hits {- if tris_overlap_3d(ta, &tris_j[tb_idx as usize], mesh_scale) {+ if tris_overlap_3d(ta, &big_tris[tb_idx as usize], mesh_scale) {return true;}}@@ -2228,12 +2274,12 @@ pub fn has_overlapping_components(mesh: &PolyMesh) -> bool {// Check solid-inside-solid full containment (skip valid negative-volume inner cavities!)if comp_vols[ci] > 1e-12 && comp_vols[cj] > 1e-12 {if let Some(t0) = tris_i.first() {- if bvh_j.point_inside(tris_j, t0.centroid) {+ if comp_bbs[cj].overlaps(&t0.aabb, aabb_eps) && bvh_j.point_inside(tris_j, t0.centroid) {return true;}}if let Some(t0) = tris_j.first() {- if bvh_i.point_inside(tris_i, t0.centroid) {+ if comp_bbs[ci].overlaps(&t0.aabb, aabb_eps) && bvh_i.point_inside(tris_i, t0.centroid) {return true;}}diff --git a/crates/forma-core/src/export.rs b/crates/forma-core/src/export.rsindex af4d6da..01fe135 100644--- a/crates/forma-core/src/export.rs+++ b/crates/forma-core/src/export.rs@@ -22,8 +22,45 @@ 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).-pub fn write_glb_bytes(mesh: &PolyMesh, yup: bool) -> Result<Vec<u8>, String> {+#[inline]+fn normalize_f32_unit(n: [f32; 3], fallback: [f32; 3], yup: bool) -> [f32; 3] {+ if n[0].is_finite() && n[1].is_finite() && n[2].is_finite() {+ let l2 = (n[0] as f64) * (n[0] as f64) + (n[1] as f64) * (n[1] as f64) + (n[2] as f64) * (n[2] as f64);+ if l2 > 1e-12 {+ let inv = 1.0 / l2.sqrt();+ return [(n[0] as f64 * inv) as f32, (n[1] as f64 * inv) as f32, (n[2] as f64 * inv) as f32];+ }+ }+ if fallback[0].is_finite() && fallback[1].is_finite() && fallback[2].is_finite() {+ let l2 = (fallback[0] as f64) * (fallback[0] as f64)+ + (fallback[1] as f64) * (fallback[1] as f64)+ + (fallback[2] as f64) * (fallback[2] as f64);+ if l2 > 1e-12 {+ let inv = 1.0 / l2.sqrt();+ return [+ (fallback[0] as f64 * inv) as f32,+ (fallback[1] as f64 * inv) as f32,+ (fallback[2] as f64 * inv) as f32,+ ];+ }+ }+ if yup { [0.0, 1.0, 0.0] } else { [0.0, 0.0, 1.0] }+}++struct PackedGlbPrim {+ gid: usize,+ positions: Vec<[f32; 3]>,+ normals: Vec<[f32; 3]>,+ uvs: Vec<[f32; 2]>,+ indices: Vec<u32>,+ bmin: [f32; 3],+ bmax: [f32; 3],+}++/// Build per-material-group compacted, unconditionally welded triangle primitives with+/// strictly unit-length normals for compact, engine-clean glTF 2.0 export.+fn pack_glb_primitives(mesh: &PolyMesh, yup: bool) -> Vec<PackedGlbPrim> {+ use std::collections::HashMap;let conv = |p: Vec3| -> [f32; 3] {if yup {[p.x as f32, p.z as f32, (-p.y) as f32]@@ -34,150 +71,216 @@ pub fn write_glb_bytes(mesh: &PolyMesh, yup: bool) -> Result<Vec<u8>, String> {let has_mats = !mesh.materials.is_empty();let num_groups = if has_mats { mesh.materials.len() } else { 1 };- let est_tris = mesh.faces.len() * 2;let corner_normals = mesh.compute_corner_normals();- let mut positions: Vec<[f32; 3]> = Vec::with_capacity(est_tris * 3);- let mut normals: Vec<[f32; 3]> = Vec::with_capacity(est_tris * 3);- let mut uvs: Vec<[f32; 2]> = Vec::with_capacity(est_tris * 3);- let mut group_indices: Vec<Vec<u32>> = (0..num_groups).map(|_| Vec::new()).collect();- if num_groups == 1 {- group_indices[0].reserve(est_tris * 3);- }- let mut bmin = [f32::INFINITY; 3];- let mut bmax = [f32::NEG_INFINITY; 3];+ type WeldKey = ([i64; 3], [i64; 3], [u32; 2]);+ struct GroupBuilder {+ positions: Vec<[f32; 3]>,+ normals: Vec<[f32; 3]>,+ uvs: Vec<[f32; 2]>,+ indices: Vec<u32>,+ bmin: [f32; 3],+ bmax: [f32; 3],+ cache: HashMap<WeldKey, u32>,+ }- let use_weld = mesh.smooth_angle_deg.is_some() || mesh.faces.iter().any(|f| !f.uvs.is_empty());- let mut vert_cache: std::collections::HashMap<([i32; 3], [i32; 3], [i32; 2]), u32> = if use_weld {- std::collections::HashMap::with_capacity(mesh.verts.len() * 2)- } else {- std::collections::HashMap::new()- };+ let mut groups: Vec<GroupBuilder> = (0..num_groups)+ .map(|_| GroupBuilder {+ positions: Vec::new(),+ normals: Vec::new(),+ uvs: Vec::new(),+ indices: Vec::new(),+ bmin: [f32::INFINITY; 3],+ bmax: [f32::NEG_INFINITY; 3],+ cache: HashMap::new(),+ })+ .collect();for (fi, f) in mesh.faces.iter().enumerate() {let raw_n = mesh.face_normal(fi);let gid = if has_mats { (f.mat_id as usize).min(num_groups - 1) } else { 0 };- let idxs = &mut group_indices[gid];+ let grp = &mut groups[gid];let has_face_uvs = f.uvs.len() == f.verts.len();let cn = &corner_normals[fi];for [ca, cb, cc] in mesh.triangulate_face_corners(fi) {- for ci in [ca, cb, cc] {+ let va = mesh.verts[f.verts[ca]];+ let vb = mesh.verts[f.verts[cb]];+ let vc = mesh.verts[f.verts[cc]];+ let tri_n = (vb - va).cross(vc - va).normalized();+ let fallback_n = if tri_n.len_sq() > 1e-18 {+ conv(tri_n)+ } else {+ conv(raw_n)+ };+ let proj_n = if raw_n.len_sq() > 1e-18 {+ raw_n+ } else if tri_n.len_sq() > 1e-18 {+ tri_n+ } else {+ cn[ca]+ };++ let mut tri_idx = [0u32; 3];+ for (slot, ci) in [ca, cb, cc].into_iter().enumerate() {let vi = f.verts[ci];let v = mesh.verts[vi];let p = conv(v);- let n = conv(cn[ci]);- let uv = if has_face_uvs { f.uvs[ci] } else { triplanar_uv(v, raw_n) };- for k in 0..3 {- bmin[k] = bmin[k].min(p[k]);- bmax[k] = bmax[k].max(p[k]);- }- if use_weld {- let key = (- [(p[0] * 1e5).round() as i32, (p[1] * 1e5).round() as i32, (p[2] * 1e5).round() as i32],- [(n[0] * 1e4).round() as i32, (n[1] * 1e4).round() as i32, (n[2] * 1e4).round() as i32],- [(uv[0] * 1e5).round() as i32, (uv[1] * 1e5).round() as i32],- );- let idx = *vert_cache.entry(key).or_insert_with(|| {- let id = positions.len() as u32;- positions.push(p);- normals.push(n);- uvs.push(uv);- id- });- idxs.push(idx);+ let n = normalize_f32_unit(conv(cn[ci]), fallback_n, yup);+ let uv = if has_face_uvs {+ let u = f.uvs[ci];+ [+ if u[0].is_finite() { u[0] } else { 0.0 },+ if u[1].is_finite() { u[1] } else { 0.0 },+ ]} else {- let id = positions.len() as u32;- positions.push(p);- normals.push(n);- uvs.push(uv);- idxs.push(id);- }+ triplanar_uv(v, proj_n)+ };+ let uv_bits = |x: f32| -> u32 {+ if x == 0.0 { 0 } else { x.to_bits() }+ };+ let key = (+ [+ (p[0] as f64 * 1e6).round() as i64,+ (p[1] as f64 * 1e6).round() as i64,+ (p[2] as f64 * 1e6).round() as i64,+ ],+ [+ (n[0] as f64 * 1e4).round() as i64,+ (n[1] as f64 * 1e4).round() as i64,+ (n[2] as f64 * 1e4).round() as i64,+ ],+ [uv_bits(uv[0]), uv_bits(uv[1])],+ );+ let idx = *grp.cache.entry(key).or_insert_with(|| {+ let id = grp.positions.len() as u32;+ for (k, &coord) in p.iter().enumerate() {+ grp.bmin[k] = grp.bmin[k].min(coord);+ grp.bmax[k] = grp.bmax[k].max(coord);+ }+ grp.positions.push(p);+ grp.normals.push(n);+ grp.uvs.push(uv);+ id+ });+ tri_idx[slot] = idx;+ }+ if tri_idx[0] != tri_idx[1] && tri_idx[1] != tri_idx[2] && tri_idx[2] != tri_idx[0] {+ grp.indices.extend_from_slice(&tri_idx);}}}- if positions.is_empty() {+ groups+ .into_iter()+ .enumerate()+ .filter(|(_, g)| !g.indices.is_empty() && !g.positions.is_empty())+ .map(|(gid, g)| PackedGlbPrim {+ gid,+ positions: g.positions,+ normals: g.normals,+ uvs: g.uvs,+ indices: g.indices,+ bmin: g.bmin,+ bmax: g.bmax,+ })+ .collect()+}++/// Serialize a PolyMesh to binary glTF 2.0 (.glb) bytes in memory (zero disk I/O).+pub fn write_glb_bytes(mesh: &PolyMesh, yup: bool) -> Result<Vec<u8>, String> {+ let has_mats = !mesh.materials.is_empty();+ let prims = pack_glb_primitives(mesh, yup);+ if prims.is_empty() {return Err("cannot export empty mesh to GLB".into());}- // Build BIN chunk: positions | normals | uvs | indices_group_0 | indices_group_1 ...- let pos_bytes_len = positions.len() * 12;- let nrm_bytes_len = normals.len() * 12;- let uv_bytes_len = uvs.len() * 8;- let total_idx_count: usize = group_indices.iter().map(|g| g.len()).sum();- let mut bin = Vec::with_capacity(pos_bytes_len + nrm_bytes_len + uv_bytes_len + total_idx_count * 4 + 8);- for p in &positions {- bin.extend_from_slice(&p[0].to_le_bytes());- bin.extend_from_slice(&p[1].to_le_bytes());- bin.extend_from_slice(&p[2].to_le_bytes());- }- let nrm_offset = bin.len();- for n in &normals {- bin.extend_from_slice(&n[0].to_le_bytes());- bin.extend_from_slice(&n[1].to_le_bytes());- bin.extend_from_slice(&n[2].to_le_bytes());- }- let uv_offset = bin.len();- for uv in &uvs {- bin.extend_from_slice(&uv[0].to_le_bytes());- bin.extend_from_slice(&uv[1].to_le_bytes());- }+ let est_bytes: usize = prims+ .iter()+ .map(|p| p.positions.len() * 32 + p.indices.len() * 4 + 16)+ .sum();+ let mut bin = Vec::with_capacity(est_bytes);+ let mut bviews_json = String::new();+ let mut accs_json = String::new();+ let mut prims_json = String::new();+ let mut bv_idx = 0usize;+ let mut acc_idx = 0usize;- // Emit index slices for each non-empty material group- let mut idx_views: Vec<(usize, usize, usize, usize)> = Vec::new(); // (gid, byte_offset, byte_len, count)- for (gid, idxs) in group_indices.iter().enumerate() {- if idxs.is_empty() {- continue;+ for (k, p) in prims.iter().enumerate() {+ while (bin.len() & 3) != 0 {+ bin.push(0);}- let off = bin.len();- for &i in idxs {- bin.extend_from_slice(&i.to_le_bytes());+ let pos_off = bin.len();+ for v in &p.positions {+ bin.extend_from_slice(&v[0].to_le_bytes());+ bin.extend_from_slice(&v[1].to_le_bytes());+ bin.extend_from_slice(&v[2].to_le_bytes());}- idx_views.push((gid, off, idxs.len() * 4, idxs.len()));- }- while bin.len() % 4 != 0 {- bin.push(0);- }+ let pos_blen = p.positions.len() * 12;- // Direct JSON serialization (zero serde_json::Value DOM allocation)- let mut prims_json = String::new();- let mut bviews_json = format!(- r#"{{"buffer":0,"byteOffset":0,"byteLength":{},"target":34962}},{{"buffer":0,"byteOffset":{},"byteLength":{},"target":34962}},{{"buffer":0,"byteOffset":{},"byteLength":{},"target":34962}}"#,- pos_bytes_len, nrm_offset, nrm_bytes_len, uv_offset, uv_bytes_len- );- let mut accs_json = format!(- r#"{{"bufferView":0,"componentType":5126,"count":{},"type":"VEC3","min":[{},{},{}],"max":[{},{},{}]}},{{"bufferView":1,"componentType":5126,"count":{},"type":"VEC3"}},{{"bufferView":2,"componentType":5126,"count":{},"type":"VEC2"}}"#,- positions.len(),- bmin[0], bmin[1], bmin[2],- bmax[0], bmax[1], bmax[2],- normals.len(),- uvs.len(),- );+ let nrm_off = bin.len();+ for n in &p.normals {+ bin.extend_from_slice(&n[0].to_le_bytes());+ bin.extend_from_slice(&n[1].to_le_bytes());+ bin.extend_from_slice(&n[2].to_le_bytes());+ }+ let nrm_blen = p.normals.len() * 12;++ let uv_off = bin.len();+ for uv in &p.uvs {+ bin.extend_from_slice(&uv[0].to_le_bytes());+ bin.extend_from_slice(&uv[1].to_le_bytes());+ }+ let uv_blen = p.uvs.len() * 8;++ let idx_off = bin.len();+ let use_u16 = p.positions.len() < u16::MAX as usize;+ let (idx_ctype, idx_blen) = if use_u16 {+ for &ix in &p.indices {+ bin.extend_from_slice(&(ix as u16).to_le_bytes());+ }+ (5123u32, p.indices.len() * 2)+ } else {+ for &ix in &p.indices {+ bin.extend_from_slice(&ix.to_le_bytes());+ }+ (5125u32, p.indices.len() * 4)+ };+ while (bin.len() & 3) != 0 {+ bin.push(0);+ }++ if k > 0 {+ bviews_json.push(',');+ accs_json.push(',');+ prims_json.push(',');+ }+ let (pos_bv, nrm_bv, uv_bv, idx_bv) = (bv_idx, bv_idx + 1, bv_idx + 2, bv_idx + 3);+ let (pos_acc, nrm_acc, uv_acc, idx_acc) = (acc_idx, acc_idx + 1, acc_idx + 2, acc_idx + 3);+ bv_idx += 4;+ acc_idx += 4;- for (k, &(gid, off, blen, cnt)) in idx_views.iter().enumerate() {- let bv_idx = 3 + k;- let acc_idx = 3 + k;bviews_json.push_str(&format!(- r#",{{"buffer":0,"byteOffset":{},"byteLength":{},"target":34963}}"#,- off, blen+ r#"{{"buffer":0,"byteOffset":{pos_off},"byteLength":{pos_blen},"target":34962}},{{"buffer":0,"byteOffset":{nrm_off},"byteLength":{nrm_blen},"target":34962}},{{"buffer":0,"byteOffset":{uv_off},"byteLength":{uv_blen},"target":34962}},{{"buffer":0,"byteOffset":{idx_off},"byteLength":{idx_blen},"target":34963}}"#));accs_json.push_str(&format!(- r#",{{"bufferView":{},"componentType":5125,"count":{},"type":"SCALAR"}}"#,- bv_idx, cnt+ r#"{{"bufferView":{pos_bv},"componentType":5126,"count":{},"type":"VEC3","min":[{},{},{}],"max":[{},{},{}]}},{{"bufferView":{nrm_bv},"componentType":5126,"count":{},"type":"VEC3"}},{{"bufferView":{uv_bv},"componentType":5126,"count":{},"type":"VEC2"}},{{"bufferView":{idx_bv},"componentType":{idx_ctype},"count":{},"type":"SCALAR"}}"#,+ p.positions.len(),+ p.bmin[0], p.bmin[1], p.bmin[2],+ p.bmax[0], p.bmax[1], p.bmax[2],+ p.normals.len(),+ p.uvs.len(),+ p.indices.len(),));- if k > 0 {- prims_json.push(',');- }+if has_mats {prims_json.push_str(&format!(- r#"{{"attributes":{{"POSITION":0,"NORMAL":1,"TEXCOORD_0":2}},"indices":{},"material":{},"mode":4}}"#,- acc_idx, gid+ r#"{{"attributes":{{"POSITION":{pos_acc},"NORMAL":{nrm_acc},"TEXCOORD_0":{uv_acc}}},"indices":{idx_acc},"material":{},"mode":4}}"#,+ p.gid));} else {prims_json.push_str(&format!(- r#"{{"attributes":{{"POSITION":0,"NORMAL":1,"TEXCOORD_0":2}},"indices":{},"mode":4}}"#,- acc_idx+ r#"{{"attributes":{{"POSITION":{pos_acc},"NORMAL":{nrm_acc},"TEXCOORD_0":{uv_acc}}},"indices":{idx_acc},"mode":4}}"#,));}}@@ -264,81 +367,57 @@ pub fn write_scene_glb_bytes(} else {let mesh = arc_mesh.as_ref();let has_mats = !mesh.materials.is_empty();- let num_groups = if has_mats { mesh.materials.len() } else { 1 };- let corner_normals = mesh.compute_corner_normals();- let mut positions: Vec<[f32; 3]> = Vec::new();- let mut normals: Vec<[f32; 3]> = Vec::new();- let mut uvs: Vec<[f32; 2]> = Vec::new();- let mut group_indices: Vec<Vec<u32>> = (0..num_groups).map(|_| Vec::new()).collect();- let mut bmin = [f32::INFINITY; 3];- let mut bmax = [f32::NEG_INFINITY; 3];-- for (fi, f) in mesh.faces.iter().enumerate() {- let raw_n = mesh.face_normal(fi);- let gid = if has_mats { (f.mat_id as usize).min(num_groups - 1) } else { 0 };- let has_uvs = f.uvs.len() == f.verts.len();- let cn = &corner_normals[fi];- 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 p = conv(v);- let n = conv(cn[ci]);- let uv = if has_uvs { f.uvs[ci] } else { triplanar_uv(v, raw_n) };- for k in 0..3 {- bmin[k] = bmin[k].min(p[k]);- bmax[k] = bmax[k].max(p[k]);- }- let id = positions.len() as u32;- positions.push(p);- normals.push(n);- uvs.push(uv);- group_indices[gid].push(id);- }- }- }- if positions.is_empty() {+ let packed = pack_glb_primitives(mesh, yup);+ if packed.is_empty() {continue;}- while bin.len() % 4 != 0 { bin.push(0); }- let pos_off = bin.len();- for p in &positions { for c in p { bin.extend_from_slice(&c.to_le_bytes()); } }- let pos_bv = bviews.len();- bviews.push(serde_json::json!({"buffer":0,"byteOffset":pos_off,"byteLength":positions.len()*12,"target":34962}));- let pos_acc = accessors.len();- accessors.push(serde_json::json!({"bufferView":pos_bv,"componentType":5126,"count":positions.len(),"type":"VEC3","min":bmin,"max":bmax}));-- let nrm_off = bin.len();- for n in &normals { for c in n { bin.extend_from_slice(&c.to_le_bytes()); } }- let nrm_bv = bviews.len();- bviews.push(serde_json::json!({"buffer":0,"byteOffset":nrm_off,"byteLength":normals.len()*12,"target":34962}));- let nrm_acc = accessors.len();- accessors.push(serde_json::json!({"bufferView":nrm_bv,"componentType":5126,"count":normals.len(),"type":"VEC3"}));-- let uv_off = bin.len();- for uv in &uvs { for c in uv { bin.extend_from_slice(&c.to_le_bytes()); } }- let uv_bv = bviews.len();- bviews.push(serde_json::json!({"buffer":0,"byteOffset":uv_off,"byteLength":uvs.len()*8,"target":34962}));- let uv_acc = accessors.len();- accessors.push(serde_json::json!({"bufferView":uv_bv,"componentType":5126,"count":uvs.len(),"type":"VEC2"}));-- let mut prims: Vec<serde_json::Value> = Vec::new();- for (gid, idxs) in group_indices.iter().enumerate() {- if idxs.is_empty() { continue; }+ let mut prims: Vec<serde_json::Value> = Vec::with_capacity(packed.len());+ for p in &packed {+ while (bin.len() & 3) != 0 { bin.push(0); }+ let pos_off = bin.len();+ for v in &p.positions { for c in v { bin.extend_from_slice(&c.to_le_bytes()); } }+ let pos_bv = bviews.len();+ bviews.push(serde_json::json!({"buffer":0,"byteOffset":pos_off,"byteLength":p.positions.len()*12,"target":34962}));+ let pos_acc = accessors.len();+ accessors.push(serde_json::json!({"bufferView":pos_bv,"componentType":5126,"count":p.positions.len(),"type":"VEC3","min":p.bmin,"max":p.bmax}));++ let nrm_off = bin.len();+ for n in &p.normals { for c in n { bin.extend_from_slice(&c.to_le_bytes()); } }+ let nrm_bv = bviews.len();+ bviews.push(serde_json::json!({"buffer":0,"byteOffset":nrm_off,"byteLength":p.normals.len()*12,"target":34962}));+ let nrm_acc = accessors.len();+ accessors.push(serde_json::json!({"bufferView":nrm_bv,"componentType":5126,"count":p.normals.len(),"type":"VEC3"}));++ let uv_off = bin.len();+ for uv in &p.uvs { for c in uv { bin.extend_from_slice(&c.to_le_bytes()); } }+ let uv_bv = bviews.len();+ bviews.push(serde_json::json!({"buffer":0,"byteOffset":uv_off,"byteLength":p.uvs.len()*8,"target":34962}));+ let uv_acc = accessors.len();+ accessors.push(serde_json::json!({"bufferView":uv_bv,"componentType":5126,"count":p.uvs.len(),"type":"VEC2"}));+let ioff = bin.len();- for &ix in idxs { bin.extend_from_slice(&ix.to_le_bytes()); }+ let use_u16 = p.positions.len() < u16::MAX as usize;+ let (ictype, iblen) = if use_u16 {+ for &ix in &p.indices { bin.extend_from_slice(&(ix as u16).to_le_bytes()); }+ (5123u32, p.indices.len() * 2)+ } else {+ for &ix in &p.indices { bin.extend_from_slice(&ix.to_le_bytes()); }+ (5125u32, p.indices.len() * 4)+ };+ while (bin.len() & 3) != 0 { bin.push(0); }let ibv = bviews.len();- bviews.push(serde_json::json!({"buffer":0,"byteOffset":ioff,"byteLength":idxs.len()*4,"target":34963}));+ bviews.push(serde_json::json!({"buffer":0,"byteOffset":ioff,"byteLength":iblen,"target":34963}));let iacc = accessors.len();- accessors.push(serde_json::json!({"bufferView":ibv,"componentType":5125,"count":idxs.len(),"type":"SCALAR"}));+ accessors.push(serde_json::json!({"bufferView":ibv,"componentType":ictype,"count":p.indices.len(),"type":"SCALAR"}));let mut prim = serde_json::json!({"attributes": {"POSITION": pos_acc, "NORMAL": nrm_acc, "TEXCOORD_0": uv_acc},- "indices": iacc+ "indices": iacc,+ "mode": 4});if has_mats {- let mat = &mesh.materials[gid];+ let mat = &mesh.materials[p.gid];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();diff --git a/crates/forma-core/src/mesh.rs b/crates/forma-core/src/mesh.rsindex 0fec7a8..2519b9d 100644--- a/crates/forma-core/src/mesh.rs+++ b/crates/forma-core/src/mesh.rs@@ -118,18 +118,23 @@ impl PolyMesh {}/// Compute per-face-corner shading normals respecting `smooth_angle_deg` and `weighted_normals`.- /// When `smooth_angle_deg` is `None`, returns exact flat face normals (100% backward compatible).+ /// When `smooth_angle_deg` is `None`, returns flat face normals with guaranteed unit-length+ /// fallback from incident non-degenerate faces on collinear/micro-sliver faces.pub fn compute_corner_normals(&self) -> Vec<Vec<Vec3>> {let nf = self.faces.len();let face_n: Vec<Vec3> = (0..nf).map(|fi| self.face_normal(fi)).collect();- let Some(angle_deg) = self.smooth_angle_deg else {+ let any_degen = face_n.iter().any(|n| n.len_sq() <= 1e-18);++ if self.smooth_angle_deg.is_none() && !any_degen {return (0..nf).map(|fi| vec![face_n[fi]; self.faces[fi].verts.len()]).collect();- };+ }- let cos_thresh = angle_deg.clamp(0.0, 180.0).to_radians().cos();- let face_area: Vec<f64> = if self.weighted_normals {+ let cos_thresh = self+ .smooth_angle_deg+ .map(|deg| deg.clamp(0.0, 180.0).to_radians().cos());+ let face_area: Vec<f64> = if self.weighted_normals || any_degen {(0..nf).map(|fi| self.face_area(fi).max(1e-12)).collect()} else {vec![1.0; nf]@@ -144,34 +149,73 @@ impl PolyMesh {}}+ let incident_fallback = |vi: usize| -> Vec3 {+ let mut acc = Vec3::ZERO;+ if vi < v_faces.len() {+ for &(nfi, _) in &v_faces[vi] {+ let fn1 = face_n[nfi];+ if fn1.len_sq() > 1e-18 {+ acc += fn1 * face_area[nfi];+ }+ }+ }+ acc+ };+let mut out = Vec::with_capacity(nf);for (fi, f) in self.faces.iter().enumerate() {let fn0 = face_n[fi];+ let fn0_valid = fn0.len_sq() > 1e-18;let mut cn = Vec::with_capacity(f.verts.len());for &vi in &f.verts {let mut acc = Vec3::ZERO;- if vi < v_faces.len() {- for &(nfi, nci) in &v_faces[vi] {- let fn1 = face_n[nfi];- if fn0.dot(fn1) >= cos_thresh - 1e-6 {- let mut w = face_area[nfi];- // Multiply by corner opening angle at vertex vi for exact angle+area weighting- let nf_verts = &self.faces[nfi].verts;- let k = nf_verts.len();- if k >= 3 {- let p = self.verts[nf_verts[nci]];- let prev = self.verts[nf_verts[(nci + k - 1) % k]];- let next = self.verts[nf_verts[(nci + 1) % k]];- let e1 = (prev - p).normalized();- let e2 = (next - p).normalized();- let ang = e1.dot(e2).clamp(-1.0, 1.0).acos().max(1e-4);- w *= ang;+ if let Some(ct) = cos_thresh {+ if fn0_valid && vi < v_faces.len() {+ for &(nfi, nci) in &v_faces[vi] {+ let fn1 = face_n[nfi];+ if fn1.len_sq() > 1e-18 && fn0.dot(fn1) >= ct - 1e-6 {+ let mut w = if self.weighted_normals { face_area[nfi] } else { 1.0 };+ // Multiply by corner opening angle at vertex vi for exact angle+area weighting+ let nf_verts = &self.faces[nfi].verts;+ let k = nf_verts.len();+ if k >= 3 {+ let p = self.verts[nf_verts[nci]];+ let prev = self.verts[nf_verts[(nci + k - 1) % k]];+ let next = self.verts[nf_verts[(nci + 1) % k]];+ let e1 = (prev - p).normalized();+ let e2 = (next - p).normalized();+ let ang = e1.dot(e2).clamp(-1.0, 1.0).acos().max(1e-4);+ w *= ang;+ }+ acc += fn1 * w;}- acc += fn1 * w;}}+ } else if fn0_valid {+ acc = fn0;}- let n = if acc.len_sq() > 1e-14 { acc.normalized() } else { fn0 };++ let n = if acc.len_sq() > 1e-18 {+ acc.normalized()+ } else if fn0_valid {+ fn0.normalized()+ } else {+ // Degenerate/collinear sliver face: inherit unit normal from incident valid faces+ let fb = incident_fallback(vi);+ if fb.len_sq() > 1e-18 {+ fb.normalized()+ } else {+ let mut face_fb = Vec3::ZERO;+ for &ovi in &f.verts {+ face_fb += incident_fallback(ovi);+ }+ if face_fb.len_sq() > 1e-18 {+ face_fb.normalized()+ } else {+ Vec3::Z+ }+ }+ };cn.push(n);}out.push(cn);@@ -279,17 +323,23 @@ impl PolyMesh {bb}- /// Newell's method for robust polygon normal.+ /// Origin-shifted Newell's method for translation-invariant, robust polygon normal.pub fn face_normal(&self, fi: usize) -> Vec3 {let fv = &self.faces[fi].verts;let n = fv.len();if n < 3 {return Vec3::ZERO;}+ let origin = self.verts[fv[0]];+ if n == 3 {+ let e1 = self.verts[fv[1]] - origin;+ let e2 = self.verts[fv[2]] - origin;+ return e1.cross(e2).normalized();+ }let mut norm = Vec3::ZERO;for i in 0..n {- let a = self.verts[fv[i]];- let b = self.verts[fv[(i + 1) % n]];+ let a = self.verts[fv[i]] - origin;+ let b = self.verts[fv[(i + 1) % n]] - origin;norm.x += (a.y - b.y) * (a.z + b.z);norm.y += (a.z - b.z) * (a.x + b.x);norm.z += (a.x - b.x) * (a.y + b.y);diff --git a/crates/forma-core/src/render.rs b/crates/forma-core/src/render.rsindex a2397e9..4391d23 100644--- a/crates/forma-core/src/render.rs+++ b/crates/forma-core/src/render.rs@@ -143,7 +143,8 @@ impl Framebuffer {let dx = p1[0] - p0[0];let dy = p1[1] - p0[1];let steps = dx.abs().max(dy.abs()).ceil() as i32;- if steps <= 0 || steps > 2048 {+ let max_steps = (self.w.max(self.h) * 2).max(2048) as i32;+ if steps <= 0 || steps > max_steps {return;}let inv = 1.0 / (steps as f32);@@ -154,9 +155,9 @@ impl Framebuffer {if x < vp.0 || x >= vp.2 || y < vp.1 || y >= vp.3 {continue;}- let z = p0[2] + (p1[2] - p0[2]) * t - 0.008;+ let z = p0[2] + (p1[2] - p0[2]) * t - 0.0025;let pi = y as usize * self.w + x as usize;- if z <= self.zbuf[pi] + 0.002 {+ if z <= self.zbuf[pi] + 0.001 {let ci = pi * 3;// Crisp dark blendself.rgb[ci] = ((self.rgb[ci] as u16 * 3 + color[0] as u16 * 5) / 8) as u8;@@ -169,12 +170,22 @@ impl Framebuffer {fn draw_label(&mut self, mut x: i32, y: i32, text: &str) {for ch in text.bytes() {let glyph: [u8; 5] = match ch {+ b'A' => [0b010, 0b101, 0b111, 0b101, 0b101],+ b'B' => [0b110, 0b101, 0b110, 0b101, 0b110],+ b'C' => [0b011, 0b100, 0b100, 0b100, 0b011],+ b'E' => [0b111, 0b100, 0b110, 0b100, 0b111],b'F' => [0b111, 0b100, 0b110, 0b100, 0b100],- b'R' => [0b110, 0b101, 0b110, 0b101, 0b101],- b'T' => [0b111, 0b010, 0b010, 0b010, 0b010],+ b'G' => [0b011, 0b100, 0b101, 0b101, 0b011],+ b'H' => [0b101, 0b101, 0b111, 0b101, 0b101],b'I' => [0b111, 0b010, 0b010, 0b010, 0b111],- b'S' => [0b011, 0b100, 0b010, 0b001, 0b110],+ b'K' => [0b101, 0b101, 0b110, 0b101, 0b101],+ b'L' => [0b100, 0b100, 0b100, 0b100, 0b111],+ b'N' => [0b101, 0b111, 0b111, 0b101, 0b101],b'O' => [0b111, 0b101, 0b101, 0b101, 0b111],+ b'P' => [0b110, 0b101, 0b110, 0b100, 0b100],+ b'R' => [0b110, 0b101, 0b110, 0b101, 0b101],+ b'S' => [0b011, 0b100, 0b010, 0b001, 0b110],+ b'T' => [0b111, 0b010, 0b010, 0b010, 0b010],_ => [0; 5],};for (row, &bits) in glyph.iter().enumerate() {@@ -208,18 +219,32 @@ impl OrthoCam {}}-/// Render a 2x2 multi-view orthographic + isometric contact sheet of `mesh` into a PNG file.-/// `size` is the total square width & height in pixels (e.g. `512` -> four 256x256 views).-pub fn render_quad_png(mesh: &PolyMesh, path: &Path, size: usize) -> Result<(), String> {- let bytes = render_quad_png_bytes(mesh, size)?;- 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())+fn project_view_bounds(verts: &[Vec3], cam: &OrthoCam) -> (f64, f64, f64, f64, f64, f64) {+ let (mut u_min, mut u_max) = (f64::INFINITY, f64::NEG_INFINITY);+ let (mut v_min, mut v_max) = (f64::INFINITY, f64::NEG_INFINITY);+ let (mut d_min, mut d_max) = (f64::INFINITY, f64::NEG_INFINITY);+ for &p in verts {+ let u = p.dot(cam.right);+ let v = p.dot(cam.up);+ let d = p.dot(cam.fwd);+ u_min = u_min.min(u);+ u_max = u_max.max(u);+ v_min = v_min.min(v);+ v_max = v_max.max(v);+ d_min = d_min.min(d);+ d_max = d_max.max(d);+ }+ (u_min, u_max, v_min, v_max, d_min, d_max)}-/// Render a 2x2 studio contact sheet directly to PNG bytes in memory (<3 ms for 512x512).-pub fn render_quad_png_bytes(mesh: &PolyMesh, size: usize) -> Result<Vec<u8>, String> {+type ViewSpec<'a> = (&'a str, OrthoCam, (i32, i32, i32, i32));++fn render_views_to_png(+ mesh: &PolyMesh,+ size: usize,+ views: &[ViewSpec<'_>],+ draw_crosshairs: bool,+) -> Result<Vec<u8>, String> {if mesh.faces.is_empty() || mesh.verts.is_empty() {return Err("cannot render empty mesh".into());}@@ -227,16 +252,15 @@ pub fn render_quad_png_bytes(mesh: &PolyMesh, size: usize) -> Result<Vec<u8>, Stlet half = size / 2;let mut fb = Framebuffer::new(size, size);- let bb = mesh.aabb();- let center = bb.center();- let radius = (bb.size().len() * 0.5).max(1e-4);-// Pre-extract triangles with normals & base colorslet mut tris: Vec<([Vec3; 3], Vec3, [f32; 3])> = Vec::with_capacity(mesh.faces.len() * 2);let mut face_normals: Vec<Vec3> = Vec::with_capacity(mesh.faces.len());for (fi, f) in mesh.faces.iter().enumerate() {let n = mesh.face_normal(fi);face_normals.push(n);+ if n.len_sq() <= 1e-18 {+ continue;+ }let base_rgb = if let Some(mat) = mesh.materials.get(f.mat_id as usize) {[mat.color[0], mat.color[1], mat.color[2]]} else {@@ -265,37 +289,33 @@ pub fn render_quad_png_bytes(mesh: &PolyMesh, size: usize) -> Result<Vec<u8>, Stlet is_sharp = if inc.len() != 2 {true} else {- face_normals[inc[0]].dot(face_normals[inc[1]]) < cos_thresh+ let n0 = face_normals[inc[0]];+ let n1 = face_normals[inc[1]];+ n0.len_sq() > 1e-18 && n1.len_sq() > 1e-18 && n0.dot(n1) < cos_thresh};if is_sharp {feature_edges.push((mesh.verts[u], mesh.verts[v]));}}- // 4 canonical engineering + studio views: Front (-Y -> +Y), Right (+X -> -X), Top (+Z -> -Z), Iso 3/4- let views: [(&str, OrthoCam, (i32, i32, i32, i32)); 4] = [- ("F", OrthoCam::from_dir(Vec3::new(0.0, 1.0, 0.0), Vec3::Z), (0, 0, half as i32, half as i32)),- ("R", OrthoCam::from_dir(Vec3::new(-1.0, 0.0, 0.0), Vec3::Z), (half as i32, 0, size as i32, half as i32)),- ("T", OrthoCam::from_dir(Vec3::new(0.0, 0.0, -1.0), Vec3::Y), (0, half as i32, half as i32, size as i32)),- (- "ISO",- OrthoCam::from_dir(Vec3::new(-1.0, 1.0, -0.78), Vec3::Z),- (half as i32, half as i32, size as i32, size as i32),- ),- ];-- for (label, cam, vp) in &views {+ for (label, cam, vp) in views {let vpw = (vp.2 - vp.0) as f64;let vph = (vp.3 - vp.1) as f64;- let scale = 0.42 * vpw.min(vph) / radius;+ let (u_min, u_max, v_min, v_max, d_min, d_max) = project_view_bounds(&mesh.verts, cam);+ let u_mid = 0.5 * (u_min + u_max);+ let v_mid = 0.5 * (v_min + v_max);+ let u_span = (u_max - u_min).max(1e-4);+ let v_span = (v_max - v_min).max(1e-4);+ let d_span = (d_max - d_min).max(1e-4);+ let label_pad = 22.0f64.min(vph * 0.12);+ let scale = (0.86 * vpw / u_span).min(0.86 * (vph - label_pad) / v_span);let cx = vp.0 as f64 + 0.5 * vpw;- let cy = vp.1 as f64 + 0.5 * vph;+ let cy = vp.1 as f64 + 0.5 * label_pad + 0.5 * vph;let project = |p: Vec3| -> [f32; 3] {- let d = p - center;- let sx = cx + d.dot(cam.right) * scale;- let sy = cy - d.dot(cam.up) * scale;- let sz = (d.dot(cam.fwd) / (radius * 2.0)) + 0.5;+ let sx = cx + (p.dot(cam.right) - u_mid) * scale;+ let sy = cy - (p.dot(cam.up) - v_mid) * scale;+ let sz = (p.dot(cam.fwd) - d_min) / d_span;[sx as f32, sy as f32, sz as f32]};@@ -334,17 +354,103 @@ pub fn render_quad_png_bytes(mesh: &PolyMesh, size: usize) -> Result<Vec<u8>, Stfb.draw_label(vp.0 + 8, vp.1 + 8, label);}- // Draw clean 1px quadrant crosshairs- for x in 0..size as i32 {- fb.set_px(x, half as i32, 196, 204, 218);- }- for y in 0..size as i32 {- fb.set_px(half as i32, y, 196, 204, 218);+ if draw_crosshairs {+ for x in 0..size as i32 {+ fb.set_px(x, half as i32, 196, 204, 218);+ }+ for y in 0..size as i32 {+ fb.set_px(half as i32, y, 196, 204, 218);+ }}Ok(encode_png_rgb(size as u32, size as u32, &fb.rgb))}+/// Render a 2x2 multi-view orthographic + isometric contact sheet of `mesh` into a PNG file.+/// `size` is the total square width & height in pixels (e.g. `512` -> four 256x256 views).+pub fn render_quad_png(mesh: &PolyMesh, path: &Path, size: usize) -> Result<(), String> {+ let bytes = render_quad_png_bytes(mesh, size)?;+ 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())+}++/// Render a 2x2 studio contact sheet directly to PNG bytes in memory (<3 ms for 512x512).+/// Each quadrant independently frames the mesh's exact 2D projected extents so elongated props stay readable.+pub fn render_quad_png_bytes(mesh: &PolyMesh, size: usize) -> Result<Vec<u8>, String> {+ let size = size.clamp(128, 2048);+ let half = size / 2;+ let views: [ViewSpec<'_>; 4] = [+ ("F", OrthoCam::from_dir(Vec3::new(0.0, 1.0, 0.0), Vec3::Z), (0, 0, half as i32, half as i32)),+ ("R", OrthoCam::from_dir(Vec3::new(-1.0, 0.0, 0.0), Vec3::Z), (half as i32, 0, size as i32, half as i32)),+ ("T", OrthoCam::from_dir(Vec3::new(0.0, 0.0, -1.0), Vec3::Y), (0, half as i32, half as i32, size as i32)),+ (+ "ISO",+ OrthoCam::from_dir(Vec3::new(-1.0, 1.0, -0.78), Vec3::Z),+ (half as i32, half as i32, size as i32, size as i32),+ ),+ ];+ render_views_to_png(mesh, size, &views, true)+}++/// Render a named view (`quad`, `front`, `back`, `right`, `left`, `top`, `iso`) directly to PNG bytes.+pub fn render_view_png_bytes(mesh: &PolyMesh, size: usize, view: &str) -> Result<Vec<u8>, String> {+ let size = size.clamp(128, 2048);+ let vp = (0, 0, size as i32, size as i32);+ match view.to_ascii_lowercase().as_str() {+ "quad" | "all" => render_quad_png_bytes(mesh, size),+ "front" | "f" => render_views_to_png(+ mesh,+ size,+ &[("FRONT", OrthoCam::from_dir(Vec3::new(0.0, 1.0, 0.0), Vec3::Z), vp)],+ false,+ ),+ "back" | "b" => render_views_to_png(+ mesh,+ size,+ &[("BACK", OrthoCam::from_dir(Vec3::new(0.0, -1.0, 0.0), Vec3::Z), vp)],+ false,+ ),+ "right" | "r" => render_views_to_png(+ mesh,+ size,+ &[("RIGHT", OrthoCam::from_dir(Vec3::new(-1.0, 0.0, 0.0), Vec3::Z), vp)],+ false,+ ),+ "left" | "l" => render_views_to_png(+ mesh,+ size,+ &[("LEFT", OrthoCam::from_dir(Vec3::new(1.0, 0.0, 0.0), Vec3::Z), vp)],+ false,+ ),+ "top" | "t" => render_views_to_png(+ mesh,+ size,+ &[("TOP", OrthoCam::from_dir(Vec3::new(0.0, 0.0, -1.0), Vec3::Y), vp)],+ false,+ ),+ "iso" | "hero" => render_views_to_png(+ mesh,+ size,+ &[("ISO", OrthoCam::from_dir(Vec3::new(-1.0, 1.0, -0.78), Vec3::Z), vp)],+ false,+ ),+ other => Err(format!(+ "unknown render view '{other}' (expected quad|front|back|right|left|top|iso)"+ )),+ }+}++/// Render a named view (`quad`, `front`, `back`, `right`, `left`, `top`, `iso`) to a PNG file.+pub fn render_view_png(mesh: &PolyMesh, path: &Path, size: usize, view: &str) -> Result<(), String> {+ let bytes = render_view_png_bytes(mesh, size, view)?;+ 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())+}+/// Fast screen-space ambient occlusion (cavity darkening) + outer/step depth silhouette pass.fn apply_ssao_and_silhouettes(fb: &mut Framebuffer, vp: (i32, i32, i32, i32)) {let x0 = (vp.0 + 1).max(1) as usize;@@ -638,9 +744,7 @@ pub fn render_blueprint_svg_string(mesh: &PolyMesh, title: &str) -> Result<Strin}let inv = crate::invariants::MeshInvariants::compute(mesh);let bb = mesh.aabb();- let center = bb.center();let sz = bb.size();- let radius = (sz.len() * 0.5).max(1e-4);// Collect crisp feature edges (dihedral > 22 deg or boundary)let face_normals: Vec<Vec3> = (0..mesh.faces.len()).map(|fi| mesh.face_normal(fi)).collect();@@ -684,9 +788,16 @@ pub fn render_blueprint_svg_string(mesh: &PolyMesh, title: &str) -> Result<Strin];for (label, cam, (vx, vy, vw, vh), dims) in &views {- let scale = 0.34 * vw.min(*vh) / radius;- let cx = vx + 0.5 * vw;- let cy = vy + 0.5 * vh;+ let (u_min, u_max, v_min, v_max, _, _) = project_view_bounds(&mesh.verts, cam);+ let u_mid = 0.5 * (u_min + u_max);+ let v_mid = 0.5 * (v_min + v_max);+ let u_span = (u_max - u_min).max(1e-4);+ let v_span = (v_max - v_min).max(1e-4);+ let avail_w = if dims.is_some() { vw - 120.0 } else { vw - 50.0 };+ let avail_h = if dims.is_some() { vh - 105.0 } else { vh - 60.0 };+ let scale = (avail_w.max(40.0) / u_span).min(avail_h.max(40.0) / v_span);+ let cx = vx + if dims.is_some() { 0.46 * vw } else { 0.5 * vw };+ let cy = vy + if dims.is_some() { 0.48 * vh } else { 0.52 * vh };svg.push_str(&format!(r##"<text x="{:.1}" y="{:.1}" font-family="ui-monospace, Menlo, monospace" font-size="13" font-weight="700" fill="#475569">{label}</text>"##,@@ -702,12 +813,10 @@ pub fn render_blueprint_svg_string(mesh: &PolyMesh, title: &str) -> Result<Strinsvg.push_str(r##"<g stroke="#0f172a" stroke-width="1.35" stroke-linecap="round">"##);for &(a, b) in &feature_edges {- let da = a - center;- let db = b - center;- let x0 = cx + da.dot(cam.right) * scale;- let y0 = cy - da.dot(cam.up) * scale;- let x1 = cx + db.dot(cam.right) * scale;- let y1 = cy - db.dot(cam.up) * scale;+ let x0 = cx + (a.dot(cam.right) - u_mid) * scale;+ let y0 = cy - (a.dot(cam.up) - v_mid) * scale;+ let x1 = cx + (b.dot(cam.right) - u_mid) * scale;+ let y1 = cy - (b.dot(cam.up) - v_mid) * scale;min_x = min_x.min(x0).min(x1);max_x = max_x.max(x0).max(x1);min_y = min_y.min(y0).min(y1);diff --git a/crates/forma-core/src/scene.rs b/crates/forma-core/src/scene.rsindex f2cf2cb..0c3c17b 100644--- a/crates/forma-core/src/scene.rs+++ b/crates/forma-core/src/scene.rs@@ -152,6 +152,17 @@ impl Scene {crate::render::render_quad_png(&mesh, path, size).map_err(SceneError::OpFailed)}+ pub fn render_preview_view(+ &self,+ path: &Path,+ part_opt: Option<&str>,+ size: usize,+ view: &str,+ ) -> Result<(), SceneError> {+ let mesh = self.merged_mesh(part_opt)?;+ crate::render::render_view_png(&mesh, path, 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");diff --git a/crates/forma-core/src/uv.rs b/crates/forma-core/src/uv.rsindex b7fc757..005ef83 100644--- a/crates/forma-core/src/uv.rs+++ b/crates/forma-core/src/uv.rs@@ -29,6 +29,8 @@ struct Chart {/// Bounding box width/height in normalized texel-density unitsw: f64,h: f64,+ /// Number of non-degenerate 3D triangles that inverted or collapsed in UV space+ bad_tris: usize,}/// Split a face list into face-edge-connected components so no UV chart ever has disconnected islands.@@ -70,13 +72,17 @@ fn segment_charts(mesh: &PolyMesh, angle_deg: f64) -> Vec<Vec<usize>> {face_nbrs[b].push(a);}}+ for nbrs in &mut face_nbrs {+ nbrs.sort_unstable();+ nbrs.dedup();+ }let mut visited = vec![false; nf];let mut raw_charts: Vec<Vec<usize>> = Vec::new();let mut q = VecDeque::new();for start in 0..nf {- if visited[start] { continue; }+ if visited[start] || face_n[start].len_sq() <= 1e-18 { continue; }visited[start] = true;q.push_back(start);let mut chart = Vec::new();@@ -85,8 +91,15 @@ fn segment_charts(mesh: &PolyMesh, angle_deg: f64) -> Vec<Vec<usize>> {chart.push(fi);for &nb in &face_nbrs[fi] {if visited[nb] { continue; }- // Local dihedral smoothness + bounded 80-deg drift guarantees unfoldable charts with 0 inversions!- if face_n[fi].dot(face_n[nb]) >= cos_thresh && seed_n.dot(face_n[nb]) >= 0.5733 {+ // Attach collinear/micro-sliver stitch faces directly to their neighboring chart+ if face_n[nb].len_sq() <= 1e-18 {+ visited[nb] = true;+ chart.push(nb);+ continue;+ }+ // Local dihedral smoothness + bounded 75-deg drift gives cleaner cylindrical/curved charts;+ // downstream zero-inversion check splits any chart that still folds.+ if face_n[fi].dot(face_n[nb]) >= cos_thresh && seed_n.dot(face_n[nb]) >= 0.2588 {visited[nb] = true;q.push_back(nb);}@@ -94,6 +107,13 @@ fn segment_charts(mesh: &PolyMesh, angle_deg: f64) -> Vec<Vec<usize>> {}raw_charts.push(chart);}+ // Any isolated degenerate faces not adjacent to a valid face get their own fallback chart+ for (start, seen) in visited.iter_mut().enumerate() {+ if !*seen {+ *seen = true;+ raw_charts.push(vec![start]);+ }+ }let mut out = Vec::with_capacity(raw_charts.len() * 2);let mut work: VecDeque<(Vec<usize>, usize)> = raw_charts.into_iter().map(|c| (c, 0)).collect();@@ -133,6 +153,58 @@ fn has_chart_boundary(mesh: &PolyMesh, faces: &[usize]) -> bool {ec.values().any(|&c| c == 1)}+/// Count non-degenerate 3D triangles that have inverted or collapsed 2D UV area.+fn count_bad_uv_tris(+ mesh: &PolyMesh,+ faces: &[usize],+ face_local_verts: &[Vec<usize>],+ uvs: &[[f64; 2]],+ area_3d: f64,+) -> (usize, f64) {+ let mut uv_area_abs = 0.0f64;+ for (idx, &fi) in faces.iter().enumerate() {+ let lv = &face_local_verts[idx];+ for [ca, cb, cc] in mesh.triangulate_face_corners(fi) {+ let (a, b, c) = (lv[ca], lv[cb], lv[cc]);+ uv_area_abs += 0.5+ * ((uvs[b][0] - uvs[a][0]) * (uvs[c][1] - uvs[a][1])+ - (uvs[c][0] - uvs[a][0]) * (uvs[b][1] - uvs[a][1]))+ .abs();+ }+ }+ let scale_sq = if uv_area_abs > 1e-18 && area_3d > 1e-18 {+ area_3d / uv_area_abs+ } else {+ 1.0+ };+ let mut bad = 0usize;+ for (idx, &fi) in faces.iter().enumerate() {+ let lv = &face_local_verts[idx];+ let fv = &mesh.faces[fi].verts;+ for [ca, cb, cc] in mesh.triangulate_face_corners(fi) {+ let va = mesh.verts[fv[ca]];+ let vb = mesh.verts[fv[cb]];+ let vc = mesh.verts[fv[cc]];+ let a3 = 0.5 * (vb - va).cross(vc - va).len();+ let (a, b, c) = (lv[ca], lv[cb], lv[cc]);+ let sa = 0.5+ * ((uvs[b][0] - uvs[a][0]) * (uvs[c][1] - uvs[a][1])+ - (uvs[c][0] - uvs[a][0]) * (uvs[b][1] - uvs[a][1]))+ * scale_sq;+ if a3 <= 1e-12 {+ if !sa.is_finite() || sa < -1e-12 {+ bad += 1;+ }+ continue;+ }+ if !sa.is_finite() || sa <= 1e-6 * a3 {+ bad += 1;+ }+ }+ }+ (bad, uv_area_abs)+}+/// Project a single chart via planar orthonormal basis (exact 0-distortion for flat charts)/// OR Least Squares Conformal Maps (LSCM) via pure-Rust sparse Conjugate Gradient for curved charts!fn solve_chart_lscm(mesh: &PolyMesh, faces: &[usize]) -> Chart {@@ -145,7 +217,10 @@ fn solve_chart_lscm(mesh: &PolyMesh, faces: &[usize]) -> Chart {for &fi in faces {let a = mesh.face_area(fi);area_3d += a;- avg_n += mesh.face_normal(fi) * a;+ let fnm = mesh.face_normal(fi);+ if fnm.len_sq() > 1e-18 {+ avg_n += fnm * a.max(1e-12);+ }let mut lv = Vec::with_capacity(mesh.faces[fi].verts.len());for &gvi in &mesh.faces[fi].verts {let lvi = *g2l.entry(gvi).or_insert_with(|| {@@ -159,22 +234,28 @@ fn solve_chart_lscm(mesh: &PolyMesh, faces: &[usize]) -> Chart {}let n_verts = local_to_global.len();- let n_dir = if avg_n.len_sq() > 1e-12 { avg_n.normalized() } else { Vec3::Z };+ let n_dir = if avg_n.len_sq() > 1e-18 { avg_n.normalized() } else { Vec3::Z };// Build orthonormal tangent basis (t1, t2) orthogonal to avg_nlet up = if n_dir.z.abs() < 0.9 { Vec3::Z } else { Vec3::X };let t1 = up.cross(n_dir).normalized();let t2 = n_dir.cross(t1).normalized();- // Check if chart is nearly planar (all face normals within ~2 deg of avg_n)- let is_planar = faces.iter().all(|&fi| mesh.face_normal(fi).dot(n_dir) > 0.9999);- let mut uvs: Vec<[f64; 2]> = local_to_global+ // Check if chart is nearly planar (all non-degenerate face normals within ~1 deg of avg_n)+ let is_planar = faces.iter().all(|&fi| {+ let fnm = mesh.face_normal(fi);+ fnm.len_sq() <= 1e-18 || fnm.dot(n_dir) > 0.99985+ });+ let planar_uvs: Vec<[f64; 2]> = local_to_global.iter().map(|&gvi| {let p = mesh.verts[gvi];[p.dot(t1), p.dot(t2)]}).collect();+ let (planar_bad, _) = count_bad_uv_tris(mesh, faces, &face_local_verts, &planar_uvs, area_3d);+ let mut uvs = planar_uvs;+ let mut best_bad = planar_bad;if !is_planar && n_verts >= 4 {// Collect triangles in local vertex indices@@ -200,14 +281,14 @@ fn solve_chart_lscm(mesh: &PolyMesh, faces: &[usize]) -> Chart {bverts.insert(b);}}- let bvec: Vec<usize> = if bverts.len() >= 2 {+ let mut bvec: Vec<usize> = if bverts.len() >= 2 {bverts.into_iter().collect()} else {(0..n_verts).collect()};+ bvec.sort_unstable();let (mut pin0, mut pin1) = (bvec[0], bvec[1]);let mut best_d2 = -1.0f64;- // Sample up to 48 boundary vertices to keep O(1) fast on huge chartslet step = (bvec.len() / 48).max(1);for i in (0..bvec.len()).step_by(step) {let pa = mesh.verts[local_to_global[bvec[i]]];@@ -223,7 +304,6 @@ fn solve_chart_lscm(mesh: &PolyMesh, faces: &[usize]) -> Chart {}// Assemble sparse normal equations A^T A x = A^T b for free vertices (u_i, v_i)- // Each local vertex i has 2 DOFs: 2*i (u) and 2*i+1 (v).let mut free_map = vec![usize::MAX; n_verts];let mut free_verts = Vec::with_capacity(n_verts.saturating_sub(2));for vi in 0..n_verts {@@ -233,14 +313,35 @@ fn solve_chart_lscm(mesh: &PolyMesh, faces: &[usize]) -> Chart {}}let nf_dof = free_verts.len() * 2;- if nf_dof > 0 {- let p0_uv = uvs[pin0];- let p1_uv = uvs[pin1];+ if nf_dof > 0 && best_d2 > 1e-18 {+ // Pin at well-conditioned canonical coordinates (0, 0) and (d3, 0)+ let d3 = best_d2.sqrt();+ let p0_uv = [0.0f64, 0.0f64];+ let p1_uv = [d3, 0.0f64];let mut pin_vals = vec![[0.0f64; 2]; n_verts];pin_vals[pin0] = p0_uv;pin_vals[pin1] = p1_uv;- // Sparse symmetric matrix stored as Vec<HashMap<usize, f64>>+ // Similarity-align planar initial guess to the canonical pin frame+ let mut init_uv = uvs.clone();+ let du = uvs[pin1][0] - uvs[pin0][0];+ let dv = uvs[pin1][1] - uvs[pin0][1];+ let plen2 = du * du + dv * dv;+ if plen2 > 1e-18 {+ let inv_p = d3 / plen2;+ let cu = du * inv_p;+ let cv = dv * inv_p;+ let o0 = uvs[pin0];+ for p in &mut init_uv {+ let rx = p[0] - o0[0];+ let ry = p[1] - o0[1];+ p[0] = rx * cu + ry * cv;+ p[1] = -rx * cv + ry * cu;+ }+ }+ init_uv[pin0] = p0_uv;+ init_uv[pin1] = p1_uv;+let mut ata: Vec<HashMap<usize, f64>> = vec![HashMap::new(); nf_dof];let mut atb = vec![0.0f64; nf_dof];@@ -258,17 +359,11 @@ fn solve_chart_lscm(mesh: &PolyMesh, faces: &[usize]) -> Chart {if area2 < 1e-12 { continue; }let y_ax = (n_tri / area2).cross(x_ax);- // Local 2D coordinates of triangle: (0,0), (x1,0), (x2,y2)let x1 = l1;let x2 = e2.dot(x_ax);let y2 = e2.dot(y_ax);let inv_sqrt_a = 1.0 / (area2 * 0.5).sqrt().max(1e-9);- // Conformal Cauchy-Riemann rows:- // Row 0 (Re): d(u)/dx - d(v)/dy = 0- // Row 1 (Im): d(u)/dy + d(v)/dx = 0- // Gradients of barycentric coords:- // g_x = [ -y2, y2, 0 ] / (x1 * y2), g_y = [ x2 - x1, -x2, x1 ] / (x1 * y2)let denom = (x1 * y2).abs().max(1e-12);let sgn = if x1 * y2 >= 0.0 { 1.0 } else { -1.0 };let gx = [-y2 * sgn / denom, y2 * sgn / denom, 0.0];@@ -305,7 +400,6 @@ fn solve_chart_lscm(mesh: &PolyMesh, faces: &[usize]) -> Chart {}}- // Add tiny Tikhonov regularization for guaranteed SPD stability + solve with Jacobi-PCGlet mut inv_diag = vec![1.0f64; nf_dof];for r in 0..nf_dof {let d = ata[r].entry(r).or_insert(0.0);@@ -314,10 +408,9 @@ fn solve_chart_lscm(mesh: &PolyMesh, faces: &[usize]) -> Chart {}let mut x = vec![0.0f64; nf_dof];for (fi, &vi) in free_verts.iter().enumerate() {- x[2 * fi] = uvs[vi][0];- x[2 * fi + 1] = uvs[vi][1];+ x[2 * fi] = init_uv[vi][0];+ x[2 * fi + 1] = init_uv[vi][1];}- // Compact CSR matrix eliminates HashMap hashing inside every PCG iteration!let mut row_ptr = Vec::with_capacity(nf_dof + 1);let mut col_idx = Vec::with_capacity(nf_dof * 8);let mut row_val = Vec::with_capacity(nf_dof * 8);@@ -348,13 +441,14 @@ fn solve_chart_lscm(mesh: &PolyMesh, faces: &[usize]) -> Chart {let mut z: Vec<f64> = (0..nf_dof).map(|i| r[i] * inv_diag[i]).collect();let mut p = z.clone();let mut rz: f64 = r.iter().zip(z.iter()).map(|(a, b)| a * b).sum();- let max_iters = (nf_dof * 2).clamp(40, 240);+ let rz_tol = (rz.abs() * 1e-14).max(1e-18);+ let max_iters = (nf_dof * 3).clamp(80, 480);for _ in 0..max_iters {- if rz.abs() < 1e-12 { break; }+ if rz.abs() <= rz_tol { break; }matvec_into(&p, &mut ap);let pap: f64 = p.iter().zip(ap.iter()).map(|(a, b)| a * b).sum();- if pap.abs() < 1e-18 { break; }+ if pap.abs() < 1e-22 { break; }let alpha = rz / pap;for i in 0..nf_dof {x[i] += alpha * p[i];@@ -372,8 +466,7 @@ fn solve_chart_lscm(mesh: &PolyMesh, faces: &[usize]) -> Chart {rz = rz_new;}- // Copy solved UVs back if finite and non-degenerate- let mut solved_uvs = uvs.clone();+ let mut solved_uvs = init_uv;let mut all_ok = true;for (fi, &vi) in free_verts.iter().enumerate() {let (u, v) = (x[2 * fi], x[2 * fi + 1]);@@ -384,7 +477,6 @@ fn solve_chart_lscm(mesh: &PolyMesh, faces: &[usize]) -> Chart {solved_uvs[vi] = [u, v];}if all_ok {- // Ensure consistent positive signed UV arealet mut uv_area = 0.0f64;for &[a, b, c] in &tris {let (u0, v0) = (solved_uvs[a][0], solved_uvs[a][1]);@@ -395,8 +487,14 @@ fn solve_chart_lscm(mesh: &PolyMesh, faces: &[usize]) -> Chart {if uv_area < 0.0 {for uv in &mut solved_uvs { uv[0] = -uv[0]; }}- if uv_area.abs() > 1e-10 {- uvs = solved_uvs;+ if uv_area.abs() > 1e-12 {+ let (lscm_bad, _) =+ count_bad_uv_tris(mesh, faces, &face_local_verts, &solved_uvs, area_3d);+ // Prefer LSCM whenever it achieves zero inversions or beats planar fallback+ if lscm_bad == 0 || lscm_bad <= best_bad {+ uvs = solved_uvs;+ best_bad = lscm_bad;+ }}}}@@ -499,6 +597,7 @@ fn solve_chart_lscm(mesh: &PolyMesh, faces: &[usize]) -> Chart {uvs,w,h,+ bad_tris: best_bad,}}@@ -712,21 +811,110 @@ pub fn unwrap_lscm(mesh: &mut PolyMesh, angle_deg: f64, margin: f32) -> Result<Uface_nbrs[inc[1]].push(inc[0]);}}+ for nbrs in &mut face_nbrs {+ nbrs.sort_unstable();+ nbrs.dedup();+ }++ // Compute total 3D surface area to guide concave & elongated-strip chart refinement+ let total_mesh_area: f64 = (0..mesh.faces.len()).map(|fi| mesh.face_area(fi)).sum();- // Recursive concave/hollow chart bisection: only accepts a split when it strictly reduces- // total OBB area (plus margin overhead), turning hollow rims/L-shapes into compact rectangles!+ // Pass 1: Zero-inversion repair + recursive concave/hollow chart bisection.let mut charts: Vec<Chart> = Vec::with_capacity(chart_face_lists.len() + 16);let mut pending: VecDeque<(Vec<usize>, usize)> = chart_face_lists.into_iter().map(|fl| (fl, 0)).collect();- let split_fill_thresh: f64 = 0.8500;- let split_min_faces: usize = 4;- let split_gain_ratio: f64 = 0.9405;+ let split_fill_thresh: f64 = 0.8200;+ let split_min_faces: usize = 6;+ let split_gain_ratio: f64 = 0.9200;let split_max_depth: usize = 4;+ let inv_max_depth: usize = 10;while let Some((fl, depth)) = pending.pop_front() {let ch = solve_chart_lscm(mesh, &fl);++ // Priority 1: eliminate any inverted or collapsed UV triangles by splitting offending charts+ if ch.bad_tris > 0 && fl.len() >= 2 && depth < inv_max_depth {+ let mut bad_faces = Vec::new();+ let mut good_faces = Vec::new();+ for (lfi, &fi) in ch.faces.iter().enumerate() {+ let lv = &ch.face_local_verts[lfi];+ let fv = &mesh.faces[fi].verts;+ let mut face_bad = false;+ for [ca, cb, cc] in mesh.triangulate_face_corners(fi) {+ let a3 = 0.5+ * (mesh.verts[fv[cb]] - mesh.verts[fv[ca]])+ .cross(mesh.verts[fv[cc]] - mesh.verts[fv[ca]])+ .len();+ let (a, b, c) = (lv[ca], lv[cb], lv[cc]);+ let sa = 0.5+ * ((ch.uvs[b][0] - ch.uvs[a][0]) * (ch.uvs[c][1] - ch.uvs[a][1])+ - (ch.uvs[c][0] - ch.uvs[a][0]) * (ch.uvs[b][1] - ch.uvs[a][1]));+ if a3 <= 1e-12 {+ if !sa.is_finite() || sa < -1e-12 {+ face_bad = true;+ break;+ }+ continue;+ }+ if !sa.is_finite() || sa <= 1e-6 * a3 {+ face_bad = true;+ break;+ }+ }+ if face_bad {+ bad_faces.push(fi);+ } else {+ good_faces.push(fi);+ }+ }+ let halves = if !bad_faces.is_empty() && !good_faces.is_empty() {+ [good_faces, bad_faces]+ } else {+ // Split along the longest 3D bounding-box axis (or mid-index fallback)+ let mut a_faces = Vec::new();+ let mut b_faces = Vec::new();+ let mut bb_min = Vec3::splat(f64::INFINITY);+ let mut bb_max = Vec3::splat(f64::NEG_INFINITY);+ for &fi in &fl {+ let c = mesh.face_centroid(fi);+ bb_min = bb_min.min(c);+ bb_max = bb_max.max(c);+ }+ let ext = bb_max - bb_min;+ let axis = if ext.x >= ext.y && ext.x >= ext.z {+ 0+ } else if ext.y >= ext.z {+ 1+ } else {+ 2+ };+ let mid = 0.5 * (bb_min.to_array()[axis] + bb_max.to_array()[axis]);+ for &fi in &fl {+ if mesh.face_centroid(fi).to_array()[axis] <= mid {+ a_faces.push(fi);+ } else {+ b_faces.push(fi);+ }+ }+ if a_faces.is_empty() || b_faces.is_empty() {+ let half = fl.len() / 2;+ a_faces = fl[..half].to_vec();+ b_faces = fl[half..].to_vec();+ }+ [a_faces, b_faces]+ };+ for half in halves {+ for comp in split_connected_components(&half, &face_nbrs) {+ pending.push_back((comp, depth + 1));+ }+ }+ continue;+ }++ // Priority 2: bisect hollow/concave charts that waste significant atlas arealet ch_bb = (ch.w * ch.h).max(1e-9);let area3: f64 = ch.faces.iter().map(|&fi| mesh.face_area(fi)).sum();let fill = area3 / ch_bb;- if depth < split_max_depth && fl.len() >= split_min_faces && fill < split_fill_thresh {+ let waste_significant = (ch_bb - area3) > 0.004 * total_mesh_area.max(1e-6);+ if depth < split_max_depth && fl.len() >= split_min_faces && fill < split_fill_thresh && waste_significant {let mut best_children: Option<(f64, Vec<Vec<usize>>)> = None;let split_pad_weight: f64 = 0.0050;for split_u in [true, false] {@@ -744,18 +932,26 @@ pub fn unwrap_lscm(mesh: &mut PolyMesh, angle_deg: f64, margin: f32) -> Result<Uif a_faces.len() < 2 || b_faces.len() < 2 { continue; }let mut comps = Vec::new();let mut sum_bb = 0.0;+ let mut any_bad = false;for half in [a_faces, b_faces] {for comp in split_connected_components(&half, &face_nbrs) {let sub = solve_chart_lscm(mesh, &comp);+ if sub.bad_tris > 0 {+ any_bad = true;+ break;+ }let p = split_pad_weight * ch.w.max(ch.h);sum_bb += (sub.w + p) * (sub.h + p);comps.push(comp);}+ if any_bad { break; }}- if sum_bb < ch_bb * split_gain_ratio {- if best_children.as_ref().map_or(true, |(b, _)| sum_bb < *b) {- best_children = Some((sum_bb, comps));- }+ let better = match &best_children {+ None => true,+ Some((b, _)) => sum_bb < *b,+ };+ if !any_bad && sum_bb < ch_bb * split_gain_ratio && better {+ best_children = Some((sum_bb, comps));}}}@@ -769,6 +965,73 @@ pub fn unwrap_lscm(mesh: &mut PolyMesh, angle_deg: f64, margin: f32) -> Result<Ucharts.push(ch);}+ // Pass 2: Bisect ultra-elongated multi-face strips whose length forces the square UV atlas+ // to bloat far beyond `sqrt(total_mesh_area)` (e.g., long rails, beams, trim strips).+ let target_max_side = (total_mesh_area.sqrt() * 1.15).max(1e-4);+ let mut final_charts: Vec<Chart> = Vec::with_capacity(charts.len() + 16);+ let mut long_queue: VecDeque<(Chart, usize)> = charts.into_iter().map(|c| (c, 0)).collect();+ while let Some((ch, depth)) = long_queue.pop_front() {+ let max_side = ch.w.max(ch.h);+ if depth < 4 && ch.faces.len() >= 2 && max_side > target_max_side {+ let split_u = ch.w >= ch.h;+ let span = if split_u { ch.w } else { ch.h };+ let mut best_split: Option<(f64, Vec<Chart>)> = None;+ for &frac in &[0.50f64, 0.40, 0.60, 0.30, 0.70] {+ let cut = span * frac;+ let mut a_faces = Vec::new();+ let mut b_faces = Vec::new();+ for (lfi, &fi) in ch.faces.iter().enumerate() {+ let lv = &ch.face_local_verts[lfi];+ let avg = lv+ .iter()+ .map(|&v| if split_u { ch.uvs[v][0] } else { ch.uvs[v][1] })+ .sum::<f64>()+ / (lv.len().max(1) as f64);+ if avg <= cut {+ a_faces.push(fi);+ } else {+ b_faces.push(fi);+ }+ }+ if a_faces.is_empty() || b_faces.is_empty() {+ continue;+ }+ let mut subs = Vec::new();+ let mut worst_side = 0.0f64;+ let mut ok = true;+ for half in [a_faces, b_faces] {+ for comp in split_connected_components(&half, &face_nbrs) {+ let sub = solve_chart_lscm(mesh, &comp);+ if sub.bad_tris > ch.bad_tris {+ ok = false;+ break;+ }+ worst_side = worst_side.max(sub.w.max(sub.h));+ subs.push(sub);+ }+ if !ok {+ break;+ }+ }+ let better = match &best_split {+ None => true,+ Some((b, _)) => worst_side < *b,+ };+ if ok && worst_side < max_side * 0.90 && better {+ best_split = Some((worst_side, subs));+ }+ }+ if let Some((_, subs)) = best_split {+ for sub in subs {+ long_queue.push_back((sub, depth + 1));+ }+ continue;+ }+ }+ final_charts.push(ch);+ }+ let charts = final_charts;+let sizes: Vec<(f64, f64)> = charts.iter().map(|c| (c.w, c.h)).collect();let total_rect_area: f64 = sizes.iter().map(|(w, h)| w * h).sum();let max_dim: f64 = sizes.iter().map(|(w, h)| w.max(*h)).fold(0.0, f64::max);diff --git a/crates/forma-core/tests/regression_fixes.rs b/crates/forma-core/tests/regression_fixes.rsnew file mode 100644index 0000000..6e0a989--- /dev/null+++ b/crates/forma-core/tests/regression_fixes.rs@@ -0,0 +1,263 @@+use forma_core::boolean::has_overlapping_components;+use forma_core::export::{write_glb_bytes, write_scene_glb_bytes};+use forma_core::import::read_glb_bytes;+use forma_core::math::Vec3;+use forma_core::mesh::{Material, PolyMesh};+use forma_core::primitives::{make_box, make_cylinder};+use forma_core::render::{render_blueprint_svg_string, render_quad_png_bytes, render_view_png_bytes};+use forma_core::uv::unwrap_lscm;+use std::sync::Arc;+use std::time::Instant;++fn parse_glb(bytes: &[u8]) -> (serde_json::Value, &[u8]) {+ let json_len = u32::from_le_bytes(bytes[12..16].try_into().unwrap()) as usize;+ let json: serde_json::Value = serde_json::from_slice(&bytes[20..20 + json_len]).unwrap();+ let bin_hdr = 20 + json_len;+ let bin_len = u32::from_le_bytes(bytes[bin_hdr..bin_hdr + 4].try_into().unwrap()) as usize;+ let bin = &bytes[bin_hdr + 8..bin_hdr + 8 + bin_len];+ (json, bin)+}++#[test]+fn test_zero_length_normals_repaired_and_shifted_newell_accurate() {+ // Box far from origin with an intentional collinear stitch triangle attached+ let mut mesh = make_box(1.0, 1.0, 1.0, 1);+ mesh.translate(Vec3::new(1000.0, -500.0, 250.0));+ let v0 = mesh.verts[0];+ let v1 = mesh.verts[1];+ let mid = (v0 + v1) * 0.5;+ let vm = mesh.add_vert(mid);+ // Collinear micro-sliver triangle (exact zero 3D area)+ mesh.add_face(smallvec::smallvec![0, vm, 1], 2, Some("sliver"));++ for smooth in [None, Some(38.0)] {+ let mut m = mesh.clone();+ m.smooth_angle_deg = smooth;+ m.weighted_normals = smooth.is_some();++ let cn = m.compute_corner_normals();+ for face_cn in &cn {+ for &n in face_cn {+ assert!(n.is_finite(), "non-finite corner normal");+ assert!(+ (n.len() - 1.0).abs() < 1e-6,+ "non-unit corner normal len={}",+ n.len()+ );+ }+ }++ let glb = write_glb_bytes(&m, true).expect("glb export");+ let (json, bin) = parse_glb(&glb);+ let prims = json["meshes"][0]["primitives"].as_array().unwrap();+ for prim in prims {+ let nrm_acc_i = prim["attributes"]["NORMAL"].as_u64().unwrap() as usize;+ let nrm_acc = &json["accessors"][nrm_acc_i];+ let bv = &json["bufferViews"][nrm_acc["bufferView"].as_u64().unwrap() as usize];+ let off = bv["byteOffset"].as_u64().unwrap() as usize;+ let cnt = nrm_acc["count"].as_u64().unwrap() as usize;+ for i in 0..cnt {+ let o = off + i * 12;+ let nx = f32::from_le_bytes(bin[o..o + 4].try_into().unwrap());+ let ny = f32::from_le_bytes(bin[o + 4..o + 8].try_into().unwrap());+ let nz = f32::from_le_bytes(bin[o + 8..o + 12].try_into().unwrap());+ let l2 = (nx as f64).powi(2) + (ny as f64).powi(2) + (nz as f64).powi(2);+ assert!(+ (l2 - 1.0).abs() < 1e-4,+ "GLB normal #{i} non-unit: [{nx},{ny},{nz}] len^2={l2}"+ );+ }+ }+ }+}++#[test]+fn test_glb_unconditional_welding_per_prim_compaction_and_u16_indices() {+ let mut a = make_cylinder(0.1, 1.0, 16, 1);+ a.assign_material(+ Material {+ name: "orange".into(),+ color: [0.92, 0.28, 0.08, 1.0],+ metallic: 0.2,+ roughness: 0.3,+ },+ None,+ );+ let mut b = make_box(0.4, 0.4, 0.1, 2);+ b.translate(Vec3::new(0.0, 0.0, -0.55));+ b.assign_material(+ Material {+ name: "steel".into(),+ color: [0.58, 0.62, 0.67, 1.0],+ metallic: 0.85,+ roughness: 0.35,+ },+ None,+ );+ // Raw mesh: smooth_angle_deg = None, no UVs+ a.append_mesh(&b);+ assert!(a.smooth_angle_deg.is_none());++ let glb = write_glb_bytes(&a, true).expect("raw glb");+ let (json, _bin) = parse_glb(&glb);+ let prims = json["meshes"][0]["primitives"].as_array().unwrap();+ assert_eq!(prims.len(), 2);++ // Distinct per-primitive vertex attribute accessors (no cross-material sharing)+ let pos0 = prims[0]["attributes"]["POSITION"].as_u64().unwrap();+ let pos1 = prims[1]["attributes"]["POSITION"].as_u64().unwrap();+ assert_ne!(pos0, pos1, "primitives must have compacted independent POSITION buffers");++ // Both primitives use u16 (5123) indices and weld vertices (< 3 * tris)+ for prim in prims {+ let idx_acc = &json["accessors"][prim["indices"].as_u64().unwrap() as usize];+ assert_eq!(idx_acc["componentType"].as_u64().unwrap(), 5123);+ let pos_cnt = json["accessors"][prim["attributes"]["POSITION"].as_u64().unwrap() as usize]["count"]+ .as_u64()+ .unwrap();+ let idx_cnt = idx_acc["count"].as_u64().unwrap();+ assert!(pos_cnt < idx_cnt, "raw GLB vertices should be welded ({pos_cnt} vs {idx_cnt})");+ }++ // Scene GLB export also welds, compacts per-prim, and uses u16 indices+ let arc_a = Arc::new(a);+ let sglb = write_scene_glb_bytes(&[("prop", &arc_a, [0.0, 0.0, 0.0])], true).expect("scene glb");+ let (sjson, _) = parse_glb(&sglb);+ let sprims = sjson["meshes"][0]["primitives"].as_array().unwrap();+ assert_eq!(sprims.len(), 2);+ assert_ne!(+ sprims[0]["attributes"]["POSITION"],+ sprims[1]["attributes"]["POSITION"]+ );+ assert_eq!(+ sjson["accessors"][sprims[0]["indices"].as_u64().unwrap() as usize]["componentType"],+ 5123+ );++ // Round-trip import succeeds with u16 indices+ let rt = read_glb_bytes(&glb).expect("round-trip u16 glb");+ assert_eq!(rt.faces.len(), arc_a.triangulated().faces.len());+}++#[test]+fn test_uv_unwrap_deterministic_zero_inversions_and_elongated_packing() {+ // Build an 8m kinked tubular rail with stanchions (representative elongated prop)+ let pts = vec![+ Vec3::new(-4.0, 0.0, 0.85),+ Vec3::new(-1.5, 0.0, 0.85),+ Vec3::new(1.5, 0.0, 0.35),+ Vec3::new(4.0, 0.0, 0.35),+ ];+ let bar = forma_core::primitives::make_tube(&pts, 0.045, 16, false, 1).expect("tube");+ let mut post1 = make_cylinder(0.032, 0.85, 12, 2);+ post1.translate(Vec3::new(-3.4, 0.0, 0.445));+ let mut post2 = make_cylinder(0.032, 0.35, 12, 3);+ post2.translate(Vec3::new(3.4, 0.0, 0.195));+ let m1 = forma_core::boolean::boolean_op(&bar, &post1, forma_core::boolean::BoolOp::Union, None, 4)+ .expect("union 1");+ let base = forma_core::boolean::boolean_op(&m1, &post2, forma_core::boolean::BoolOp::Union, None, 5)+ .expect("union 2");++ let mut run1 = base.clone();+ let stats1 = unwrap_lscm(&mut run1, 45.0, 0.01).expect("unwrap run1");+ let mut run2 = base.clone();+ let stats2 = unwrap_lscm(&mut run2, 45.0, 0.01).expect("unwrap run2");++ assert_eq!(stats1.charts, stats2.charts, "chart count must be deterministic");+ assert!((stats1.utilization - stats2.utilization).abs() < 1e-12);+ assert_eq!(stats1.inverted_tris, 0, "expected zero inverted UV tris");+ // Longest single indivisible quad on the middle ramp is 3.04m while total surface area is ~2.53 m^2,+ // so the theoretical square-atlas ceiling is 2.53 / 3.04^2 = 27.4%.+ assert!(+ stats1.utilization >= 0.25,+ "expected >=25% atlas utilization (near 27.4% theoretical ceiling), got {:.1}%",+ stats1.utilization * 100.0+ );+ // Byte-identical GLB output across runs+ let g1 = write_glb_bytes(&run1, true).unwrap();+ let g2 = write_glb_bytes(&run2, true).unwrap();+ assert_eq!(g1, g2, "unwrapped GLB must be byte-identical across runs");++ // Multi-segment elongated rail with baseplates reaches >40% utilization+ let seg_pts = vec![+ Vec3::new(-4.0, 0.0, 0.85),+ Vec3::new(-2.5, 0.0, 0.85),+ Vec3::new(-1.0, 0.0, 0.85),+ Vec3::new(0.5, 0.0, 0.60),+ Vec3::new(2.0, 0.0, 0.35),+ Vec3::new(4.0, 0.0, 0.35),+ ];+ let mut seg_rail = forma_core::primitives::make_tube(&seg_pts, 0.045, 16, false, 10).unwrap();+ for x in [-3.4, -1.5, 1.5, 3.4] {+ let mut plate = make_box(0.32, 0.42, 0.03, 11);+ plate.translate(Vec3::new(x, 0.0, 0.015));+ seg_rail.append_mesh(&plate);+ }+ let seg_stats = unwrap_lscm(&mut seg_rail, 45.0, 0.01).expect("unwrap seg_rail");+ assert_eq!(seg_stats.inverted_tris, 0);+ assert!(+ seg_stats.utilization >= 0.45,+ "expected >=45% utilization on segmented rail + plates, got {:.1}%",+ seg_stats.utilization * 100.0+ );+}++#[test]+fn test_renderer_per_view_tight_framing_on_elongated_prop() {+ // 20:1 aspect ratio beam (8.0m X, 0.4m Y, 0.4m Z)+ let beam = make_box(8.0, 0.4, 0.4, 1);+ let png = render_quad_png_bytes(&beam, 256).expect("quad png");+ assert_eq!(&png[..8], &[137, 80, 78, 71, 13, 10, 26, 10]);++ for view in ["quad", "front", "back", "right", "left", "top", "iso"] {+ let bytes = render_view_png_bytes(&beam, 256, view).expect(view);+ assert_eq!(&bytes[..8], &[137, 80, 78, 71, 13, 10, 26, 10]);+ }+ let svg = render_blueprint_svg_string(&beam, "beam").expect("svg");+ assert!(svg.contains("8.000 m"));+ assert!(svg.contains("0.400 m"));+}++#[test]+fn test_issue_17_sweep_and_prune_many_disjoint_shells_fast_and_accurate() {+ // 10 x 10 x 10 = 1,000 disjoint shells (previously O(S^2) = 500k AABB pairs)+ let mut grid = PolyMesh::new();+ let unit = make_box(0.5, 0.5, 0.5, 1);+ for ix in 0..10 {+ for iy in 0..10 {+ for iz in 0..10 {+ let mut c = unit.clone();+ c.translate(Vec3::new(ix as f64 * 1.0, iy as f64 * 1.0, iz as f64 * 1.0));+ grid.append_mesh(&c);+ }+ }+ }+ let t0 = Instant::now();+ let ov = has_overlapping_components(&grid);+ let elapsed_ms = t0.elapsed().as_secs_f64() * 1000.0;+ assert!(!ov, "disjoint 1,000-shell grid must not report overlap");+ let max_ms = if cfg!(debug_assertions) { 2000.0 } else { 250.0 };+ assert!(+ elapsed_ms < max_ms,+ "1,000-shell overlap check took too long: {elapsed_ms:.2} ms (limit {max_ms:.0} ms)"+ );++ // Inject one overlapping shell into the grid -> must return true+ let mut collider = make_box(0.6, 0.6, 0.6, 2);+ collider.translate(Vec3::new(4.2, 4.2, 4.2));+ grid.append_mesh(&collider);+ assert!(+ has_overlapping_components(&grid),+ "injected overlapping shell must be detected"+ );++ // Valid negative-volume inner cavity inside an outer shell -> must return false+ let mut hollow = make_box(2.0, 2.0, 2.0, 3);+ let mut cavity = make_box(1.0, 1.0, 1.0, 4);+ cavity.flip_winding();+ hollow.append_mesh(&cavity);+ assert!(+ !has_overlapping_components(&hollow),+ "valid negative-volume inner cavity must not trigger overlap"+ );+}