diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index d1ac12191..41bd4bbcf 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -403,23 +403,55 @@ pub fn stl_ascii(meshes: &[Mesh], name: &str) -> String { s } -/// Wavefront OBJ, one object per body. +/// Wavefront OBJ, one object per body. Positions and normals are each written once per +/// distinct value, so a face's vertices are shared while the normals keep edges between +/// faces sharp. Names are written as they are (OBJ takes the rest of the line). pub fn obj(meshes: &[(String, Mesh)]) -> String { + use std::collections::HashMap; let mut s = String::from("# SolidCraft OBJ export (mm)\n"); - let mut base = 1usize; + let (mut vbase, mut nbase) = (1usize, 1usize); for (name, m) in meshes { - s += &format!("o {}\n", name.replace(char::is_whitespace, "_")); - for p in &m.positions { - s += &format!("v {} {} {}\n", p.x, p.y, p.z); - } - for n in &m.normals { - s += &format!("vn {} {} {}\n", n.x, n.y, n.z); - } + let name: String = name.chars().map(|c| if c.is_control() { ' ' } else { c }).collect(); + s += &format!("o {name}\n"); + // `+ 0.0` turns -0 into 0, so both merge. + let key = |x: f64, y: f64, z: f64| [x + 0.0, y + 0.0, z + 0.0].map(f64::to_bits); + let mut vmap: HashMap<[u64; 3], usize> = HashMap::new(); + let mut nmap: HashMap<[u64; 3], usize> = HashMap::new(); + let vi: Vec = m + .positions + .iter() + .map(|p| { + let next = vmap.len(); + *vmap.entry(key(p.x, p.y, p.z)).or_insert_with(|| { + s += &format!("v {} {} {}\n", p.x, p.y, p.z); + next + }) + }) + .collect(); + let ni: Vec = m + .normals + .iter() + .map(|n| { + let next = nmap.len(); + *nmap.entry(key(n.x, n.y, n.z)).or_insert_with(|| { + s += &format!("vn {} {} {}\n", n.x, n.y, n.z); + next + }) + }) + .collect(); for t in &m.triangles { - let [a, b, c] = t.map(|i| i as usize + base); - s += &format!("f {a}//{a} {b}//{b} {c}//{c}\n"); + let (Some(a), Some(b), Some(c)) = (vi.get(t[0] as usize), vi.get(t[1] as usize), vi.get(t[2] as usize)) else { continue }; + let (a, b, c) = (a + vbase, b + vbase, c + vbase); + match (ni.get(t[0] as usize), ni.get(t[1] as usize), ni.get(t[2] as usize)) { + (Some(na), Some(nb), Some(nc)) => { + let (na, nb, nc) = (na + nbase, nb + nbase, nc + nbase); + s += &format!("f {a}//{na} {b}//{nb} {c}//{nc}\n"); + } + _ => s += &format!("f {a} {b} {c}\n"), + } } - base += m.positions.len(); + vbase += vmap.len(); + nbase += nmap.len(); } s } @@ -751,6 +783,24 @@ mod tests { assert!(o.contains("o Body1") && o.contains("\nf ")); } + /// OBJ shares a face's vertices (a cube: 8 positions, 6 normals, not 36 of each) and keeps + /// the body name as written, spaces included. + #[test] + fn obj_export_is_welded_and_keeps_names() { + let (_, m) = model(); + let mut st = (*m.state()).clone(); + for b in &mut st.bodies { + b.name = "Red Block".into(); + } + let o = String::from_utf8(export(&st, &[], Format::Obj, "t").unwrap()).unwrap(); + let count = |p: &str| o.lines().filter(|l| l.starts_with(p)).count(); + assert!(o.contains("\no Red Block\n"), "{o}"); + assert_eq!((count("v "), count("vn "), count("f ")), (8, 6, 12), "{o}"); + let ids: Vec = + o.lines().filter(|l| l.starts_with("f ")).flat_map(|l| l.split([' ', '/']).skip(1)).filter_map(|x| x.parse().ok()).collect(); + assert!(ids.iter().all(|i| (1..=8).contains(i) || (1..=6).contains(i))); + } + /// The design properties land in each format's own metadata (#1015): STEP and IGES headers, /// 3MF model metadata. Other tools' keys never leave the design file. #[test]