Skip to main content

animsmith_core/
model.rs

1//! The loader-facing layer: clips, tracks, and the skeleton before metric
2//! resampling or repair. The glTF loader preserves authored animation
3//! values; the FBX loader normalizes scene coordinates and bakes takes to
4//! linear TRS tracks. Mechanical checks (NaN, quaternion flips, key
5//! density, …) read this layer; semantic checks read the sampled layer
6//! built from it (see [`crate::sample`]).
7
8use glam::{Mat3, Mat4, Quat, Vec3};
9use serde::{Deserialize, Serialize};
10use std::collections::{BTreeMap, BTreeSet};
11
12/// Stable machine-readable reason a positive-uniform affine linear part failed
13/// classification.
14///
15/// Core consumers map these typed facts into their own domain-specific
16/// diagnostics rather than sharing a broad operation error enum.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18#[non_exhaustive]
19pub enum AffineDomainViolation {
20    /// The linear part's axis lengths are not equal (non-uniform scale).
21    NonUniformScale,
22    /// The linear part's axes are not mutually orthogonal (shear).
23    Sheared,
24    /// The linear part has a negative determinant (reflection).
25    Reflected,
26    /// The linear part is singular or near-singular.
27    Singular,
28    /// The linear part contains a non-finite component.
29    NonFinite,
30}
31
32/// Tolerances supplied by one caller of
33/// [`classify_positive_uniform_affine`].
34///
35/// The classifier deliberately owns no global policy: Appendix D scale
36/// planning uses its versioned `f64` policy, while skinned bind-pose
37/// canonicalization retains its established `1e-4` acceptance band.
38#[derive(Debug, Clone, Copy, PartialEq)]
39pub(crate) struct PositiveUniformAffineTolerance {
40    pub(crate) equal_axis: f64,
41    pub(crate) relative_orthogonality: f64,
42    pub(crate) singular_determinant_relative: f64,
43}
44
45/// Policy-neutral geometric facts for one affine linear part.
46///
47/// Every derived operation widens the source `f32` columns to `f64` first.
48/// Callers deliberately apply their own tolerance and precedence policies to
49/// this one fact record: strict positive-uniform operations reject a domain
50/// violation, while measurement retains finite descriptive evidence.
51#[derive(Debug, Clone, Copy, PartialEq)]
52pub(crate) struct AffineGeometryFacts {
53    pub(crate) axis_lengths: [f64; 3],
54    pub(crate) mean_axis_length: f64,
55    pub(crate) determinant: f64,
56    pub(crate) axis_length_product: f64,
57    /// Widened dot products in XY, XZ, YZ order.
58    pub(crate) cross_axis_dots: [f64; 3],
59}
60
61impl AffineGeometryFacts {
62    /// Derive the complete finite fact record, or reject it atomically.
63    ///
64    /// The scalar triple product's operation order is part of the established
65    /// Appendix D classifier behavior and must not be replaced with an f32
66    /// determinant or a differently associated f64 expansion.
67    pub(crate) fn from_linear(linear: Mat3) -> Result<Self, AffineDomainViolation> {
68        if !linear.is_finite() {
69            return Err(AffineDomainViolation::NonFinite);
70        }
71        let columns = [
72            linear.x_axis.as_dvec3(),
73            linear.y_axis.as_dvec3(),
74            linear.z_axis.as_dvec3(),
75        ];
76        let axis_lengths = affine_axis_lengths(linear);
77        let mean_axis_length = average_affine_axis_length(axis_lengths);
78        let determinant = columns[2].dot(columns[0].cross(columns[1]));
79        let axis_length_product = axis_lengths[0] * axis_lengths[1] * axis_lengths[2];
80        let cross_axis_dots = [
81            columns[0].dot(columns[1]),
82            columns[0].dot(columns[2]),
83            columns[1].dot(columns[2]),
84        ];
85        if axis_lengths.iter().any(|value| !value.is_finite())
86            || !mean_axis_length.is_finite()
87            || !determinant.is_finite()
88            || !axis_length_product.is_finite()
89            || cross_axis_dots.iter().any(|value| !value.is_finite())
90        {
91            return Err(AffineDomainViolation::NonFinite);
92        }
93        Ok(Self {
94            axis_lengths,
95            mean_axis_length,
96            determinant,
97            axis_length_product,
98            cross_axis_dots,
99        })
100    }
101
102    /// Whether every axis lies within a symmetric mean-relative band.
103    ///
104    /// Comparing every value to the mean removes the privileged-X behavior
105    /// of pairwise-from-X tests. The longer-operand base keeps the predicate
106    /// symmetric around the mean, and `<=` makes the boundary inclusive.
107    pub(crate) fn has_equal_axis_lengths(self, relative_tolerance: f64) -> bool {
108        values_equal_to_mean(
109            &self.axis_lengths,
110            self.mean_axis_length,
111            relative_tolerance,
112        )
113    }
114}
115
116/// Whether every finite value lies within a symmetric relative band around
117/// `mean`, using the longer operand as the relative base.
118pub(crate) fn values_equal_to_mean(values: &[f64], mean: f64, relative_tolerance: f64) -> bool {
119    values
120        .iter()
121        .all(|&value| (value - mean).abs() <= relative_tolerance * mean.abs().max(value.abs()))
122}
123
124/// Classify an affine linear part as an orientation-preserving positive
125/// uniform scale and return its common factor.
126///
127/// Inputs widen to `f64` before every derived calculation. This preserves the
128/// Appendix D scale classifier's boundary behaviour; callers choose the
129/// tolerance policy appropriate to their separate contract.
130pub(crate) fn classify_positive_uniform_affine(
131    linear: Mat3,
132    tolerance: PositiveUniformAffineTolerance,
133) -> Result<f64, AffineDomainViolation> {
134    let facts = AffineGeometryFacts::from_linear(linear)?;
135    if facts.mean_axis_length <= 0.0 {
136        return Err(AffineDomainViolation::Singular);
137    }
138
139    // Check singularity before the shape facts. A degenerate basis that is
140    // also non-uniform or sheared is still singular, which keeps the
141    // independently named rejection classes deterministic.
142    // Expand the scalar triple product from the widened columns. Calling
143    // `Mat3::determinant` here would perform the derived arithmetic in f32
144    // before widening and moves the singular boundary.
145    if facts.determinant.abs()
146        <= tolerance.singular_determinant_relative * facts.axis_length_product
147    {
148        return Err(AffineDomainViolation::Singular);
149    }
150    // This is a relative band with no unit floor: a floor would become an
151    // absolute tolerance for sub-unit transforms. The longer-operand base
152    // keeps the comparison symmetric, and `>` makes the boundary inclusive.
153    if !facts.has_equal_axis_lengths(tolerance.equal_axis) {
154        return Err(AffineDomainViolation::NonUniformScale);
155    }
156
157    // Scale the dot-product band by the square of the common factor. As with
158    // the axis band, equality is accepted and only a value beyond it rejects.
159    let orthogonality_tolerance =
160        tolerance.relative_orthogonality * facts.mean_axis_length * facts.mean_axis_length;
161    if facts
162        .cross_axis_dots
163        .iter()
164        .any(|dot| dot.abs() > orthogonality_tolerance)
165    {
166        return Err(AffineDomainViolation::Sheared);
167    }
168    if facts.determinant < 0.0 {
169        return Err(AffineDomainViolation::Reflected);
170    }
171    Ok(facts.mean_axis_length)
172}
173
174/// The three column lengths of a linear part, widened to `f64` first.
175///
176/// The positive-uniform classifier and the scale proof's observed-factor
177/// witness both use this helper so that their factor is one shared quantity.
178pub(crate) fn affine_axis_lengths(linear: Mat3) -> [f64; 3] {
179    [
180        linear.x_axis.as_dvec3().length(),
181        linear.y_axis.as_dvec3().length(),
182        linear.z_axis.as_dvec3().length(),
183    ]
184}
185
186/// The arithmetic-mean common factor represented by three affine axis
187/// lengths.
188///
189/// The finite widened inputs are summed in ascending order so this shared
190/// factor does not depend on an affine matrix's authored column order.
191pub(crate) fn average_affine_axis_length(lengths: [f64; 3]) -> f64 {
192    let mut ascending = lengths;
193    ascending.sort_by(f64::total_cmp);
194    (ascending[0] + ascending[1] + ascending[2]) / 3.0
195}
196
197#[cfg(test)]
198pub(crate) mod affine_test_fixtures {
199    use super::{Mat3, Vec3};
200
201    /// A finite diagonal basis intentionally between the two callers' equal
202    /// axis bands: Appendix D rejects it, while skinned canonicalization's
203    /// established `1e-4` policy accepts it.
204    pub(crate) fn tolerance_divergence_basis() -> Mat3 {
205        Mat3::from_diagonal(Vec3::new(1.0, 1.000_05, 1.0))
206    }
207
208    /// A nearly orthogonal basis whose only non-zero cross-axis dot product
209    /// lies between the two callers' orthogonality bands.
210    pub(crate) fn orthogonality_tolerance_divergence_basis() -> Mat3 {
211        Mat3::from_cols(Vec3::X, Vec3::new(5.0e-5, 1.0, 0.0), Vec3::Z)
212    }
213
214    /// All signed column orders of the exact Appendix D v6 mean fixture.
215    ///
216    /// Odd permutations negate their first column, preserving orientation
217    /// without changing any axis length.
218    pub(crate) fn appendix_d_v6_mean_permutations() -> [Mat3; 6] {
219        let columns = [
220            Vec3::new(
221                f32::from_bits(0x3f0e_8cbb),
222                f32::from_bits(0x3f26_fbbe),
223                f32::from_bits(0x3f21_9bc7),
224            ),
225            Vec3::new(
226                f32::from_bits(0x3d9c_b415),
227                f32::from_bits(0x3e92_d82b),
228                f32::from_bits(0x3f82_e85d),
229            ),
230            Vec3::new(
231                f32::from_bits(0x3f14_5226),
232                f32::from_bits(0x3e9e_e50d),
233                f32::from_bits(0x3f56_817c),
234            ),
235        ];
236        [
237            Mat3::from_cols(columns[0], columns[1], columns[2]),
238            Mat3::from_cols(-columns[0], columns[2], columns[1]),
239            Mat3::from_cols(-columns[1], columns[0], columns[2]),
240            Mat3::from_cols(columns[1], columns[2], columns[0]),
241            Mat3::from_cols(columns[2], columns[0], columns[1]),
242            Mat3::from_cols(-columns[2], columns[1], columns[0]),
243        ]
244    }
245}
246
247/// Index into [`Skeleton::bones`].
248pub type BoneId = usize;
249
250/// Node-local TRS transform.
251#[derive(Debug, Clone, Copy, PartialEq)]
252pub struct Transform {
253    /// Translation in scene units.
254    pub translation: Vec3,
255    /// Orientation relative to the parent node.
256    pub rotation: Quat,
257    /// Non-uniform local scale.
258    pub scale: Vec3,
259}
260
261impl Transform {
262    /// The identity transform: zero translation, identity rotation, and
263    /// unit scale.
264    pub const IDENTITY: Self = Self {
265        translation: Vec3::ZERO,
266        rotation: Quat::IDENTITY,
267        scale: Vec3::ONE,
268    };
269
270    /// Convert this TRS transform to a matrix using glam's
271    /// scale-rotation-translation order.
272    pub fn to_mat4(&self) -> Mat4 {
273        Mat4::from_scale_rotation_translation(self.scale, self.rotation, self.translation)
274    }
275}
276
277impl Default for Transform {
278    fn default() -> Self {
279        Self::IDENTITY
280    }
281}
282
283/// One skeleton node/bone in parent-before-child order.
284#[derive(Debug, Clone)]
285pub struct Bone {
286    /// Bone/node name as authored or normalized by the loader.
287    pub name: String,
288    /// Parent bone index; `None` means this is a root bone.
289    pub parent: Option<BoneId>,
290    /// Rest pose, node-local. Whether this or the inverse-bind-derived
291    /// rest is authoritative is a `bind-pose` check concern.
292    pub rest: Transform,
293    /// Inverse bind matrix from a skin, when one references this bone.
294    pub inverse_bind: Option<Mat4>,
295}
296
297/// Bones in topological order: a bone's parent always precedes it.
298/// Loaders are responsible for establishing this invariant.
299#[derive(Debug, Clone, Default)]
300pub struct Skeleton {
301    /// Bones in topological order.
302    pub bones: Vec<Bone>,
303}
304
305impl Skeleton {
306    /// Name of the bone at `id`.
307    ///
308    /// # Panics
309    ///
310    /// Panics if `id` is not a valid index into [`Skeleton::bones`].
311    pub fn bone_name(&self, id: BoneId) -> &str {
312        &self.bones[id].name
313    }
314}
315
316/// Structural failure composing [`Skeleton`] rest-local transforms into
317/// world matrices, returned by [`world_rest_matrices`].
318///
319/// This is deliberately generic over the eventual caller-facing error: every
320/// caller of [`world_rest_matrices`] maps one of these two structural facts
321/// into its own typed error variant rather than sharing an error enum across
322/// module boundaries.
323#[derive(Debug, Clone, Copy, PartialEq, Eq)]
324pub(crate) enum WorldMatrixError {
325    /// The node's local or accumulated world transform has a non-finite
326    /// component.
327    NonFiniteTransform {
328        /// The node with the non-finite transform.
329        node: BoneId,
330    },
331    /// The node's parent is not earlier in [`Skeleton::bones`], so the
332    /// skeleton is not in the required parent-before-child order.
333    InvalidParent {
334        /// The node with an invalid parent.
335        node: BoneId,
336        /// The invalid parent index.
337        parent: BoneId,
338    },
339}
340
341/// Compose every [`Bone::rest`] local transform in `skeleton` into a
342/// parent-before-child world matrix, shared by every module that needs plain
343/// rest-world FK (skin bind-pose canonicalization, static mesh baking, and
344/// scale planning/proof).
345///
346/// `skeleton.bones` order is trusted as parent-before-child, matching
347/// [`Skeleton`]'s documented invariant; a parent index that is not strictly
348/// less than its child's is reported as [`WorldMatrixError::InvalidParent`]
349/// rather than assumed.
350pub(crate) fn world_rest_matrices(skeleton: &Skeleton) -> Result<Vec<Mat4>, WorldMatrixError> {
351    let mut worlds = Vec::with_capacity(skeleton.bones.len());
352    for (node, bone) in skeleton.bones.iter().enumerate() {
353        let local = bone.rest.to_mat4();
354        if !mat4_is_finite(local) {
355            return Err(WorldMatrixError::NonFiniteTransform { node });
356        }
357        let world = match bone.parent {
358            Some(parent) if parent < node => worlds[parent] * local,
359            Some(parent) => return Err(WorldMatrixError::InvalidParent { node, parent }),
360            None => local,
361        };
362        if !mat4_is_finite(world) {
363            return Err(WorldMatrixError::NonFiniteTransform { node });
364        }
365        worlds.push(world);
366    }
367    Ok(worlds)
368}
369
370/// Compose rest-world matrices for a partial-evidence consumer.
371///
372/// Unlike [`world_rest_matrices`], this deliberately preserves a slot for
373/// every bone and makes only the malformed chain unavailable. Measurement
374/// uses that behaviour to retain finite evidence from unrelated roots.
375pub(crate) fn tolerant_world_rest_matrices(skeleton: &Skeleton) -> Vec<Option<Mat4>> {
376    let mut worlds = Vec::with_capacity(skeleton.bones.len());
377    for bone in &skeleton.bones {
378        let local = bone.rest.to_mat4();
379        let world = match bone.parent {
380            Some(parent) => worlds
381                .get(parent)
382                .copied()
383                .flatten()
384                .map(|parent_world| parent_world * local),
385            None => Some(local),
386        }
387        .filter(|matrix| mat4_is_finite(*matrix));
388        worlds.push(world);
389    }
390    worlds
391}
392
393pub(crate) fn mat4_is_finite(matrix: Mat4) -> bool {
394    matrix.to_cols_array().into_iter().all(f32::is_finite)
395}
396
397/// Animated property targeted by a [`Track`].
398#[derive(Debug, Clone, Copy, PartialEq, Eq)]
399pub enum Property {
400    /// Local translation channel.
401    Translation,
402    /// Local rotation channel.
403    Rotation,
404    /// Local scale channel.
405    Scale,
406}
407
408impl Property {
409    /// Stable snake-case name used in diagnostics and serialized
410    /// metadata.
411    pub fn as_str(self) -> &'static str {
412        match self {
413            Property::Translation => "translation",
414            Property::Rotation => "rotation",
415            Property::Scale => "scale",
416        }
417    }
418}
419
420/// Interpolation mode for a [`Track`].
421#[derive(Debug, Clone, Copy, PartialEq, Eq)]
422pub enum Interpolation {
423    /// Linear interpolation between key values.
424    Linear,
425    /// Hold the previous key until the next key.
426    Step,
427    /// glTF cubic spline: `values` holds `[in-tangent, value, out-tangent]`
428    /// triplets per keyframe. Use [`Track::value_index`] to address the
429    /// value elements.
430    CubicSpline,
431}
432
433/// Storage for a track's key values.
434#[derive(Debug, Clone)]
435pub enum TrackValues {
436    /// Translation or scale values.
437    Vec3s(Vec<Vec3>),
438    /// Rotation values.
439    Quats(Vec<Quat>),
440}
441
442impl TrackValues {
443    /// Number of stored values, including tangents for cubic-spline
444    /// tracks.
445    pub fn len(&self) -> usize {
446        match self {
447            TrackValues::Vec3s(v) => v.len(),
448            TrackValues::Quats(v) => v.len(),
449        }
450    }
451
452    /// Whether there are no stored values.
453    pub fn is_empty(&self) -> bool {
454        self.len() == 0
455    }
456}
457
458/// One animated property of one bone.
459#[derive(Debug, Clone)]
460pub struct Track {
461    /// Bone index targeted by this track.
462    pub bone: BoneId,
463    /// Property animated on the target bone.
464    pub property: Property,
465    /// Interpolation mode used between keys.
466    pub interpolation: Interpolation,
467    /// Keyframe times in seconds. Same length as the keyframe count
468    /// (tangent elements in cubic tracks do not add times).
469    pub times: Vec<f32>,
470    /// Key values, with cubic-spline tracks storing tangent triplets.
471    pub values: TrackValues,
472}
473
474impl Track {
475    /// Number of keyframes.
476    pub fn key_count(&self) -> usize {
477        self.times.len()
478    }
479
480    /// Index into `values` of keyframe `k`'s value element (skips
481    /// tangents for cubic tracks).
482    pub fn value_index(&self, k: usize) -> usize {
483        match self.interpolation {
484            Interpolation::CubicSpline => 3 * k + 1,
485            _ => k,
486        }
487    }
488
489    /// Keyframe `k`'s value, for Vec3 tracks.
490    pub fn key_vec3(&self, k: usize) -> Option<Vec3> {
491        match &self.values {
492            TrackValues::Vec3s(v) => v.get(self.value_index(k)).copied(),
493            TrackValues::Quats(_) => None,
494        }
495    }
496
497    /// Keyframe `k`'s value, for rotation tracks.
498    pub fn key_quat(&self, k: usize) -> Option<Quat> {
499        match &self.values {
500            TrackValues::Quats(v) => v.get(self.value_index(k)).copied(),
501            TrackValues::Vec3s(_) => None,
502        }
503    }
504
505    /// First key time, or `0.0` for an empty track.
506    pub fn start_time(&self) -> f32 {
507        self.times.first().copied().unwrap_or(0.0)
508    }
509
510    /// Last key time, or `0.0` for an empty track.
511    pub fn end_time(&self) -> f32 {
512        self.times.last().copied().unwrap_or(0.0)
513    }
514}
515
516/// One animation clip targeting the document skeleton.
517#[derive(Debug, Clone)]
518pub struct Clip {
519    /// Clip name, used as the key in measurement maps and config
520    /// expectations.
521    pub name: String,
522    /// Clip length in seconds (max sampler end time across tracks).
523    pub duration_s: f64,
524    /// Animated tracks belonging to this clip.
525    pub tracks: Vec<Track>,
526}
527
528/// Loader-provided provenance for a [`Document`].
529#[derive(Debug, Clone, Default)]
530pub struct SourceInfo {
531    /// Source path, when the loader was given one.
532    pub path: Option<String>,
533    /// Source format label such as `"glb"` or `"fbx"`.
534    pub format: Option<String>,
535}
536
537/// A loaded file: one skeleton, any number of clips targeting it, and
538/// the scene assets (meshes, materials, and textures) that rode in alongside
539/// them.
540/// `assets` is default-empty: the check catalog judges animation and
541/// ignores it, but the load/write round-trip carries it so `transform`
542/// and `convert` preserve geometry instead of silently dropping it.
543#[derive(Debug, Clone, Default)]
544pub struct Document {
545    /// Skeleton shared by every clip.
546    pub skeleton: Skeleton,
547    /// Animation clips targeting [`Document::skeleton`].
548    pub clips: Vec<Clip>,
549    /// Meshes, materials, and textures carried by the loaded scene.
550    pub assets: SceneAssets,
551    /// Optional source provenance.
552    pub source: SourceInfo,
553}
554
555/// A structural invariant violated by [`validate_document_shape`].
556///
557/// Validation is a snapshot, not a durable guarantee: [`Document`] and its
558/// nested fields are publicly mutable. Strict operations that rely on this
559/// full shape must validate again at each public boundary.
560#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
561#[non_exhaustive]
562pub enum DocumentShapeError {
563    /// A bone's local rest transform or its composed rest-world transform is
564    /// non-finite.
565    #[error("node {node} has a non-finite rest transform")]
566    NonFiniteSkeletonRest {
567        /// The affected skeleton node.
568        node: BoneId,
569    },
570    /// A bone's parent does not precede it in parent-before-child order.
571    #[error("node {node} has invalid parent {parent}")]
572    InvalidSkeletonParent {
573        /// The affected skeleton node.
574        node: BoneId,
575        /// The invalid parent index.
576        parent: BoneId,
577    },
578    /// The source-node projection declares one source node identity twice.
579    #[error("source skeleton declares duplicate source node index {source_node_index}")]
580    DuplicateSourceNodeIndex {
581        /// The duplicated source-node index.
582        source_node_index: usize,
583    },
584    /// The source-skin projection declares one source skin identity twice.
585    #[error("source skeleton declares duplicate source skin index {source_skin_index}")]
586    DuplicateSourceSkinIndex {
587        /// The duplicated source-skin index.
588        source_skin_index: usize,
589    },
590    /// A complete source-node projection contradicts the normalized skeleton.
591    #[error(
592        "source node {source_node_index} contradicts the document skeleton's parent chain ({violation})"
593    )]
594    SourceProjection {
595        /// The source node whose projection failed.
596        source_node_index: usize,
597        /// The typed projection failure.
598        violation: SourceProjectionViolation,
599    },
600    /// A clip declares the same target `(node, property)` more than once.
601    #[error("clip {clip_index} declares duplicate {property:?} tracks for node {node}")]
602    DuplicateClipTrack {
603        /// Index into [`Document::clips`].
604        clip_index: usize,
605        /// The duplicated target node.
606        node: BoneId,
607        /// The duplicated animated property.
608        property: Property,
609    },
610    /// A track is malformed for its target, interpolation, or value storage.
611    #[error("clip {clip_index} track for node {node} has an invalid shape ({violation})")]
612    TrackShape {
613        /// Index into [`Document::clips`].
614        clip_index: usize,
615        /// The track's target node.
616        node: BoneId,
617        /// The typed track-shape failure.
618        violation: TrackShapeViolation,
619    },
620    /// A mesh instance has an invalid reference or inverse-bind payload.
621    #[error("mesh instance {instance_index} is invalid ({violation})")]
622    MeshInstanceShape {
623        /// Index into [`SceneAssets::instances`].
624        instance_index: usize,
625        /// The typed mesh-instance failure.
626        violation: MeshInstanceShapeViolation,
627    },
628    /// A bone-level inverse-bind matrix is non-finite.
629    #[error("node {node} has a non-finite inverse-bind matrix")]
630    NonFiniteBoneInverseBind {
631        /// The affected skeleton node.
632        node: BoneId,
633    },
634}
635
636/// The way a complete source-node projection contradicts the skeleton.
637#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
638#[non_exhaustive]
639pub enum SourceProjectionViolation {
640    /// A projected bone index is outside [`Skeleton::bones`].
641    #[error("projected_bone_out_of_range")]
642    ProjectedBoneOutOfRange,
643    /// Two source-node rows project to the same normalized bone.
644    #[error("two_source_nodes_project_to_one_bone")]
645    TwoSourceNodesProjectToOneBone,
646    /// An ancestor walk names a source node absent from the projection table.
647    #[error("parent_source_node_is_missing")]
648    ParentSourceNodeMissing,
649    /// An ancestor walk through unprojected rows does not terminate.
650    #[error("cyclic_unprojected_source_parent_chain")]
651    CyclicUnprojectedSourceParentChain,
652    /// The nearest projected source ancestor differs from the bone parent.
653    #[error("projection_and_skeleton_parents_differ")]
654    NearestProjectedParentMismatch,
655    /// A projected bone has an unprojected direct skeleton child.
656    #[error("projected_bone_has_an_unprojected_skeleton_child")]
657    ProjectedBoneHasUnprojectedSkeletonChild,
658}
659
660/// The way a clip track is malformed.
661#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
662#[non_exhaustive]
663pub enum TrackShapeViolation {
664    /// The target bone index is outside [`Skeleton::bones`].
665    #[error("bone_index_out_of_range")]
666    BoneIndexOutOfRange,
667    /// The track has no keyframe times.
668    #[error("empty_times")]
669    EmptyTimes,
670    /// At least one keyframe time is not finite.
671    #[error("non_finite_time")]
672    NonFiniteTime,
673    /// Keyframe times are not strictly increasing.
674    #[error("times_not_strictly_increasing")]
675    TimesNotStrictlyIncreasing,
676    /// Stored value count disagrees with the interpolation's key count.
677    #[error("value_count_mismatch")]
678    ValueCountMismatch,
679    /// The value storage does not match the targeted property.
680    #[error("value_type_mismatches_property")]
681    ValueTypeMismatchesProperty,
682    /// At least one stored value is not finite.
683    #[error("non_finite_value")]
684    NonFiniteValue,
685}
686
687/// The way a mesh instance is malformed.
688#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
689#[non_exhaustive]
690pub enum MeshInstanceShapeViolation {
691    /// The instance node index is outside [`Skeleton::bones`].
692    #[error("node_index_out_of_range")]
693    NodeIndexOutOfRange,
694    /// The mesh index is outside [`SceneAssets::meshes`].
695    #[error("mesh_index_out_of_range")]
696    MeshIndexOutOfRange,
697    /// A skin joint index is outside [`Skeleton::bones`].
698    #[error("skin_joint_out_of_range")]
699    SkinJointOutOfRange,
700    /// A non-empty inverse-bind array has a different length from skin joints.
701    #[error("skin_ibm_count_mismatch")]
702    SkinInverseBindCountMismatch,
703    /// An instance inverse-bind matrix is not finite.
704    #[error("non_finite_inverse_bind")]
705    NonFiniteSkinInverseBind,
706}
707
708// --- Scene assets (meshes/materials) -----------------------------------
709//
710// The geometry half of a [`Document`]. Populated by both format loaders and
711// emitted by the writer, so a full conversion preserves geometry. Primitives
712// may be indexed already; [`Primitive::weld`] can index unindexed exact
713// duplicates without collapsing authored seams.
714
715/// One triangle-list primitive sharing a material. Attribute arrays may be
716/// indexed already; [`Primitive::weld`] dedupes an unindexed primitive into
717/// indexed form.
718///
719/// Additional glTF skin-influence attribute sets are intentionally metadata
720/// only. The primary four influences remain in [`Self::joints`] and
721/// [`Self::weights`]; consumers can use this metadata to apply their own
722/// policy without the core assuming how additional influences are evaluated.
723#[derive(Debug, Clone, Default)]
724pub struct Primitive {
725    /// Index into [`SceneAssets::materials`].
726    pub material: Option<usize>,
727    /// Triangle indices into the attribute arrays; empty = unindexed.
728    pub indices: Vec<u32>,
729    /// Vertex positions in scene units.
730    pub positions: Vec<Vec3>,
731    /// Same length as `positions`, or empty.
732    pub normals: Vec<Vec3>,
733    /// Same length as `positions`, or empty.
734    pub uvs: Vec<[f32; 2]>,
735    /// Indices into an owning instance's skin-joint list; empty if unskinned.
736    pub joints: Vec<[u16; 4]>,
737    /// Skinning weights parallel to [`Primitive::joints`].
738    pub weights: Vec<[f32; 4]>,
739    /// Declared non-primary skin-influence attribute sets.
740    ///
741    /// Each entry records whether the glTF primitive had `JOINTS_n` and/or
742    /// `WEIGHTS_n` for `n >= 1`. Entries are sorted by
743    /// [`AdditionalInfluenceSet::set_index`].
744    pub additional_influence_sets: Vec<AdditionalInfluenceSet>,
745}
746
747/// Presence metadata for one non-primary glTF skin-influence attribute set.
748///
749/// A set may contain only one side because source assets can declare
750/// `JOINTS_n` and `WEIGHTS_n` independently. This type deliberately does not
751/// retain the corresponding per-vertex values: the core model's skinning
752/// semantics remain the primary `JOINTS_0` / `WEIGHTS_0` set.
753#[derive(Debug, Clone, Copy, PartialEq, Eq)]
754pub struct AdditionalInfluenceSet {
755    /// glTF attribute-set number (`n >= 1`).
756    pub set_index: u32,
757    /// Whether `JOINTS_n` was declared.
758    pub joints_present: bool,
759    /// Whether `WEIGHTS_n` was declared.
760    pub weights_present: bool,
761}
762
763/// One source mesh definition, independent of any node that instances it.
764#[derive(Debug, Clone, Default)]
765pub struct MeshAsset {
766    /// Mesh name.
767    pub name: String,
768    /// Stable index of this definition in the source format.
769    ///
770    /// glTF permits several nodes to instance one mesh definition. Loaders
771    /// preserve that distinction through [`SceneAssets::instances`].
772    pub source_mesh_index: usize,
773    /// Triangle-list primitives belonging to this mesh.
774    pub primitives: Vec<Primitive>,
775}
776
777/// One node instance of a source [`MeshAsset`] definition.
778#[derive(Debug, Clone, Default)]
779pub struct MeshInstance {
780    /// Index of the source-format node that owns this mesh instance.
781    pub source_node_index: usize,
782    /// The node this mesh hangs off in the core skeleton.
783    pub node: BoneId,
784    /// Index into [`SceneAssets::meshes`] of the instanced definition.
785    pub mesh: usize,
786    /// Skin joints in cluster order. Empty = unskinned.
787    pub skin_joints: Vec<BoneId>,
788    /// Per-joint inverse bind matrices, parallel to `skin_joints`
789    /// (glTF convention: joint-bind-world⁻¹ × geometry-to-world, all
790    /// in the converted scene space). Falls back to the bones'
791    /// `inverse_bind` when empty.
792    pub skin_ibms: Vec<Mat4>,
793}
794
795/// One declared source scene and its root nodes.
796#[derive(Debug, Clone, Default)]
797pub struct SceneAsset {
798    /// Index of this scene in the source-format scene array.
799    pub source_scene_index: usize,
800    /// Authored scene name, when the source format provides one.
801    pub name: Option<String>,
802    /// Root nodes belonging to this scene, represented as core bone ids.
803    pub roots: Vec<BoneId>,
804}
805
806/// Whether a loader supplied source-node and source-skin identity evidence.
807///
808/// The skeleton used by sampling is deliberately format-neutral and is ordered
809/// for parent-before-child FK. Source formats can use a different stable node
810/// order, so this coverage flag keeps an empty source table from being
811/// mistaken for a source file with no nodes or skins.
812#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
813#[serde(rename_all = "snake_case")]
814pub enum SourceSkeletonCoverage {
815    /// The loader cannot provide source-node and source-skin identity facts.
816    #[default]
817    Unavailable,
818    /// The source-node and source-skin tables describe the loaded input.
819    /// Source nodes with [`SourceNodeAsset::bone`] form the downward-closed
820    /// projection consumed by strict operations.
821    Complete,
822}
823
824/// The authored local-rest representation of one source node.
825///
826/// glTF permits either decomposed TRS properties or a matrix. Keeping this
827/// representation separate from [`Bone::rest`] avoids presenting a lossy
828/// matrix decomposition as though it were authored TRS evidence.
829#[derive(Debug, Clone)]
830pub enum SourceNodeLocalRest {
831    /// Source node declared translation, rotation, and scale properties.
832    Trs {
833        /// Local translation in scene units.
834        translation: Vec3,
835        /// Local orientation relative to the parent node.
836        rotation: Quat,
837        /// Local non-uniform scale.
838        scale: Vec3,
839    },
840    /// Source node declared a column-major 4×4 local transform matrix.
841    Matrix(Mat4),
842}
843
844/// One source-format node with source-native identity facts.
845///
846/// Marked `#[non_exhaustive]` because this projection grows as loaders learn
847/// to carry more source-native identity (`bone` was the most recent
848/// addition): out-of-crate embedders construct it through
849/// [`SourceNodeAsset::new`] and assign the optional facts they have, so a
850/// later field cannot break their build. The sibling source-asset structs in
851/// this module are not yet marked; they are stable in a way this one has
852/// already demonstrated it is not.
853#[derive(Debug, Clone)]
854#[non_exhaustive]
855pub struct SourceNodeAsset {
856    /// Stable node-array index in the source format.
857    pub source_node_index: usize,
858    /// Authored node name, when present.
859    pub name: Option<String>,
860    /// Source node-array index of the authored parent, when any.
861    pub parent_source_node_index: Option<usize>,
862    /// Declared source scenes that name this node as a root, in source-scene
863    /// index order.
864    pub scene_root_indices: Vec<usize>,
865    /// Authored local-rest representation.
866    pub local_rest: SourceNodeLocalRest,
867    /// The core [`BoneId`] this source node normalized to, when the loader
868    /// retained it as an independent normalized node.
869    ///
870    /// `None` means this source row has no independent [`Skeleton`] bone. A
871    /// loader may have dropped an unreachable node, or it may have folded a
872    /// static connector's authored local rest into the next projected node.
873    /// The row remains authoritative source identity and local-rest evidence
874    /// under [`SourceSkeletonCoverage::Complete`]. Format-neutral consumers
875    /// that need to resolve a raw source-node selector (for example
876    /// [`crate::scale::ScaleOperation::RestBindUniformScale`]'s
877    /// `source_root_node_index`/skin joints) into the normalized
878    /// [`Skeleton`] must use this field rather than assuming source-node
879    /// order equals bone order.
880    ///
881    /// With [`SourceSkeletonCoverage::Complete`] coverage, the `Some` rows
882    /// must form a downward-closed, nearest-projected-parent-preserving
883    /// projection into the normalized skeleton. Unprojected source rows may
884    /// occur between projected ancestors; [`validate_document_shape`]
885    /// verifies that relation.
886    pub bone: Option<BoneId>,
887}
888
889impl SourceNodeAsset {
890    /// One source node identified by its stable source-array index and its
891    /// authored local rest — the two facts every loader necessarily has.
892    ///
893    /// Every remaining fact ([`Self::name`], [`Self::parent_source_node_index`],
894    /// [`Self::scene_root_indices`], [`Self::bone`]) starts absent and is
895    /// assigned through the public fields. This is the only way to build the
896    /// value outside `animsmith-core`, since the type is `#[non_exhaustive]`.
897    pub fn new(source_node_index: usize, local_rest: SourceNodeLocalRest) -> Self {
898        Self {
899            source_node_index,
900            name: None,
901            parent_source_node_index: None,
902            scene_root_indices: Vec::new(),
903            local_rest,
904            bone: None,
905        }
906    }
907}
908
909/// Read status for a source skin's inverse-bind accessor.
910#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
911#[serde(rename_all = "snake_case")]
912pub enum SourceInverseBindAccessorStatus {
913    /// The skin did not declare an inverse-bind accessor.
914    #[default]
915    Absent,
916    /// The accessor was readable and had at least one matrix per declared joint.
917    Available,
918    /// The source declared a count-zero inverse-bind accessor.
919    EmptyAccessor,
920    /// The accessor was readable but has fewer matrices than declared joints.
921    CountMismatch,
922    /// The source declared an accessor that the loader could not read.
923    Unreadable,
924}
925
926/// Read-side evidence for one source skin inverse-bind accessor.
927#[derive(Debug, Clone, Default)]
928pub struct SourceInverseBindAccessor {
929    /// Whether the accessor was absent, complete, or malformed.
930    pub status: SourceInverseBindAccessorStatus,
931    /// Declared source accessor count, or `None` when no accessor was declared.
932    pub declared_count: Option<usize>,
933    /// Raw matrices in accessor order when they were readable.
934    ///
935    /// This may contain non-finite values from a parseable binary accessor.
936    /// Measurement serialization must classify those values rather than emit
937    /// non-finite JSON numbers.
938    pub matrices: Vec<Mat4>,
939}
940
941/// One source node that declares use of a source skin.
942#[derive(Debug, Clone)]
943pub struct SourceSkinAttachment {
944    /// Stable node-array index of the attachment node.
945    pub source_node_index: usize,
946    /// Stable source mesh-definition index, when the node declares a mesh.
947    ///
948    /// This remains present even when the current core mesh importer skips the
949    /// definition (for example, because it has no triangle-list primitive).
950    pub source_mesh_index: Option<usize>,
951}
952
953/// One source skin definition, kept separate from bone-level convenience data.
954#[derive(Debug, Clone, Default)]
955pub struct SourceSkinAsset {
956    /// Stable skin-array index in the source format.
957    pub source_skin_index: usize,
958    /// Authored skin name, when present.
959    pub name: Option<String>,
960    /// Explicitly declared skeleton root, when present; never inferred.
961    pub skeleton_root_source_node_index: Option<usize>,
962    /// Source joints in declared skin-slot order.
963    pub joint_source_node_indices: Vec<usize>,
964    /// Exact inverse-bind accessor evidence for this skin.
965    pub inverse_bind_accessor: SourceInverseBindAccessor,
966    /// Source nodes that reference this skin, in source-node order.
967    pub attachments: Vec<SourceSkinAttachment>,
968}
969
970/// Source-node and source-skin evidence carried beside normalized scene assets.
971#[derive(Debug, Clone, Default)]
972pub struct SourceSkeletonAssets {
973    /// Whether these source tables are complete for the loaded input.
974    pub coverage: SourceSkeletonCoverage,
975    /// Source nodes in stable source-node order.
976    pub nodes: Vec<SourceNodeAsset>,
977    /// Source skins in stable source-skin order.
978    pub skins: Vec<SourceSkinAsset>,
979}
980
981/// An embedded texture: raw encoded image bytes (glTF embeds the file
982/// as-is, no decoding).
983#[derive(Debug, Clone)]
984pub struct TextureAsset {
985    /// Encoded image bytes.
986    pub bytes: Vec<u8>,
987    /// "image/png" or "image/jpeg".
988    pub mime: String,
989}
990
991/// A normal-map texture and the scalar applied to its X/Y components.
992///
993/// Keeping the scale beside the texture makes the glTF normal-texture state
994/// atomic: a scale cannot accidentally survive after its texture is removed.
995#[derive(Debug, Clone)]
996pub struct NormalTextureAsset {
997    /// Embedded encoded normal-map image.
998    pub texture: TextureAsset,
999    /// Scalar multiplier for the decoded tangent-space X/Y components.
1000    pub scale: f32,
1001}
1002
1003/// An occlusion texture and the scalar applied to its sampled value.
1004///
1005/// Keeping the strength beside the texture makes the glTF occlusion-texture
1006/// state atomic: a strength cannot accidentally survive after its texture is
1007/// removed.
1008#[derive(Debug, Clone)]
1009pub struct OcclusionTextureAsset {
1010    /// Embedded encoded occlusion texture.
1011    pub texture: TextureAsset,
1012    /// Scalar multiplier for the sampled occlusion value.
1013    pub strength: f32,
1014}
1015
1016/// PBR material factors plus optional embedded glTF texture slots.
1017#[derive(Debug, Clone)]
1018pub struct MaterialAsset {
1019    /// Material name.
1020    pub name: String,
1021    /// Multiplied with the texture when one is present (set to white
1022    /// by the FBX loader in that case, matching exporter convention).
1023    pub base_color: [f32; 4],
1024    /// Metallic factor.
1025    pub metallic: f32,
1026    /// Roughness factor.
1027    pub roughness: f32,
1028    /// Embedded base-color texture, if one was loaded.
1029    pub base_color_texture: Option<TextureAsset>,
1030    /// Embedded tangent-space normal texture, if one was loaded.
1031    pub normal_texture: Option<NormalTextureAsset>,
1032    /// Embedded metallic-roughness texture, if one was loaded.
1033    ///
1034    /// glTF stores roughness in green and metallic in blue.
1035    pub metallic_roughness_texture: Option<TextureAsset>,
1036    /// Embedded occlusion texture, if one was loaded.
1037    pub occlusion_texture: Option<OcclusionTextureAsset>,
1038}
1039
1040/// Whether source material-resource inspection covers the whole input.
1041///
1042/// This sidecar is deliberately separate from writer-facing [`MaterialAsset`]
1043/// values. A loader may preserve materials for writing while declining to
1044/// inspect resource provenance or decode image metadata.
1045#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1046#[serde(rename_all = "snake_case")]
1047pub enum MaterialResourceCoverage {
1048    /// The loader inspected its complete documented source material-resource
1049    /// domain. Format-specific documentation defines which binding slots that
1050    /// domain includes.
1051    Complete,
1052    /// The loader cannot provide source resource evidence.
1053    #[default]
1054    Unavailable,
1055}
1056
1057/// A material texture slot with stable source-format meaning.
1058///
1059/// Declaration order is the stable wire order used by material-resource
1060/// measurements.
1061#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1062#[serde(rename_all = "snake_case")]
1063pub enum MaterialTextureSlot {
1064    /// Base-color texture.
1065    BaseColor,
1066    /// Tangent-space normal texture.
1067    Normal,
1068    /// Combined metallic-roughness texture.
1069    MetallicRoughness,
1070    /// Occlusion texture.
1071    Occlusion,
1072    /// Emissive texture.
1073    Emissive,
1074}
1075
1076/// One source material-to-texture binding.
1077#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1078pub struct SourceMaterialTextureBinding {
1079    /// Material slot in stable semantic order.
1080    pub slot: MaterialTextureSlot,
1081    /// Stable source texture index.
1082    pub texture_index: usize,
1083}
1084
1085/// One source material definition, independent of writer-facing material data.
1086#[derive(Debug, Clone, Default)]
1087pub struct SourceMaterialAsset {
1088    /// Stable source material index.
1089    pub material_index: usize,
1090    /// Authored name, when present.
1091    pub name: Option<String>,
1092    /// Source texture bindings, sorted by [`SourceMaterialTextureBinding::slot`].
1093    pub texture_bindings: Vec<SourceMaterialTextureBinding>,
1094}
1095
1096/// One source texture definition.
1097#[derive(Debug, Clone, Default)]
1098pub struct SourceTextureAsset {
1099    /// Stable source texture index.
1100    pub texture_index: usize,
1101    /// Authored name, when present.
1102    pub name: Option<String>,
1103    /// Stable source image index referenced by this texture.
1104    pub image_index: usize,
1105}
1106
1107/// How an image payload was declared by its source format.
1108#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1109#[serde(rename_all = "snake_case")]
1110pub enum ImageSourceKind {
1111    /// Bytes embedded directly in a container record.
1112    Embedded,
1113    /// Bytes encoded in a data URI.
1114    DataUri,
1115    /// A relative or otherwise external resource reference.
1116    External,
1117}
1118
1119/// Image container format recognized by inspection.
1120#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1121#[serde(rename_all = "snake_case")]
1122pub enum ImageContainerFormat {
1123    /// PNG image data.
1124    Png,
1125    /// JPEG image data.
1126    Jpeg,
1127}
1128
1129/// Decoded image color representation reported by inspection.
1130#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1131#[serde(rename_all = "snake_case")]
1132pub enum DecodedImageColorType {
1133    /// Single-channel, 8-bit luminance.
1134    L8,
1135    /// Luminance plus alpha, 8-bit channels.
1136    La8,
1137    /// RGB, 8-bit channels.
1138    Rgb8,
1139    /// RGBA, 8-bit channels.
1140    Rgba8,
1141    /// Single-channel, 16-bit luminance.
1142    L16,
1143    /// Luminance plus alpha, 16-bit channels.
1144    La16,
1145    /// RGB, 16-bit channels.
1146    Rgb16,
1147    /// RGBA, 16-bit channels.
1148    Rgba16,
1149}
1150
1151/// Why source-image inspection could not produce decoded metadata.
1152#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1153#[serde(rename_all = "snake_case")]
1154pub enum ImageUnavailableReason {
1155    /// The source does not make the image payload available to the loader.
1156    SourceUnavailable,
1157    /// A data URI could not be parsed or decoded.
1158    InvalidDataUri,
1159    /// The image container is not supported for inspection.
1160    UnsupportedContainer,
1161    /// Supported image bytes could not be decoded.
1162    DecodeFailed,
1163    /// Inspection declined the resource because it exceeded a resource limit.
1164    ResourceLimit,
1165}
1166
1167/// Result of bounded source-image inspection.
1168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1169pub enum SourceImageInspection {
1170    /// Decoded metadata was available without retaining decoded pixels.
1171    Available {
1172        /// Pixel width.
1173        width: u32,
1174        /// Pixel height.
1175        height: u32,
1176        /// Number of decoded channels.
1177        channel_count: u8,
1178        /// Decoded color representation.
1179        color_type: DecodedImageColorType,
1180    },
1181    /// Inspection could not provide decoded metadata.
1182    Unavailable {
1183        /// Stable unavailability reason.
1184        reason: ImageUnavailableReason,
1185    },
1186}
1187
1188/// One source image definition and bounded inspection result.
1189#[derive(Debug, Clone)]
1190pub struct SourceImageAsset {
1191    /// Stable source image index.
1192    pub image_index: usize,
1193    /// Authored name, when present.
1194    pub name: Option<String>,
1195    /// Source declaration kind.
1196    pub source_kind: ImageSourceKind,
1197    /// MIME type declared by the source, when present.
1198    pub declared_mime_type: Option<String>,
1199    /// Detected container format, when recognisable.
1200    pub detected_container: Option<ImageContainerFormat>,
1201    /// Bounded image-inspection result.
1202    pub inspection: SourceImageInspection,
1203}
1204
1205/// Read-only source material-resource evidence carried beside scene assets.
1206#[derive(Debug, Clone, Default)]
1207pub struct MaterialResourceAssets {
1208    /// Whether the source resource lists are complete.
1209    pub coverage: MaterialResourceCoverage,
1210    /// Source materials in source order.
1211    pub materials: Vec<SourceMaterialAsset>,
1212    /// Source textures in source order.
1213    pub textures: Vec<SourceTextureAsset>,
1214    /// Source images in source order.
1215    pub images: Vec<SourceImageAsset>,
1216}
1217
1218impl Primitive {
1219    /// Dedupe identical corners into indexed triangles. Exact
1220    /// bit-equality only — no tolerance welding, so seams authored via
1221    /// split normals/UVs are preserved.
1222    pub fn weld(&mut self) {
1223        if !self.indices.is_empty() || self.positions.is_empty() {
1224            return;
1225        }
1226        let corner_key = |i: usize| -> Vec<u8> {
1227            let mut key = Vec::with_capacity(64);
1228            let mut push_f32s = |vals: &[f32]| {
1229                for v in vals {
1230                    key.extend_from_slice(&v.to_le_bytes());
1231                }
1232            };
1233            push_f32s(&self.positions[i].to_array());
1234            if let Some(n) = self.normals.get(i) {
1235                push_f32s(&n.to_array());
1236            }
1237            if let Some(uv) = self.uvs.get(i) {
1238                push_f32s(uv);
1239            }
1240            if let Some(w) = self.weights.get(i) {
1241                push_f32s(w);
1242            }
1243            if let Some(j) = self.joints.get(i) {
1244                for v in j {
1245                    key.extend_from_slice(&v.to_le_bytes());
1246                }
1247            }
1248            key
1249        };
1250        let mut seen: std::collections::HashMap<Vec<u8>, u32> = std::collections::HashMap::new();
1251        let mut indices = Vec::with_capacity(self.positions.len());
1252        let mut positions = Vec::new();
1253        let mut normals = Vec::new();
1254        let mut uvs = Vec::new();
1255        let mut joints = Vec::new();
1256        let mut weights = Vec::new();
1257        for i in 0..self.positions.len() {
1258            let index = *seen.entry(corner_key(i)).or_insert_with(|| {
1259                positions.push(self.positions[i]);
1260                if let Some(n) = self.normals.get(i) {
1261                    normals.push(*n);
1262                }
1263                if let Some(uv) = self.uvs.get(i) {
1264                    uvs.push(*uv);
1265                }
1266                if let Some(j) = self.joints.get(i) {
1267                    joints.push(*j);
1268                }
1269                if let Some(w) = self.weights.get(i) {
1270                    weights.push(*w);
1271                }
1272                (positions.len() - 1) as u32
1273            });
1274            indices.push(index);
1275        }
1276        self.indices = indices;
1277        self.positions = positions;
1278        self.normals = normals;
1279        self.uvs = uvs;
1280        self.joints = joints;
1281        self.weights = weights;
1282    }
1283}
1284
1285/// Mesh definitions, their node instances, scenes, and materials carried
1286/// alongside animation data.
1287#[derive(Debug, Clone, Default)]
1288pub struct SceneAssets {
1289    /// Mesh definitions in source order, including definitions without a node
1290    /// instance.
1291    pub meshes: Vec<MeshAsset>,
1292    /// Node instances of the mesh definitions, in source node order.
1293    pub instances: Vec<MeshInstance>,
1294    /// Materials referenced by mesh primitives.
1295    pub materials: Vec<MaterialAsset>,
1296    /// Read-only source material, texture, and image evidence for measurement.
1297    /// Writer-facing material slots remain in [`Self::materials`].
1298    pub material_resources: MaterialResourceAssets,
1299    /// Declared source scenes in source order.
1300    pub scenes: Vec<SceneAsset>,
1301    /// Source scene index selected by default, when one was declared.
1302    pub default_scene: Option<usize>,
1303    /// Source-node and source-skin identity evidence for skeleton measurements.
1304    ///
1305    /// This is intentionally separate from the normalized [`Skeleton`] and
1306    /// from [`MeshInstance::skin_ibms`]: a source node order need not match
1307    /// FK order, and one joint can have different inverse binds in different
1308    /// source skins.
1309    pub source_skeleton: SourceSkeletonAssets,
1310}
1311
1312/// Validate the enumerated structural snapshot strict document operations
1313/// rely on.
1314///
1315/// This is a snapshot only: [`Document`] is publicly mutable, so a successful
1316/// call does not certify a document against later mutation. Any strict
1317/// operation that relies on this full shape must rerun validation at its own
1318/// public boundary.
1319/// Tolerant analysis APIs may intentionally accept documents this rejects and
1320/// preserve the valid evidence they can read. This function does not validate
1321/// operation-specific capability, affine, closure, proof, or payload
1322/// invariants such as primitive skinning shape and base positions.
1323///
1324/// # Errors
1325///
1326/// Returns a typed [`DocumentShapeError`] for the first violation in stable
1327/// validation order: skeleton rest/topology, source identity/projection,
1328/// tracks, instances, then bone-level inverse binds.
1329pub fn validate_document_shape(document: &Document) -> Result<(), DocumentShapeError> {
1330    validate_skeleton_rest(&document.skeleton)?;
1331    validate_source_skeleton_identity(&document.assets.source_skeleton)?;
1332    validate_source_projection(document)?;
1333    validate_clip_tracks(document)?;
1334    validate_mesh_instances(document)?;
1335    validate_bone_inverse_binds(&document.skeleton)
1336}
1337
1338fn validate_skeleton_rest(skeleton: &Skeleton) -> Result<(), DocumentShapeError> {
1339    world_rest_matrices(skeleton)
1340        .map(|_| ())
1341        .map_err(|error| match error {
1342            WorldMatrixError::NonFiniteTransform { node } => {
1343                DocumentShapeError::NonFiniteSkeletonRest { node }
1344            }
1345            WorldMatrixError::InvalidParent { node, parent } => {
1346                DocumentShapeError::InvalidSkeletonParent { node, parent }
1347            }
1348        })
1349}
1350
1351fn validate_source_skeleton_identity(
1352    source_skeleton: &SourceSkeletonAssets,
1353) -> Result<(), DocumentShapeError> {
1354    let mut seen_nodes = BTreeSet::new();
1355    for node in &source_skeleton.nodes {
1356        if !seen_nodes.insert(node.source_node_index) {
1357            return Err(DocumentShapeError::DuplicateSourceNodeIndex {
1358                source_node_index: node.source_node_index,
1359            });
1360        }
1361    }
1362    let mut seen_skins = BTreeSet::new();
1363    for skin in &source_skeleton.skins {
1364        if !seen_skins.insert(skin.source_skin_index) {
1365            return Err(DocumentShapeError::DuplicateSourceSkinIndex {
1366                source_skin_index: skin.source_skin_index,
1367            });
1368        }
1369    }
1370    Ok(())
1371}
1372
1373/// Validate the identity relation a `Complete` source projection claims.
1374///
1375/// Projected rows must be injective, preserve each bone's nearest projected
1376/// ancestor, and be downward-closed in the normalized skeleton. Unprojected
1377/// source rows may remain between projected ancestors, and unrelated
1378/// unprojected roots remain legal; totality is not required. Non-`Complete`
1379/// rows are not identity evidence and are deliberately ignored.
1380///
1381/// The rule is load-bearing for consumers such as scale that select a rewrite
1382/// domain through source-node ancestry but apply and prove it through
1383/// [`Skeleton::bones`]. Without agreement, a normalized child can sit outside
1384/// the selected source closure while its parent moves, leaving its displaced
1385/// world rest outside every declared proof walk.
1386fn validate_source_projection(document: &Document) -> Result<(), DocumentShapeError> {
1387    let source_skeleton = &document.assets.source_skeleton;
1388    if source_skeleton.coverage != SourceSkeletonCoverage::Complete {
1389        return Ok(());
1390    }
1391
1392    let bones = &document.skeleton.bones;
1393    let mut bone_of_source = BTreeMap::new();
1394    let mut source_of_bone = BTreeMap::new();
1395    let mut skeleton_parents = Vec::with_capacity(source_skeleton.nodes.len());
1396    for node in &source_skeleton.nodes {
1397        let Some(bone) = node.bone else {
1398            continue;
1399        };
1400        let skeleton_parent = bones
1401            .get(bone)
1402            .ok_or(DocumentShapeError::SourceProjection {
1403                source_node_index: node.source_node_index,
1404                violation: SourceProjectionViolation::ProjectedBoneOutOfRange,
1405            })?
1406            .parent;
1407        if source_of_bone
1408            .insert(bone, node.source_node_index)
1409            .is_some()
1410        {
1411            return Err(DocumentShapeError::SourceProjection {
1412                source_node_index: node.source_node_index,
1413                violation: SourceProjectionViolation::TwoSourceNodesProjectToOneBone,
1414            });
1415        }
1416        bone_of_source.insert(node.source_node_index, bone);
1417        skeleton_parents.push((node, skeleton_parent));
1418    }
1419
1420    let by_source_index: BTreeMap<_, _> = source_skeleton
1421        .nodes
1422        .iter()
1423        .map(|node| (node.source_node_index, node))
1424        .collect();
1425    let unprojected_rows = source_skeleton.nodes.len() - bone_of_source.len();
1426    // Cache only successful suffix resolutions. A malformed suffix still
1427    // fails on the first projected row that reaches it, preserving that row
1428    // as the error owner; a later row is never visited after the error.
1429    let mut resolved_unprojected = BTreeMap::<usize, Option<BoneId>>::new();
1430    for (node, skeleton_parent) in skeleton_parents {
1431        let mut cursor = node.parent_source_node_index;
1432        let mut unresolved_suffix = Vec::new();
1433        let projected_parent = loop {
1434            let Some(parent_source_node_index) = cursor else {
1435                break None;
1436            };
1437            if let Some(&bone) = bone_of_source.get(&parent_source_node_index) {
1438                break Some(bone);
1439            }
1440            if let Some(&projected_parent) = resolved_unprojected.get(&parent_source_node_index) {
1441                break projected_parent;
1442            }
1443            let parent = by_source_index.get(&parent_source_node_index).ok_or(
1444                DocumentShapeError::SourceProjection {
1445                    source_node_index: node.source_node_index,
1446                    violation: SourceProjectionViolation::ParentSourceNodeMissing,
1447                },
1448            )?;
1449            unresolved_suffix.push(parent_source_node_index);
1450            if unresolved_suffix.len() > unprojected_rows {
1451                return Err(DocumentShapeError::SourceProjection {
1452                    source_node_index: node.source_node_index,
1453                    violation: SourceProjectionViolation::CyclicUnprojectedSourceParentChain,
1454                });
1455            }
1456            cursor = parent.parent_source_node_index;
1457        };
1458        for source_node_index in unresolved_suffix {
1459            resolved_unprojected.insert(source_node_index, projected_parent);
1460        }
1461        if projected_parent != skeleton_parent {
1462            return Err(DocumentShapeError::SourceProjection {
1463                source_node_index: node.source_node_index,
1464                violation: SourceProjectionViolation::NearestProjectedParentMismatch,
1465            });
1466        }
1467    }
1468
1469    for (bone, child) in bones.iter().enumerate() {
1470        if source_of_bone.contains_key(&bone) {
1471            continue;
1472        }
1473        if let Some(parent) = child.parent
1474            && let Some(&source_node_index) = source_of_bone.get(&parent)
1475        {
1476            return Err(DocumentShapeError::SourceProjection {
1477                source_node_index,
1478                violation: SourceProjectionViolation::ProjectedBoneHasUnprojectedSkeletonChild,
1479            });
1480        }
1481    }
1482    Ok(())
1483}
1484
1485fn validate_clip_tracks(document: &Document) -> Result<(), DocumentShapeError> {
1486    let bone_count = document.skeleton.bones.len();
1487    for (clip_index, clip) in document.clips.iter().enumerate() {
1488        let mut seen = Vec::with_capacity(clip.tracks.len());
1489        for track in &clip.tracks {
1490            if track.bone >= bone_count {
1491                return Err(DocumentShapeError::TrackShape {
1492                    clip_index,
1493                    node: track.bone,
1494                    violation: TrackShapeViolation::BoneIndexOutOfRange,
1495                });
1496            }
1497            if seen.contains(&(track.bone, track.property)) {
1498                return Err(DocumentShapeError::DuplicateClipTrack {
1499                    clip_index,
1500                    node: track.bone,
1501                    property: track.property,
1502                });
1503            }
1504            seen.push((track.bone, track.property));
1505            validate_track_shape(clip_index, track)?;
1506        }
1507    }
1508    Ok(())
1509}
1510
1511fn validate_track_shape(clip_index: usize, track: &Track) -> Result<(), DocumentShapeError> {
1512    let violation = if track.times.is_empty() {
1513        Some(TrackShapeViolation::EmptyTimes)
1514    } else if track.times.iter().any(|time| !time.is_finite()) {
1515        Some(TrackShapeViolation::NonFiniteTime)
1516    } else if track.times.windows(2).any(|times| times[0] >= times[1]) {
1517        Some(TrackShapeViolation::TimesNotStrictlyIncreasing)
1518    } else {
1519        let expected_values = match track.interpolation {
1520            Interpolation::CubicSpline => track.times.len().checked_mul(3),
1521            Interpolation::Linear | Interpolation::Step => Some(track.times.len()),
1522        };
1523        if expected_values != Some(track.values.len()) {
1524            Some(TrackShapeViolation::ValueCountMismatch)
1525        } else if !matches!(
1526            (&track.values, track.property),
1527            (
1528                TrackValues::Vec3s(_),
1529                Property::Translation | Property::Scale
1530            ) | (TrackValues::Quats(_), Property::Rotation)
1531        ) {
1532            Some(TrackShapeViolation::ValueTypeMismatchesProperty)
1533        } else if match &track.values {
1534            TrackValues::Vec3s(values) => values.iter().any(|value| !value.is_finite()),
1535            TrackValues::Quats(values) => values.iter().any(|value| !value.is_finite()),
1536        } {
1537            Some(TrackShapeViolation::NonFiniteValue)
1538        } else {
1539            None
1540        }
1541    };
1542    violation.map_or(Ok(()), |violation| {
1543        Err(DocumentShapeError::TrackShape {
1544            clip_index,
1545            node: track.bone,
1546            violation,
1547        })
1548    })
1549}
1550
1551fn validate_mesh_instances(document: &Document) -> Result<(), DocumentShapeError> {
1552    let bone_count = document.skeleton.bones.len();
1553    let mesh_count = document.assets.meshes.len();
1554    for (instance_index, instance) in document.assets.instances.iter().enumerate() {
1555        let violation = if instance.node >= bone_count {
1556            Some(MeshInstanceShapeViolation::NodeIndexOutOfRange)
1557        } else if instance.mesh >= mesh_count {
1558            Some(MeshInstanceShapeViolation::MeshIndexOutOfRange)
1559        } else if instance
1560            .skin_joints
1561            .iter()
1562            .any(|&joint| joint >= bone_count)
1563        {
1564            Some(MeshInstanceShapeViolation::SkinJointOutOfRange)
1565        } else if !instance.skin_ibms.is_empty()
1566            && instance.skin_ibms.len() != instance.skin_joints.len()
1567        {
1568            Some(MeshInstanceShapeViolation::SkinInverseBindCountMismatch)
1569        } else if instance.skin_ibms.iter().any(|ibm| !mat4_is_finite(*ibm)) {
1570            Some(MeshInstanceShapeViolation::NonFiniteSkinInverseBind)
1571        } else {
1572            None
1573        };
1574        if let Some(violation) = violation {
1575            return Err(DocumentShapeError::MeshInstanceShape {
1576                instance_index,
1577                violation,
1578            });
1579        }
1580    }
1581    Ok(())
1582}
1583
1584fn validate_bone_inverse_binds(skeleton: &Skeleton) -> Result<(), DocumentShapeError> {
1585    for (node, bone) in skeleton.bones.iter().enumerate() {
1586        if let Some(inverse_bind) = bone.inverse_bind
1587            && !mat4_is_finite(inverse_bind)
1588        {
1589            return Err(DocumentShapeError::NonFiniteBoneInverseBind { node });
1590        }
1591    }
1592    Ok(())
1593}
1594
1595#[cfg(test)]
1596mod tests {
1597    use super::*;
1598
1599    fn bone(parent: Option<BoneId>) -> Bone {
1600        Bone {
1601            name: "bone".into(),
1602            parent,
1603            rest: Transform::IDENTITY,
1604            inverse_bind: None,
1605        }
1606    }
1607
1608    fn one_bone_document() -> Document {
1609        Document {
1610            skeleton: Skeleton {
1611                bones: vec![bone(None)],
1612            },
1613            ..Document::default()
1614        }
1615    }
1616
1617    fn source_node(
1618        source_node_index: usize,
1619        parent_source_node_index: Option<usize>,
1620        bone: Option<BoneId>,
1621    ) -> SourceNodeAsset {
1622        SourceNodeAsset {
1623            source_node_index,
1624            name: None,
1625            parent_source_node_index,
1626            scene_root_indices: Vec::new(),
1627            local_rest: SourceNodeLocalRest::Trs {
1628                translation: Vec3::ZERO,
1629                rotation: Quat::IDENTITY,
1630                scale: Vec3::ONE,
1631            },
1632            bone,
1633        }
1634    }
1635
1636    fn valid_track() -> Track {
1637        Track {
1638            bone: 0,
1639            property: Property::Translation,
1640            interpolation: Interpolation::Linear,
1641            times: vec![0.0],
1642            values: TrackValues::Vec3s(vec![Vec3::ZERO]),
1643        }
1644    }
1645
1646    fn track_document(track: Track) -> Document {
1647        let mut document = one_bone_document();
1648        document.clips.push(Clip {
1649            name: "clip".into(),
1650            duration_s: 0.0,
1651            tracks: vec![track],
1652        });
1653        document
1654    }
1655
1656    fn instance_document() -> Document {
1657        let mut document = one_bone_document();
1658        document.assets.meshes.push(MeshAsset::default());
1659        document.assets.instances.push(MeshInstance {
1660            node: 0,
1661            mesh: 0,
1662            ..MeshInstance::default()
1663        });
1664        document
1665    }
1666
1667    #[test]
1668    fn document_shape_validation_accepts_a_complete_projection_with_an_unprojected_intermediate() {
1669        let mut document = Document {
1670            skeleton: Skeleton {
1671                bones: vec![bone(None), bone(Some(0))],
1672            },
1673            assets: SceneAssets {
1674                source_skeleton: SourceSkeletonAssets {
1675                    coverage: SourceSkeletonCoverage::Complete,
1676                    nodes: vec![
1677                        source_node(10, None, Some(0)),
1678                        source_node(11, Some(10), None),
1679                        source_node(12, Some(11), Some(1)),
1680                    ],
1681                    ..SourceSkeletonAssets::default()
1682                },
1683                meshes: vec![MeshAsset::default()],
1684                instances: vec![MeshInstance {
1685                    node: 1,
1686                    mesh: 0,
1687                    skin_joints: vec![0, 1],
1688                    skin_ibms: vec![Mat4::IDENTITY, Mat4::IDENTITY],
1689                    ..MeshInstance::default()
1690                }],
1691                ..SceneAssets::default()
1692            },
1693            ..Document::default()
1694        };
1695        document.clips.push(Clip {
1696            name: "clip".into(),
1697            duration_s: 0.0,
1698            tracks: vec![valid_track()],
1699        });
1700
1701        assert_eq!(validate_document_shape(&document), Ok(()));
1702    }
1703
1704    #[test]
1705    fn shared_unprojected_parent_suffix_preserves_each_projected_parent() {
1706        const CONNECTORS: usize = 64;
1707        const PROJECTED_CHILDREN: usize = 64;
1708
1709        let mut nodes = Vec::with_capacity(1 + CONNECTORS + PROJECTED_CHILDREN);
1710        nodes.push(source_node(0, None, Some(0)));
1711        for source_node_index in 1..=CONNECTORS {
1712            nodes.push(source_node(
1713                source_node_index,
1714                Some(source_node_index - 1),
1715                None,
1716            ));
1717        }
1718        for child in 0..PROJECTED_CHILDREN {
1719            nodes.push(source_node(
1720                1 + CONNECTORS + child,
1721                Some(CONNECTORS),
1722                Some(1 + child),
1723            ));
1724        }
1725        let document = Document {
1726            skeleton: Skeleton {
1727                bones: std::iter::once(bone(None))
1728                    .chain((0..PROJECTED_CHILDREN).map(|_| bone(Some(0))))
1729                    .collect(),
1730            },
1731            assets: SceneAssets {
1732                source_skeleton: SourceSkeletonAssets {
1733                    coverage: SourceSkeletonCoverage::Complete,
1734                    nodes,
1735                    ..SourceSkeletonAssets::default()
1736                },
1737                ..SceneAssets::default()
1738            },
1739            ..Document::default()
1740        };
1741
1742        assert_eq!(validate_document_shape(&document), Ok(()));
1743        let mut mismatched = document.clone();
1744        mismatched.skeleton.bones[PROJECTED_CHILDREN].parent = None;
1745        assert_eq!(
1746            validate_document_shape(&mismatched),
1747            Err(DocumentShapeError::SourceProjection {
1748                source_node_index: CONNECTORS + PROJECTED_CHILDREN,
1749                violation: SourceProjectionViolation::NearestProjectedParentMismatch,
1750            })
1751        );
1752    }
1753
1754    #[test]
1755    fn document_shape_validation_has_an_analytic_error_for_every_variant() {
1756        let projection_error =
1757            |source_node_index, violation| DocumentShapeError::SourceProjection {
1758                source_node_index,
1759                violation,
1760            };
1761        let track_error = |node, violation| DocumentShapeError::TrackShape {
1762            clip_index: 0,
1763            node,
1764            violation,
1765        };
1766        let instance_error = |violation| DocumentShapeError::MeshInstanceShape {
1767            instance_index: 0,
1768            violation,
1769        };
1770
1771        let mut non_finite_rest = one_bone_document();
1772        non_finite_rest.skeleton.bones[0].rest.translation.x = f32::NAN;
1773        let overflowed_rest_world = Document {
1774            skeleton: Skeleton {
1775                bones: vec![
1776                    Bone {
1777                        rest: Transform {
1778                            scale: Vec3::splat(f32::MAX),
1779                            ..Transform::IDENTITY
1780                        },
1781                        ..bone(None)
1782                    },
1783                    Bone {
1784                        rest: Transform {
1785                            translation: Vec3::splat(2.0),
1786                            ..Transform::IDENTITY
1787                        },
1788                        ..bone(Some(0))
1789                    },
1790                ],
1791            },
1792            ..Document::default()
1793        };
1794        let self_parent = Document {
1795            skeleton: Skeleton {
1796                bones: vec![bone(Some(0))],
1797            },
1798            ..Document::default()
1799        };
1800        let forward_parent = Document {
1801            skeleton: Skeleton {
1802                bones: vec![bone(Some(1)), bone(None)],
1803            },
1804            ..Document::default()
1805        };
1806        let far_parent = Document {
1807            skeleton: Skeleton {
1808                bones: vec![bone(Some(99))],
1809            },
1810            ..Document::default()
1811        };
1812        let duplicate_node = Document {
1813            assets: SceneAssets {
1814                source_skeleton: SourceSkeletonAssets {
1815                    nodes: vec![
1816                        source_node(9, None, None),
1817                        source_node(10, None, None),
1818                        source_node(9, None, None),
1819                    ],
1820                    ..SourceSkeletonAssets::default()
1821                },
1822                ..SceneAssets::default()
1823            },
1824            ..Document::default()
1825        };
1826        let duplicate_skin = Document {
1827            assets: SceneAssets {
1828                source_skeleton: SourceSkeletonAssets {
1829                    skins: vec![
1830                        SourceSkinAsset {
1831                            source_skin_index: 4,
1832                            ..SourceSkinAsset::default()
1833                        },
1834                        SourceSkinAsset {
1835                            source_skin_index: 5,
1836                            ..SourceSkinAsset::default()
1837                        },
1838                        SourceSkinAsset {
1839                            source_skin_index: 4,
1840                            ..SourceSkinAsset::default()
1841                        },
1842                    ],
1843                    ..SourceSkeletonAssets::default()
1844                },
1845                ..SceneAssets::default()
1846            },
1847            ..Document::default()
1848        };
1849        let complete_projection = |nodes| SceneAssets {
1850            source_skeleton: SourceSkeletonAssets {
1851                coverage: SourceSkeletonCoverage::Complete,
1852                nodes,
1853                ..SourceSkeletonAssets::default()
1854            },
1855            ..SceneAssets::default()
1856        };
1857        let out_of_range_projection = Document {
1858            skeleton: Skeleton {
1859                bones: vec![bone(None)],
1860            },
1861            assets: complete_projection(vec![source_node(10, None, Some(1))]),
1862            ..Document::default()
1863        };
1864        let non_injective_projection = Document {
1865            skeleton: Skeleton {
1866                bones: vec![bone(None)],
1867            },
1868            assets: complete_projection(vec![
1869                source_node(10, None, Some(0)),
1870                source_node(11, None, Some(0)),
1871            ]),
1872            ..Document::default()
1873        };
1874        let missing_projection_parent = Document {
1875            skeleton: Skeleton {
1876                bones: vec![bone(None), bone(Some(0))],
1877            },
1878            assets: complete_projection(vec![source_node(11, Some(99), Some(1))]),
1879            ..Document::default()
1880        };
1881        // Exactly one unprojected row lies between projected child 11 and the
1882        // genuinely missing parent 99. The strict `> unprojected_rows` guard
1883        // must preserve the missing-parent classification; `>=` reports a
1884        // cycle at this exact boundary instead.
1885        let missing_projection_parent_at_cycle_bound = Document {
1886            skeleton: Skeleton {
1887                bones: vec![bone(None), bone(Some(0))],
1888            },
1889            assets: complete_projection(vec![
1890                source_node(10, None, Some(0)),
1891                source_node(11, Some(12), Some(1)),
1892                source_node(12, Some(99), None),
1893            ]),
1894            ..Document::default()
1895        };
1896        let cyclic_unprojected_parent = Document {
1897            skeleton: Skeleton {
1898                bones: vec![bone(None), bone(Some(0))],
1899            },
1900            assets: complete_projection(vec![
1901                source_node(11, Some(12), Some(1)),
1902                source_node(12, Some(12), None),
1903            ]),
1904            ..Document::default()
1905        };
1906        let cyclic_unprojected_parent_pair = Document {
1907            skeleton: Skeleton {
1908                bones: vec![bone(None), bone(Some(0))],
1909            },
1910            assets: complete_projection(vec![
1911                source_node(11, Some(12), Some(1)),
1912                source_node(12, Some(13), None),
1913                source_node(13, Some(12), None),
1914            ]),
1915            ..Document::default()
1916        };
1917        let mismatched_nearest_parent = Document {
1918            skeleton: Skeleton {
1919                bones: vec![bone(None), bone(Some(0))],
1920            },
1921            assets: complete_projection(vec![
1922                source_node(10, None, Some(0)),
1923                source_node(11, None, Some(1)),
1924            ]),
1925            ..Document::default()
1926        };
1927        let unprojected_child = Document {
1928            skeleton: Skeleton {
1929                bones: vec![bone(None), bone(Some(0))],
1930            },
1931            assets: complete_projection(vec![source_node(10, None, Some(0))]),
1932            ..Document::default()
1933        };
1934
1935        let duplicate_track = {
1936            let track = valid_track();
1937            let mut document = track_document(track.clone());
1938            document.clips[0].tracks.push(Track {
1939                property: Property::Scale,
1940                ..valid_track()
1941            });
1942            document.clips[0].tracks.push(track);
1943            document
1944        };
1945        let mut boundary_out_of_range_track = valid_track();
1946        boundary_out_of_range_track.bone = 1;
1947        let mut far_out_of_range_track = valid_track();
1948        far_out_of_range_track.bone = 99;
1949        let empty_track = Track {
1950            times: Vec::new(),
1951            values: TrackValues::Vec3s(Vec::new()),
1952            ..valid_track()
1953        };
1954        let non_finite_later_time = Track {
1955            times: vec![0.0, f32::NAN],
1956            values: TrackValues::Vec3s(vec![Vec3::ZERO, Vec3::ZERO]),
1957            ..valid_track()
1958        };
1959        let unordered_times = Track {
1960            times: vec![1.0, 0.0],
1961            values: TrackValues::Vec3s(vec![Vec3::ZERO, Vec3::ZERO]),
1962            ..valid_track()
1963        };
1964        let equal_times = Track {
1965            times: vec![0.0, 0.0],
1966            values: TrackValues::Vec3s(vec![Vec3::ZERO, Vec3::ZERO]),
1967            ..valid_track()
1968        };
1969        let wrong_linear_value_count = Track {
1970            values: TrackValues::Vec3s(Vec::new()),
1971            ..valid_track()
1972        };
1973        let excess_linear_value_count = Track {
1974            values: TrackValues::Vec3s(vec![Vec3::ZERO, Vec3::ZERO]),
1975            ..valid_track()
1976        };
1977        let wrong_step_value_count = Track {
1978            interpolation: Interpolation::Step,
1979            times: vec![0.0, 1.0],
1980            values: TrackValues::Vec3s(vec![Vec3::ZERO]),
1981            ..valid_track()
1982        };
1983        let excess_step_value_count = Track {
1984            interpolation: Interpolation::Step,
1985            values: TrackValues::Vec3s(vec![Vec3::ZERO, Vec3::ZERO]),
1986            ..valid_track()
1987        };
1988        let wrong_cubic_value_count = Track {
1989            interpolation: Interpolation::CubicSpline,
1990            times: vec![0.0, 1.0],
1991            values: TrackValues::Vec3s(vec![Vec3::ZERO; 4]),
1992            ..valid_track()
1993        };
1994        let excess_cubic_value_count = Track {
1995            interpolation: Interpolation::CubicSpline,
1996            values: TrackValues::Vec3s(vec![Vec3::ZERO; 4]),
1997            ..valid_track()
1998        };
1999        let wrong_translation_value_type = Track {
2000            values: TrackValues::Quats(vec![Quat::IDENTITY]),
2001            ..valid_track()
2002        };
2003        let wrong_scale_value_type = Track {
2004            property: Property::Scale,
2005            values: TrackValues::Quats(vec![Quat::IDENTITY]),
2006            ..valid_track()
2007        };
2008        let wrong_rotation_value_type = Track {
2009            property: Property::Rotation,
2010            values: TrackValues::Vec3s(vec![Vec3::ZERO]),
2011            ..valid_track()
2012        };
2013        let non_finite_value = Track {
2014            values: TrackValues::Vec3s(vec![Vec3::splat(f32::NAN)]),
2015            ..valid_track()
2016        };
2017
2018        let mut bad_instance_node = instance_document();
2019        bad_instance_node.assets.instances[0].node = 1;
2020        let mut far_instance_node = instance_document();
2021        far_instance_node.assets.instances[0].node = 99;
2022        let mut bad_instance_mesh = instance_document();
2023        bad_instance_mesh.assets.instances[0].mesh = 1;
2024        let mut far_instance_mesh = instance_document();
2025        far_instance_mesh.assets.instances[0].mesh = 99;
2026        let mut bad_instance_joint = instance_document();
2027        bad_instance_joint.assets.instances[0].skin_joints = vec![1];
2028        let mut far_instance_joint = instance_document();
2029        far_instance_joint.assets.instances[0].skin_joints = vec![99];
2030        let mut bad_instance_count = instance_document();
2031        bad_instance_count.assets.instances[0].skin_joints = vec![0];
2032        bad_instance_count.assets.instances[0].skin_ibms = vec![Mat4::IDENTITY, Mat4::IDENTITY];
2033        let mut short_instance_count = instance_document();
2034        short_instance_count.skeleton.bones.push(bone(Some(0)));
2035        short_instance_count.assets.instances[0].skin_joints = vec![0, 1];
2036        short_instance_count.assets.instances[0].skin_ibms = vec![Mat4::IDENTITY];
2037        let mut bad_instance_ibm = instance_document();
2038        bad_instance_ibm.assets.instances[0].skin_joints = vec![0];
2039        bad_instance_ibm.assets.instances[0].skin_ibms =
2040            vec![Mat4::from_cols_array(&[f32::NAN; 16])];
2041        let mut bad_bone_ibm = one_bone_document();
2042        bad_bone_ibm.skeleton.bones[0].inverse_bind = Some(Mat4::from_cols_array(&[f32::NAN; 16]));
2043
2044        let cases = vec![
2045            (
2046                "non-finite rest",
2047                non_finite_rest,
2048                DocumentShapeError::NonFiniteSkeletonRest { node: 0 },
2049            ),
2050            (
2051                "non-finite composed rest world",
2052                overflowed_rest_world,
2053                DocumentShapeError::NonFiniteSkeletonRest { node: 1 },
2054            ),
2055            (
2056                "self parent",
2057                self_parent,
2058                DocumentShapeError::InvalidSkeletonParent { node: 0, parent: 0 },
2059            ),
2060            (
2061                "forward parent",
2062                forward_parent,
2063                DocumentShapeError::InvalidSkeletonParent { node: 0, parent: 1 },
2064            ),
2065            (
2066                "far parent",
2067                far_parent,
2068                DocumentShapeError::InvalidSkeletonParent {
2069                    node: 0,
2070                    parent: 99,
2071                },
2072            ),
2073            (
2074                "duplicate source node",
2075                duplicate_node,
2076                DocumentShapeError::DuplicateSourceNodeIndex {
2077                    source_node_index: 9,
2078                },
2079            ),
2080            (
2081                "duplicate source skin",
2082                duplicate_skin,
2083                DocumentShapeError::DuplicateSourceSkinIndex {
2084                    source_skin_index: 4,
2085                },
2086            ),
2087            (
2088                "projected bone range",
2089                out_of_range_projection,
2090                projection_error(10, SourceProjectionViolation::ProjectedBoneOutOfRange),
2091            ),
2092            (
2093                "projection injectivity",
2094                non_injective_projection,
2095                projection_error(
2096                    11,
2097                    SourceProjectionViolation::TwoSourceNodesProjectToOneBone,
2098                ),
2099            ),
2100            (
2101                "missing projection parent",
2102                missing_projection_parent,
2103                projection_error(11, SourceProjectionViolation::ParentSourceNodeMissing),
2104            ),
2105            (
2106                "missing projection parent at cycle bound",
2107                missing_projection_parent_at_cycle_bound,
2108                projection_error(11, SourceProjectionViolation::ParentSourceNodeMissing),
2109            ),
2110            (
2111                "cyclic projection parent",
2112                cyclic_unprojected_parent,
2113                projection_error(
2114                    11,
2115                    SourceProjectionViolation::CyclicUnprojectedSourceParentChain,
2116                ),
2117            ),
2118            (
2119                "cyclic projection parent pair",
2120                cyclic_unprojected_parent_pair,
2121                projection_error(
2122                    11,
2123                    SourceProjectionViolation::CyclicUnprojectedSourceParentChain,
2124                ),
2125            ),
2126            (
2127                "nearest projection parent",
2128                mismatched_nearest_parent,
2129                projection_error(
2130                    11,
2131                    SourceProjectionViolation::NearestProjectedParentMismatch,
2132                ),
2133            ),
2134            (
2135                "projection downward closure",
2136                unprojected_child,
2137                projection_error(
2138                    10,
2139                    SourceProjectionViolation::ProjectedBoneHasUnprojectedSkeletonChild,
2140                ),
2141            ),
2142            (
2143                "duplicate track",
2144                duplicate_track,
2145                DocumentShapeError::DuplicateClipTrack {
2146                    clip_index: 0,
2147                    node: 0,
2148                    property: Property::Translation,
2149                },
2150            ),
2151            (
2152                "track bone range boundary",
2153                track_document(boundary_out_of_range_track),
2154                track_error(1, TrackShapeViolation::BoneIndexOutOfRange),
2155            ),
2156            (
2157                "track bone range far",
2158                track_document(far_out_of_range_track),
2159                track_error(99, TrackShapeViolation::BoneIndexOutOfRange),
2160            ),
2161            (
2162                "empty track",
2163                track_document(empty_track),
2164                track_error(0, TrackShapeViolation::EmptyTimes),
2165            ),
2166            (
2167                "non-finite time",
2168                track_document(non_finite_later_time),
2169                track_error(0, TrackShapeViolation::NonFiniteTime),
2170            ),
2171            (
2172                "unordered times",
2173                track_document(unordered_times),
2174                track_error(0, TrackShapeViolation::TimesNotStrictlyIncreasing),
2175            ),
2176            (
2177                "equal times",
2178                track_document(equal_times),
2179                track_error(0, TrackShapeViolation::TimesNotStrictlyIncreasing),
2180            ),
2181            (
2182                "linear value count",
2183                track_document(wrong_linear_value_count),
2184                track_error(0, TrackShapeViolation::ValueCountMismatch),
2185            ),
2186            (
2187                "linear excess value count",
2188                track_document(excess_linear_value_count),
2189                track_error(0, TrackShapeViolation::ValueCountMismatch),
2190            ),
2191            (
2192                "step value count",
2193                track_document(wrong_step_value_count),
2194                track_error(0, TrackShapeViolation::ValueCountMismatch),
2195            ),
2196            (
2197                "step excess value count",
2198                track_document(excess_step_value_count),
2199                track_error(0, TrackShapeViolation::ValueCountMismatch),
2200            ),
2201            (
2202                "cubic value count",
2203                track_document(wrong_cubic_value_count),
2204                track_error(0, TrackShapeViolation::ValueCountMismatch),
2205            ),
2206            (
2207                "cubic excess value count",
2208                track_document(excess_cubic_value_count),
2209                track_error(0, TrackShapeViolation::ValueCountMismatch),
2210            ),
2211            (
2212                "translation value type",
2213                track_document(wrong_translation_value_type),
2214                track_error(0, TrackShapeViolation::ValueTypeMismatchesProperty),
2215            ),
2216            (
2217                "scale value type",
2218                track_document(wrong_scale_value_type),
2219                track_error(0, TrackShapeViolation::ValueTypeMismatchesProperty),
2220            ),
2221            (
2222                "rotation value type",
2223                track_document(wrong_rotation_value_type),
2224                track_error(0, TrackShapeViolation::ValueTypeMismatchesProperty),
2225            ),
2226            (
2227                "non-finite value",
2228                track_document(non_finite_value),
2229                track_error(0, TrackShapeViolation::NonFiniteValue),
2230            ),
2231            (
2232                "instance node boundary",
2233                bad_instance_node,
2234                instance_error(MeshInstanceShapeViolation::NodeIndexOutOfRange),
2235            ),
2236            (
2237                "instance node far",
2238                far_instance_node,
2239                instance_error(MeshInstanceShapeViolation::NodeIndexOutOfRange),
2240            ),
2241            (
2242                "instance mesh boundary",
2243                bad_instance_mesh,
2244                instance_error(MeshInstanceShapeViolation::MeshIndexOutOfRange),
2245            ),
2246            (
2247                "instance mesh far",
2248                far_instance_mesh,
2249                instance_error(MeshInstanceShapeViolation::MeshIndexOutOfRange),
2250            ),
2251            (
2252                "instance joint boundary",
2253                bad_instance_joint,
2254                instance_error(MeshInstanceShapeViolation::SkinJointOutOfRange),
2255            ),
2256            (
2257                "instance joint far",
2258                far_instance_joint,
2259                instance_error(MeshInstanceShapeViolation::SkinJointOutOfRange),
2260            ),
2261            (
2262                "instance ibm count excess",
2263                bad_instance_count,
2264                instance_error(MeshInstanceShapeViolation::SkinInverseBindCountMismatch),
2265            ),
2266            (
2267                "instance ibm count short",
2268                short_instance_count,
2269                instance_error(MeshInstanceShapeViolation::SkinInverseBindCountMismatch),
2270            ),
2271            (
2272                "instance ibm finite",
2273                bad_instance_ibm,
2274                instance_error(MeshInstanceShapeViolation::NonFiniteSkinInverseBind),
2275            ),
2276            (
2277                "bone ibm finite",
2278                bad_bone_ibm,
2279                DocumentShapeError::NonFiniteBoneInverseBind { node: 0 },
2280            ),
2281        ];
2282        for (name, document, expected) in cases {
2283            assert_eq!(validate_document_shape(&document), Err(expected), "{name}");
2284        }
2285    }
2286
2287    #[test]
2288    fn document_shape_finiteness_checks_every_stored_component() {
2289        for component in 0..3 {
2290            let mut translation = Vec3::ZERO.to_array();
2291            translation[component] = f32::NAN;
2292            let mut document = one_bone_document();
2293            document.skeleton.bones[0].rest.translation = Vec3::from_array(translation);
2294            assert_eq!(
2295                validate_document_shape(&document),
2296                Err(DocumentShapeError::NonFiniteSkeletonRest { node: 0 }),
2297                "rest translation component {component}"
2298            );
2299
2300            let mut scale = Vec3::ONE.to_array();
2301            scale[component] = f32::NAN;
2302            let mut document = one_bone_document();
2303            document.skeleton.bones[0].rest.scale = Vec3::from_array(scale);
2304            assert_eq!(
2305                validate_document_shape(&document),
2306                Err(DocumentShapeError::NonFiniteSkeletonRest { node: 0 }),
2307                "rest scale component {component}"
2308            );
2309
2310            let mut value = Vec3::ZERO.to_array();
2311            value[component] = f32::NAN;
2312            let document = track_document(Track {
2313                values: TrackValues::Vec3s(vec![Vec3::from_array(value)]),
2314                ..valid_track()
2315            });
2316            assert_eq!(
2317                validate_document_shape(&document),
2318                Err(DocumentShapeError::TrackShape {
2319                    clip_index: 0,
2320                    node: 0,
2321                    violation: TrackShapeViolation::NonFiniteValue,
2322                }),
2323                "track Vec3 component {component}"
2324            );
2325        }
2326
2327        for component in 0..4 {
2328            let mut rotation = Quat::IDENTITY.to_array();
2329            rotation[component] = f32::NAN;
2330            let mut document = one_bone_document();
2331            document.skeleton.bones[0].rest.rotation = Quat::from_array(rotation);
2332            assert_eq!(
2333                validate_document_shape(&document),
2334                Err(DocumentShapeError::NonFiniteSkeletonRest { node: 0 }),
2335                "rest rotation component {component}"
2336            );
2337
2338            let document = track_document(Track {
2339                property: Property::Rotation,
2340                values: TrackValues::Quats(vec![Quat::from_array(rotation)]),
2341                ..valid_track()
2342            });
2343            assert_eq!(
2344                validate_document_shape(&document),
2345                Err(DocumentShapeError::TrackShape {
2346                    clip_index: 0,
2347                    node: 0,
2348                    violation: TrackShapeViolation::NonFiniteValue,
2349                }),
2350                "track quaternion component {component}"
2351            );
2352        }
2353
2354        for key in 0..3 {
2355            let mut times = vec![0.0, 1.0, 2.0];
2356            times[key] = f32::NAN;
2357            let document = track_document(Track {
2358                times,
2359                values: TrackValues::Vec3s(vec![Vec3::ZERO; 3]),
2360                ..valid_track()
2361            });
2362            assert_eq!(
2363                validate_document_shape(&document),
2364                Err(DocumentShapeError::TrackShape {
2365                    clip_index: 0,
2366                    node: 0,
2367                    violation: TrackShapeViolation::NonFiniteTime,
2368                }),
2369                "track time {key}"
2370            );
2371        }
2372
2373        for component in 0..16 {
2374            let mut columns = Mat4::IDENTITY.to_cols_array();
2375            columns[component] = f32::NAN;
2376            let inverse_bind = Mat4::from_cols_array(&columns);
2377
2378            let mut instance_document = instance_document();
2379            instance_document.assets.instances[0].skin_joints = vec![0];
2380            instance_document.assets.instances[0].skin_ibms = vec![inverse_bind];
2381            assert_eq!(
2382                validate_document_shape(&instance_document),
2383                Err(DocumentShapeError::MeshInstanceShape {
2384                    instance_index: 0,
2385                    violation: MeshInstanceShapeViolation::NonFiniteSkinInverseBind,
2386                }),
2387                "instance inverse-bind component {component}"
2388            );
2389
2390            let mut bone_document = one_bone_document();
2391            bone_document.skeleton.bones[0].inverse_bind = Some(inverse_bind);
2392            assert_eq!(
2393                validate_document_shape(&bone_document),
2394                Err(DocumentShapeError::NonFiniteBoneInverseBind { node: 0 }),
2395                "bone inverse-bind component {component}"
2396            );
2397        }
2398    }
2399
2400    #[test]
2401    fn document_shape_rejects_duplicate_tracks_for_every_property() {
2402        let tracks = [
2403            (Property::Translation, TrackValues::Vec3s(vec![Vec3::ZERO])),
2404            (Property::Scale, TrackValues::Vec3s(vec![Vec3::ONE])),
2405            (Property::Rotation, TrackValues::Quats(vec![Quat::IDENTITY])),
2406        ];
2407
2408        for (property, values) in tracks {
2409            let track = Track {
2410                property,
2411                values,
2412                ..valid_track()
2413            };
2414            let mut document = track_document(track.clone());
2415            document.clips[0].tracks.push(track);
2416
2417            assert_eq!(
2418                validate_document_shape(&document),
2419                Err(DocumentShapeError::DuplicateClipTrack {
2420                    clip_index: 0,
2421                    node: 0,
2422                    property,
2423                }),
2424                "duplicate {property:?} track"
2425            );
2426        }
2427    }
2428
2429    #[test]
2430    fn document_shape_rejects_infinite_times_quaternions_and_inverse_binds() {
2431        for non_finite in [f32::INFINITY, f32::NEG_INFINITY] {
2432            let document = track_document(Track {
2433                times: vec![non_finite],
2434                values: TrackValues::Vec3s(vec![Vec3::ZERO]),
2435                ..valid_track()
2436            });
2437            assert_eq!(
2438                validate_document_shape(&document),
2439                Err(DocumentShapeError::TrackShape {
2440                    clip_index: 0,
2441                    node: 0,
2442                    violation: TrackShapeViolation::NonFiniteTime,
2443                }),
2444                "track time {non_finite}"
2445            );
2446
2447            let document = track_document(Track {
2448                property: Property::Rotation,
2449                values: TrackValues::Quats(vec![Quat::from_xyzw(non_finite, 0.0, 0.0, 1.0)]),
2450                ..valid_track()
2451            });
2452            assert_eq!(
2453                validate_document_shape(&document),
2454                Err(DocumentShapeError::TrackShape {
2455                    clip_index: 0,
2456                    node: 0,
2457                    violation: TrackShapeViolation::NonFiniteValue,
2458                }),
2459                "track quaternion {non_finite}"
2460            );
2461
2462            let mut columns = Mat4::IDENTITY.to_cols_array();
2463            columns[0] = non_finite;
2464            let inverse_bind = Mat4::from_cols_array(&columns);
2465            let mut document = instance_document();
2466            document.assets.instances[0].skin_joints = vec![0];
2467            document.assets.instances[0].skin_ibms = vec![inverse_bind];
2468            assert_eq!(
2469                validate_document_shape(&document),
2470                Err(DocumentShapeError::MeshInstanceShape {
2471                    instance_index: 0,
2472                    violation: MeshInstanceShapeViolation::NonFiniteSkinInverseBind,
2473                }),
2474                "instance inverse bind {non_finite}"
2475            );
2476
2477            let mut document = one_bone_document();
2478            document.skeleton.bones[0].inverse_bind = Some(inverse_bind);
2479            assert_eq!(
2480                validate_document_shape(&document),
2481                Err(DocumentShapeError::NonFiniteBoneInverseBind { node: 0 }),
2482                "bone inverse bind {non_finite}"
2483            );
2484        }
2485    }
2486
2487    #[test]
2488    fn document_shape_checks_mesh_and_joint_references_on_later_instances() {
2489        let later_instance = MeshInstance {
2490            node: 0,
2491            mesh: 0,
2492            ..MeshInstance::default()
2493        };
2494
2495        let mut document = instance_document();
2496        document.assets.instances.push(later_instance.clone());
2497        document.assets.instances[1].mesh = 1;
2498        assert_eq!(
2499            validate_document_shape(&document),
2500            Err(DocumentShapeError::MeshInstanceShape {
2501                instance_index: 1,
2502                violation: MeshInstanceShapeViolation::MeshIndexOutOfRange,
2503            })
2504        );
2505
2506        let mut document = instance_document();
2507        document.assets.instances.push(later_instance);
2508        document.assets.instances[1].skin_joints = vec![1];
2509        assert_eq!(
2510            validate_document_shape(&document),
2511            Err(DocumentShapeError::MeshInstanceShape {
2512                instance_index: 1,
2513                violation: MeshInstanceShapeViolation::SkinJointOutOfRange,
2514            })
2515        );
2516    }
2517
2518    #[test]
2519    fn document_shape_finds_duplicates_that_do_not_involve_the_first_item() {
2520        let mut document = Document::default();
2521        document.assets.source_skeleton.skins = [4, 5, 5]
2522            .into_iter()
2523            .map(|source_skin_index| SourceSkinAsset {
2524                source_skin_index,
2525                ..SourceSkinAsset::default()
2526            })
2527            .collect();
2528        assert_eq!(
2529            validate_document_shape(&document),
2530            Err(DocumentShapeError::DuplicateSourceSkinIndex {
2531                source_skin_index: 5,
2532            })
2533        );
2534
2535        let scale_track = Track {
2536            property: Property::Scale,
2537            values: TrackValues::Vec3s(vec![Vec3::ONE]),
2538            ..valid_track()
2539        };
2540        let mut document = track_document(valid_track());
2541        document.clips[0].tracks.push(scale_track.clone());
2542        document.clips[0].tracks.push(scale_track);
2543        assert_eq!(
2544            validate_document_shape(&document),
2545            Err(DocumentShapeError::DuplicateClipTrack {
2546                clip_index: 0,
2547                node: 0,
2548                property: Property::Scale,
2549            })
2550        );
2551    }
2552
2553    #[test]
2554    fn document_shape_checks_later_tracks_and_inverse_binds() {
2555        let mut document = track_document(valid_track());
2556        document.clips[0].tracks.push(Track {
2557            property: Property::Scale,
2558            times: Vec::new(),
2559            values: TrackValues::Vec3s(Vec::new()),
2560            ..valid_track()
2561        });
2562        assert_eq!(
2563            validate_document_shape(&document),
2564            Err(DocumentShapeError::TrackShape {
2565                clip_index: 0,
2566                node: 0,
2567                violation: TrackShapeViolation::EmptyTimes,
2568            })
2569        );
2570
2571        let scale_track = Track {
2572            property: Property::Scale,
2573            values: TrackValues::Vec3s(vec![Vec3::ONE]),
2574            ..valid_track()
2575        };
2576        let mut document = track_document(valid_track());
2577        document.clips.push(Clip {
2578            name: "later".into(),
2579            duration_s: 0.0,
2580            tracks: vec![scale_track.clone(), scale_track],
2581        });
2582        assert_eq!(
2583            validate_document_shape(&document),
2584            Err(DocumentShapeError::DuplicateClipTrack {
2585                clip_index: 1,
2586                node: 0,
2587                property: Property::Scale,
2588            })
2589        );
2590
2591        let mut document = track_document(valid_track());
2592        document.clips.push(Clip {
2593            name: "later".into(),
2594            duration_s: 0.0,
2595            tracks: vec![Track {
2596                property: Property::Scale,
2597                times: Vec::new(),
2598                values: TrackValues::Vec3s(Vec::new()),
2599                ..valid_track()
2600            }],
2601        });
2602        assert_eq!(
2603            validate_document_shape(&document),
2604            Err(DocumentShapeError::TrackShape {
2605                clip_index: 1,
2606                node: 0,
2607                violation: TrackShapeViolation::EmptyTimes,
2608            })
2609        );
2610
2611        let mut columns = Mat4::IDENTITY.to_cols_array();
2612        columns[15] = f32::NAN;
2613        let non_finite_inverse_bind = Mat4::from_cols_array(&columns);
2614
2615        let mut document = instance_document();
2616        document.skeleton.bones.push(bone(Some(0)));
2617        document.assets.instances[0].skin_joints = vec![0, 1];
2618        document.assets.instances[0].skin_ibms = vec![Mat4::IDENTITY, non_finite_inverse_bind];
2619        assert_eq!(
2620            validate_document_shape(&document),
2621            Err(DocumentShapeError::MeshInstanceShape {
2622                instance_index: 0,
2623                violation: MeshInstanceShapeViolation::NonFiniteSkinInverseBind,
2624            })
2625        );
2626
2627        let mut document = instance_document();
2628        document.assets.instances.push(MeshInstance {
2629            node: 0,
2630            mesh: 0,
2631            skin_joints: vec![0],
2632            skin_ibms: vec![non_finite_inverse_bind],
2633            ..MeshInstance::default()
2634        });
2635        assert_eq!(
2636            validate_document_shape(&document),
2637            Err(DocumentShapeError::MeshInstanceShape {
2638                instance_index: 1,
2639                violation: MeshInstanceShapeViolation::NonFiniteSkinInverseBind,
2640            })
2641        );
2642
2643        let mut document = instance_document();
2644        document.assets.instances.push(MeshInstance {
2645            node: 0,
2646            mesh: 0,
2647            skin_joints: vec![0],
2648            skin_ibms: vec![Mat4::IDENTITY, Mat4::IDENTITY],
2649            ..MeshInstance::default()
2650        });
2651        assert_eq!(
2652            validate_document_shape(&document),
2653            Err(DocumentShapeError::MeshInstanceShape {
2654                instance_index: 1,
2655                violation: MeshInstanceShapeViolation::SkinInverseBindCountMismatch,
2656            })
2657        );
2658
2659        let mut document = one_bone_document();
2660        document.skeleton.bones.push(Bone {
2661            inverse_bind: Some(non_finite_inverse_bind),
2662            ..bone(Some(0))
2663        });
2664        assert_eq!(
2665            validate_document_shape(&document),
2666            Err(DocumentShapeError::NonFiniteBoneInverseBind { node: 1 })
2667        );
2668    }
2669
2670    #[test]
2671    fn document_shape_violation_names_remain_machine_stable() {
2672        let source_projection = [
2673            (
2674                SourceProjectionViolation::ProjectedBoneOutOfRange,
2675                "projected_bone_out_of_range",
2676            ),
2677            (
2678                SourceProjectionViolation::TwoSourceNodesProjectToOneBone,
2679                "two_source_nodes_project_to_one_bone",
2680            ),
2681            (
2682                SourceProjectionViolation::ParentSourceNodeMissing,
2683                "parent_source_node_is_missing",
2684            ),
2685            (
2686                SourceProjectionViolation::CyclicUnprojectedSourceParentChain,
2687                "cyclic_unprojected_source_parent_chain",
2688            ),
2689            (
2690                SourceProjectionViolation::NearestProjectedParentMismatch,
2691                "projection_and_skeleton_parents_differ",
2692            ),
2693            (
2694                SourceProjectionViolation::ProjectedBoneHasUnprojectedSkeletonChild,
2695                "projected_bone_has_an_unprojected_skeleton_child",
2696            ),
2697        ];
2698        for (violation, expected) in source_projection {
2699            assert_eq!(violation.to_string(), expected);
2700        }
2701
2702        let track = [
2703            (
2704                TrackShapeViolation::BoneIndexOutOfRange,
2705                "bone_index_out_of_range",
2706            ),
2707            (TrackShapeViolation::EmptyTimes, "empty_times"),
2708            (TrackShapeViolation::NonFiniteTime, "non_finite_time"),
2709            (
2710                TrackShapeViolation::TimesNotStrictlyIncreasing,
2711                "times_not_strictly_increasing",
2712            ),
2713            (
2714                TrackShapeViolation::ValueCountMismatch,
2715                "value_count_mismatch",
2716            ),
2717            (
2718                TrackShapeViolation::ValueTypeMismatchesProperty,
2719                "value_type_mismatches_property",
2720            ),
2721            (TrackShapeViolation::NonFiniteValue, "non_finite_value"),
2722        ];
2723        for (violation, expected) in track {
2724            assert_eq!(violation.to_string(), expected);
2725        }
2726
2727        let instance = [
2728            (
2729                MeshInstanceShapeViolation::NodeIndexOutOfRange,
2730                "node_index_out_of_range",
2731            ),
2732            (
2733                MeshInstanceShapeViolation::MeshIndexOutOfRange,
2734                "mesh_index_out_of_range",
2735            ),
2736            (
2737                MeshInstanceShapeViolation::SkinJointOutOfRange,
2738                "skin_joint_out_of_range",
2739            ),
2740            (
2741                MeshInstanceShapeViolation::SkinInverseBindCountMismatch,
2742                "skin_ibm_count_mismatch",
2743            ),
2744            (
2745                MeshInstanceShapeViolation::NonFiniteSkinInverseBind,
2746                "non_finite_inverse_bind",
2747            ),
2748        ];
2749        for (violation, expected) in instance {
2750            assert_eq!(violation.to_string(), expected);
2751        }
2752    }
2753
2754    #[test]
2755    fn tolerant_world_rests_keep_unrelated_partial_evidence() {
2756        let skeleton = Skeleton {
2757            bones: vec![
2758                bone(None),
2759                bone(Some(99)),
2760                Bone {
2761                    rest: Transform {
2762                        translation: Vec3::X,
2763                        ..Transform::IDENTITY
2764                    },
2765                    ..bone(None)
2766                },
2767                Bone {
2768                    rest: Transform {
2769                        translation: Vec3::Y,
2770                        ..Transform::IDENTITY
2771                    },
2772                    ..bone(Some(2))
2773                },
2774                bone(Some(1)),
2775            ],
2776        };
2777
2778        let worlds = tolerant_world_rest_matrices(&skeleton);
2779        assert_eq!(worlds.len(), 5);
2780        assert_eq!(worlds[0], Some(Mat4::IDENTITY));
2781        assert_eq!(worlds[1], None, "the malformed parent is unavailable");
2782        assert_eq!(worlds[2], Some(Mat4::from_translation(Vec3::X)));
2783        assert_eq!(
2784            worlds[3],
2785            Some(Mat4::from_translation(Vec3::new(1.0, 1.0, 0.0))),
2786            "a finite independent chain remains measurable"
2787        );
2788        assert_eq!(
2789            worlds[4], None,
2790            "a child of unavailable evidence is unavailable"
2791        );
2792    }
2793
2794    #[test]
2795    fn shared_affine_classifier_respects_distinct_caller_tolerances() {
2796        let equal_axis_basis = affine_test_fixtures::tolerance_divergence_basis();
2797        let strict = PositiveUniformAffineTolerance {
2798            equal_axis: 1.0e-5,
2799            relative_orthogonality: 1.0e-5,
2800            singular_determinant_relative: 1.0e-6,
2801        };
2802        let loose = PositiveUniformAffineTolerance {
2803            equal_axis: 1.0e-4,
2804            relative_orthogonality: 1.0e-4,
2805            singular_determinant_relative: 0.0,
2806        };
2807
2808        assert_eq!(
2809            classify_positive_uniform_affine(equal_axis_basis, strict),
2810            Err(AffineDomainViolation::NonUniformScale),
2811            "the stricter caller rejects this equal-axis difference"
2812        );
2813        assert!(
2814            classify_positive_uniform_affine(equal_axis_basis, loose).is_ok(),
2815            "the looser caller accepts this equal-axis difference"
2816        );
2817
2818        let orthogonality_basis = affine_test_fixtures::orthogonality_tolerance_divergence_basis();
2819        assert_eq!(
2820            classify_positive_uniform_affine(orthogonality_basis, strict),
2821            Err(AffineDomainViolation::Sheared),
2822            "the stricter caller rejects this cross-axis dot product"
2823        );
2824        assert!(
2825            classify_positive_uniform_affine(orthogonality_basis, loose).is_ok(),
2826            "the looser caller accepts this cross-axis dot product"
2827        );
2828    }
2829
2830    #[test]
2831    fn shared_affine_classifier_pins_its_symmetric_f64_formula() {
2832        let policy = PositiveUniformAffineTolerance {
2833            equal_axis: 1.0e-5,
2834            relative_orthogonality: 1.0e-5,
2835            singular_determinant_relative: 1.0e-6,
2836        };
2837
2838        // Exact binary32 lengths whose mean is exactly 99_999 in binary64.
2839        // The longest-axis deviation is exactly 1: accepted only when the
2840        // relative base is max(mean, axis), then refused one binary32 ulp
2841        // farther out.
2842        let on_long_edge = Mat3::from_diagonal(Vec3::new(99_998.5, 99_998.5, 100_000.0));
2843        assert_eq!(
2844            classify_positive_uniform_affine(on_long_edge, policy),
2845            Ok(99_999.0)
2846        );
2847        let short = 99_998.5;
2848        let long = 100_000.0 + 0.007_812_5;
2849        for diagonal in [
2850            Vec3::new(long, short, short),
2851            Vec3::new(short, long, short),
2852            Vec3::new(short, short, long),
2853        ] {
2854            assert_eq!(
2855                classify_positive_uniform_affine(Mat3::from_diagonal(diagonal), policy),
2856                Err(AffineDomainViolation::NonUniformScale)
2857            );
2858        }
2859
2860        // A one-sided comparison would miss the uniquely short axis. At this
2861        // exact binary32 step the short-axis deviation is outside the band,
2862        // while each longer axis remains inside it.
2863        let short = 1.0 - 2.0_f32.powi(-16);
2864        for diagonal in [
2865            Vec3::new(short, 1.0, 1.0),
2866            Vec3::new(1.0, short, 1.0),
2867            Vec3::new(1.0, 1.0, short),
2868        ] {
2869            assert_eq!(
2870                classify_positive_uniform_affine(Mat3::from_diagonal(diagonal), policy),
2871                Err(AffineDomainViolation::NonUniformScale)
2872            );
2873        }
2874
2875        // Only binary64 dot-product arithmetic places this basis outside the
2876        // orthogonality band; binary32 rounds the deciding dot back inside.
2877        let c0 = Vec3::new(0.12792248, -0.99066633, -0.047073245);
2878        let c1 = Vec3::new(-0.34637994, -0.00016034879, -0.93809813);
2879        let c2 = Vec3::new(0.92933476, 0.13630849, -0.3431568);
2880        assert!((c1.dot(c2) as f64).abs() < 1.0e-5);
2881        assert!(c1.as_dvec3().dot(c2.as_dvec3()).abs() > 1.0e-5);
2882        assert_eq!(
2883            classify_positive_uniform_affine(Mat3::from_cols(c0, c1, c2), policy),
2884            Err(AffineDomainViolation::Sheared)
2885        );
2886
2887        // Orthogonality is sign-independent; dropping abs() accepts the
2888        // negative case while leaving the positive fixture green.
2889        for shear in [2.0_f32.powi(-15), -2.0_f32.powi(-15)] {
2890            let basis = Mat3::from_cols(Vec3::X, Vec3::new(shear, 1.0, 0.0), Vec3::Z);
2891            assert_eq!(
2892                classify_positive_uniform_affine(basis, policy),
2893                Err(AffineDomainViolation::Sheared)
2894            );
2895        }
2896    }
2897
2898    #[test]
2899    fn affine_axis_mean_is_ascending_and_column_order_invariant() {
2900        // This is the audited counterexample. These are the widened lengths
2901        // of three exact binary32 columns; their authored-order sum changes
2902        // by one binary64 ulp when the columns are cycled. The canonical
2903        // ascending association is the lower result.
2904        let lengths = [
2905            f64::from_bits(0x3ff1_09e7_e000_022c),
2906            f64::from_bits(0x3ff1_09ec_6000_0eb5),
2907            f64::from_bits(0x3ff1_09fa_e000_3cde),
2908        ];
2909        let expected = f64::from_bits(0x3ff1_09ef_b555_6f3f);
2910        let ascending = (lengths[0] + lengths[1] + lengths[2]) / 3.0;
2911        let descending = (lengths[2] + lengths[1] + lengths[0]) / 3.0;
2912        assert_eq!(expected.to_bits(), 0x3ff1_09ef_b555_6f3f);
2913        assert_eq!(ascending.to_bits(), expected.to_bits());
2914        assert_eq!(descending.to_bits(), 0x3ff1_09ef_b555_6f40);
2915        for order in [
2916            [0, 1, 2],
2917            [0, 2, 1],
2918            [1, 0, 2],
2919            [1, 2, 0],
2920            [2, 0, 1],
2921            [2, 1, 0],
2922        ] {
2923            assert_eq!(
2924                average_affine_axis_length(order.map(|index| lengths[index])),
2925                expected,
2926                "axis order {order:?}"
2927            );
2928        }
2929
2930        // The association is observable even for exactly representable
2931        // dyadic inputs: adding the two small terms first retains them,
2932        // while adding either to `2^53` loses both. This catches replacing
2933        // the canonical sort with a different fixed input order.
2934        let dyadic = [2.0_f64.powi(53), 1.0, 1.0];
2935        let ascending = (dyadic[1] + dyadic[2] + dyadic[0]) / 3.0;
2936        let descending = (dyadic[0] + dyadic[1] + dyadic[2]) / 3.0;
2937        assert_ne!(ascending, descending);
2938        assert_eq!(average_affine_axis_length(dyadic), ascending);
2939
2940        // The same exact binary32 columns exercise the classifier. Every
2941        // permutation below preserves orientation: odd column permutations
2942        // negate one column, which leaves lengths unchanged and restores the
2943        // determinant's sign. The equal-axis boundary must consequently
2944        // reject the same geometry in all six authored axis orders.
2945        let permutations = affine_test_fixtures::appendix_d_v6_mean_permutations();
2946        let expected_length_bits = lengths.map(f64::to_bits);
2947        assert_eq!(
2948            affine_axis_lengths(permutations[0]).map(f64::to_bits),
2949            expected_length_bits
2950        );
2951        let tolerance = PositiveUniformAffineTolerance {
2952            equal_axis: 1.0e-5,
2953            relative_orthogonality: 1.0e-5,
2954            singular_determinant_relative: 1.0e-6,
2955        };
2956        for (permutation, linear) in permutations.into_iter().enumerate() {
2957            assert!(
2958                linear
2959                    .x_axis
2960                    .as_dvec3()
2961                    .cross(linear.y_axis.as_dvec3())
2962                    .dot(linear.z_axis.as_dvec3())
2963                    > 0.0,
2964                "orientation for permutation {permutation}"
2965            );
2966            assert_eq!(
2967                average_affine_axis_length(affine_axis_lengths(linear)).to_bits(),
2968                expected.to_bits(),
2969                "mean for permutation {permutation}"
2970            );
2971            assert_eq!(
2972                classify_positive_uniform_affine(linear, tolerance),
2973                Err(AffineDomainViolation::NonUniformScale),
2974                "classification for permutation {permutation}"
2975            );
2976        }
2977    }
2978
2979    #[test]
2980    fn shared_affine_classifier_pins_f64_determinant_arithmetic() {
2981        // These exact binary32 columns make the f32 scalar triple product
2982        // land above the same threshold that the product of widened columns
2983        // lands below. The remaining bands are deliberately loose so only
2984        // singularity arithmetic decides the result.
2985        let linear = Mat3::from_cols(
2986            Vec3::new(
2987                f32::from_bits(0x3ff3_5574),
2988                f32::from_bits(0x3f0e_fa3c),
2989                0.0,
2990            ),
2991            Vec3::new(
2992                f32::from_bits(0x3ff5_5e17),
2993                f32::from_bits(0x3f10_2c31),
2994                0.0,
2995            ),
2996            Vec3::Z,
2997        );
2998        let columns = [
2999            linear.x_axis.as_dvec3(),
3000            linear.y_axis.as_dvec3(),
3001            linear.z_axis.as_dvec3(),
3002        ];
3003        let determinant_f64 = columns[2].dot(columns[0].cross(columns[1]));
3004        let determinant_f32 = f64::from(linear.determinant());
3005        let lengths = affine_axis_lengths(linear);
3006        let threshold = (determinant_f64 + determinant_f32) / 2.0;
3007        assert!(determinant_f64 < threshold);
3008        assert!(determinant_f32 > threshold);
3009
3010        assert_eq!(
3011            classify_positive_uniform_affine(
3012                linear,
3013                PositiveUniformAffineTolerance {
3014                    equal_axis: 10.0,
3015                    relative_orthogonality: 10.0,
3016                    singular_determinant_relative: threshold
3017                        / (lengths[0] * lengths[1] * lengths[2]),
3018                },
3019            ),
3020            Err(AffineDomainViolation::Singular)
3021        );
3022
3023        // Every derived determinant operand must stay widened as well. A
3024        // binary32 axis-product intermediate overflows on this otherwise
3025        // finite, positive, exactly uniform basis and falsely calls it
3026        // singular under Appendix D's non-zero relative threshold.
3027        let large_uniform = 2.0e19_f32;
3028        assert_eq!(
3029            classify_positive_uniform_affine(
3030                Mat3::from_diagonal(Vec3::splat(large_uniform)),
3031                PositiveUniformAffineTolerance {
3032                    equal_axis: 1.0e-5,
3033                    relative_orthogonality: 1.0e-5,
3034                    singular_determinant_relative: 1.0e-6,
3035                },
3036            ),
3037            Ok(f64::from(large_uniform))
3038        );
3039    }
3040
3041    #[test]
3042    fn affine_geometry_facts_pin_every_widened_field_and_slot() {
3043        let linear = Mat3::from_cols(
3044            Vec3::new(1.0, 2.0, 3.0),
3045            Vec3::new(4.0, 5.0, 6.0),
3046            Vec3::new(7.0, 8.0, 10.0),
3047        );
3048
3049        let facts = AffineGeometryFacts::from_linear(linear).expect("finite widened facts");
3050        assert_eq!(
3051            facts.axis_lengths.map(f64::to_bits),
3052            [
3053                0x400d_eeea_1168_3f49,
3054                0x4021_8cc8_21d6_d3e3,
3055                0x402d_3064_dcc8_ae67,
3056            ]
3057        );
3058        assert_eq!(facts.mean_axis_length.to_bits(), 0x4022_12f7_d653_30b4);
3059        assert_eq!(facts.determinant.to_bits(), 0xc008_0000_0000_0000);
3060        assert_eq!(facts.axis_length_product.to_bits(), 0x407d_f2e3_88f2_1b01);
3061        assert_eq!(
3062            facts.cross_axis_dots.map(f64::to_bits),
3063            [
3064                0x4040_0000_0000_0000,
3065                0x404a_8000_0000_0000,
3066                0x4060_0000_0000_0000,
3067            ],
3068            "cross-axis slots are XY, XZ, YZ"
3069        );
3070    }
3071
3072    #[test]
3073    fn affine_geometry_facts_widen_every_dot_product_before_multiplying() {
3074        let x = Vec3::new(
3075            f32::from_bits(0x3ff3_5574),
3076            f32::from_bits(0x3f0e_fa3c),
3077            0.0,
3078        );
3079        let y = Vec3::new(
3080            f32::from_bits(0x3ff5_5e17),
3081            f32::from_bits(0x3f10_2c31),
3082            0.0,
3083        );
3084        let widened_dot = x.as_dvec3().dot(y.as_dvec3());
3085        let f32_then_widened = f64::from(x.dot(y));
3086
3087        for (slot, linear) in [
3088            (0, Mat3::from_cols(x, y, Vec3::Z)),
3089            (1, Mat3::from_cols(x, Vec3::Z, y)),
3090            (2, Mat3::from_cols(Vec3::Z, x, y)),
3091        ] {
3092            let facts = AffineGeometryFacts::from_linear(linear).expect("finite widened facts");
3093            assert_eq!(facts.cross_axis_dots[slot], widened_dot);
3094            assert_ne!(
3095                facts.cross_axis_dots[slot], f32_then_widened,
3096                "dot slot {slot} must multiply and add in f64, not widen an f32 result"
3097            );
3098        }
3099    }
3100
3101    #[test]
3102    fn weld_preserves_uv_seams_at_shared_positions() {
3103        let mut primitive = Primitive {
3104            positions: vec![Vec3::ZERO, Vec3::ZERO, Vec3::ZERO],
3105            uvs: vec![[0.0, 0.0], [1.0, 0.0], [0.0, 0.0]],
3106            ..Primitive::default()
3107        };
3108
3109        primitive.weld();
3110
3111        assert_eq!(primitive.positions.len(), 2);
3112        let reconstructed_corners = primitive
3113            .indices
3114            .iter()
3115            .map(|&index| {
3116                let index = index as usize;
3117                (primitive.positions[index], primitive.uvs[index])
3118            })
3119            .collect::<Vec<_>>();
3120        assert_eq!(
3121            reconstructed_corners,
3122            vec![
3123                (Vec3::ZERO, [0.0, 0.0]),
3124                (Vec3::ZERO, [1.0, 0.0]),
3125                (Vec3::ZERO, [0.0, 0.0]),
3126            ]
3127        );
3128    }
3129}