diff --git a/crates/mesh/Cargo.toml b/crates/mesh/Cargo.toml index 17519cb07e..6a0d7d0294 100644 --- a/crates/mesh/Cargo.toml +++ b/crates/mesh/Cargo.toml @@ -15,14 +15,15 @@ default = ["stl", "obj", "ply", "gltf", "fbx", "threemf"] stl = [] obj = [] ply = [] -gltf = ["dep:serde_json"] +gltf = [] fbx = ["dep:miniz_oxide", "dep:craft-zip"] threemf = ["dep:craft-opc", "dep:craft-xml"] dae = ["dep:craft-xml"] abc = [] [dependencies] -serde_json = { workspace = true, optional = true } +# glTF reading and writing, and the `extensions` and `extras` values in the model. +serde_json = { workspace = true } # zlib-compressed arrays in binary FBX. miniz_oxide = { version = "0.9", optional = true } craft-zip = { workspace = true, optional = true } diff --git a/crates/mesh/README.md b/crates/mesh/README.md index 5d77168fc4..6bd635e646 100644 --- a/crates/mesh/README.md +++ b/crates/mesh/README.md @@ -8,7 +8,7 @@ a `Scene` into bytes. One Cargo feature per format, all on by default. | `stl` | STL, binary and ASCII | yes | binary and ASCII | none | | `obj` | Wavefront OBJ with MTL | yes | OBJ and MTL | none | | `ply` | PLY, ASCII and both binary byte orders | yes | no (no app writes PLY) | none | -| `gltf` | glTF 2.0 (`.gltf`) and GLB | yes | GLB | `serde_json` | +| `gltf` | glTF 2.0 (`.gltf`) and GLB | yes | GLB | `serde_json` (a dependency with every feature) | | `threemf` | 3MF, core and materials extension | yes | no | `craft-opc`, `craft-xml` | | `fbx` | FBX 6.x and 7.x, binary and ASCII | yes | no | `miniz_oxide` | | `dae` | COLLADA (`.dae`), scenes, transforms, cameras | yes | no | `craft-xml` | @@ -22,7 +22,11 @@ USD is not here yet. `lights`, plus `external` (every other file the file names) and `warnings` (what was left out or repaired). - `Mesh`: a name, attribute pools (`positions` and `normals` as `f64`, `uv_sets`, per-position - `colors`, `joints` and `weights`) and `parts`. + `colors`, `joints` and `weights`) and `parts`, and glTF morph targets (`morph_targets`, each a + name and position, normal and tangent offsets, with their default `morph_weights`). +- glTF's `extensions` and `extras` of the file, nodes, meshes and materials are kept on + `Scene`, `Node`, `Mesh` and `Material` as `serde_json` values (re-exported as + `craft_mesh::serde_json`), whole, the ones the reader also reads into the model included. - `Part`: the faces of a mesh that share a group name, a material and a smoothing group. A face is a polygon of three or more `Corner`s; each corner indexes a position and optionally a normal and a UV. Formats with separate indices (OBJ) are kept exactly, and polygons stay whole. @@ -84,8 +88,10 @@ texture slots, UV set, sampler wrap modes and `KHR_texture_transform`, `KHR_mate `KHR_materials_unlit`, `KHR_materials_pbrSpecularGlossiness` (diffuse colour and texture, no metal, roughness from the glossiness); textures whose image is in `EXT_texture_webp`; images embedded in a buffer view or a `data:` URI, or named; skins; translation, rotation and scale animations; -cameras; `KHR_lights_punctual`. Primitives of a mesh that name the same accessors share their -vertices. `write_glb` writes nodes, meshes (positions, normals, UV sets, colours), materials with +cameras; `KHR_lights_punctual`; morph targets (POSITION, NORMAL and TANGENT offsets, dense or +sparse, with the mesh's default `weights`, a node's own `weights` and names from +`extras.targetNames`). Primitives of a mesh that name the same accessors and morph targets share +their vertices. `write_glb` writes nodes, meshes (positions, normals, UV sets, colours), materials with their texture transforms and sampler wrap modes, and images; `write_glb_with_options` also writes each sampler's `magFilter` and `minFilter` when its `GlbWriteOptions` set them. The other formats' writers do not write texture transforms. @@ -115,10 +121,12 @@ FBX 6.x files (a `Model` holds its mesh, `Properties60`, objects connected by na geometry, transforms, the hierarchy and materials. Not read: FBX 5 and older, 6.x textures, animation, skin deformers, blend shapes, cameras, lights, NURBS. -Not read (glTF): required geometry extensions (Draco, meshopt) are `Error::Unsupported`. Points, -lines and morph targets are left out and counted in a warning; scenes other than the default are -named in one; other extensions are passed over. -Not written: skins, animations, cameras, lights, and `.gltf` with separate files. +Not read (glTF): required geometry extensions (Draco, meshopt) are `Error::Unsupported`. Points +and lines are left out and counted in a warning, as are the morph targets of a mesh with more than +`max_morph_targets`; scenes other than the default are named in one; animations of morph target +weights are passed over. +Not written: skins, morph targets, animations, cameras, lights, kept `extensions` and `extras`, +and `.gltf` with separate files. ## Hostile input @@ -137,8 +145,9 @@ mutations of every byte of good files. | `max_materials` | 100 000 | materials; images; OBJ material libraries; 3MF base materials and textures together | | `max_nodes` | 100 000 | nodes, and node visits when the hierarchy is walked (ends cycles); 3MF placed objects, build items and components | | `max_depth` | 64 | node nesting; 3MF component nesting (ends cycles) | -| `max_data_bytes` | 1 GiB | buffers and material libraries taken from the resolver; embedded image bytes; skin and animation values; the binary chunk `write_glb` builds; what a 3MF package inflates to, and its textures; an FBX file's meshes, image bytes and parsed values (binary: 8 bytes per array element, and other values are not counted; ASCII: `size_of::()` per value, each array element included, plus string bytes; record names and the overhead of records and their containers are not counted) | +| `max_data_bytes` | 1 GiB | buffers and material libraries taken from the resolver; embedded image bytes; skin and animation values; morph targets and their offsets (8 bytes per value); the binary chunk `write_glb` builds; what a 3MF package inflates to, and its textures; an FBX file's meshes, image bytes and parsed values (binary: 8 bytes per array element, and other values are not counted; ASCII: `size_of::()` per value, each array element included, plus string bytes; record names and the overhead of records and their containers are not counted) | | `max_extras` | 10 000 | skins, animations, cameras, lights, buffers (each); channels of one animation | +| `max_morph_targets` | 256 | morph targets of one glTF mesh; a mesh with more is read in its base shape with a warning, not refused | Fixed bounds: a PLY header of 1 MiB, 64 elements and 256 properties per element; 2^24 components for glTF accessors without a buffer view, over the whole file; 10 000 parts in a 3MF package; FBX diff --git a/crates/mesh/src/gltf.rs b/crates/mesh/src/gltf.rs index d43af5e999..590624a146 100644 --- a/crates/mesh/src/gltf.rs +++ b/crates/mesh/src/gltf.rs @@ -12,12 +12,26 @@ //! in a buffer view or a `data:` URI, or named), skins, animations of translation, rotation //! and scale, cameras and `KHR_lights_punctual` lights. A glTF mesh becomes one [`Mesh`] whose //! pools hold its primitives' vertices one after another (once for primitives that name the -//! same accessors), and each primitive a [`Part`]. +//! same accessors and morph targets), and each primitive a [`Part`]. +//! +//! Morph targets: each target's POSITION, NORMAL and TANGENT offsets (dense or sparse +//! accessors, any component type) become one [`MorphTarget`] of the mesh, with the mesh's +//! default `weights`, names from `extras.targetNames`, and a node's own `weights` in +//! [`Node::morph_weights`]. A mesh with more targets than [`Limits::max_morph_targets`] is read +//! in its base shape, and its targets are named in a warning. The offsets count against +//! [`Limits::max_data_bytes`] at 8 bytes per value, the zero offsets of vertices a target does +//! not move included, and so does each [`MorphTarget`] itself. The buffers count against the +//! same limit, and the offsets, images, skins and animations get what the buffers leave of it. +//! +//! The `extensions` and `extras` of the file, its nodes, meshes and materials are kept as +//! written ([`Scene::extensions`], [`Node::extensions`], …), for a caller that reads an +//! extension this module does not. They are kept whole: an extension that is also read into +//! the model's own fields (lights, the material extensions) stays in them as written. //! //! Not read: required extensions that change how geometry is stored (Draco, meshopt) are -//! [`Error::Unsupported`]; points, lines, morph targets, scenes other than the default and -//! other extensions are passed over (skipped primitives, primitives with morph targets and the -//! other scenes are named in warnings). +//! [`Error::Unsupported`]; points, lines, scenes other than the default and animations of +//! morph target weights are passed over (skipped primitives and the other scenes are named in +//! warnings). //! //! Buffers are needed to read anything, so an external buffer is asked of the resolver (by its //! percent-decoded URI) and is [`Error::Missing`] when declined. External images are only named @@ -28,7 +42,8 @@ //! left out and counted in a warning. //! //! Written ([`write_glb`]): nodes, meshes (positions, normals, every UV set, colours), -//! materials and images. Skins, animations, cameras and lights are not written. +//! materials and images. Skins, morph targets, animations, cameras, lights, `extensions` the +//! writer does not produce itself, and `extras` are not written. use std::cell::Cell; @@ -36,7 +51,8 @@ use serde_json::{Map, Value, json}; use crate::{ AlphaMode, Animation, Camera, Channel, ChannelPath, Corner, Error, IDENTITY, Image, Interpolation, Light, LightKind, Limits, Material, Mesh, - NONE, Node, Part, Projection, Resolver, Result, Scene, Skin, TextureRef, Trs, UvTransform, Wrap, count_warning, malformed, too_large, + MorphTarget, NONE, Node, Part, Projection, Resolver, Result, Scene, Skin, TextureRef, Trs, UvTransform, Wrap, count_warning, malformed, + too_large, }; const KIND: &str = "glTF"; @@ -258,6 +274,11 @@ impl Doc<'_> { /// The accessor's values, `n` per element, at most `max` elements: every length is checked /// against the bytes that are there before anything is allocated from a count. fn rows(&self, a: usize, max: usize, what: &str) -> Result<(Vec, usize)> { + self.rows_with(a, max, what, &self.zero_left) + } + + /// [`Doc::rows`], taking the zeros of an accessor without a buffer view from `zeros`. + fn rows_with(&self, a: usize, max: usize, what: &str, zeros: &Cell) -> Result<(Vec, usize)> { let acc = self.accessor(a)?; let n = match acc.get("type").and_then(Value::as_str).unwrap_or("") { "SCALAR" => 1, @@ -287,7 +308,7 @@ impl Doc<'_> { let mut out = match idx(acc, "bufferView") { // No buffer view: all zeros. None => { - charge(&self.zero_left, total, "values without a buffer")?; + charge(zeros, total, "values without a buffer")?; vec![0.0; total] } Some(bv) => self.dense(acc, bv, (ct, csize, norm), n, count)?, @@ -364,7 +385,12 @@ impl Doc<'_> { struct Skipped { triangles: usize, primitives: usize, + /// Primitives of meshes with more morph targets than the limit allows. morphs: usize, + /// Primitives whose number of morph targets differs from their mesh's. + uneven: usize, + /// Morph target attributes that do not fit their primitive's vertices. + unfit: usize, } fn rows_of(v: &[f64]) -> impl Iterator + '_ { @@ -446,12 +472,89 @@ fn attributes(d: &Doc, attrs: &Value, pos: &[f64], mesh: &mut Mesh) -> Result<[u Ok([base, normal_base, uv_base, tangent_base]) } +/// Append the offsets of the primitive's morph targets (`list`) to the mesh's targets, from +/// where the primitive's vertices start in each pool. An attribute that does not have one +/// `VEC3` per vertex, or that moves a pool the primitive does not fill, is left out. +fn morph_targets( + d: &Doc, + list: &[Value], + mesh: &mut Mesh, + [base, normal_base, _, tangent_base]: [u32; 4], + nv: usize, + skipped: &mut Skipped, +) -> Result<()> { + // Every value is counted against the data limit before it is read, so the zeros of an + // accessor without a buffer view are not counted again. + let unbounded = Cell::new(usize::MAX); + for (target, t) in mesh.morph_targets.iter_mut().zip(list) { + for (start, key, offsets) in + [(base, "POSITION", &mut target.positions), (normal_base, "NORMAL", &mut target.normals), (tangent_base, "TANGENT", &mut target.tangents)] + { + let Some(a) = idx(t, key) else { continue }; + let vec3 = d.accessor(a)?.get("type").and_then(Value::as_str) == Some("VEC3"); + if start == NONE || !vec3 || d.count(a) != Some(nv) { + skipped.unfit += 1; + continue; + } + charge(&d.data_left, nv.saturating_mul(size_of::<[f64; 3]>()), "morph target bytes")?; + let (v, _) = d.rows_with(a, nv, "morph target offsets", &unbounded)?; + // Vertices of earlier primitives that this target does not move get no offset. + pad(&d.data_left, offsets, start as usize)?; + offsets.extend(rows_of::<3>(&v)); + } + } + Ok(()) +} + +/// Give `offsets` `len` entries, the new ones zero, counting their bytes against the data +/// limit. +fn pad(data_left: &Cell, offsets: &mut Vec<[f64; 3]>, len: usize) -> Result<()> { + let added = len.saturating_sub(offsets.len()); + charge(data_left, added.saturating_mul(size_of::<[f64; 3]>()), "morph target bytes")?; + offsets.resize(len.max(offsets.len()), [0.0; 3]); + Ok(()) +} + +/// Name the mesh's morph targets (`extras.targetNames`), set their default weights, and give +/// every list of offsets the length of the pool it moves. +fn finish_morph_targets(d: &Doc, m: &Value, mesh: &mut Mesh) -> Result<()> { + if mesh.morph_targets.is_empty() { + return Ok(()); + } + let names = m.get("extras").map_or(&[][..], |e| arr(e, "targetNames")); + let pools = [mesh.positions.len(), mesh.normals.len(), mesh.tangents.len()]; + for (k, t) in mesh.morph_targets.iter_mut().enumerate() { + t.name = names.get(k).and_then(Value::as_str).unwrap_or("").to_string(); + for (offsets, len) in [&mut t.positions, &mut t.normals, &mut t.tangents].into_iter().zip(pools) { + if !offsets.is_empty() { + pad(&d.data_left, offsets, len)?; + } + } + } + let weights = arr(m, "weights"); + mesh.morph_weights = (0..mesh.morph_targets.len()).map(|k| weights.get(k).map_or(0.0, finite_f32)).collect(); + Ok(()) +} + +/// A JSON number as `f32`; 0 when it is not a finite number. +fn finite_f32(v: &Value) -> f32 { + v.as_f64().map(|x| x as f32).filter(|x| x.is_finite()).unwrap_or(0.0) +} + +/// The object's `extensions` and `extras`, as written. Each is a part of the JSON chunk that is +/// kept once, so together they are never larger than it. +fn extension_data(v: &Value) -> (Map, Option) { + (v.get("extensions").and_then(Value::as_object).cloned().unwrap_or_default(), v.get("extras").cloned()) +} + /// Where the vertices of one set of attribute accessors start in the mesh's pools (positions, /// normals, UVs), and how many there are. Primitives of a mesh that name the same accessors /// (one vertex buffer, several materials) share the vertices. type Shared = std::collections::HashMap; -fn primitive(d: &Doc, p: &Value, mesh: &mut Mesh, shared: &mut Shared, materials: usize, skipped: &mut Skipped) -> Result<()> { +/// `targets` is the number of morph targets read for the mesh: 0 when it has none, or more +/// than the limit allows. +fn primitive(d: &Doc, p: &Value, mesh: &mut Mesh, shared: &mut Shared, materials: usize, targets: usize, skipped: &mut Skipped) -> Result<()> { let mode = idx(p, "mode").unwrap_or(4); let position = p.get("attributes").and_then(|a| idx(a, "POSITION")); let (Some(attrs), Some(pa), 4..=6) = (p.get("attributes"), position, mode) else { @@ -459,8 +562,15 @@ fn primitive(d: &Doc, p: &Value, mesh: &mut Mesh, shared: &mut Shared, materials return Ok(()); }; charge(&d.parts_left, 1, "primitives")?; - skipped.morphs += usize::from(!arr(p, "targets").is_empty()); - let key = attrs.to_string(); + let own = arr(p, "targets"); + if targets == 0 { + skipped.morphs += usize::from(!own.is_empty()); + } else { + skipped.uneven += usize::from(own.len() != targets); + } + // Primitives that name the same attributes but other morph targets move differently, so + // they do not share vertices. + let key = if targets == 0 { attrs.to_string() } else { json!([attrs, p.get("targets")]).to_string() }; let ([base, normal_base, uv_base, tangent_base], nv) = match shared.get(&key) { Some(known) => *known, None => { @@ -469,7 +579,11 @@ fn primitive(d: &Doc, p: &Value, mesh: &mut Mesh, shared: &mut Shared, materials return Err(malformed(KIND, "POSITION is not VEC3")); } charge(&d.vertices_left, pos.len() / 3, "vertices")?; - let placed = (attributes(d, attrs, &pos, mesh)?, pos.len() / 3); + let bases = attributes(d, attrs, &pos, mesh)?; + if targets > 0 { + morph_targets(d, own, mesh, bases, pos.len() / 3, skipped)?; + } + let placed = (bases, pos.len() / 3); shared.insert(key, placed); placed } @@ -621,6 +735,7 @@ fn materials(j: &Value, limits: &Limits, scene: &mut Scene) -> Result<()> { let strength = ext.and_then(|e| e.get("KHR_materials_emissive_strength")).map_or(1.0, |e| num(e, "emissiveStrength", 1.0)); let clearcoat = ext.and_then(|e| e.get("KHR_materials_clearcoat")); let sheen = ext.and_then(|e| e.get("KHR_materials_sheen")); + let (extensions, extras) = extension_data(m); scene.materials.push(Material { name: name(m), base_color: nums(pbr, "baseColorFactor", [1.0; 4]).map(|v| v as f32), @@ -649,6 +764,8 @@ fn materials(j: &Value, limits: &Limits, scene: &mut Scene) -> Result<()> { sheen_roughness: sheen.map_or(0.0, |s| num(s, "sheenRoughnessFactor", 0.0)) as f32, sheen_color_texture: sheen.and_then(|s| tref(s.get("sheenColorTexture"))), sheen_roughness_texture: sheen.and_then(|s| tref(s.get("sheenRoughnessTexture"))), + extensions, + extras, }); // The older specular-glossiness model, as the nearest metallic-roughness material: its // diffuse colour and texture, no metal, and roughness from the glossiness. @@ -669,6 +786,8 @@ fn nodes(j: &Value, limits: &Limits, scene: &mut Scene) -> Result<()> { return Err(too_large(KIND, format!("more than {} nodes", limits.max_nodes))); } let skins = arr(j, "skins").len().min(limits.max_extras); + let targets: Vec = scene.meshes.iter().map(|m| m.morph_targets.len()).collect(); + let targets_of = |mesh: Option| mesh.and_then(|m| targets.get(m)).copied().unwrap_or(0); for n in list { let matrix = n.get("matrix").and_then(Value::as_array).filter(|a| a.len() == 16).map(|_| nums(n, "matrix", IDENTITY)); let trs = Trs { @@ -676,6 +795,7 @@ fn nodes(j: &Value, limits: &Limits, scene: &mut Scene) -> Result<()> { rotation: nums(n, "rotation", [0.0, 0.0, 0.0, 1.0]), scale: nums(n, "scale", [1.0; 3]), }; + let (extensions, extras) = extension_data(n); scene.nodes.push(Node { name: name(n), transform: matrix.unwrap_or_else(|| trs.matrix()), @@ -685,6 +805,10 @@ fn nodes(j: &Value, limits: &Limits, scene: &mut Scene) -> Result<()> { camera: idx(n, "camera").filter(|c| *c < scene.cameras.len()), light: n.get("extensions").and_then(|e| e.get("KHR_lights_punctual")).and_then(|e| idx(e, "light")).filter(|l| *l < scene.lights.len()), children: indices(n, "children", list.len()), + // Only as many as the node's mesh has targets read: none when it has none. + morph_weights: arr(n, "weights").iter().take(targets_of(idx(n, "mesh"))).map(finite_f32).collect(), + extensions, + extras, }); } let scenes = arr(j, "scenes"); @@ -861,16 +985,20 @@ pub fn read(bytes: &[u8], limits: &Limits, resolve: Resolver) -> Result { if version.split('.').next() != Some("2") { return Err(Error::Unsupported(format!("glTF: version `{}` (2.x is read)", version.chars().take(16).collect::()))); } - let mut scene = Scene::default(); + let (extensions, extras) = extension_data(&j); + let mut scene = Scene { extensions, extras, ..Scene::default() }; check_extensions(&j, &mut scene)?; + let buffers = buffers(&j, bin, limits, &mut scene, resolve)?; + // What is read out of the buffers shares one limit with the buffers themselves. + let data_left = limits.max_data_bytes.saturating_sub(buffers.iter().map(Vec::len).sum()); let d = Doc { j: &j, - buffers: buffers(&j, bin, limits, &mut scene, resolve)?, + buffers, vertices_left: Cell::new(limits.max_vertices), triangles_left: Cell::new(limits.max_triangles), parts_left: Cell::new(limits.max_parts), zero_left: Cell::new(MAX_ZERO_COMPONENTS), - data_left: Cell::new(limits.max_data_bytes), + data_left: Cell::new(data_left), }; images(&d, limits, &mut scene)?; materials(&j, limits, &mut scene)?; @@ -879,11 +1007,22 @@ pub fn read(bytes: &[u8], limits: &Limits, resolve: Resolver) -> Result { } let mut skipped = Skipped::default(); for m in arr(&j, "meshes") { - let mut mesh = Mesh { name: name(m), ..Mesh::default() }; + // glTF gives every primitive of a mesh the same number of morph targets; a primitive + // with fewer is not moved by the targets it lacks. + // Primitives that are left out (points, lines) do not count. + let read_primitive = + |p: &&Value| matches!(idx(p, "mode").unwrap_or(4), 4..=6) && p.get("attributes").and_then(|a| idx(a, "POSITION")).is_some(); + let targets = arr(m, "primitives").iter().filter(read_primitive).map(|p| arr(p, "targets").len()).max().unwrap_or(0); + let targets = if targets > limits.max_morph_targets { 0 } else { targets }; + // Targets without offsets still take memory, and across many meshes it adds up. + charge(&d.data_left, targets.saturating_mul(size_of::()), "morph target bytes")?; + let (extensions, extras) = extension_data(m); + let mut mesh = Mesh { name: name(m), morph_targets: vec![MorphTarget::default(); targets], extensions, extras, ..Mesh::default() }; let mut shared = Shared::new(); for p in arr(m, "primitives") { - primitive(&d, p, &mut mesh, &mut shared, scene.materials.len(), &mut skipped)?; + primitive(&d, p, &mut mesh, &mut shared, scene.materials.len(), targets, &mut skipped)?; } + finish_morph_targets(&d, m, &mut mesh)?; scene.meshes.push(mesh); } cameras_and_lights(&j, limits, &mut scene)?; @@ -892,7 +1031,13 @@ pub fn read(bytes: &[u8], limits: &Limits, resolve: Resolver) -> Result { animations(&d, limits, &mut scene)?; count_warning(&mut scene.warnings, skipped.primitives, "primitive(s) are points, lines or have no positions and were left out"); count_warning(&mut scene.warnings, skipped.triangles, "triangle(s) could not be read and were left out"); - count_warning(&mut scene.warnings, skipped.morphs, "primitive(s) have morph targets, which were left out (drawn in the base shape)"); + count_warning( + &mut scene.warnings, + skipped.morphs, + "primitive(s) have more morph targets than the limit allows, which were left out (drawn in the base shape)", + ); + count_warning(&mut scene.warnings, skipped.uneven, "primitive(s) have fewer morph targets than their mesh; the others do not move them"); + count_warning(&mut scene.warnings, skipped.unfit, "morph target attribute(s) do not fit their primitive's vertices and were left out"); // A hierarchy with a cycle, or one too deep to walk, is refused here rather than by every caller. scene.instances(limits)?; Ok(scene) diff --git a/crates/mesh/src/lib.rs b/crates/mesh/src/lib.rs index c1d2e1d4bd..2d566e19de 100644 --- a/crates/mesh/src/lib.rs +++ b/crates/mesh/src/lib.rs @@ -26,7 +26,8 @@ //! of the caller's [`Resolver`], which may decline. //! //! Depends on no other Craft crate, except that `threemf` opens its package with `craft-opc` -//! and reads its XML with `craft-xml`. +//! and reads its XML with `craft-xml`. `serde_json` holds glTF's `extensions` and `extras` in +//! the model, so it is a dependency with every feature. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] // The helpers the formats share are not all used by every subset of them. @@ -65,6 +66,10 @@ mod triangulate; use std::collections::HashMap; use std::fmt; +/// The JSON types of the `extensions` and `extras` fields. +pub use serde_json; +use serde_json::{Map, Value}; + /// Why a file could not be read or a scene could not be written. #[derive(Clone, Debug, PartialEq)] pub enum Error { @@ -123,6 +128,9 @@ pub struct Limits { pub max_data_bytes: usize, /// Most skins, animations, cameras and lights (each), and most channels of one animation. pub max_extras: usize, + /// Most morph targets of one mesh. A mesh with more keeps its base shape, and its targets + /// are left out and counted in a warning. + pub max_morph_targets: usize, } impl Default for Limits { @@ -138,6 +146,7 @@ impl Default for Limits { max_depth: 64, max_data_bytes: 1 << 30, max_extras: 10_000, + max_morph_targets: 256, } } } @@ -255,6 +264,30 @@ pub struct Mesh { pub joints: Vec<[u16; 4]>, pub weights: Vec<[f32; 4]>, pub parts: Vec, + /// Morph targets (glTF): shapes whose offsets, times a weight, are added to the base shape. + pub morph_targets: Vec, + /// The weight of each morph target when nothing sets one (glTF `mesh.weights`); one per + /// target. + pub morph_weights: Vec, + /// The file's `extensions` object for the mesh (glTF), as written; empty when it has none. + pub extensions: Map, + /// The file's `extras` value for the mesh (glTF), as written. + pub extras: Option, +} + +/// One morph target of a [`Mesh`]: offsets added to the base shape, times the target's weight. +/// Each list is empty when the target does not move that attribute, or as long as the mesh's +/// pool it moves. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct MorphTarget { + /// The target's name, from the mesh's `extras.targetNames` (glTF); empty when it has none. + pub name: String, + /// One offset per entry of [`Mesh::positions`]. + pub positions: Vec<[f64; 3]>, + /// One offset per entry of [`Mesh::normals`]. + pub normals: Vec<[f64; 3]>, + /// One offset of `[x, y, z]` per entry of [`Mesh::tangents`]; the handedness does not move. + pub tangents: Vec<[f64; 3]>, } /// A triangle list with one index per vertex, as [`Mesh::unified`] builds it. @@ -297,6 +330,20 @@ impl Mesh { if self.parts.iter().any(|p| p.has_tangents) && self.tangents.len() != self.positions.len() { return bad("a part names tangents but the tangent array does not match the positions"); } + if !self.morph_weights.is_empty() && self.morph_weights.len() != self.morph_targets.len() { + return bad("the morph weights do not match the morph targets"); + } + for t in &self.morph_targets { + for (what, len, pool) in [ + ("positions", t.positions.len(), self.positions.len()), + ("normals", t.normals.len(), self.normals.len()), + ("tangents", t.tangents.len(), self.tangents.len()), + ] { + if len != 0 && len != pool { + return bad(&format!("morph target `{}`: its {what} do not match the mesh's", t.name)); + } + } + } for p in &self.parts { let total = if p.face_sizes.is_empty() { (p.corners.len() % 3 == 0).then_some(p.corners.len()) @@ -471,6 +518,11 @@ pub struct Material { pub sheen_roughness: f32, pub sheen_color_texture: Option, pub sheen_roughness_texture: Option, + /// The file's `extensions` object for the material (glTF), as written, the ones read into + /// the fields above included; empty when it has none. + pub extensions: Map, + /// The file's `extras` value for the material (glTF), as written. + pub extras: Option, } impl Default for Material { @@ -499,6 +551,8 @@ impl Default for Material { sheen_roughness: 0.0, sheen_color_texture: None, sheen_roughness_texture: None, + extensions: Map::new(), + extras: None, } } } @@ -615,11 +669,31 @@ pub struct Node { pub skin: Option, /// Indices into [`Scene::nodes`]. pub children: Vec, + /// Morph target weights for this node's mesh (glTF `node.weights`), in place of the mesh's + /// [`Mesh::morph_weights`]; at most one per target the mesh has, and empty when the node + /// sets none. + pub morph_weights: Vec, + /// The file's `extensions` object for the node (glTF), as written; empty when it has none. + pub extensions: Map, + /// The file's `extras` value for the node (glTF), as written. + pub extras: Option, } impl Default for Node { fn default() -> Self { - Node { name: String::new(), transform: IDENTITY, trs: None, camera: None, light: None, mesh: None, skin: None, children: Vec::new() } + Node { + name: String::new(), + transform: IDENTITY, + trs: None, + camera: None, + light: None, + mesh: None, + skin: None, + children: Vec::new(), + morph_weights: Vec::new(), + extensions: Map::new(), + extras: None, + } } } @@ -727,6 +801,11 @@ pub struct Scene { pub external: Vec, /// What was left out or repaired while reading. pub warnings: Vec, + /// The file's top-level `extensions` object (glTF), as written, the lights read into + /// [`Scene::lights`] included; empty when it has none. + pub extensions: Map, + /// The file's top-level `extras` value (glTF), as written. + pub extras: Option, } impl Scene { diff --git a/crates/mesh/src/tests/gltf.rs b/crates/mesh/src/tests/gltf.rs index 42eabc4028..1eb513e8d9 100644 --- a/crates/mesh/src/tests/gltf.rs +++ b/crates/mesh/src/tests/gltf.rs @@ -5,8 +5,8 @@ use crate::gltf::{ GlbWriteOptions, MAX_ZERO_COMPONENTS, MagFilter, MinFilter, glb_container, read, split_glb, uri_decode, write_glb, write_glb_with_options, }; use crate::{ - AlphaMode, ChannelPath, Corner, Error, IDENTITY, Image, Interpolation, LightKind, Limits, Material, Mesh, NONE, Node, Part, Projection, Scene, - TextureRef, UvTransform, Wrap, face_normal, no_external, transform_point, + AlphaMode, ChannelPath, Corner, Error, IDENTITY, Image, Interpolation, LightKind, Limits, Material, Mesh, MorphTarget, NONE, Node, Part, + Projection, Scene, TextureRef, UvTransform, Wrap, face_normal, no_external, transform_point, }; /// Builds the binary chunk with its buffer views and accessors. @@ -652,8 +652,11 @@ fn limits_count_shared_accessors_expansions_and_extras() { assert!(with(&glb, &|l| l.max_extras = 4).is_ok(), "{key}"); assert!(too(with(&glb, &|l| l.max_extras = 3)), "{key}"); } - let image_and_keys = with(&r, &|l| l.max_data_bytes = split_glb(&r).unwrap().1.unwrap().len()); - assert!(image_and_keys.is_ok()); + // The skin's 32 matrix values and the channel's 8 keys are charged on top of the buffer + // they are read from. + let bin = split_glb(&r).unwrap().1.unwrap().len(); + assert!(with(&r, &|l| l.max_data_bytes = bin + 40).is_ok()); + assert!(too(with(&r, &|l| l.max_data_bytes = bin + 39))); } #[test] @@ -770,7 +773,13 @@ fn written_files_read_back() { // The materials; the image without bytes or a name takes its texture slot with it. let mut wood = scene.materials[0].clone(); wood.occlusion_texture = None; - assert_eq!(back.materials, [wood, scene.materials[1].clone()]); + // The reader also keeps the extensions the writer wrote for the fields as they are written. + let mut read = back.materials.clone(); + assert_eq!( + Value::Object(std::mem::take(&mut read[0].extensions)), + json!({ "KHR_materials_emissive_strength": { "emissiveStrength": 2.0 }, "KHR_materials_unlit": {} }) + ); + assert_eq!(read, [wood, scene.materials[1].clone()]); assert_eq!(back.images.len(), 2); assert_eq!((back.images[0].data.as_deref(), back.images[0].mime_type.as_deref()), (Some(&b"\x89PNG wood"[..]), Some("image/png"))); assert_eq!(back.images[1].uri.as_deref(), Some("bump.png")); @@ -889,7 +898,7 @@ fn specular_glossiness_and_webp_textures() { } #[test] -fn morph_targets_and_other_scenes_are_named_in_warnings() { +fn other_scenes_are_named_in_warnings_and_read_morph_targets_are_not() { let mut b = B::default(); let p = b.f32s(&QUAD[..9], "VEC3", 3); let d = b.f32s(&[0.0; 9], "VEC3", 3); @@ -900,33 +909,237 @@ fn morph_targets_and_other_scenes_are_named_in_warnings() { "scene": scene, "scenes": scenes, "nodes": [{ "mesh": 0 }, { "mesh": 0 }], - "meshes": [{ "primitives": [plain, morphed, morphed] }], + "meshes": [{ "primitives": [morphed, morphed] }], })) }; let s = parse(&doc(json!(1), json!([{ "nodes": [0] }, { "nodes": [1] }, { "nodes": [] }]))).unwrap(); assert_eq!(s.roots, [1]); - assert_eq!( - s.warnings, - ["scene 1 of 3 was read; the others were left out", "2 primitive(s) have morph targets, which were left out (drawn in the base shape)",] - ); - // The morphed primitives are still drawn, in their base shape. - assert_eq!(s.meshes[0].parts.len(), 3); - let morphs = "2 primitive(s) have morph targets, which were left out (drawn in the base shape)"; + // The morph targets are read, so they are not named. + assert_eq!(s.warnings, ["scene 1 of 3 was read; the others were left out"]); + assert_eq!((s.meshes[0].parts.len(), s.meshes[0].morph_targets.len()), (2, 1)); // An out-of-range choice falls back to the first scene. let s = parse(&doc(json!(5), json!([{ "nodes": [1] }, { "nodes": [0] }]))).unwrap(); assert_eq!(s.roots, [1]); - assert_eq!(s.warnings, ["scene 0 of 2 was read; the others were left out", morphs]); + assert_eq!(s.warnings, ["scene 0 of 2 was read; the others were left out"]); // One scene, or none, is not a warning about scenes. let s = parse(&doc(json!(5), json!([{ "nodes": [0] }]))).unwrap(); assert_eq!(s.roots, [0]); - assert_eq!(s.warnings, [morphs]); + assert!(s.warnings.is_empty(), "{:?}", s.warnings); let s = parse(&doc(json!(null), json!(null))).unwrap(); assert_eq!(s.roots, [0, 1]); - assert_eq!(s.warnings, [morphs]); + assert!(s.warnings.is_empty(), "{:?}", s.warnings); let s = parse(&one_mesh(&b, plain.clone())).unwrap(); assert!(s.warnings.is_empty(), "{:?}", s.warnings); } +/// A quad with normals and tangents and two morph targets: "smile" moves every position, normal +/// and tangent by dense accessors, and "blink" moves two positions by a sparse accessor without +/// a buffer view. The mesh's default weights name only the first target; the node sets both. +fn morphed() -> Vec { + let mut b = B::default(); + let p = b.f32s(&QUAD, "VEC3", 3); + let n = b.f32s(&[0.0, 0.0, 1.0].repeat(4), "VEC3", 3); + let t = b.f32s(&[1.0, 0.0, 0.0, 1.0].repeat(4), "VEC4", 4); + let i = b.u16s(&[0, 1, 2, 0, 2, 3]); + let lift = b.f32s(&[0.0, 0.0, 1.0].repeat(4), "VEC3", 3); + let tilt = b.f32s(&[0.5, 0.0, 0.0].repeat(4), "VEC3", 3); + let turn = b.f32s(&[0.0, 1.0, 0.0].repeat(4), "VEC3", 3); + let which = b.view(&[1u8, 3]); + let moves = b.view(&[0.0f32, 2.0, 0.0, 0.0, 0.0, -1.0].iter().flat_map(|x| x.to_le_bytes()).collect::>()); + b.accessors.push(json!({ "componentType": 5126, "count": 4, "type": "VEC3", + "sparse": { "count": 2, "indices": { "bufferView": which, "componentType": 5121 }, "values": { "bufferView": moves } } })); + let blink = b.accessors.len() - 1; + b.glb(json!({ + "nodes": [{ "mesh": 0, "weights": [0.5, 1.0] }], + "meshes": [{ + "name": "Face", + "primitives": [{ + "attributes": { "POSITION": p, "NORMAL": n, "TANGENT": t }, + "indices": i, + "targets": [{ "POSITION": lift, "NORMAL": tilt, "TANGENT": turn }, { "POSITION": blink }], + }], + "weights": [0.25], + "extras": { "targetNames": ["smile", "blink"] }, + }], + })) +} + +#[test] +fn morph_targets_are_read_with_their_names_and_weights() { + let s = parse(&morphed()).unwrap(); + s.validate().unwrap(); + assert!(s.warnings.is_empty(), "{:?}", s.warnings); + let m = &s.meshes[0]; + let names: Vec<&str> = m.morph_targets.iter().map(|t| t.name.as_str()).collect(); + assert_eq!(names, ["smile", "blink"]); + // A weight the mesh leaves out is 0; the node's own weights stand in for the mesh's. + assert_eq!(m.morph_weights, [0.25, 0.0]); + assert_eq!(s.nodes[0].morph_weights, [0.5, 1.0]); + let (smile, blink) = (&m.morph_targets[0], &m.morph_targets[1]); + assert_eq!( + (smile.positions.clone(), smile.normals.clone(), smile.tangents.clone()), + (vec![[0.0, 0.0, 1.0]; 4], vec![[0.5, 0.0, 0.0]; 4], vec![[0.0, 1.0, 0.0]; 4]) + ); + // The sparse target moves only the positions it names, and no normals or tangents. + assert_eq!(blink.positions, [[0.0; 3], [0.0, 2.0, 0.0], [0.0; 3], [0.0, 0.0, -1.0]]); + assert!(blink.normals.is_empty() && blink.tangents.is_empty()); + // The glTF rule: each position is its base plus every target's offset times its weight. + // With the node's weights 0.5 and 1.0, worked out by hand from the offsets above: + let weights = &s.nodes[0].morph_weights; + let shaped: Vec<[f64; 3]> = m + .positions + .iter() + .enumerate() + .map(|(v, base)| { + let mut p = *base; + for (t, w) in m.morph_targets.iter().zip(weights) { + for (k, x) in p.iter_mut().enumerate() { + *x += f64::from(*w) * t.positions[v][k]; + } + } + p + }) + .collect(); + assert_eq!(shaped, [[0.0, 0.0, 0.5], [1.0, 2.0, 0.5], [1.0, 1.0, 0.5], [0.0, 1.0, -0.5]]); +} + +#[test] +fn morph_targets_follow_their_primitives_vertices() { + let mut b = B::default(); + let three = b.f32s(&QUAD[..9], "VEC3", 3); + let normals = b.f32s(&[0.0, 0.0, 1.0].repeat(3), "VEC3", 3); + let four = b.f32s(&QUAD, "VEC3", 3); + let up = b.f32s(&[0.0, 0.0, 1.0].repeat(3), "VEC3", 3); + let bend = b.f32s(&[0.0, 1.0, 0.0].repeat(3), "VEC3", 3); + let out = b.f32s(&[1.0, 0.0, 0.0].repeat(4), "VEC3", 3); + let i = b.u16s(&[0, 1, 2, 0, 2, 3]); + let a = json!({ "attributes": { "POSITION": three, "NORMAL": normals }, "targets": [{ "POSITION": up, "NORMAL": bend }] }); + // The second primitive has no normals, so its target's NORMAL has nothing to move. + let b2 = json!({ "attributes": { "POSITION": four }, "indices": i, "targets": [{ "POSITION": out, "NORMAL": out }] }); + // The fourth names the first one's positions without its targets: its own vertices, not + // moved. + let still = json!({ "attributes": { "POSITION": three, "NORMAL": normals } }); + let s = parse(&b.glb(json!({ "meshes": [{ "primitives": [a, b2, a, still] }] }))).unwrap(); + s.validate().unwrap(); + assert_eq!( + s.warnings, + [ + "1 primitive(s) have fewer morph targets than their mesh; the others do not move them", + "1 morph target attribute(s) do not fit their primitive's vertices and were left out", + ] + ); + let m = &s.meshes[0]; + // The third primitive shares the first one's vertices; the fourth has its own. + assert_eq!((m.positions.len(), m.normals.len(), m.parts.len()), (10, 6, 4)); + let t = &m.morph_targets[0]; + let mut positions = vec![[0.0, 0.0, 1.0]; 3]; + positions.extend([[1.0, 0.0, 0.0]; 4]); + positions.extend([[0.0; 3]; 3]); + assert_eq!(t.positions, positions); + let mut normals = vec![[0.0, 1.0, 0.0]; 3]; + normals.extend([[0.0; 3]; 3]); + assert_eq!(t.normals, normals); +} + +#[test] +fn morph_target_limits() { + let glb = morphed(); + assert_eq!(with(&glb, &|l| l.max_morph_targets = 2).unwrap().meshes[0].morph_targets.len(), 2); + // Past the limit the mesh is read in its base shape, and its targets are named. + let s = with(&glb, &|l| l.max_morph_targets = 1).unwrap(); + s.validate().unwrap(); + let m = &s.meshes[0]; + assert!(m.morph_targets.is_empty() && m.morph_weights.is_empty()); + assert_eq!((m.positions.len(), m.triangle_count()), (4, 2)); + assert_eq!(s.warnings, ["1 primitive(s) have more morph targets than the limit allows, which were left out (drawn in the base shape)"]); + // The node's weights have no targets left to move, so they go too. + assert!(s.nodes[0].morph_weights.is_empty()); + + // The offsets count against the data limit, so targets that all name one accessor cannot + // multiply it without bound: 200 targets of 4 vertices are 2,400 values of 8 bytes. + let mut b = B::default(); + let p = b.f32s(&QUAD, "VEC3", 3); + let d = b.f32s(&[0.25; 12], "VEC3", 3); + let targets: Vec = (0..200).map(|_| json!({ "POSITION": d })).collect(); + let many = one_mesh(&b, json!({ "attributes": { "POSITION": p }, "targets": targets })); + assert!(b.bin.len() < 19_200); + // The buffer's own bytes come out of the same limit. + let bin = |glb: &[u8]| split_glb(glb).unwrap().1.unwrap().len(); + let structs = 200 * size_of::(); + let s = with(&many, &|l| l.max_data_bytes = bin(&many) + 19_200 + structs).unwrap(); + assert_eq!((s.meshes[0].morph_targets.len(), s.meshes[0].morph_targets[199].positions[3]), (200, [0.25; 3])); + assert!(too(with(&many, &|l| l.max_data_bytes = bin(&many) + 19_200 + structs - 1))); + // The zero offsets of vertices a target does not move count too: 200 targets that move + // only the second primitive's 3 vertices also hold zeros for the first one's 4, so + // 200 x 7 x 3 values of 8 bytes. + let three = b.f32s(&QUAD[..9], "VEC3", 3); + let d3 = b.f32s(&[0.25; 9], "VEC3", 3); + let unmoved = json!({ "attributes": { "POSITION": p }, "targets": vec![json!({}); 200] }); + let moved = json!({ "attributes": { "POSITION": three }, "targets": vec![json!({ "POSITION": d3 }); 200] }); + let padded = b.glb(json!({ "meshes": [{ "primitives": [unmoved, moved] }] })); + let s = with(&padded, &|l| l.max_data_bytes = bin(&padded) + 33_600 + structs).unwrap(); + assert_eq!(s.meshes[0].morph_targets[0].positions.len(), 7); + assert!(too(with(&padded, &|l| l.max_data_bytes = bin(&padded) + 33_600 + structs - 1))); + // So do the targets themselves, offsets or not: many meshes of empty targets cannot + // allocate without bound. + let empty = json!({ "primitives": [{ "attributes": { "POSITION": p }, "targets": vec![json!({}); 200] }] }); + let meshes = b.glb(json!({ "meshes": vec![empty; 50] })); + assert!(with(&meshes, &|l| l.max_data_bytes = bin(&meshes) + 50 * structs).is_ok()); + assert!(too(with(&meshes, &|l| l.max_data_bytes = bin(&meshes) + 50 * structs - 1))); + // One triangle: its positions and offsets take 72 bytes of buffer, and its target holds + // 9 offsets of 8 bytes, so it needs one target's size plus 144 bytes. + let mut t = B::default(); + let p3 = t.f32s(&QUAD[..9], "VEC3", 3); + let d3 = t.f32s(&[0.25; 9], "VEC3", 3); + let triangle = one_mesh(&t, json!({ "attributes": { "POSITION": p3 }, "targets": [{ "POSITION": d3 }] })); + assert_eq!(bin(&triangle), 72); + let one = size_of::(); + assert!(with(&triangle, &|l| l.max_data_bytes = one + 144).is_ok()); + assert!(too(with(&triangle, &|l| l.max_data_bytes = one + 143))); + // A primitive that is left out (points) does not count towards the mesh's targets. + let three: Vec = (0..3).map(|_| json!({ "POSITION": d })).collect(); + let points = json!({ "attributes": { "POSITION": p }, "mode": 0, "targets": three }); + let one = json!({ "attributes": { "POSITION": p }, "targets": [{ "POSITION": d }] }); + let mixed = b.glb(json!({ "meshes": [{ "primitives": [points, one] }] })); + let s = with(&mixed, &|l| l.max_morph_targets = 1).unwrap(); + assert_eq!(s.meshes[0].morph_targets.len(), 1); + assert_eq!( + s.warnings, + ["1 primitive(s) are points, lines or have no positions and were left out", "1 triangle(s) could not be read and were left out"] + ); + hammer(&glb, &parse); +} + +#[test] +fn extensions_and_extras_are_kept() { + let mut b = B::default(); + let p = b.f32s(&QUAD[..9], "VEC3", 3); + let root = json!({ "VENDOR_avatar": { "bones": [{ "node": 0, "bone": "head" }] }, "KHR_lights_punctual": { "lights": [{ "type": "point", "extras": 1 }] } }); + let node = json!({ "VENDOR_bone": { "stiff": 0.5 }, "KHR_lights_punctual": { "light": 0 } }); + let material = + json!({ "KHR_materials_unlit": {}, "KHR_materials_clearcoat": { "clearcoatFactor": 0.5 }, "VENDOR_toon": { "shade": [0.5, 0.5, 0.5] } }); + let s = parse(&b.glb(json!({ + "extensionsUsed": ["VENDOR_avatar", "KHR_lights_punctual", "KHR_materials_unlit", "KHR_materials_clearcoat", "VENDOR_toon"], + "extensions": root.clone(), + "extras": { "author": "test" }, + "nodes": [{ "mesh": 0, "extensions": node.clone(), "extras": 7 }], + "meshes": [{ "primitives": [{ "attributes": { "POSITION": p }, "material": 0 }], "extensions": { "VENDOR_mesh": {} }, "extras": [1, 2] }], + "materials": [{ "extensions": material.clone(), "extras": "x" }], + }))) + .unwrap(); + // Extensions the reader reads are kept whole as well, with what its fields do not hold + // (the light's extras). + assert_eq!((s.lights.len(), s.nodes[0].light, s.materials[0].unlit, s.materials[0].clearcoat), (1, Some(0), true, 0.5)); + assert_eq!((Value::Object(s.extensions.clone()), s.extras.clone()), (root, Some(json!({ "author": "test" })))); + assert_eq!((Value::Object(s.nodes[0].extensions.clone()), s.nodes[0].extras.clone()), (node, Some(json!(7)))); + assert_eq!((Value::Object(s.meshes[0].extensions.clone()), s.meshes[0].extras.clone()), (json!({ "VENDOR_mesh": {} }), Some(json!([1, 2])))); + let m = &s.materials[0]; + assert_eq!((Value::Object(m.extensions.clone()), m.extras.clone()), (material, Some(json!("x")))); + // An `extensions` that is not an object is passed over. + let s = parse(&b.glb(json!({ "extensions": [1], "meshes": [{ "primitives": [{ "attributes": { "POSITION": p } }] }] }))).unwrap(); + assert!(s.extensions.is_empty() && s.extras.is_none()); +} + #[test] fn strict_uri_decoding_preserves_exact_names_and_rejects_invalid_utf8() { use crate::gltf::uri_decode_strict;