diff --git a/crates/engine/tests/it/bake.rs b/crates/engine/tests/it/bake.rs index acf54274..4c5314ad 100644 --- a/crates/engine/tests/it/bake.rs +++ b/crates/engine/tests/it/bake.rs @@ -637,6 +637,21 @@ fn a_failed_multi_set_bake_restores_settings_pixels_and_history() { assert_eq!(session.history_labels(), history); } +#[test] +fn obj_submesh_id_separates_objects_with_the_same_name_and_material() { + use texturecraft_engine::{core::IdColorSource, formats::import_mesh_bytes}; + let file = b"o Part\nusemtl Shared\nv 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 0.45 0\nvt 0 1\nf 1/1 2/2 3/3\no Part\nusemtl Shared\nv 2 0 0\nv 3 0 0\nv 2 1 0\nvt 0.5 0\nvt 0.95 0\nvt 0.5 1\nf 4/4 5/5 6/6"; + let mesh = import_mesh_bytes("parts.obj", file).unwrap().mesh; + assert_eq!(mesh.materials.len(), 1); + assert_eq!(mesh.submeshes.len(), 2); + let mut session = Session::new_project("parts", mesh, "parts.obj", None, 128).unwrap(); + session.doc.project.texture_sets[0].bake.maps.id.parameters.source = IdColorSource::Submesh; + execute(&mut session, "bake.run", &json!({"resolution":128,"maps":["id"],"dilation":0})).unwrap(); + let map = &session.doc.baked[&0].maps[&BakedMap::Id]; + let pixel = |x: usize| &map[(100 * 128 + x) * 3..(100 * 128 + x) * 3 + 3]; + assert_ne!(pixel(10), pixel(74)); +} + /// `file.changeMesh` swaps the mesh under a baked project: the high poly and the skew map stay, /// the project counts as changed, and image resources are decoded in the new session. #[test] diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index f0231d11..5b4a0c7c 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -130,6 +130,9 @@ pub(crate) struct RawMesh { pub colors: Option>, /// Triangles (vertex indices) per (material, part name); an empty part is unnamed. pub groups: Vec<(String, String, Vec)>, + // Build-time index; group names are restored only after polygon collection ends + // Nested maps allow borrowed lookups without allocating keys for every polygon + group_index: HashMap>, pub warnings: Vec, pub cameras: Vec, /// Materials whose base color is not plain white (glTF). @@ -148,11 +151,13 @@ pub(crate) struct RawBaseColor { impl RawMesh { /// Triangle list of `material` in `part`, created on first use. pub fn group(&mut self, material: &str, part: &str) -> &mut Vec { - let i = match self.groups.iter().position(|(m, p, _)| m == material && p == part) { + let i = match self.group_index.get(material).and_then(|parts| parts.get(part)).copied() { Some(i) => i, None => { - self.groups.push((material.to_string(), part.to_string(), Vec::new())); - self.groups.len() - 1 + let i = self.groups.len(); + self.groups.push((material.to_owned(), part.to_owned(), Vec::new())); + self.group_index.entry(material.to_owned()).or_default().insert(part.to_owned(), i); + i } }; &mut self.groups[i].2 diff --git a/crates/formats/src/mesh_import/obj.rs b/crates/formats/src/mesh_import/obj.rs index 267aa8ea..e2d1fb52 100644 --- a/crates/formats/src/mesh_import/obj.rs +++ b/crates/formats/src/mesh_import/obj.rs @@ -31,10 +31,11 @@ fn read_inner(bytes: &[u8]) -> Result { let mut raw = RawMesh::default(); let (mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new()); let (mut missing_normals, mut missing_uvs) = (false, false); - for mesh in &scene.meshes { + for (mesh_id, mesh) in scene.meshes.iter().enumerate() { + // The shared reader preserves declarations as meshes, even when their names match + let declaration = mesh_id.to_string(); for part in &mesh.parts { let material = part.material.and_then(|i| scene.materials.get(i)).map_or("Default", |m| m.name.as_str()); - let name = if part.name.is_empty() { mesh.name.as_str() } else { part.name.as_str() }; // OBJ model/material runs have independent v/vt/vn deduplication. let mut ids = HashMap::new(); for face in part.faces() { @@ -73,10 +74,16 @@ fn read_inner(bytes: &[u8]) -> Result { }; polygon.push(id); } - raw.polygon(material, name, &polygon); + raw.polygon(material, &declaration, &polygon); } } } + // Restore display names only after grouping by declaration and material + for (_, name, _) in &mut raw.groups { + if let Some(mesh) = name.parse::().ok().and_then(|id| scene.meshes.get(id)) { + *name = mesh.name.clone(); + } + } if missing_uvs { raw.warnings.push("some objects have no UVs; default UVs were assigned".into()); } @@ -85,3 +92,23 @@ fn read_inner(bytes: &[u8]) -> Result { raw.colors = any_colors.then_some(colors); Ok(raw) } + +#[cfg(test)] +mod tests { + #[test] + #[ignore = "release benchmark for declaration-heavy OBJ input"] + fn declaration_import_benchmark() { + for count in [10_000, 50_000] { + let mut source = String::from("v 0 0 0\nv 1 0 0\nv 0 1 0\n"); + for _ in 0..count { + source.push_str("o repeated\nf 1 2 3\n"); + } + let start = std::time::Instant::now(); + let raw = super::read(source.as_bytes()).unwrap(); + println!("{count} declarations: {:?}", start.elapsed()); + assert_eq!(raw.groups.len(), count); + assert_eq!(raw.triangle_count(), count); + assert!(raw.groups.iter().all(|(_, name, tris)| name == "repeated" && tris.len() == 3)); + } + } +} diff --git a/crates/formats/src/mesh_import/stl.rs b/crates/formats/src/mesh_import/stl.rs index e087b711..95eeee6b 100644 --- a/crates/formats/src/mesh_import/stl.rs +++ b/crates/formats/src/mesh_import/stl.rs @@ -55,7 +55,8 @@ pub(crate) fn read(bytes: &[u8]) -> Result { if has_colors { raw.colors = Some(vertex_colors); } - raw.groups.push(("Default".into(), String::new(), (0..raw.positions.len() as u32).collect())); + let vertex_count = raw.positions.len() as u32; + raw.group("Default", "").extend(0..vertex_count); Ok(raw) } diff --git a/crates/formats/src/mesh_import/tests.rs b/crates/formats/src/mesh_import/tests.rs index 88509a05..99f9173c 100644 --- a/crates/formats/src/mesh_import/tests.rs +++ b/crates/formats/src/mesh_import/tests.rs @@ -610,3 +610,22 @@ fn ply_face_element_before_vertex_element() { let bad = format!("{head}3 0 1 5\n0 0 0\n1 0 0\n0 1 0\n"); assert!(import_mesh_bytes("a.ply", bad.as_bytes()).is_err()); } + +#[test] +fn group_index_preserves_order_and_reuses_nonadjacent_material_parts() { + let mut raw = super::RawMesh::default(); + for i in 0..1000 { + raw.group("shared", &i.to_string()).extend_from_slice(&[0, 1, 2]); + } + for i in (0..1000).rev() { + raw.group("shared", &i.to_string()).extend_from_slice(&[3, 4, 5]); + } + raw.group("other", "0").extend_from_slice(&[6, 7, 8]); + assert_eq!(raw.groups.len(), 1001); + for (i, (material, part, indices)) in raw.groups.iter().take(1000).enumerate() { + assert_eq!(material, "shared"); + assert_eq!(part, &i.to_string()); + assert_eq!(indices, &[0, 1, 2, 3, 4, 5]); + } + assert_eq!(raw.groups[1000], ("other".into(), "0".into(), vec![6, 7, 8])); +}