From 0486899125c6761d1962c22b8ef1fa3e6f92bbfe Mon Sep 17 00:00:00 2001 From: Chris Hassebrook Date: Sun, 15 Nov 2026 02:59:04 -0500 Subject: [PATCH 01/18] formats: read FBX vertex colors so ID bakes see them (#422) --- crates/formats/src/mesh_import/abc/mod.rs | 2 +- crates/formats/src/mesh_import/dae.rs | 1 + crates/formats/src/mesh_import/fbx.rs | 14 +++++---- crates/formats/src/mesh_import/mod.rs | 25 ++++++++++++++-- crates/formats/src/mesh_import/scene_tests.rs | 29 ++++++++++++++++++- crates/formats/src/mesh_import/usd/mod.rs | 1 + 6 files changed, 62 insertions(+), 10 deletions(-) diff --git a/crates/formats/src/mesh_import/abc/mod.rs b/crates/formats/src/mesh_import/abc/mod.rs index b0a0ef22..e2abf0be 100644 --- a/crates/formats/src/mesh_import/abc/mod.rs +++ b/crates/formats/src/mesh_import/abc/mod.rs @@ -554,7 +554,7 @@ impl Walk<'_, '_> { Vec2::ZERO } }); - corners.push(Corner { p: *p, n, uv }); + corners.push(Corner { p: *p, n, uv, color: None }); } k = end; if !keep_order { diff --git a/crates/formats/src/mesh_import/dae.rs b/crates/formats/src/mesh_import/dae.rs index d23ea61b..bb104455 100644 --- a/crates/formats/src/mesh_import/dae.rs +++ b/crates/formats/src/mesh_import/dae.rs @@ -356,6 +356,7 @@ fn add_geometry(d: &mut Doc, sink: &mut PolygonSink, geom: &El, m: Mat4, bind: & p: m.transform_point3(Vec3::from(pos)), n: n.map(|n| nm * Vec3::from(n)), uv: t.map(|[u, v]| Vec2::new(u, 1.0 - v)), + color: None, }); } next = next.saturating_add(size); diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 08087283..ba54c5b0 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -1,7 +1,7 @@ //! FBX 6.x and 7.x, binary (32- and 64-bit node records, zlib-compressed arrays) and -//! ASCII: mesh geometry with normals, UVs and per-polygon materials from the layer elements, every -//! Model's transform and parent hierarchy, and the file's unit and axis system (converted to -//! meters, Y up, like glTF). FBX 6 keeps the geometry inside its Model, names objects instead of +//! ASCII: mesh geometry with normals, UVs, vertex colors and per-polygon materials from the layer +//! elements, every Model's transform and parent hierarchy, and the file's unit and axis system +//! (converted to meters, Y up, like glTF). FBX 6 keeps the geometry inside its Model, names objects instead of //! numbering them and lists properties in `Properties60`; both read into the same scene. //! Materials bring their diffuse color and, when the file embeds it (a Video's `Content`), the //! diffuse texture (for high-poly color map bakes); a texture kept as a file beside the FBX comes @@ -803,9 +803,10 @@ fn add_geometry(sink: &mut PolygonSink, geometry: &Node, transform: Mat4, slots: let polygon_indices = geometry.child("PolygonVertexIndex").map(Node::arr).unwrap_or_default(); let normals = Layer::read(geometry, "LayerElementNormal", "Normals", "NormalsIndex"); let uvs = Layer::read(geometry, "LayerElementUV", "UV", "UVIndex"); + let colors = Layer::read(geometry, "LayerElementColor", "Colors", "ColorIndex"); let materials = Layer::read(geometry, "LayerElementMaterial", "Materials", ""); if vertices.iter().chain(polygon_indices.iter()).any(|v| !v.is_finite()) - || [&normals, &uvs, &materials] + || [&normals, &uvs, &colors, &materials] .into_iter() .flatten() .any(|layer| layer.data.iter().any(|v| !v.is_finite()) || layer.index.as_ref().is_some_and(|index| index.iter().any(|v| !v.is_finite()))) @@ -838,7 +839,10 @@ fn add_geometry(sink: &mut PolygonSink, geometry: &Node, transform: Mat4, slots: Vec2::ZERO } }); - corners.push(Corner { p: *p, n, uv }); + // FBX color layers hold one RGBA value per item. + let color = + colors.as_ref().and_then(|l| l.get::<4>(k, control_point, polygon_index)).map(|[r, g, b, a]| Vec4::new(r as f32, g as f32, b as f32, a as f32)); + corners.push(Corner { p: *p, n, uv, color }); if last || k + 1 == polygon_indices.len() { if flip { corners.reverse(); diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index 42497364..f0231d11 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -2,7 +2,7 @@ //! world-space [`Mesh`] with one submesh per material and part (glTF node, OBJ object, FBX //! model, COLLADA node, USD Mesh prim, Alembic PolyMesh; unnamed parts take the file stem), materials contiguous, //! glTF UV convention (origin top-left, v down), -//! normals (computed when missing), vertex colors (glTF, OBJ, PLY), UVs (auto-unwrapped when +//! normals (computed when missing), vertex colors (glTF, FBX, OBJ, PLY), UVs (auto-unwrapped when //! missing) and MikkTSpace tangents. glTF, FBX, COLLADA and USD cameras come along as the //! project's camera list. @@ -182,10 +182,11 @@ pub(crate) struct Corner { pub p: Vec3, pub n: Option, pub uv: Option, + pub color: Option, } /// Collects polygons into a [`RawMesh`]: fan triangulation, one vertex per unique corner, and -/// normals / UVs kept only when every corner has them (else computed / unwrapped). +/// normals / UVs / colors kept only when every corner has them (else computed / unwrapped / white). #[derive(Default)] pub(crate) struct PolygonSink { /// Part name of the polygons that follow. @@ -193,10 +194,13 @@ pub(crate) struct PolygonSink { raw: RawMesh, normals: Vec, uvs: Vec, + /// Allocated by the first coloured corner, so a scene without colors pays nothing for them. + colors: Option>, missing_normals: bool, missing_uvs: bool, some_uvs: bool, - ids: HashMap<[u32; 8], u32>, + missing_colors: bool, + ids: HashMap<[u32; 12], u32>, polygon: Vec, triangles: usize, } @@ -213,13 +217,24 @@ impl PolygonSink { self.missing_normals |= c.n.is_none(); self.missing_uvs |= c.uv.is_none(); self.some_uvs |= c.uv.is_some(); + self.missing_colors |= c.color.is_none(); let (n, uv) = (c.n.unwrap_or_default(), c.uv.unwrap_or_default()); + // A corner without a color must not merge with one that has it. + let color_key = c.color.map_or([u32::MAX; 4], |v| v.to_array().map(f32::to_bits)); let key = [c.p.x, c.p.y, c.p.z, n.x, n.y, n.z, uv.x, uv.y].map(f32::to_bits); + let key = [key[0], key[1], key[2], key[3], key[4], key[5], key[6], key[7], color_key[0], color_key[1], color_key[2], color_key[3]]; let id = match self.ids.entry(key) { Entry::Occupied(e) => *e.get(), Entry::Vacant(e) => { let id = self.raw.positions.len(); check_vertices(id + 1)?; + // White stands in for the corners before the first coloured one. + if c.color.is_some() && self.colors.is_none() { + self.colors = Some(vec![Vec4::ONE; id]); + } + if let Some(colors) = self.colors.as_mut() { + colors.push(c.color.unwrap_or(Vec4::ONE)); + } self.raw.positions.push(c.p); self.normals.push(n); self.uvs.push(uv); @@ -242,8 +257,12 @@ impl PolygonSink { if self.missing_uvs && self.some_uvs { self.warn("some polygons have no UVs; the whole mesh was unwrapped automatically".into()); } + if self.missing_colors && self.colors.is_some() { + self.warn("some polygon corners have no color in the color layer; vertex colors were dropped".into()); + } self.raw.normals = (!self.missing_normals).then_some(self.normals); self.raw.uvs = (!self.missing_uvs).then_some(self.uvs); + self.raw.colors = if self.missing_colors { None } else { self.colors.take() }; self.raw } } diff --git a/crates/formats/src/mesh_import/scene_tests.rs b/crates/formats/src/mesh_import/scene_tests.rs index 00a97922..015724a1 100644 --- a/crates/formats/src/mesh_import/scene_tests.rs +++ b/crates/formats/src/mesh_import/scene_tests.rs @@ -3,7 +3,7 @@ use std::io::Write as _; -use texturecraft_geom::glam::{Vec2, Vec3}; +use texturecraft_geom::glam::{Vec2, Vec3, Vec4}; use super::tests::hammer; use super::*; @@ -298,6 +298,33 @@ fn fbx_binary_32_and_64_bit_compressed_or_not() { } } +/// [`scene`] with a per-polygon-vertex color layer: corner `i` gets `(i/8, 1 - i/8, 0.25, 1)`. +fn colored_scene() -> Vec { + let mut nodes = scene(false); + let objects = nodes.iter_mut().find(|node| node.name == "Objects").unwrap(); + let geometry = objects.children.iter_mut().find(|node| node.name == "Geometry").unwrap(); + let colors: Vec = (0..7).flat_map(|i| [i as f64 / 8.0, 1.0 - i as f64 / 8.0, 0.25, 1.0]).collect(); + geometry.children.push(layer( + "LayerElementColor", + "ByPolygonVertex", + "IndexToDirect", + vec![n("Colors", vec![P::Doubles(colors)], vec![]), n("ColorIndex", vec![P::Ints((0..7).collect())], vec![])], + )); + nodes +} + +#[test] +fn fbx_vertex_colors_reach_the_mesh_and_high_polys() { + let nodes = colored_scene(); + let expected: Vec = (0..7).map(|i| Vec4::new(i as f32 / 8.0, 1.0 - i as f32 / 8.0, 0.25, 1.0)).collect(); + for (label, bytes) in [("binary", binary_fbx(&nodes, 7400, false)), ("ascii", ascii_fbx(&nodes).into_bytes())] { + let imported = import_mesh_bytes("colors.fbx", &bytes).unwrap_or_else(|e| panic!("{label}: {e}")); + assert_eq!(imported.mesh.colors, expected, "{label}: the color layer reaches the mesh"); + let high = import_high_poly_bytes("colors.fbx", &bytes).unwrap_or_else(|e| panic!("{label}: {e}")); + assert_eq!(high.mesh.colors, expected, "{label}: and the high poly used for ID bakes"); + } +} + /// [`scene`] with a diffuse color on Red and an embedded diffuse texture on Blue. #[test] fn fbx_camera_models_are_capped_during_import() { diff --git a/crates/formats/src/mesh_import/usd/mod.rs b/crates/formats/src/mesh_import/usd/mod.rs index e7f9d0fe..9f6f6d41 100644 --- a/crates/formats/src/mesh_import/usd/mod.rs +++ b/crates/formats/src/mesh_import/usd/mod.rs @@ -576,6 +576,7 @@ impl<'a> Stage<'a> { p: m.transform_point3(Vec3::from(p)), n: normals.as_ref().and_then(|pv| pv.get::<3>(at)).map(|v| nm * Vec3::from(v)), uv: uvs.as_ref().and_then(|pv| pv.get::<2>(at)).map(|[u, v]| Vec2::new(u, 1.0 - v)), + color: None, }); } if flip { From 6e8d421260cd2c8d7f1491f8c7580dc43f22f32d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:34:52 +0000 Subject: [PATCH 02/18] Use shared FBX scene and package readers --- Cargo.lock | 20 +- Cargo.toml | 2 +- crates/formats/src/mesh_import/fbx.rs | 1044 +++---------------------- 3 files changed, 128 insertions(+), 938 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d63a2ff2..b27f7dac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -820,7 +820,7 @@ name = "craft-mcmat" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" dependencies = [ - "craft-zip", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31)", "serde", "serde_json", "thiserror 2.0.21", @@ -842,7 +842,11 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d6ed8c20f12188c1f39c89b3a8436bd0d09c3748#d6ed8c20f12188c1f39c89b3a8436bd0d09c3748" +source = "git+https://github.com/storytold/craft-libs?rev=543098150ffc09914b662e61053d8cddf239bbe6#543098150ffc09914b662e61053d8cddf239bbe6" +dependencies = [ + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=543098150ffc09914b662e61053d8cddf239bbe6)", + "miniz_oxide 0.9.1", +] [[package]] name = "craft-quit" @@ -924,6 +928,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=543098150ffc09914b662e61053d8cddf239bbe6#543098150ffc09914b662e61053d8cddf239bbe6" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "craft-zip" version = "0.1.0" @@ -4417,7 +4431,7 @@ dependencies = [ "craft-materialx", "craft-mcmat", "craft-mesh", - "craft-zip", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31)", "exr", "flate2", "gltf", diff --git a/Cargo.toml b/Cargo.toml index 65ce6e99..3a263a6c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d6ed8c20f12188c1f39c89b3a8436bd0d09c3748", default-features = false, features = ["stl"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "543098150ffc09914b662e61053d8cddf239bbe6", default-features = false, features = ["stl", "fbx"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index ba54c5b0..8faf623c 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -1,960 +1,136 @@ -//! FBX 6.x and 7.x, binary (32- and 64-bit node records, zlib-compressed arrays) and -//! ASCII: mesh geometry with normals, UVs, vertex colors and per-polygon materials from the layer -//! elements, every Model's transform and parent hierarchy, and the file's unit and axis system -//! (converted to meters, Y up, like glTF). FBX 6 keeps the geometry inside its Model, names objects instead of -//! numbering them and lists properties in `Properties60`; both read into the same scene. -//! Materials bring their diffuse color and, when the file embeds it (a Video's `Content`), the -//! diffuse texture (for high-poly color map bakes); a texture kept as a file beside the FBX comes -//! along when the FBX is packaged with it ([`package`]: a stored zip of the FBX first and the -//! files under their paths below its folder, which [`read`] opens like the FBX). Camera Models become the file's cameras (lens -//! from their camera NodeAttribute, or the Model's own properties in FBX 6). - -use std::borrow::Cow; -use std::collections::{HashMap, HashSet}; -use std::io::Read as _; - -use base64::Engine as _; -use texturecraft_geom::glam::{Mat3, Mat4, Vec2, Vec3, Vec4}; - -use super::external::below; -use super::{ - Corner, MAX_MESH_FILE_BYTES, MAX_TEXTURE_BYTES, MAX_ZIP_ENTRIES, PolygonSink, RawBaseColor, RawCamera, RawMesh, check_vertices, lens_fov, zip_entry, -}; +//! FBX scene import through the shared bounded reader. +use super::{Corner, MAX_MESH_FILE_BYTES, MAX_TEXTURE_BYTES, MAX_ZIP_ENTRIES, PolygonSink, RawBaseColor, RawCamera, RawMesh}; use crate::{FormatError, Result, malformed}; - +use texturecraft_geom::glam::{Mat3, Mat4, Vec2, Vec3, Vec4}; const KIND: &str = "FBX"; -const MAGIC: &[u8] = b"Kaydara FBX Binary \0"; -/// A zip package of an FBX and its texture files ([`package`]). -const ZIP_MAGIC: &[u8] = b"PK\x03\x04"; -/// First FBX version with the object/connection layout read here (6.0). -const MIN_VERSION: i64 = 6000; -/// Deepest node nesting (and Model parent chain) followed. -const MAX_DEPTH: usize = 64; -/// Memory budget for parsed nodes and properties (arrays are held as f64). -const MAX_DECODED_BYTES: usize = 1 << 31; -/// Maximum control points transformed across all mesh instances in one import. -const MAX_INSTANCE_POINTS: usize = 200_000_000; -/// Approximate memory charged per node and per scalar property. -const NODE_COST: usize = 96; -const PROP_COST: usize = 32; - -enum Prop { - I(i64), - F(f64), - S(String), - /// Binary data (`R`), such as an embedded image. - Raw(Vec), - Arr(Vec), -} - -impl Prop { - fn num(&self) -> Option { - match self { - Prop::I(v) => Some(*v as f64), - Prop::F(v) => Some(*v), - _ => None, - } - } -} - -struct Node { - name: String, - props: Vec, - children: Vec, -} - -impl Node { - fn child(&self, name: &str) -> Option<&Node> { - self.children.iter().find(|c| c.name == name) - } - - fn all<'a>(&'a self, name: &'a str) -> impl Iterator { - self.children.iter().filter(move |c| c.name == name) - } - - fn int_at(&self, i: usize) -> Option { - match self.props.get(i) { - Some(Prop::I(v)) => Some(*v), - _ => None, - } - } - - /// Object id: the number (7.x) or the `Class::Name` string (6.x). - fn id_at(&self, i: usize) -> Option { - match self.props.get(i) { - Some(Prop::I(v)) => Some(v.to_string()), - Some(Prop::S(s)) if !s.is_empty() => Some(s.clone()), - _ => None, - } - } - - /// An object's name: after its id (7.x) or the id itself (6.x). - fn object_name(&self) -> &str { - clean_name(if self.int_at(0).is_some() { self.str_at(1) } else { self.str_at(0) }) - } - - /// An object's class (`Mesh`, `Camera`, …): after its name. - fn class(&self) -> &str { - self.str_at(if self.int_at(0).is_some() { 2 } else { 1 }) - } - - fn str_at(&self, i: usize) -> &str { - match self.props.get(i) { - Some(Prop::S(s)) => s, - _ => "", - } - } - - fn child_str(&self, name: &str) -> &str { - self.child(name).map_or("", |c| c.str_at(0)) - } - - /// Embedded file bytes of a Video: binary data, or base64 text in ASCII files. - fn content(&self) -> Option> { - let c = self.child("Content")?; - let bytes = match c.props.first()? { - Prop::Raw(b) => b.clone(), - _ => { - let text: String = c.props.iter().filter_map(|p| if let Prop::S(s) = p { Some(s.as_str()) } else { None }).collect(); - base64::engine::general_purpose::STANDARD.decode(text.trim()).ok()? - } - }; - (!bytes.is_empty()).then_some(bytes) - } - - /// Array payload: a binary array, an ASCII `*N { a: ... }` block or a bare value list. - fn arr(&self) -> Cow<'_, [f64]> { - if let Some(Prop::Arr(a)) = self.props.first() { - return Cow::Borrowed(a); - } - if let Some(a) = self.child("a") { - return a.arr(); - } - Cow::Owned(self.props.iter().map(|p| p.num().unwrap_or(f64::NAN)).collect()) - } - - /// The numbers of entry `name` in Properties70 (`P: name, type, subtype, flags, values`) or - /// Properties60 (`Property: name, type, flags, values`). - fn property(&self, name: &str) -> Option> { - let list = self.child("Properties70").or_else(|| self.child("Properties60"))?; - let first_value = if list.name == "Properties70" { 4 } else { 3 }; - list.children.iter().find(|p| p.str_at(0) == name).map(|p| p.props.iter().skip(first_value).map(|v| v.num().unwrap_or(f64::NAN)).collect()) - } - - fn vec3(&self, name: &str, default: Vec3) -> Vec3 { - match self.property(name).as_deref() { - Some([x, y, z, ..]) => Vec3::new(*x as f32, *y as f32, *z as f32), - _ => default, - } - } - - fn number(&self, name: &str) -> Option { - self.property(name)?.first().copied() - } -} - -/// Charges parsed data against [`MAX_DECODED_BYTES`]. -struct Budget(usize); - -impl Budget { - fn charge(&mut self, bytes: usize) -> Result<()> { - self.0 = self.0.checked_sub(bytes).ok_or_else(|| FormatError::TooLarge(format!("the FBX file decodes to more than {MAX_DECODED_BYTES} bytes")))?; - Ok(()) - } -} - -// --------------------------------------------------------------------------------------------- -// Binary. - -struct Binary<'a> { - b: &'a [u8], - pos: usize, - /// 64-bit node records (version 7500 and later). - wide: bool, - budget: Budget, -} - -impl<'a> Binary<'a> { - fn take(&mut self, n: usize) -> Result<&'a [u8]> { - let s = self.pos.checked_add(n).and_then(|end| self.b.get(self.pos..end)).ok_or_else(|| malformed(KIND, "unexpected end of file"))?; - self.pos += n; - Ok(s) - } - - fn bytes(&mut self) -> Result<[u8; N]> { - let mut a = [0u8; N]; - a.copy_from_slice(self.take(N)?); - Ok(a) - } - - fn u32(&mut self) -> Result { - Ok(u32::from_le_bytes(self.bytes()?) as usize) - } - - fn uint(&mut self) -> Result { - Ok(if self.wide { u64::from_le_bytes(self.bytes()?) } else { u32::from_le_bytes(self.bytes()?) as u64 }) - } - - /// The next node ending at or before `limit`, or None at a null record / the end. - fn node(&mut self, limit: usize, depth: usize) -> Result> { - let header = if self.wide { 25 } else { 13 }; - if limit.saturating_sub(self.pos) < header { - return Ok(None); - } - let (end, nprops, plen) = (self.uint()?, self.uint()?, self.uint()?); - let [name_len] = self.bytes()?; - if end == 0 { - return Ok(None); - } - if depth > MAX_DEPTH { - return Err(malformed(KIND, "nodes are nested too deeply")); - } - let end = usize::try_from(end).ok().filter(|e| *e > self.pos && *e <= limit).ok_or_else(|| malformed(KIND, "node end offset out of range"))?; - self.budget.charge(NODE_COST)?; - let name = String::from_utf8_lossy(self.take(name_len as usize)?).into_owned(); - let props_end = usize::try_from(plen).ok().and_then(|p| self.pos.checked_add(p)).filter(|e| *e <= end); - let props_end = props_end.ok_or_else(|| malformed(KIND, format!("properties of \"{name}\" overrun the node")))?; - let mut props = Vec::new(); - for _ in 0..nprops { - if self.pos >= props_end { - return Err(malformed(KIND, format!("\"{name}\" claims more properties than it holds"))); - } - props.push(self.prop()?); - } - if self.pos > props_end { - return Err(malformed(KIND, format!("properties of \"{name}\" overrun their list"))); - } - self.pos = props_end; - let mut children = Vec::new(); - while let Some(c) = self.node(end, depth + 1)? { - children.push(c); - } - self.pos = end; - Ok(Some(Node { name, props, children })) - } - - fn prop(&mut self) -> Result { - self.budget.charge(PROP_COST)?; - let [ty] = self.bytes()?; - Ok(match ty { - b'Y' => Prop::I(i16::from_le_bytes(self.bytes()?) as i64), - b'C' | b'B' => Prop::I(self.bytes::<1>()?[0] as i64), - b'I' => Prop::I(i32::from_le_bytes(self.bytes()?) as i64), - b'L' => Prop::I(i64::from_le_bytes(self.bytes()?)), - b'F' => Prop::F(f32::from_le_bytes(self.bytes()?) as f64), - b'D' => Prop::F(f64::from_le_bytes(self.bytes()?)), - b'S' => { - let n = self.u32()?; - Prop::S(String::from_utf8_lossy(self.take(n)?).into_owned()) - } - b'R' => { - let n = self.u32()?; - self.budget.charge(n)?; - Prop::Raw(self.take(n)?.to_vec()) - } - b'f' | b'd' | b'l' | b'i' | b'b' => Prop::Arr(self.array(ty)?), - other => return Err(malformed(KIND, format!("unknown property type 0x{other:02x}"))), - }) - } - - fn array(&mut self, value_type: u8) -> Result> { - let (count, encoding, stored) = (self.u32()?, self.u32()?, self.u32()?); - let value_bytes = match value_type { - b'd' | b'l' => 8, - b'f' | b'i' => 4, - _ => 1, - }; - let decoded_bytes = count.checked_mul(value_bytes).ok_or_else(|| malformed(KIND, "array too large"))?; - self.budget.charge(count.saturating_mul(8))?; - - let data = self.take(stored)?; - let raw: Cow<[u8]> = match encoding { - 0 if stored == decoded_bytes => Cow::Borrowed(data), - 1 => { - let mut out = Vec::new(); - flate2::read::ZlibDecoder::new(data) - .take(decoded_bytes as u64 + 1) - .read_to_end(&mut out) - .map_err(|e| malformed(KIND, format!("bad compressed array: {e}")))?; - if out.len() != decoded_bytes { - return Err(malformed(KIND, "compressed array has the wrong length")); - } - - Cow::Owned(out) - } - _ => return Err(malformed(KIND, format!("array encoding {encoding} with {stored} bytes for {count} items"))), - }; - - Ok(match value_type { - b'd' => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(*c)).collect(), - b'l' => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(*c) as f64).collect(), - b'f' => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c) as f64).collect(), - b'i' => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(*c) as f64).collect(), - _ => raw.iter().map(|b| *b as f64).collect(), - }) - } -} - -fn parse_binary(b: &[u8]) -> Result<(Vec, i64)> { - let mut r = Binary { b, pos: MAGIC.len(), wide: false, budget: Budget(MAX_DECODED_BYTES) }; - let _reserved: [u8; 2] = r.bytes()?; - let version = u32::from_le_bytes(r.bytes()?); - r.wide = version >= 7500; - let mut nodes = Vec::new(); - while let Some(n) = r.node(b.len(), 0)? { - nodes.push(n); - } - Ok((nodes, version as i64)) -} - -// --------------------------------------------------------------------------------------------- -// ASCII. - -#[derive(Clone, Copy)] -enum Tok<'a> { - /// `name:` - Key(&'a str), - Str(&'a [u8]), - Word(&'a str), - Comma, - Open, - Close, -} - -struct Ascii<'a> { - s: &'a [u8], - pos: usize, - budget: Budget, -} - -impl<'a> Ascii<'a> { - /// The next token and the position after it (the position is not advanced). - fn lex(&self) -> Result, usize)>> { - let mut i = self.pos; - loop { - match self.s.get(i) { - None => return Ok(None), - Some(c) if c.is_ascii_whitespace() => i += 1, - Some(b';') => i += self.s.get(i..).unwrap_or_default().iter().position(|c| *c == b'\n').unwrap_or(self.s.len() - i), - Some(_) => break, - } - } - let rest = self.s.get(i..).unwrap_or_default(); - Ok(Some(match rest.first() { - Some(b',') => (Tok::Comma, i + 1), - Some(b'{') => (Tok::Open, i + 1), - Some(b'}') => (Tok::Close, i + 1), - Some(b'"') => { - let len = rest.get(1..).unwrap_or_default().iter().position(|c| *c == b'"').ok_or_else(|| malformed(KIND, "unterminated string"))?; - (Tok::Str(rest.get(1..1 + len).unwrap_or_default()), i + len + 2) - } - _ => { - let len = rest.iter().position(|c| c.is_ascii_whitespace() || b",{}\":;".contains(c)).unwrap_or(rest.len()); - if len == 0 { - return Err(malformed(KIND, format!("unexpected character at byte {i}"))); - } - let word = std::str::from_utf8(rest.get(..len).unwrap_or_default()).map_err(|_| malformed(KIND, "text is not UTF-8"))?; - if rest.get(len) == Some(&b':') { (Tok::Key(word), i + len + 1) } else { (Tok::Word(word), i + len) } - } - })) - } - - /// Nodes until `}` (left for the caller) or the end. - fn nodes(&mut self, depth: usize) -> Result> { - if depth > MAX_DEPTH { - return Err(malformed(KIND, "nodes are nested too deeply")); - } - let mut out = Vec::new(); - while let Some((tok, after)) = self.lex()? { - match tok { - Tok::Close => break, - Tok::Key(name) => { - self.pos = after; - out.push(self.node(name, depth)?); - } - _ => return Err(malformed(KIND, format!("expected a property name at byte {}", self.pos))), - } - } - Ok(out) - } - - fn node(&mut self, name: &str, depth: usize) -> Result { - self.budget.charge(NODE_COST)?; - let mut props = Vec::new(); - // An empty first value (`Content: , "..."`). - if let Some((Tok::Comma, after)) = self.lex()? { - self.pos = after; - } - while let Some((tok, after)) = self.lex()? { - let prop = match tok { - Tok::Str(s) => Some(Prop::S(String::from_utf8_lossy(s).into_owned())), - // `*N` announces an array's length. - Tok::Word(w) if w.starts_with('*') => None, - Tok::Word(w) => Some(w.parse::().map(Prop::I).or_else(|_| w.parse::().map(Prop::F)).unwrap_or_else(|_| Prop::S(w.to_string()))), - _ => break, - }; - self.pos = after; - if let Some(p) = prop { - self.budget.charge(PROP_COST)?; - props.push(p); - } - match self.lex()? { - Some((Tok::Comma, after)) => self.pos = after, - _ => break, - } - } - let mut children = Vec::new(); - if let Some((Tok::Open, after)) = self.lex()? { - self.pos = after; - children = self.nodes(depth + 1)?; - match self.lex()? { - Some((Tok::Close, after)) => self.pos = after, - _ => return Err(malformed(KIND, format!("\"{name}\" is missing its closing brace"))), - } - } - // Long value lists (arrays) are stored compactly. - if props.len() > 1 && props.iter().all(|p| p.num().is_some()) { - props = vec![Prop::Arr(props.iter().filter_map(Prop::num).collect())]; - } - Ok(Node { name: name.to_string(), props, children }) - } -} - -fn parse_ascii(s: &[u8]) -> Result<(Vec, i64)> { - let mut a = Ascii { s, pos: 0, budget: Budget(MAX_DECODED_BYTES) }; - let nodes = a.nodes(0)?; - if a.lex()?.is_some() { - return Err(malformed(KIND, "unbalanced closing brace")); - } - let version = nodes.iter().find(|n| n.name == "FBXHeaderExtension").and_then(|h| h.child("FBXVersion")).and_then(|v| v.int_at(0)); - let version = version.ok_or_else(|| malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)"))?; - Ok((nodes, version)) -} - -// --------------------------------------------------------------------------------------------- -// Scene. - -/// The bytes of the first of a texture's candidate file paths (relative to the FBX's folder) -/// that exists. type Files<'a> = dyn FnMut(&[&str]) -> Option> + 'a; - -/// An FBX, or a package of one and its texture files. -pub(crate) fn read(bytes: &[u8]) -> Result { - if !bytes.starts_with(ZIP_MAGIC) { - return crate::guard(KIND, || read_inner(bytes, &mut |_| None)); +fn limits() -> craft_mesh::Limits { + craft_mesh::Limits { + max_vertices: super::MAX_VERTICES, + max_triangles: texturecraft_geom::MAX_TRIANGLES, + max_data_bytes: 1 << 31, + max_extras: 100_000, + ..Default::default() } +} + +fn package_limits() -> craft_mesh::fbx::package::PackageLimits { + craft_mesh::fbx::package::PackageLimits { + max_entries: MAX_ZIP_ENTRIES as u64, + max_model_bytes: MAX_MESH_FILE_BYTES, + max_texture_bytes: MAX_TEXTURE_BYTES, + max_total_bytes: MAX_MESH_FILE_BYTES, + } +} + +fn convert(e: craft_mesh::Error) -> FormatError { + match e { + craft_mesh::Error::TooLarge(s) => FormatError::TooLarge(s), + craft_mesh::Error::Unsupported(s) => FormatError::Unsupported(s), + e => FormatError::Invalid(e.to_string()), + } +} + +pub(crate) fn read(bytes: &[u8]) -> Result { crate::guard(KIND, || { - let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| malformed(KIND, format!("FBX package: {e}")))?; - if zip.len() > MAX_ZIP_ENTRIES { - return Err(FormatError::TooLarge(format!("the FBX package has more than {MAX_ZIP_ENTRIES} entries"))); + if !craft_mesh::fbx::package::is_package(bytes) { + return read_inner(bytes, &mut |_| None); } - let name = zip.file_names().flatten().filter(|n| super::extension(n) == "fbx").min_by_key(|n| zip.index_for_name(n)).map(Cow::into_owned); - let name = name.ok_or_else(|| malformed(KIND, "the package contains no FBX file"))?; - let fbx = zip_entry(&mut zip, &name, MAX_MESH_FILE_BYTES) - .ok_or_else(|| FormatError::TooLarge("the packaged FBX is unreadable or larger than 2 GiB".into()))?; - if fbx.starts_with(ZIP_MAGIC) { - return Err(malformed(KIND, "the package holds another package")); - } - read_inner(&fbx, &mut |paths| paths.iter().find_map(|p| zip_entry(&mut zip, &below(p)?, MAX_TEXTURE_BYTES))) + let mut package = craft_mesh::fbx::package::Package::open(bytes, package_limits()).map_err(convert)?; + let fbx = package.model().map_err(convert)?; + read_inner(&fbx, &mut |paths| package.texture(paths)) }) } -/// An FBX whose base color textures are files, as a package holding it (first) and the files -/// `found` has, under their paths below its folder; None when it found none (or `bytes` is a -/// package already). Also the texture paths it could not find. pub(crate) fn package(file_name: &str, bytes: &[u8], found: &mut dyn FnMut(&str) -> Option>) -> Result<(Option>, Vec)> { - if bytes.starts_with(ZIP_MAGIC) { + if craft_mesh::fbx::package::is_package(bytes) { return Ok((None, Vec::new())); } crate::guard(KIND, || { - let (mut files, mut missing): (Vec<(String, Vec)>, Vec) = (Vec::new(), Vec::new()); - read_inner(bytes, &mut |paths| { - if let Some((_, data)) = files.iter().find(|(n, _)| paths.iter().any(|p| below(p).as_ref() == Some(n))) { - return Some(data.clone()); - } - for p in paths { - if let (Some(name), Some(data)) = (below(p), found(p).filter(|d| d.len() as u64 <= MAX_TEXTURE_BYTES)) { - files.push((name, data.clone())); - return Some(data); - } - } - // A texture is missing when none of its paths was found; named by its first. - if let Some(first) = paths.first().filter(|f| !missing.iter().any(|m| m == *f)) { - missing.push(first.to_string()); - } - None - })?; - if files.is_empty() { - return Ok((None, missing)); + let limits = limits(); + let doc = craft_mesh::fbx::read_document(bytes, &limits).map_err(convert)?; + if doc.version == 0 { + return Err(malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)")); } - let total = files.iter().fold(bytes.len() as u64, |t, (_, d)| t.saturating_add(d.len() as u64)); - if total > MAX_MESH_FILE_BYTES { - return Err(FormatError::TooLarge("the FBX and its textures exceed 2 GiB".into())); - } - let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("mesh.fbx"); - Ok((Some(crate::mesh_export::usd::usdz(leaf, bytes, &files)?), missing)) + doc.scene_with_options(&limits, &mut craft_mesh::no_external, &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true }).map_err(convert)?; + craft_mesh::fbx::package::write(&doc, file_name, bytes, &limits, package_limits(), found).map_err(convert) }) } fn read_inner(bytes: &[u8], files: &mut Files) -> Result { - let (nodes, version) = if bytes.starts_with(MAGIC) { parse_binary(bytes)? } else { parse_ascii(bytes)? }; - if version < MIN_VERSION { - return Err(FormatError::Unsupported(format!("FBX version {version} (re-export as FBX 2006 / 6.1 or newer)"))); + let limits = limits(); + let doc = craft_mesh::fbx::read_document(bytes, &limits).map_err(convert)?; + if doc.version == 0 { + return Err(malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)")); } - let root = |name: &str| nodes.iter().find(|n| n.name == name); - let objects = root("Objects").ok_or_else(|| malformed(KIND, "the file has no Objects"))?; - let (mut geometries, mut models, mut materials) = (HashMap::new(), HashMap::new(), HashMap::new()); - let (mut textures, mut videos, mut attributes) = (HashMap::new(), HashMap::new(), HashMap::new()); - // (geometry, model) instances; an FBX 6 Model holds its geometry itself. - let mut instances: Vec<(String, Option)> = Vec::new(); - for o in &objects.children { - let Some(id) = o.id_at(0) else { continue }; - match o.name.as_str() { - "Geometry" if o.child("Vertices").is_some() => geometries.insert(id, o), - "Model" => { - if o.child("Vertices").is_some() { - geometries.insert(id.clone(), o); - instances.push((id.clone(), Some(id.clone()))); - } - models.insert(id, o) - } - "Material" => materials.insert(id, o), - "Texture" => textures.insert(id, o), - "Video" => videos.insert(id, o), - "NodeAttribute" => attributes.insert(id, o), - _ => None, - }; - } - // Model parents, and each Model's materials in slot order. - let mut parents: HashMap = HashMap::new(); - let mut slots: HashMap> = HashMap::new(); - let mut attribute_of: HashMap = HashMap::new(); - let connections: Vec<&Node> = root("Connections").into_iter().flat_map(|c| c.all("C").chain(c.all("Connect"))).collect(); - for c in &connections { - let (Some(child), Some(parent)) = (c.id_at(1), c.id_at(2)) else { continue }; - if c.str_at(0) != "OO" || child == parent || !models.contains_key(&parent) { - continue; - } - if models.contains_key(&child) { - parents.insert(child, parent); - } else if geometries.contains_key(&child) { - instances.push((child, Some(parent))); - } else if let Some(m) = materials.get(&child) { - slots.entry(parent).or_default().push(material_name(&child, m)); - } else if let Some(a) = attributes.get(&child) { - attribute_of.insert(parent, *a); - } - } - // Repeated connections describe the same instance; keep distinct model placements in order. - let mut seen_instances = HashSet::new(); - instances.retain(|instance| seen_instances.insert(instance.clone())); - let placed: HashSet<&String> = instances.iter().map(|(g, _)| g).collect(); - let mut unplaced: Vec = geometries.keys().filter(|g| !placed.contains(g)).cloned().collect(); - unplaced.sort_unstable(); - instances.extend(unplaced.into_iter().map(|g| (g, None))); - - let base_colors = base_colors(&materials, &textures, &videos, &connections, files); - let global = global_transform(root("GlobalSettings").or_else(|| objects.child("GlobalSettings"))); + let colors = doc.diffuse_materials(&limits, files).map_err(convert)?; + let scene = + doc.scene_with_options(&limits, &mut craft_mesh::no_external, &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true }).map_err(convert)?; + let to_mat = |m: craft_mesh::Mat4| Mat4::from_cols_array(&m.map(|v| v as f32)); + let global = to_mat(doc.axes_to_y_up()) * Mat4::from_scale(Vec3::splat((doc.unit_scale().unwrap_or(1.0) / 100.0) as f32)); let mut sink = PolygonSink::default(); - let mut remaining_points = MAX_INSTANCE_POINTS; - let no_slots = Vec::new(); - for (geom, model) in instances { - let Some(g) = geometries.get(&geom) else { continue }; - let m = match model.as_ref().and_then(|m| models.get(m).map(|n| (m, n))) { - Some((id, node)) => { - sink.part = node.object_name().to_string(); - world(&models, &parents, id)? * geometric(node) + let mut cameras = Vec::new(); + let mut stack: Vec<_> = scene.roots.iter().rev().map(|i| (*i, global, String::new(), 0usize)).collect(); + let mut visited = 0usize; + let mut points = 0usize; + while let Some((id, parent, inherited, depth)) = stack.pop() { + visited += 1; + if visited > limits.max_nodes || depth > limits.max_depth { + return Err(FormatError::TooLarge("FBX hierarchy exceeds its traversal limit".into())); + } + let node = scene.nodes.get(id).ok_or_else(|| malformed(KIND, "node index out of range"))?; + let world = parent * to_mat(node.transform); + let part = if node.name.ends_with(" geometry") { inherited } else { node.name.clone() }; + for child in node.children.iter().rev() { + stack.push((*child, world, part.clone(), depth + 1)); + } + if let Some(index) = node.camera { + if cameras.len() < super::MAX_CAMERAS { + if let Some(camera) = scene.cameras.get(index) { + let (fov, ortho) = match camera.projection { + craft_mesh::Projection::Perspective { yfov, .. } => (yfov.to_degrees() as f32, None), + craft_mesh::Projection::Orthographic { ymag, .. } => (40.0, Some(ymag as f32)), + }; + cameras.push(RawCamera::placed(camera.name.clone(), world, Vec3::NEG_Z, fov, ortho)); + } } - None => { - sink.part.clear(); - Mat4::IDENTITY + } + let Some(index) = node.mesh else { continue }; + let mesh = scene.meshes.get(index).ok_or_else(|| malformed(KIND, "mesh index out of range"))?; + points = points.checked_add(mesh.positions.len()).ok_or_else(|| FormatError::TooLarge("FBX instance work overflow".into()))?; + if points > 200_000_000 { + return Err(FormatError::TooLarge("FBX instances exceed the 200000000 control-point work limit".into())); + } + let normal_transform = Mat3::from_mat4(world).inverse().transpose(); + let flip = world.determinant() < 0.0; + sink.part = part; + for group in &mesh.parts { + let material = group.material.and_then(|m| scene.materials.get(m)).map_or("Default", |m| m.name.as_str()); + for face in group.faces() { + let mut corners = Vec::with_capacity(face.len()); + for c in face { + let p = mesh.positions.get(c.position as usize).ok_or_else(|| malformed(KIND, "position index out of range"))?; + let p = world.transform_point3(Vec3::new(p[0] as f32, p[1] as f32, p[2] as f32)); + let n = mesh.normals.get(c.normal as usize).map(|n| normal_transform * Vec3::new(n[0] as f32, n[1] as f32, n[2] as f32)); + let uv = mesh.uv_sets.first().and_then(|set| set.get(c.uv as usize)).map(|v| Vec2::new(v[0], v[1])); + let color = mesh.colors.get(c.position as usize).copied().map(Vec4::from_array); + corners.push(Corner { p, n, uv, color }); + } + if flip { + corners.reverse(); + } + sink.polygon(material, &corners)?; } - }; - let names = model.as_ref().and_then(|m| slots.get(m)).unwrap_or(&no_slots); - add_geometry(&mut sink, g, global * m, names, &mut remaining_points)?; + } + } + if visited < scene.nodes.len() { + return Err(malformed(KIND, "cycle in model hierarchy")); + } + for warning in scene.warnings { + sink.warn(warning); } let mut raw = sink.finish(); - raw.base_colors = base_colors; - // In file order; FBX 6's built-in "Producer" views are not the scene's cameras. - for o in objects.children.iter().filter(|o| o.name == "Model" && o.class() == "Camera" && !o.object_name().starts_with("Producer ")) { - if raw.cameras.len() >= super::MAX_CAMERAS { - break; - } - let Some(id) = o.id_at(0) else { continue }; - if let Ok(m) = world(&models, &parents, &id) { - raw.cameras.push(camera(o, attribute_of.get(&id).copied().unwrap_or(o), global * m)); - } - } + raw.cameras = cameras; + raw.base_colors = colors.into_iter().map(|c| RawBaseColor { material: c.name, factor: Vec4::from_array(c.factor), image: c.image }).collect(); Ok(raw) } - -/// A camera Model at `m` with its lens in `lens`: FBX cameras look down +X with +Y up. The -/// vertical field of view comes from the focal length (mm) over the film height (inches). -/// shortcut: `OrthoZoom` is taken as the orthographic half view height in scene units; check it -/// against an exporter's orthographic camera when one is at hand. -fn camera(model: &Node, lens: &Node, m: Mat4) -> RawCamera { - let num = |k: &str| lens.number(k).map(|v| v as f32).filter(|v| v.is_finite() && *v > 0.0); - let fov = match num("FocalLength") { - Some(f) => lens_fov(f, num("FilmHeight").unwrap_or(0.612) * 25.4), - None => num("FieldOfViewY").or_else(|| num("FieldOfView")).unwrap_or(40.0), - }; - let ortho = (lens.number("CameraProjectionType") == Some(1.0)).then(|| num("OrthoZoom").unwrap_or(1.0)); - RawCamera::placed(model.object_name().to_string(), m, Vec3::X, fov, ortho) -} - -/// A material's name in the mesh: its object name, or `Material_` when it has none. -fn material_name(id: &str, m: &Node) -> String { - let name = m.object_name(); - if name.is_empty() { format!("Material_{id}") } else { name.to_string() } -} - -/// Preserve material colors independently of textures for ID baking -fn base_colors( - materials: &HashMap, - textures: &HashMap, - videos: &HashMap, - connections: &[&Node], - files: &mut Files, -) -> Vec { - // Texture → its Video, material → its diffuse texture (a property connection wins). - let (mut video_of, mut diffuse) = (HashMap::new(), HashMap::new()); - for c in connections { - let (Some(child), Some(parent)) = (c.id_at(1), c.id_at(2)) else { continue }; - if videos.contains_key(&child) && textures.contains_key(&parent) { - video_of.insert(parent, child); - } else if textures.contains_key(&child) && materials.contains_key(&parent) { - match (c.str_at(0), c.str_at(3)) { - ("OP", "DiffuseColor" | "Maya|baseColor") => { - diffuse.insert(parent, child); - } - ("OO", _) => { - diffuse.entry(parent).or_insert(child); - } - _ => {} - } - } - } - let mut out: Vec = materials - .iter() - .filter_map(|(id, m)| { - let texture = diffuse.get(id); - let (video, tex) = (texture.and_then(|t| video_of.get(t)).and_then(|v| videos.get(v)), texture.and_then(|t| textures.get(t))); - // Embedded content first, then the file the texture (or its video) names. - let image = video.or(tex).and_then(|n| n.content()).or_else(|| [tex, video].into_iter().flatten().find_map(|n| texture_file(n, files))); - let diffuse_color = m.property("DiffuseColor"); - let factor = match diffuse_color.as_deref() { - Some([r, g, b, ..]) => { - let f = m.number("DiffuseFactor").unwrap_or(1.0); - Vec4::new((r * f) as f32, (g * f) as f32, (b * f) as f32, 1.0) - } - _ => Vec4::ONE, - }; - (factor.is_finite() && (image.is_some() || diffuse_color.is_some())).then(|| RawBaseColor { material: material_name(id, m), factor, image }) - }) - .collect(); - out.sort_by(|a, b| a.material.cmp(&b.material)); - out -} - -/// The file a Texture or Video names: its relative path, else its absolute path's file name -/// (looked for in the FBX's folder). -fn texture_file(n: &Node, files: &mut Files) -> Option> { - let relative = n.child_str("RelativeFilename"); - let absolute = [n.child_str("FileName"), n.child_str("Filename")].into_iter().find(|s| !s.is_empty()).unwrap_or_default(); - let leaf = absolute.rsplit(['/', '\\']).next().unwrap_or_default(); - let mut paths: Vec<&str> = Vec::new(); - for p in [relative, leaf] { - if !p.is_empty() && !paths.contains(&p) { - paths.push(p); - } - } - if paths.is_empty() { None } else { files(&paths) } -} - -/// `Name\0\1Class` (binary) or `Class::Name` (ASCII) to `Name`. -fn clean_name(s: &str) -> &str { - match s.split_once("\u{0}\u{1}") { - Some((name, _)) => name, - None => s.split_once("::").map_or(s, |(_, name)| name), - } -} - -/// Unit scale to meters and the file's axis system to Y up (+Z front, +X right). -fn global_transform(settings: Option<&Node>) -> Mat4 { - let get = |name: &str, default: f64| settings.and_then(|s| s.number(name)).filter(|v| v.is_finite()).unwrap_or(default); - let unit = get("UnitScaleFactor", 1.0); - let unit = if unit > 0.0 { unit / 100.0 } else { 0.01 }; - let axis = |a: &str, s: &str, default: f64| (get(a, default) as i64, if get(s, 1.0) < 0.0 { -1.0 } else { 1.0 }); - let [(right, rs), (up, us), (front, fs)] = - [axis("CoordAxis", "CoordAxisSign", 0.0), axis("UpAxis", "UpAxisSign", 1.0), axis("FrontAxis", "FrontAxisSign", 2.0)]; - let basis = |a: i64| [Vec3::X, Vec3::Y, Vec3::Z].get(a as usize).copied().filter(|_| a >= 0); - let rows = match (basis(right), basis(up), basis(front)) { - (Some(r), Some(u), Some(f)) if r.cross(u).dot(f).abs() > 0.5 => Mat3::from_cols(r * rs, u * us, f * fs).transpose(), - _ => Mat3::IDENTITY, - }; - Mat4::from_mat3(rows) * Mat4::from_scale(Vec3::splat(unit as f32)) -} - -/// Euler rotation in degrees, `order` as FBX RotationOrder (0 = XYZ: X applied first). -fn euler(deg: Vec3, order: i64) -> Mat4 { - use Vec3 as V; - let axes = match order { - 1 => [V::X, V::Z, V::Y], - 2 => [V::Y, V::Z, V::X], - 3 => [V::Y, V::X, V::Z], - 4 => [V::Z, V::X, V::Y], - 5 => [V::Z, V::Y, V::X], - _ => [V::X, V::Y, V::Z], - }; - axes.iter().fold(Mat4::IDENTITY, |m, a| Mat4::from_axis_angle(*a, deg.dot(*a).to_radians()) * m) -} - -/// A Model's local transform: T · Roff · Rp · Rpre · R · Rpost⁻¹ · Rp⁻¹ · Soff · Sp · S · Sp⁻¹. -fn local(m: &Node) -> Mat4 { - let t = |name: &str| Mat4::from_translation(m.vec3(name, Vec3::ZERO)); - let order = m.number("RotationOrder").unwrap_or(0.0) as i64; - let (rp, sp) = (m.vec3("RotationPivot", Vec3::ZERO), m.vec3("ScalingPivot", Vec3::ZERO)); - t("Lcl Translation") - * t("RotationOffset") - * Mat4::from_translation(rp) - * euler(m.vec3("PreRotation", Vec3::ZERO), 0) - * euler(m.vec3("Lcl Rotation", Vec3::ZERO), order) - * euler(m.vec3("PostRotation", Vec3::ZERO), 0).inverse() - * Mat4::from_translation(-rp) - * t("ScalingOffset") - * Mat4::from_translation(sp) - * Mat4::from_scale(m.vec3("Lcl Scaling", Vec3::ONE)) - * Mat4::from_translation(-sp) -} - -/// The geometry offset of a Model (not inherited by its children). -fn geometric(m: &Node) -> Mat4 { - Mat4::from_translation(m.vec3("GeometricTranslation", Vec3::ZERO)) - * euler(m.vec3("GeometricRotation", Vec3::ZERO), 0) - * Mat4::from_scale(m.vec3("GeometricScaling", Vec3::ONE)) -} - -fn world(models: &HashMap, parents: &HashMap, id: &str) -> Result { - let mut m = Mat4::IDENTITY; - let mut cur = Some(id); - for _ in 0..=MAX_DEPTH { - let Some(node) = cur.and_then(|c| models.get(c)) else { return Ok(m) }; - m = local(node) * m; - cur = cur.and_then(|c| parents.get(c)).map(String::as_str); - } - Err(malformed(KIND, "the Model hierarchy is nested too deeply (or cyclic)")) -} - -#[derive(Clone, Copy)] -enum Mapping { - PolygonVertex, - ControlPoint, - Polygon, - AllSame, -} - -/// One LayerElement's items, optionally through an index array. -struct Layer<'a> { - mapping: Mapping, - data: Cow<'a, [f64]>, - index: Option>, -} - -impl Layer<'_> { - /// Element `index` names the index array (empty: the data is never indexed). - fn read<'a>(geom: &'a Node, element: &str, data: &str, index: &str) -> Option> { - let el = geom.children.iter().filter(|c| c.name == element).min_by_key(|e| e.int_at(0) != Some(0))?; - let mapping = match el.child_str("MappingInformationType") { - "ByPolygonVertex" => Mapping::PolygonVertex, - "ByVertice" | "ByVertex" | "ByControlPoint" => Mapping::ControlPoint, - "ByPolygon" => Mapping::Polygon, - "AllSame" => Mapping::AllSame, - _ => return None, - }; - let indexed = !index.is_empty() && matches!(el.child_str("ReferenceInformationType"), "IndexToDirect" | "Index"); - let index = if indexed { Some(el.child(index)?.arr()) } else { None }; - Some(Layer { mapping, data: el.child(data)?.arr(), index }) - } - - /// The `W` numbers of polygon vertex `k` (control point `cp`, polygon `poly`). - fn get(&self, k: usize, cp: usize, poly: usize) -> Option<[f64; W]> { - let i = match self.mapping { - Mapping::PolygonVertex => k, - Mapping::ControlPoint => cp, - Mapping::Polygon => poly, - Mapping::AllSame => 0, - }; - let i = match &self.index { - Some(ix) => Some(*ix.get(i)?).filter(|v| *v >= 0.0)? as usize, - None => i, - }; - let start = i.checked_mul(W)?; - self.data.get(start..start.checked_add(W)?)?.try_into().ok() - } -} - -fn add_geometry(sink: &mut PolygonSink, geometry: &Node, transform: Mat4, slots: &[String], remaining_points: &mut usize) -> Result<()> { - let vertices = geometry.child("Vertices").map(Node::arr).unwrap_or_default(); - check_vertices(vertices.len() / 3)?; - *remaining_points = remaining_points - .checked_sub(vertices.len() / 3) - .ok_or_else(|| FormatError::TooLarge(format!("FBX instances exceed the {MAX_INSTANCE_POINTS} control-point work limit")))?; - let points: Vec = vertices.as_chunks::<3>().0.iter().map(|c| transform.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect(); - let polygon_indices = geometry.child("PolygonVertexIndex").map(Node::arr).unwrap_or_default(); - let normals = Layer::read(geometry, "LayerElementNormal", "Normals", "NormalsIndex"); - let uvs = Layer::read(geometry, "LayerElementUV", "UV", "UVIndex"); - let colors = Layer::read(geometry, "LayerElementColor", "Colors", "ColorIndex"); - let materials = Layer::read(geometry, "LayerElementMaterial", "Materials", ""); - if vertices.iter().chain(polygon_indices.iter()).any(|v| !v.is_finite()) - || [&normals, &uvs, &colors, &materials] - .into_iter() - .flatten() - .any(|layer| layer.data.iter().any(|v| !v.is_finite()) || layer.index.as_ref().is_some_and(|index| index.iter().any(|v| !v.is_finite()))) - { - return Err(malformed(KIND, "mesh array contains a non-numeric or non-finite value")); - } - let normal_transform = Mat3::from_mat4(transform).inverse().transpose(); - let flip = transform.determinant() < 0.0; - let (mut corners, mut polygon_index, mut bad_normals, mut bad_uvs) = (Vec::new(), 0usize, 0usize, 0usize); - - for (k, &v) in polygon_indices.iter().enumerate() { - // The last corner of each polygon is stored as -(index + 1) - let (control_point, last) = if v < 0.0 { (-v - 1.0, true) } else { (v, false) }; - let p = points - .get(control_point as usize) - .filter(|_| control_point.fract() == 0.0) - .ok_or_else(|| malformed(KIND, format!("polygon vertex index {v} out of range")))?; - let control_point = control_point as usize; - let n = normals.as_ref().and_then(|l| { - let n = l.get(k, control_point, polygon_index).map(|[x, y, z]| normal_transform * Vec3::new(x as f32, y as f32, z as f32)); - bad_normals += usize::from(n.is_none()); - n - }); - - // A UV layer with holes keeps its layout: missing items read as 0, 0 - let uv = uvs.as_ref().map(|l| match l.get(k, control_point, polygon_index) { - Some([u, v]) => Vec2::new(u as f32, 1.0 - v as f32), - None => { - bad_uvs += 1; - Vec2::ZERO - } - }); - // FBX color layers hold one RGBA value per item. - let color = - colors.as_ref().and_then(|l| l.get::<4>(k, control_point, polygon_index)).map(|[r, g, b, a]| Vec4::new(r as f32, g as f32, b as f32, a as f32)); - corners.push(Corner { p: *p, n, uv, color }); - if last || k + 1 == polygon_indices.len() { - if flip { - corners.reverse(); - } - let slot = materials.as_ref().and_then(|l| l.get(polygon_index, polygon_index, polygon_index)).map_or(0.0, |[s]| s); - let name = slots.get(slot as usize).filter(|_| slot >= 0.0).map_or("Default", String::as_str); - sink.polygon(name, &corners)?; - corners.clear(); - polygon_index += 1; - } - } - - if bad_normals > 0 { - sink.warn(format!("{bad_normals} polygon corners have no normal in the FBX normal layer; normals were recomputed")); - } - if bad_uvs > 0 { - sink.warn(format!("{bad_uvs} polygon corners have no UV in the FBX UV layer (set to 0, 0)")); - } - - Ok(()) -} - -#[cfg(test)] -mod instance_budget_tests { - use super::*; - - #[test] - fn ascii_array_keeps_invalid_values_in_place() { - let (nodes, _) = parse_ascii( - br#"FBXHeaderExtension: { FBXVersion: 7400 } -Vertices: 1, 1.#INF, 3, "x", 5 -"#, - ) - .unwrap(); - let values = nodes[1].arr(); - assert_eq!(values.len(), 5); - assert!(values[1].is_nan() && values[3].is_nan()); - assert_eq!((values[0], values[2], values[4]), (1.0, 3.0, 5.0)); - } - - #[test] - fn ascii_bad_vertex_is_rejected() { - let (nodes, _) = parse_ascii( - br#"FBXHeaderExtension: { FBXVersion: 7400 } -Geometry: { Vertices: 0, 0, 0, 1, -1.#IND, 0, 0, 1, 0 -PolygonVertexIndex: 0, 1, -3 } -"#, - ) - .unwrap(); - let mut remaining = usize::MAX; - let result = add_geometry(&mut PolygonSink::default(), &nodes[1], Mat4::IDENTITY, &[], &mut remaining); - assert!(result.is_err()); - } - - #[test] - fn ascii_bad_index_and_uv_are_rejected() { - for payload in [ - "PolygonVertexIndex: 0, oops, -3", - "PolygonVertexIndex: 0, 1, -3\nLayerElementUV: 0 { MappingInformationType: \"ByPolygonVertex\"\nReferenceInformationType: \"Direct\"\nUV: 0, 0, oops, 1, 1, 0 }", - ] { - let source = format!("FBXHeaderExtension: {{ FBXVersion: 7400 }}\nGeometry: {{ Vertices: 0, 0, 0, 1, 0, 0, 0, 1, 0\n{payload} }}"); - let (nodes, _) = parse_ascii(source.as_bytes()).unwrap(); - let mut remaining = usize::MAX; - assert!(add_geometry(&mut PolygonSink::default(), &nodes[1], Mat4::IDENTITY, &[], &mut remaining).is_err()); - } - } - - #[test] - fn ascii_transform_metadata_does_not_shift_values() { - let (nodes, _) = parse_ascii( - br#"FBXHeaderExtension: { FBXVersion: 7400 } -Model: { Properties70: { P: "Lcl Translation", "Lcl Translation", "", "A", 1, 2, 3 } } -"#, - ) - .unwrap(); - assert_eq!(nodes[1].property("Lcl Translation"), Some(vec![1.0, 2.0, 3.0])); - let (nodes, _) = parse_ascii( - br#"FBXHeaderExtension: { FBXVersion: 7400 } -Model: { Properties60: { Property: "Lcl Translation", "Lcl Translation", "A", 1, 2, 3 } } -"#, - ) - .unwrap(); - assert_eq!(nodes[1].property("Lcl Translation"), Some(vec![1.0, 2.0, 3.0])); - } - - #[test] - fn malformed_transform_value_keeps_its_position_in_both_property_formats() { - for (list, entry) in [ - ("Properties70", "P: \"Lcl Translation\", \"Lcl Translation\", \"\", \"A\", 1, oops, 3"), - ("Properties60", "Property: \"Lcl Translation\", \"Lcl Translation\", \"A\", 1, oops, 3"), - ] { - let source = format!("FBXHeaderExtension: {{ FBXVersion: 7400 }}\nModel: {{ {list}: {{ {entry} }} }}"); - let (nodes, _) = parse_ascii(source.as_bytes()).unwrap(); - let values = nodes[1].property("Lcl Translation").unwrap(); - assert_eq!(values.len(), 3); - assert_eq!((values[0], values[2]), (1.0, 3.0)); - assert!(values[1].is_nan()); - } - } - - #[test] - fn instance_points_are_charged_before_transforming_each_copy() { - let geometry = Node { - name: "Geometry".into(), - props: vec![], - children: vec![Node { name: "Vertices".into(), props: vec![Prop::Arr(vec![0.0; 9])], children: vec![] }], - }; - let mut sink = PolygonSink::default(); - let mut remaining = 5; - add_geometry(&mut sink, &geometry, Mat4::IDENTITY, &[], &mut remaining).unwrap(); - assert_eq!(remaining, 2); - assert!(matches!(add_geometry(&mut sink, &geometry, Mat4::IDENTITY, &[], &mut remaining), Err(FormatError::TooLarge(_)))); - assert_eq!(remaining, 2); - } -} From a5fb695381e22c07935e2aca3c5b336d70fce32f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:38:53 +0000 Subject: [PATCH 03/18] Preserve strict FBX geometry behavior --- Cargo.lock | 6 +++--- Cargo.toml | 2 +- crates/formats/src/mesh_import/fbx.rs | 13 ++++++++++--- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b27f7dac..e94d4e44 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -842,9 +842,9 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=543098150ffc09914b662e61053d8cddf239bbe6#543098150ffc09914b662e61053d8cddf239bbe6" +source = "git+https://github.com/storytold/craft-libs?rev=4a84c00372972fb99755cba34978a5e73387c3f0#4a84c00372972fb99755cba34978a5e73387c3f0" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=543098150ffc09914b662e61053d8cddf239bbe6)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=4a84c00372972fb99755cba34978a5e73387c3f0)", "miniz_oxide 0.9.1", ] @@ -931,7 +931,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=543098150ffc09914b662e61053d8cddf239bbe6#543098150ffc09914b662e61053d8cddf239bbe6" +source = "git+https://github.com/storytold/craft-libs?rev=4a84c00372972fb99755cba34978a5e73387c3f0#4a84c00372972fb99755cba34978a5e73387c3f0" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 3a263a6c..a4a3231c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "543098150ffc09914b662e61053d8cddf239bbe6", default-features = false, features = ["stl", "fbx"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "4a84c00372972fb99755cba34978a5e73387c3f0", default-features = false, features = ["stl", "fbx"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 8faf623c..7b9fb643 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -8,6 +8,11 @@ fn limits() -> craft_mesh::Limits { craft_mesh::Limits { max_vertices: super::MAX_VERTICES, max_triangles: texturecraft_geom::MAX_TRIANGLES, + max_face_corners: super::MAX_VERTICES, + max_meshes: super::MAX_VERTICES, + max_parts: super::MAX_VERTICES, + max_materials: super::MAX_VERTICES, + max_nodes: super::MAX_VERTICES, max_data_bytes: 1 << 31, max_extras: 100_000, ..Default::default() @@ -52,7 +57,8 @@ pub(crate) fn package(file_name: &str, bytes: &[u8], found: &mut dyn FnMut(&str) if doc.version == 0 { return Err(malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)")); } - doc.scene_with_options(&limits, &mut craft_mesh::no_external, &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true }).map_err(convert)?; + doc.scene_with_options(&limits, &mut craft_mesh::no_external, &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true }) + .map_err(convert)?; craft_mesh::fbx::package::write(&doc, file_name, bytes, &limits, package_limits(), found).map_err(convert) }) } @@ -64,8 +70,9 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { return Err(malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)")); } let colors = doc.diffuse_materials(&limits, files).map_err(convert)?; - let scene = - doc.scene_with_options(&limits, &mut craft_mesh::no_external, &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true }).map_err(convert)?; + let scene = doc + .scene_with_options(&limits, &mut craft_mesh::no_external, &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true }) + .map_err(convert)?; let to_mat = |m: craft_mesh::Mat4| Mat4::from_cols_array(&m.map(|v| v as f32)); let global = to_mat(doc.axes_to_y_up()) * Mat4::from_scale(Vec3::splat((doc.unit_scale().unwrap_or(1.0) / 100.0) as f32)); let mut sink = PolygonSink::default(); From 8d593fdebec93c9b5ff8468aa17cad6f97aaa47b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:39:42 +0000 Subject: [PATCH 04/18] Keep FBX UV layers with missing corners --- crates/formats/src/mesh_import/fbx.rs | 46 ++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 7b9fb643..897ebd99 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -111,6 +111,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { let normal_transform = Mat3::from_mat4(world).inverse().transpose(); let flip = world.determinant() < 0.0; sink.part = part; + let (mut bad_normals, mut bad_uvs) = (0usize, 0usize); for group in &mesh.parts { let material = group.material.and_then(|m| scene.materials.get(m)).map_or("Default", |m| m.name.as_str()); for face in group.faces() { @@ -119,7 +120,16 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { let p = mesh.positions.get(c.position as usize).ok_or_else(|| malformed(KIND, "position index out of range"))?; let p = world.transform_point3(Vec3::new(p[0] as f32, p[1] as f32, p[2] as f32)); let n = mesh.normals.get(c.normal as usize).map(|n| normal_transform * Vec3::new(n[0] as f32, n[1] as f32, n[2] as f32)); - let uv = mesh.uv_sets.first().and_then(|set| set.get(c.uv as usize)).map(|v| Vec2::new(v[0], v[1])); + if !mesh.normals.is_empty() && n.is_none() { + bad_normals += 1; + } + let uv = mesh.uv_sets.first().map(|set| match set.get(c.uv as usize) { + Some(v) => Vec2::new(v[0], v[1]), + None => { + bad_uvs += 1; + Vec2::ZERO + } + }); let color = mesh.colors.get(c.position as usize).copied().map(Vec4::from_array); corners.push(Corner { p, n, uv, color }); } @@ -129,6 +139,12 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { sink.polygon(material, &corners)?; } } + if bad_normals > 0 { + sink.warn(format!("{bad_normals} polygon corners have no normal in the FBX normal layer; normals were recomputed")); + } + if bad_uvs > 0 { + sink.warn(format!("{bad_uvs} polygon corners have no UV in the FBX UV layer (set to 0, 0)")); + } } if visited < scene.nodes.len() { return Err(malformed(KIND, "cycle in model hierarchy")); @@ -141,3 +157,31 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { raw.base_colors = colors.into_iter().map(|c| RawBaseColor { material: c.name, factor: Vec4::from_array(c.factor), image: c.image }).collect(); Ok(raw) } + +#[cfg(test)] +mod tests { + #[test] + fn incomplete_uv_layer_keeps_other_uvs() { + let bytes = br#"FBXHeaderExtension: { FBXVersion: 7400 } +Objects: { + Geometry: 1, "Geometry::G", "Mesh" { + Vertices: 0,0,0,1,0,0,0,1,0 + PolygonVertexIndex: 0,1,-3 + LayerElementUV: 0 { + MappingInformationType: "ByPolygonVertex" + ReferenceInformationType: "IndexToDirect" + UV: 0.25,0.5, 0.75,0.5 + UVIndex: 0,1 + } + } + Model: 2, "Model::M", "Mesh" {} +} +Connections: { C: "OO",1,2 } +"#; + let raw = super::read(bytes).unwrap(); + let uvs = raw.uvs.unwrap(); + assert!(uvs.contains(&texturecraft_geom::glam::Vec2::new(0.25, 0.5))); + assert!(uvs.contains(&texturecraft_geom::glam::Vec2::ZERO)); + assert!(raw.warnings.iter().any(|w| w.contains("1 polygon corners have no UV"))); + } +} From 5a70a033cc6cd9e7ea6959db5218a1bf2e6e5959 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:41:48 +0000 Subject: [PATCH 05/18] Use strict shared FBX record parsing --- Cargo.lock | 6 +++--- Cargo.toml | 2 +- crates/formats/src/mesh_import/fbx.rs | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e94d4e44..63ba1709 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -842,9 +842,9 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4a84c00372972fb99755cba34978a5e73387c3f0#4a84c00372972fb99755cba34978a5e73387c3f0" +source = "git+https://github.com/storytold/craft-libs?rev=17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f#17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=4a84c00372972fb99755cba34978a5e73387c3f0)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f)", "miniz_oxide 0.9.1", ] @@ -931,7 +931,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=4a84c00372972fb99755cba34978a5e73387c3f0#4a84c00372972fb99755cba34978a5e73387c3f0" +source = "git+https://github.com/storytold/craft-libs?rev=17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f#17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index a4a3231c..c6f1dcfc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "4a84c00372972fb99755cba34978a5e73387c3f0", default-features = false, features = ["stl", "fbx"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f", default-features = false, features = ["stl", "fbx"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 897ebd99..0c9d707f 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -53,7 +53,7 @@ pub(crate) fn package(file_name: &str, bytes: &[u8], found: &mut dyn FnMut(&str) } crate::guard(KIND, || { let limits = limits(); - let doc = craft_mesh::fbx::read_document(bytes, &limits).map_err(convert)?; + let doc = craft_mesh::fbx::read_document_strict(bytes, &limits).map_err(convert)?; if doc.version == 0 { return Err(malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)")); } @@ -65,7 +65,7 @@ pub(crate) fn package(file_name: &str, bytes: &[u8], found: &mut dyn FnMut(&str) fn read_inner(bytes: &[u8], files: &mut Files) -> Result { let limits = limits(); - let doc = craft_mesh::fbx::read_document(bytes, &limits).map_err(convert)?; + let doc = craft_mesh::fbx::read_document_strict(bytes, &limits).map_err(convert)?; if doc.version == 0 { return Err(malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)")); } From cf85d478a29dc646e92a9b05a00d0c708f1159f7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:42:20 +0000 Subject: [PATCH 06/18] Keep FBX cameras in file order --- crates/formats/src/mesh_import/fbx.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 0c9d707f..470cf433 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -77,6 +77,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { let global = to_mat(doc.axes_to_y_up()) * Mat4::from_scale(Vec3::splat((doc.unit_scale().unwrap_or(1.0) / 100.0) as f32)); let mut sink = PolygonSink::default(); let mut cameras = Vec::new(); + cameras.resize_with(scene.cameras.len().min(super::MAX_CAMERAS), || None); let mut stack: Vec<_> = scene.roots.iter().rev().map(|i| (*i, global, String::new(), 0usize)).collect(); let mut visited = 0usize; let mut points = 0usize; @@ -87,19 +88,17 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { } let node = scene.nodes.get(id).ok_or_else(|| malformed(KIND, "node index out of range"))?; let world = parent * to_mat(node.transform); - let part = if node.name.ends_with(" geometry") { inherited } else { node.name.clone() }; + let part = if node.name == format!("{inherited} geometry") { inherited } else { node.name.clone() }; for child in node.children.iter().rev() { stack.push((*child, world, part.clone(), depth + 1)); } if let Some(index) = node.camera { - if cameras.len() < super::MAX_CAMERAS { - if let Some(camera) = scene.cameras.get(index) { - let (fov, ortho) = match camera.projection { - craft_mesh::Projection::Perspective { yfov, .. } => (yfov.to_degrees() as f32, None), - craft_mesh::Projection::Orthographic { ymag, .. } => (40.0, Some(ymag as f32)), - }; - cameras.push(RawCamera::placed(camera.name.clone(), world, Vec3::NEG_Z, fov, ortho)); - } + if let (Some(camera), Some(slot)) = (scene.cameras.get(index), cameras.get_mut(index)) { + let (fov, ortho) = match camera.projection { + craft_mesh::Projection::Perspective { yfov, .. } => (yfov.to_degrees() as f32, None), + craft_mesh::Projection::Orthographic { ymag, .. } => (40.0, Some(ymag as f32)), + }; + *slot = Some(RawCamera::placed(camera.name.clone(), world, Vec3::NEG_Z, fov, ortho)); } } let Some(index) = node.mesh else { continue }; @@ -153,7 +152,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { sink.warn(warning); } let mut raw = sink.finish(); - raw.cameras = cameras; + raw.cameras = cameras.into_iter().flatten().collect(); raw.base_colors = colors.into_iter().map(|c| RawBaseColor { material: c.name, factor: Vec4::from_array(c.factor), image: c.image }).collect(); Ok(raw) } From f22c9d31a5eb8dc27bbbc761a7ec7271df0269c8 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:44:07 +0000 Subject: [PATCH 07/18] Preserve FBX parent connection precedence --- Cargo.lock | 8 ++++---- Cargo.toml | 2 +- crates/formats/src/mesh_import/fbx.rs | 14 +++++++++++--- 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 63ba1709..3de76013 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -842,9 +842,9 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f#17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f" +source = "git+https://github.com/storytold/craft-libs?rev=f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc#f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc)", "miniz_oxide 0.9.1", ] @@ -931,7 +931,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f#17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f" +source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" dependencies = [ "flate2", "thiserror 2.0.21", @@ -941,7 +941,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" +source = "git+https://github.com/storytold/craft-libs?rev=f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc#f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index c6f1dcfc..88363c22 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "17e18e31c29fb8c4bf56bb7242ff9dcdb3d3a66f", default-features = false, features = ["stl", "fbx"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc", default-features = false, features = ["stl", "fbx"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 470cf433..d63cf89a 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -57,8 +57,12 @@ pub(crate) fn package(file_name: &str, bytes: &[u8], found: &mut dyn FnMut(&str) if doc.version == 0 { return Err(malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)")); } - doc.scene_with_options(&limits, &mut craft_mesh::no_external, &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true }) - .map_err(convert)?; + doc.scene_with_options( + &limits, + &mut craft_mesh::no_external, + &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true, prefer_last_parent: true }, + ) + .map_err(convert)?; craft_mesh::fbx::package::write(&doc, file_name, bytes, &limits, package_limits(), found).map_err(convert) }) } @@ -71,7 +75,11 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { } let colors = doc.diffuse_materials(&limits, files).map_err(convert)?; let scene = doc - .scene_with_options(&limits, &mut craft_mesh::no_external, &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true }) + .scene_with_options( + &limits, + &mut craft_mesh::no_external, + &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true, prefer_last_parent: true }, + ) .map_err(convert)?; let to_mat = |m: craft_mesh::Mat4| Mat4::from_cols_array(&m.map(|v| v as f32)); let global = to_mat(doc.axes_to_y_up()) * Mat4::from_scale(Vec3::splat((doc.unit_scale().unwrap_or(1.0) / 100.0) as f32)); From fa817f859210c6e42d6384b964a945801301d8be Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:46:16 +0000 Subject: [PATCH 08/18] Preserve FBX material slot behavior --- Cargo.lock | 6 +++--- Cargo.toml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3de76013..e457fa9e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -842,9 +842,9 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc#f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc" +source = "git+https://github.com/storytold/craft-libs?rev=e91ff8718535fa2c963f2442fcc6de4a9eaada12#e91ff8718535fa2c963f2442fcc6de4a9eaada12" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e91ff8718535fa2c963f2442fcc6de4a9eaada12)", "miniz_oxide 0.9.1", ] @@ -941,7 +941,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc#f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc" +source = "git+https://github.com/storytold/craft-libs?rev=e91ff8718535fa2c963f2442fcc6de4a9eaada12#e91ff8718535fa2c963f2442fcc6de4a9eaada12" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 88363c22..a8cbab52 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "f4edcdcad9ce138dc6bf36e8214b4844c0cf8fbc", default-features = false, features = ["stl", "fbx"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "e91ff8718535fa2c963f2442fcc6de4a9eaada12", default-features = false, features = ["stl", "fbx"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). From 4b0621384eb4b710cd58bc55be7f72370287b753 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:48:50 +0000 Subject: [PATCH 09/18] Bound shared binary FBX allocations --- Cargo.lock | 6 +++--- Cargo.toml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e457fa9e..cf520318 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -842,9 +842,9 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e91ff8718535fa2c963f2442fcc6de4a9eaada12#e91ff8718535fa2c963f2442fcc6de4a9eaada12" +source = "git+https://github.com/storytold/craft-libs?rev=fd97d5b1fe1c28c11dc57ad411b38d30065711df#fd97d5b1fe1c28c11dc57ad411b38d30065711df" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e91ff8718535fa2c963f2442fcc6de4a9eaada12)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fd97d5b1fe1c28c11dc57ad411b38d30065711df)", "miniz_oxide 0.9.1", ] @@ -941,7 +941,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e91ff8718535fa2c963f2442fcc6de4a9eaada12#e91ff8718535fa2c963f2442fcc6de4a9eaada12" +source = "git+https://github.com/storytold/craft-libs?rev=fd97d5b1fe1c28c11dc57ad411b38d30065711df#fd97d5b1fe1c28c11dc57ad411b38d30065711df" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index a8cbab52..021f9c80 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "e91ff8718535fa2c963f2442fcc6de4a9eaada12", default-features = false, features = ["stl", "fbx"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "fd97d5b1fe1c28c11dc57ad411b38d30065711df", default-features = false, features = ["stl", "fbx"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). From 48885c910f3a5ded9d7cc5f163d0ba8b75d7dd1a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:49:20 +0000 Subject: [PATCH 10/18] Ignore unused cyclic FBX models --- crates/formats/src/mesh_import/fbx.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index d63cf89a..7c65bf50 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -87,6 +87,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { let mut cameras = Vec::new(); cameras.resize_with(scene.cameras.len().min(super::MAX_CAMERAS), || None); let mut stack: Vec<_> = scene.roots.iter().rev().map(|i| (*i, global, String::new(), 0usize)).collect(); + let mut reached = vec![false; scene.nodes.len()]; let mut visited = 0usize; let mut points = 0usize; while let Some((id, parent, inherited, depth)) = stack.pop() { @@ -95,6 +96,9 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { return Err(FormatError::TooLarge("FBX hierarchy exceeds its traversal limit".into())); } let node = scene.nodes.get(id).ok_or_else(|| malformed(KIND, "node index out of range"))?; + if let Some(seen) = reached.get_mut(id) { + *seen = true; + } let world = parent * to_mat(node.transform); let part = if node.name == format!("{inherited} geometry") { inherited } else { node.name.clone() }; for child in node.children.iter().rev() { @@ -153,7 +157,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { sink.warn(format!("{bad_uvs} polygon corners have no UV in the FBX UV layer (set to 0, 0)")); } } - if visited < scene.nodes.len() { + if scene.nodes.iter().enumerate().any(|(i, node)| node.mesh.is_some() && !reached.get(i).copied().unwrap_or(false)) { return Err(malformed(KIND, "cycle in model hierarchy")); } for warning in scene.warnings { From b6115309aa0cc2a29a07c226f296a9e644aacf5d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:51:13 +0000 Subject: [PATCH 11/18] Preserve FBX object connection handling --- Cargo.lock | 8 ++++---- Cargo.toml | 2 +- crates/formats/src/mesh_import/fbx.rs | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cf520318..7d5b1adb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -842,9 +842,9 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=fd97d5b1fe1c28c11dc57ad411b38d30065711df#fd97d5b1fe1c28c11dc57ad411b38d30065711df" +source = "git+https://github.com/storytold/craft-libs?rev=1ef59f89052096ad20353635258ef00177962c12#1ef59f89052096ad20353635258ef00177962c12" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=fd97d5b1fe1c28c11dc57ad411b38d30065711df)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1ef59f89052096ad20353635258ef00177962c12)", "miniz_oxide 0.9.1", ] @@ -931,7 +931,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" +source = "git+https://github.com/storytold/craft-libs?rev=1ef59f89052096ad20353635258ef00177962c12#1ef59f89052096ad20353635258ef00177962c12" dependencies = [ "flate2", "thiserror 2.0.21", @@ -941,7 +941,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=fd97d5b1fe1c28c11dc57ad411b38d30065711df#fd97d5b1fe1c28c11dc57ad411b38d30065711df" +source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 021f9c80..acc6c6a3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "fd97d5b1fe1c28c11dc57ad411b38d30065711df", default-features = false, features = ["stl", "fbx"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "1ef59f89052096ad20353635258ef00177962c12", default-features = false, features = ["stl", "fbx"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 7c65bf50..9763af2c 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -60,7 +60,7 @@ pub(crate) fn package(file_name: &str, bytes: &[u8], found: &mut dyn FnMut(&str) doc.scene_with_options( &limits, &mut craft_mesh::no_external, - &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true, prefer_last_parent: true }, + &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true, prefer_last_parent: true, only_object_connections: true }, ) .map_err(convert)?; craft_mesh::fbx::package::write(&doc, file_name, bytes, &limits, package_limits(), found).map_err(convert) @@ -78,7 +78,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { .scene_with_options( &limits, &mut craft_mesh::no_external, - &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true, prefer_last_parent: true }, + &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true, prefer_last_parent: true, only_object_connections: true }, ) .map_err(convert)?; let to_mat = |m: craft_mesh::Mat4| Mat4::from_cols_array(&m.map(|v| v as f32)); From 9fa832274acb219e52254ac9e44ffee152ddc22a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:55:20 +0000 Subject: [PATCH 12/18] Adopt FBX integration lint fixes --- Cargo.lock | 8 ++++---- Cargo.toml | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7d5b1adb..88c4e71c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -842,9 +842,9 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1ef59f89052096ad20353635258ef00177962c12#1ef59f89052096ad20353635258ef00177962c12" +source = "git+https://github.com/storytold/craft-libs?rev=afea2ec3c56b14dccf3d006bbad47592d85b0232#afea2ec3c56b14dccf3d006bbad47592d85b0232" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=1ef59f89052096ad20353635258ef00177962c12)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=afea2ec3c56b14dccf3d006bbad47592d85b0232)", "miniz_oxide 0.9.1", ] @@ -931,7 +931,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1ef59f89052096ad20353635258ef00177962c12#1ef59f89052096ad20353635258ef00177962c12" +source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" dependencies = [ "flate2", "thiserror 2.0.21", @@ -941,7 +941,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" +source = "git+https://github.com/storytold/craft-libs?rev=afea2ec3c56b14dccf3d006bbad47592d85b0232#afea2ec3c56b14dccf3d006bbad47592d85b0232" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index acc6c6a3..0792af3b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "1ef59f89052096ad20353635258ef00177962c12", default-features = false, features = ["stl", "fbx"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "afea2ec3c56b14dccf3d006bbad47592d85b0232", default-features = false, features = ["stl", "fbx"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). From e6c149cbd6cba6db35497e11fe35bf10dda05833 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:56:07 +0000 Subject: [PATCH 13/18] Simplify shared FBX camera selection --- crates/formats/src/mesh_import/fbx.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 9763af2c..890dfccb 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -104,14 +104,14 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { for child in node.children.iter().rev() { stack.push((*child, world, part.clone(), depth + 1)); } - if let Some(index) = node.camera { - if let (Some(camera), Some(slot)) = (scene.cameras.get(index), cameras.get_mut(index)) { - let (fov, ortho) = match camera.projection { - craft_mesh::Projection::Perspective { yfov, .. } => (yfov.to_degrees() as f32, None), - craft_mesh::Projection::Orthographic { ymag, .. } => (40.0, Some(ymag as f32)), - }; - *slot = Some(RawCamera::placed(camera.name.clone(), world, Vec3::NEG_Z, fov, ortho)); - } + if let Some(index) = node.camera + && let (Some(camera), Some(slot)) = (scene.cameras.get(index), cameras.get_mut(index)) + { + let (fov, ortho) = match camera.projection { + craft_mesh::Projection::Perspective { yfov, .. } => (yfov.to_degrees() as f32, None), + craft_mesh::Projection::Orthographic { ymag, .. } => (40.0, Some(ymag as f32)), + }; + *slot = Some(RawCamera::placed(camera.name.clone(), world, Vec3::NEG_Z, fov, ortho)); } let Some(index) = node.mesh else { continue }; let mesh = scene.meshes.get(index).ok_or_else(|| malformed(KIND, "mesh index out of range"))?; From e2ff5144cd65e72415c4a28d62ad620765672c93 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 18:58:03 +0000 Subject: [PATCH 14/18] Bound FBX color seam staging --- Cargo.lock | 8 ++++---- Cargo.toml | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 88c4e71c..fa9af7d8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -842,9 +842,9 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=afea2ec3c56b14dccf3d006bbad47592d85b0232#afea2ec3c56b14dccf3d006bbad47592d85b0232" +source = "git+https://github.com/storytold/craft-libs?rev=0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1#0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=afea2ec3c56b14dccf3d006bbad47592d85b0232)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1)", "miniz_oxide 0.9.1", ] @@ -931,7 +931,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" +source = "git+https://github.com/storytold/craft-libs?rev=0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1#0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1" dependencies = [ "flate2", "thiserror 2.0.21", @@ -941,7 +941,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=afea2ec3c56b14dccf3d006bbad47592d85b0232#afea2ec3c56b14dccf3d006bbad47592d85b0232" +source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 0792af3b..a34b9a78 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "afea2ec3c56b14dccf3d006bbad47592d85b0232", default-features = false, features = ["stl", "fbx"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1", default-features = false, features = ["stl", "fbx"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). From 59a7c022a1bcd32d18d87528ef3fdfef7edfcd15 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 19:01:11 +0000 Subject: [PATCH 15/18] Bound FBX hierarchy traversal memory --- crates/formats/src/mesh_import/fbx.rs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 890dfccb..7db5d789 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -86,7 +86,9 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { let mut sink = PolygonSink::default(); let mut cameras = Vec::new(); cameras.resize_with(scene.cameras.len().min(super::MAX_CAMERAS), || None); - let mut stack: Vec<_> = scene.roots.iter().rev().map(|i| (*i, global, String::new(), 0usize)).collect(); + // Keep parent indices rather than copying names into every pending child: a hostile + // hierarchy may fan one very long model name out to many children. + let mut stack: Vec<_> = scene.roots.iter().rev().map(|i| (*i, global, None::, 0usize)).collect(); let mut reached = vec![false; scene.nodes.len()]; let mut visited = 0usize; let mut points = 0usize; @@ -100,9 +102,14 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { *seen = true; } let world = parent * to_mat(node.transform); - let part = if node.name == format!("{inherited} geometry") { inherited } else { node.name.clone() }; + let parent_name = inherited.and_then(|i| scene.nodes.get(i)).map_or("", |n| n.name.as_str()); + let synthetic = node.mesh.is_some() && node.name.strip_suffix(" geometry") == Some(parent_name); + let next_parent = if synthetic { inherited } else { Some(id) }; for child in node.children.iter().rev() { - stack.push((*child, world, part.clone(), depth + 1)); + if stack.len() >= limits.max_data_bytes / std::mem::size_of::<(usize, Mat4, Option, usize)>() { + return Err(FormatError::TooLarge("FBX hierarchy exceeds its memory limit".into())); + } + stack.push((*child, world, next_parent, depth + 1)); } if let Some(index) = node.camera && let (Some(camera), Some(slot)) = (scene.cameras.get(index), cameras.get_mut(index)) @@ -121,7 +128,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { } let normal_transform = Mat3::from_mat4(world).inverse().transpose(); let flip = world.determinant() < 0.0; - sink.part = part; + sink.part = if synthetic { parent_name.to_string() } else { node.name.clone() }; let (mut bad_normals, mut bad_uvs) = (0usize, 0usize); for group in &mesh.parts { let material = group.material.and_then(|m| scene.materials.get(m)).map_or("Default", |m| m.name.as_str()); From 12168ad47537ff5fbd55e56fe757de66f62c5970 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 19:01:25 +0000 Subject: [PATCH 16/18] Bound FBX root traversal allocation --- crates/formats/src/mesh_import/fbx.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 7db5d789..ab8248ea 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -88,6 +88,10 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { cameras.resize_with(scene.cameras.len().min(super::MAX_CAMERAS), || None); // Keep parent indices rather than copying names into every pending child: a hostile // hierarchy may fan one very long model name out to many children. + let stack_limit = limits.max_data_bytes / std::mem::size_of::<(usize, Mat4, Option, usize)>(); + if scene.roots.len() > stack_limit { + return Err(FormatError::TooLarge("FBX hierarchy exceeds its memory limit".into())); + } let mut stack: Vec<_> = scene.roots.iter().rev().map(|i| (*i, global, None::, 0usize)).collect(); let mut reached = vec![false; scene.nodes.len()]; let mut visited = 0usize; @@ -106,7 +110,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { let synthetic = node.mesh.is_some() && node.name.strip_suffix(" geometry") == Some(parent_name); let next_parent = if synthetic { inherited } else { Some(id) }; for child in node.children.iter().rev() { - if stack.len() >= limits.max_data_bytes / std::mem::size_of::<(usize, Mat4, Option, usize)>() { + if stack.len() >= stack_limit { return Err(FormatError::TooLarge("FBX hierarchy exceeds its memory limit".into())); } stack.push((*child, world, next_parent, depth + 1)); From da1e2df96da227cfb9fb0684107219720c45f78c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 19:02:01 +0000 Subject: [PATCH 17/18] Keep root FBX model names --- crates/formats/src/mesh_import/fbx.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index ab8248ea..e8fbee03 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -107,7 +107,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { } let world = parent * to_mat(node.transform); let parent_name = inherited.and_then(|i| scene.nodes.get(i)).map_or("", |n| n.name.as_str()); - let synthetic = node.mesh.is_some() && node.name.strip_suffix(" geometry") == Some(parent_name); + let synthetic = inherited.is_some() && node.mesh.is_some() && node.name.strip_suffix(" geometry") == Some(parent_name); let next_parent = if synthetic { inherited } else { Some(id) }; for child in node.children.iter().rev() { if stack.len() >= stack_limit { From b81a54228fda4fa3fbe5485658ed87b2c6b9f27f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 19:10:16 +0000 Subject: [PATCH 18/18] Preserve FBX placement and polygon order --- Cargo.lock | 8 +++--- Cargo.toml | 2 +- crates/formats/src/mesh_import/fbx.rs | 40 ++++++++++++++------------- 3 files changed, 26 insertions(+), 24 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fa9af7d8..3cf85cc8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -842,9 +842,9 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1#0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1" +source = "git+https://github.com/storytold/craft-libs?rev=d0abb8772cd5e33ae4e2174e4a1760ede822466a#d0abb8772cd5e33ae4e2174e4a1760ede822466a" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d0abb8772cd5e33ae4e2174e4a1760ede822466a)", "miniz_oxide 0.9.1", ] @@ -931,7 +931,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1#0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1" +source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" dependencies = [ "flate2", "thiserror 2.0.21", @@ -941,7 +941,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=828b07f3c9f3f6a2e935087b859016a5e46b1c31#828b07f3c9f3f6a2e935087b859016a5e46b1c31" +source = "git+https://github.com/storytold/craft-libs?rev=d0abb8772cd5e33ae4e2174e4a1760ede822466a#d0abb8772cd5e33ae4e2174e4a1760ede822466a" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index a34b9a78..e30b64aa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -69,7 +69,7 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } -craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "0a7bab2bed0d1bb1a752a3c9ef65aeeb2a09c8f1", default-features = false, features = ["stl", "fbx"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d0abb8772cd5e33ae4e2174e4a1760ede822466a", default-features = false, features = ["stl", "fbx"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "828b07f3c9f3f6a2e935087b859016a5e46b1c31" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index e8fbee03..58a01aea 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -74,8 +74,8 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { return Err(malformed(KIND, "not an FBX file (no FBXHeaderExtension / FBXVersion)")); } let colors = doc.diffuse_materials(&limits, files).map_err(convert)?; - let scene = doc - .scene_with_options( + let (scene, placements) = doc + .scene_with_placements( &limits, &mut craft_mesh::no_external, &craft_mesh::fbx::SceneOptions { apply_inactive_rotation: true, strict_geometry: true, prefer_last_parent: true, only_object_connections: true }, @@ -86,34 +86,34 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { let mut sink = PolygonSink::default(); let mut cameras = Vec::new(); cameras.resize_with(scene.cameras.len().min(super::MAX_CAMERAS), || None); - // Keep parent indices rather than copying names into every pending child: a hostile - // hierarchy may fan one very long model name out to many children. - let stack_limit = limits.max_data_bytes / std::mem::size_of::<(usize, Mat4, Option, usize)>(); + // Bound the stored world matrices and pending node indices together: neither depends on + // copying model names, even when a hierarchy fans out widely. + let placement_bytes = + scene.nodes.len().checked_mul(std::mem::size_of::>()).ok_or_else(|| FormatError::TooLarge("FBX hierarchy size overflow".into()))?; + let remaining = limits.max_data_bytes.checked_sub(placement_bytes).ok_or_else(|| FormatError::TooLarge("FBX hierarchy exceeds its memory limit".into()))?; + let stack_limit = remaining / std::mem::size_of::<(usize, Mat4, usize)>(); if scene.roots.len() > stack_limit { return Err(FormatError::TooLarge("FBX hierarchy exceeds its memory limit".into())); } - let mut stack: Vec<_> = scene.roots.iter().rev().map(|i| (*i, global, None::, 0usize)).collect(); - let mut reached = vec![false; scene.nodes.len()]; + let mut stack: Vec<_> = scene.roots.iter().rev().map(|i| (*i, global, 0usize)).collect(); + let mut worlds = vec![None; scene.nodes.len()]; let mut visited = 0usize; let mut points = 0usize; - while let Some((id, parent, inherited, depth)) = stack.pop() { + while let Some((id, parent, depth)) = stack.pop() { visited += 1; if visited > limits.max_nodes || depth > limits.max_depth { return Err(FormatError::TooLarge("FBX hierarchy exceeds its traversal limit".into())); } let node = scene.nodes.get(id).ok_or_else(|| malformed(KIND, "node index out of range"))?; - if let Some(seen) = reached.get_mut(id) { - *seen = true; - } let world = parent * to_mat(node.transform); - let parent_name = inherited.and_then(|i| scene.nodes.get(i)).map_or("", |n| n.name.as_str()); - let synthetic = inherited.is_some() && node.mesh.is_some() && node.name.strip_suffix(" geometry") == Some(parent_name); - let next_parent = if synthetic { inherited } else { Some(id) }; + if let Some(slot) = worlds.get_mut(id) { + *slot = Some(world); + } for child in node.children.iter().rev() { if stack.len() >= stack_limit { return Err(FormatError::TooLarge("FBX hierarchy exceeds its memory limit".into())); } - stack.push((*child, world, next_parent, depth + 1)); + stack.push((*child, world, depth + 1)); } if let Some(index) = node.camera && let (Some(camera), Some(slot)) = (scene.cameras.get(index), cameras.get_mut(index)) @@ -124,6 +124,11 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { }; *slot = Some(RawCamera::placed(camera.name.clone(), world, Vec3::NEG_Z, fov, ortho)); } + } + for placement in placements { + let id = placement.node; + let node = scene.nodes.get(id).ok_or_else(|| malformed(KIND, "placement index out of range"))?; + let world = worlds.get(id).copied().flatten().ok_or_else(|| malformed(KIND, "cycle in model hierarchy"))?; let Some(index) = node.mesh else { continue }; let mesh = scene.meshes.get(index).ok_or_else(|| malformed(KIND, "mesh index out of range"))?; points = points.checked_add(mesh.positions.len()).ok_or_else(|| FormatError::TooLarge("FBX instance work overflow".into()))?; @@ -132,7 +137,7 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { } let normal_transform = Mat3::from_mat4(world).inverse().transpose(); let flip = world.determinant() < 0.0; - sink.part = if synthetic { parent_name.to_string() } else { node.name.clone() }; + sink.part = placement.model.and_then(|i| scene.nodes.get(i)).map_or_else(String::new, |n| n.name.clone()); let (mut bad_normals, mut bad_uvs) = (0usize, 0usize); for group in &mesh.parts { let material = group.material.and_then(|m| scene.materials.get(m)).map_or("Default", |m| m.name.as_str()); @@ -168,9 +173,6 @@ fn read_inner(bytes: &[u8], files: &mut Files) -> Result { sink.warn(format!("{bad_uvs} polygon corners have no UV in the FBX UV layer (set to 0, 0)")); } } - if scene.nodes.iter().enumerate().any(|(i, node)| node.mesh.is_some() && !reached.get(i).copied().unwrap_or(false)) { - return Err(malformed(KIND, "cycle in model hierarchy")); - } for warning in scene.warnings { sink.warn(warning); }