polysmelt 0.17.5

Pure-Rust 3D asset interchange: glTF/GLB reading and writing, meshopt compression, and readers for common mesh formats, SketchUp included
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
//! Typed views of a [`Document`](crate::document::Document)'s node tree, skins and
//! animations, for code that plays or retargets motion rather than drawing triangles:
//! [`Document::rig`](crate::document::Document::rig).
//!
//! Every format's reader converts into glTF, so an FBX armature, a `UsdSkel` skeleton and a
//! glTF skin all come out the same way: nodes with their rest transforms, skins naming their
//! joints and inverse bind matrices, and animations as keyed channels on nodes. Accessors are
//! read with every component type, normalized and sparse, as the flat mesh reads them.
//!
//! Posing goes local transforms ([`Rig::pose`], or a [`Poser`] frame after frame), then world
//! matrices ([`Rig::world`]), then a skin's joint matrices ([`Rig::skin_matrices`]):
//!
//! ```
//! use polysmelt::rig::{Node, Rig, Trs};
//!
//! let mut rig = Rig::default();
//! rig.nodes.push(Node {
//!     name: Some("hips".into()),
//!     parent: None,
//!     children: vec![1],
//!     rest: Trs { translation: [0.0, 1.0, 0.0], ..Trs::IDENTITY },
//!     mesh: None,
//!     skin: None,
//! });
//! rig.nodes.push(Node {
//!     name: Some("spine".into()),
//!     parent: Some(0),
//!     children: Vec::new(),
//!     rest: Trs { translation: [0.0, 0.5, 0.0], ..Trs::IDENTITY },
//!     mesh: None,
//!     skin: None,
//! });
//! let local = rig.pose(None, 0.0); // no animation: the rest pose
//! let world = rig.world(&local);
//! let spine = rig.find("spine").unwrap();
//! assert_eq!(&world[spine][12..15], &[0.0, 1.5, 0.0]);
//! ```

/// A transform as translation, rotation (a unit quaternion, `[x, y, z, w]`) and scale, applied
/// scale first.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Trs {
    /// Where the origin moves to.
    pub translation: [f32; 3],
    /// A unit quaternion, `[x, y, z, w]`.
    pub rotation: [f32; 4],
    /// Scale along each axis.
    pub scale: [f32; 3],
}

impl Trs {
    /// No change: no translation, no rotation, unit scale.
    pub const IDENTITY: Self = Self {
        translation: [0.0; 3],
        rotation: [0.0, 0.0, 0.0, 1.0],
        scale: [1.0; 3],
    };

    /// The transform as a column-major 4×4 matrix (translation × rotation × scale), as glTF
    /// writes a node's `matrix`.
    #[must_use]
    pub fn matrix(&self) -> [f32; 16] {
        let m = crate::flatten::trs(
            self.translation.map(f64::from),
            self.rotation.map(f64::from),
            self.scale.map(f64::from),
        );
        m.map(crate::num::f32_of)
    }
}

impl Default for Trs {
    fn default() -> Self {
        Self::IDENTITY
    }
}

/// One node of the document.
#[derive(Debug, Clone, PartialEq)]
pub struct Node {
    /// Its name, if it has one.
    pub name: Option<String>,
    /// The node that lists it as a child, if any. glTF doesn't order parents before children.
    pub parent: Option<usize>,
    /// The nodes it lists as children.
    pub children: Vec<usize>,
    /// Its own transform, relative to its parent. A node written as a matrix is decomposed.
    pub rest: Trs,
    /// The glTF mesh it draws, if any.
    pub mesh: Option<usize>,
    /// The skin its mesh is bound to, an index into [`Rig::skins`], if any.
    pub skin: Option<usize>,
}

/// The joints a mesh is skinned to.
#[derive(Debug, Clone, PartialEq)]
pub struct Skin {
    /// Its name, if it has one.
    pub name: Option<String>,
    /// The joints' nodes.
    pub joints: Vec<usize>,
    /// Each joint's inverse bind matrix, column-major: identity for a skin that gives none.
    pub inverse_bind: Vec<[f32; 16]>,
    /// The node the skin names as its skeleton's root, if any.
    pub skeleton: Option<usize>,
}

/// What a channel animates: the property of its node it sets (glTF's channel target `path`).
///
/// Non-exhaustive: properties other extensions animate may be added.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Property {
    /// [`Trs::translation`], three values a key.
    Translation,
    /// [`Trs::rotation`], a quaternion a key.
    Rotation,
    /// [`Trs::scale`], three values a key.
    Scale,
    /// Morph target weights, one value a target a key.
    Weights,
}

/// How a channel's values run between keys.
///
/// Non-exhaustive: glTF extensions may add interpolations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Interpolation {
    /// Straight between keys; rotations are spherically interpolated, the short way round.
    Linear,
    /// Each key's value held until the next key.
    Step,
    /// Hermite splines: each key holds an in-tangent, a value and an out-tangent.
    CubicSpline,
}

impl Interpolation {
    /// Its glTF name.
    const fn name(self) -> &'static str {
        match self {
            Self::Linear => "LINEAR",
            Self::Step => "STEP",
            Self::CubicSpline => "CUBICSPLINE",
        }
    }
}

/// One animated property of one node.
#[derive(Debug, Clone, PartialEq)]
pub struct Channel {
    /// The node it animates, an index into [`Rig::nodes`].
    pub node: usize,
    /// What of the node it animates.
    pub property: Property,
    /// How its values run between keys.
    pub interpolation: Interpolation,
    /// Key times in seconds, ascending.
    pub times: Vec<f32>,
    /// The keys' values, flat: each key's element is `values.len() / times.len()` wide (three
    /// elements per key, in-tangent, value and out-tangent, for a cubic spline).
    pub values: Vec<f32>,
}

impl Channel {
    /// The value at `t` seconds: the first key's before it, the last's after. Rotations come
    /// out unit length. `None` for a channel without keys or with values that don't fit them.
    ///
    /// Each call allocates the vector it returns; [`Channel::sample_into`] reuses one.
    #[must_use]
    pub fn sample(&self, t: f32) -> Option<Vec<f32>> {
        let mut out = Vec::new();
        self.sample_into(t, &mut out).then_some(out)
    }

    /// [`Channel::sample`] into `out`, which is cleared first: `false`, leaving it empty, for a
    /// channel without keys or with values that don't fit them. Sampling time after time into
    /// the same vector allocates nothing after the first, for a channel up to 64 values wide
    /// (any transform, and the weights of up to 64 morph targets).
    ///
    /// ```
    /// use polysmelt::rig::{Channel, Interpolation, Property};
    ///
    /// let mut channel = Channel {
    ///     node: 0,
    ///     property: Property::Translation,
    ///     interpolation: Interpolation::Linear,
    ///     times: vec![0.0, 1.0],
    ///     values: vec![0.0, 0.0, 0.0, 2.0, 4.0, 6.0],
    /// };
    /// let mut value = Vec::new();
    /// assert!(channel.sample_into(0.5, &mut value));
    /// assert_eq!(value, [1.0, 2.0, 3.0]);
    /// channel.values.pop(); // values that don't fit the keys
    /// assert!(!channel.sample_into(0.5, &mut value));
    /// assert!(value.is_empty());
    /// ```
    pub fn sample_into(&self, t: f32, out: &mut Vec<f32>) -> bool {
        out.clear();
        let interpolation = self.interpolation.name();
        let Some(w) = crate::flatten::width(&self.times, &self.values, interpolation) else {
            return false;
        };
        let rotation = self.property == Property::Rotation;
        let k = self.times.partition_point(|&x| x <= t);
        let mut small = [0.0f64; 64];
        let mut large = Vec::new();
        let v = if w <= small.len() {
            &mut small[..w]
        } else {
            large.resize(w, 0.0);
            &mut large[..]
        };
        if !crate::flatten::sample_after(&self.times, &self.values, interpolation, t, rotation, k, v) {
            return false;
        }
        out.extend(v.iter().map(|&x| crate::num::f32_of(x)));
        true
    }

    /// [`Channel::sample`] for a channel at most four wide, without allocating, given how many of its keys are at or
    /// before `t`.
    fn sample_small(&self, t: f32, k: usize) -> Option<([f32; 4], usize)> {
        let interpolation = self.interpolation.name();
        let w = crate::flatten::width(&self.times, &self.values, interpolation)?;
        let mut v = [0.0f64; 4];
        let rotation = self.property == Property::Rotation;
        if w > 4 || !crate::flatten::sample_after(&self.times, &self.values, interpolation, t, rotation, k, &mut v[..w])
        {
            return None;
        }
        Some((v.map(crate::num::f32_of), w))
    }

    /// Sets what this channel animates of `o` to its value at `t`, given how many of its keys are at or before it.
    fn pose(&self, t: f32, k: usize, o: &mut Trs) {
        if self.property == Property::Weights {
            return;
        }
        let Some((v, w)) = self.sample_small(t, k) else {
            return;
        };
        match (self.property, w) {
            (Property::Translation, 3) => o.translation = [v[0], v[1], v[2]],
            (Property::Scale, 3) => o.scale = [v[0], v[1], v[2]],
            (Property::Rotation, 4) => o.rotation = v,
            _ => {}
        }
    }
}

/// An animation: channels keyed on nodes.
#[derive(Debug, Clone, PartialEq)]
pub struct Animation {
    /// Its name, if it has one.
    pub name: Option<String>,
    /// What it animates, a channel a property of a node.
    pub channels: Vec<Channel>,
    /// The frames per second it was made at, when the file says or its format assumes one:
    /// the animation's own (`extras.frameRate`), else the file's
    /// ([`SourceInfo::frame_rate`](crate::source::SourceInfo::frame_rate)). Key times are in
    /// seconds whatever it is; it says which times are frames.
    pub frame_rate: Option<f64>,
}

impl Animation {
    /// When its first key is, and its last: `(0, 0)` for one without keys.
    #[must_use]
    pub fn span(&self) -> (f32, f32) {
        let mut first = f32::INFINITY;
        let mut last = f32::NEG_INFINITY;
        for c in &self.channels {
            if let (Some(a), Some(b)) = (c.times.first(), c.times.last()) {
                first = first.min(*a);
                last = last.max(*b);
            }
        }
        if first <= last { (first, last) } else { (0.0, 0.0) }
    }

    /// Every key time any channel has, ascending, each once.
    #[must_use]
    pub fn key_times(&self) -> Vec<f32> {
        // Channels mostly share their times, every bone keyed on the same frames: each set is gathered once.
        let mut sets: Vec<&[f32]> = Vec::new();
        for c in &self.channels {
            if !sets.contains(&c.times.as_slice()) {
                sets.push(&c.times);
            }
        }
        let mut t: Vec<f32> = sets.concat();
        if sets.len() > 1 || !t.is_sorted_by(|a, b| a.total_cmp(b).is_le()) {
            t.sort_unstable_by(f32::total_cmp);
        }
        t.dedup();
        t
    }
}

/// Poses one animation at time after time, as [`Rig::pose_into`] does, each channel keeping its place in its keys:
/// times in order, as when a clip is played or baked, step to their keys rather than searching for them. Times in any
/// order pose the same, just no faster.
#[derive(Debug, Clone)]
pub struct Poser<'a> {
    rig: &'a Rig,
    channels: &'a [Channel],
    /// For each channel, how many of its keys were at or before the last time posed.
    keys: Vec<usize>,
}

impl Poser<'_> {
    /// Every node's transform relative to its parent at `time` seconds, into `out`, which is cleared first. Nodes
    /// the animation doesn't animate are at rest.
    pub fn pose_into(&mut self, time: f32, out: &mut Vec<Trs>) {
        out.clear();
        out.extend(self.rig.nodes.iter().map(|n| n.rest));
        for (c, k) in self.channels.iter().zip(&mut self.keys) {
            let times = &c.times;
            if *k > 0 && times.get(*k - 1).is_none_or(|&x| x > time) {
                *k = times.partition_point(|&x| x <= time);
            } else {
                // Forward a few keys at most at a time in order; a search if it's far ahead.
                let mut steps = 0;
                while times.get(*k).is_some_and(|&x| x <= time) {
                    *k += 1;
                    steps += 1;
                    if steps == 4 {
                        *k += times[*k..].partition_point(|&x| x <= time);
                        break;
                    }
                }
            }
            if let Some(o) = out.get_mut(c.node) {
                c.pose(time, *k, o);
            }
        }
    }
}

/// A document's node tree, skins and animations.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Rig {
    /// Every node, in the document's order: the indices everything else uses.
    pub nodes: Vec<Node>,
    /// Every skin, in the document's order.
    pub skins: Vec<Skin>,
    /// Every animation, in the document's order.
    pub animations: Vec<Animation>,
}

impl Rig {
    /// The first node with this name.
    #[must_use]
    pub fn find(&self, name: &str) -> Option<usize> {
        self.nodes.iter().position(|n| n.name.as_deref() == Some(name))
    }

    /// Every node's transform relative to its parent in animation `animation` at `time`
    /// seconds: its rest transform, with what the animation's channels set in place of it.
    /// `None` for the rest pose. An index past [`Rig::animations`] poses the rest pose too,
    /// rather than panicking, and a channel on a node that isn't there is skipped.
    #[must_use]
    pub fn pose(&self, animation: Option<usize>, time: f32) -> Vec<Trs> {
        let mut out = Vec::with_capacity(self.nodes.len());
        self.pose_into(animation, time, &mut out);
        out
    }

    /// [`Rig::pose`] into `out`, which is cleared first: posing frame after frame into the same
    /// vector allocates nothing after the first.
    pub fn pose_into(&self, animation: Option<usize>, time: f32, out: &mut Vec<Trs>) {
        out.clear();
        out.extend(self.nodes.iter().map(|n| n.rest));
        let Some(a) = animation.and_then(|a| self.animations.get(a)) else {
            return;
        };
        for c in &a.channels {
            if let Some(o) = out.get_mut(c.node) {
                c.pose(time, c.times.partition_point(|&x| x <= time), o);
            }
        }
    }

    /// A [`Poser`] for animation `animation`, to pose it at one time after another. An index
    /// past [`Rig::animations`] gives a poser of the rest pose, rather than panicking.
    #[must_use]
    pub fn poser(&self, animation: usize) -> Poser<'_> {
        let channels = self.animations.get(animation).map_or(&[][..], |a| &a.channels);
        Poser {
            rig: self,
            channels,
            keys: vec![0; channels.len()],
        }
    }

    /// Every node's world transform, as a column-major matrix, given each one's transform
    /// relative to its parent (a pose, as [`Rig::pose`] gives; nodes past its end at rest).
    /// A node in a cycle, which glTF forbids, or whose parent isn't there, is placed by its own
    /// transform alone.
    #[must_use]
    pub fn world(&self, local: &[Trs]) -> Vec<[f32; 16]> {
        use crate::flatten::{M4, mul};
        let own = |i: usize| -> M4 {
            let t = local.get(i).unwrap_or(&self.nodes[i].rest);
            crate::flatten::trs(
                t.translation.map(f64::from),
                t.rotation.map(f64::from),
                t.scale.map(f64::from),
            )
        };
        let mut world: Vec<M4> = (0..self.nodes.len()).map(own).collect();
        for i in self.parents_first() {
            if let Some(p) = self.nodes[i].parent.and_then(|p| world.get(p).copied()) {
                world[i] = mul(&p, &world[i]);
            }
        }
        world.into_iter().map(|m| m.map(crate::num::f32_of)).collect()
    }

    /// Skin `skin`'s joint matrices for a pose's world transforms (as [`Rig::world`] gives):
    /// each joint's world matrix times its inverse bind matrix, column-major, in the skin's
    /// joint order, which is what `JOINTS_0` indexes. A vertex blended through them lands in
    /// world space: glTF ignores the skinned mesh node's own transform. Empty for a skin there
    /// isn't.
    #[must_use]
    pub fn skin_matrices(&self, skin: usize, world: &[[f32; 16]]) -> Vec<[f32; 16]> {
        let Some(s) = self.skins.get(skin) else {
            return Vec::new();
        };
        let wide = |m: &[f32; 16]| m.map(f64::from);
        let identity = Trs::IDENTITY.matrix();
        s.joints
            .iter()
            .zip(&s.inverse_bind)
            .map(|(&j, ibm)| {
                let w = world.get(j).unwrap_or(&identity);
                crate::flatten::mul(&wide(w), &wide(ibm)).map(crate::num::f32_of)
            })
            .collect()
    }

    /// The nodes in an order where each comes after its parent, and so every joint after the
    /// joints above it; nodes in a cycle (which glTF forbids) are left out.
    #[must_use]
    pub fn parents_first(&self) -> Vec<usize> {
        let mut out = Vec::with_capacity(self.nodes.len());
        let mut seen = vec![false; self.nodes.len()];
        let mut stack: Vec<usize> = (0..self.nodes.len())
            .rev()
            .filter(|&i| self.nodes[i].parent.is_none())
            .collect();
        while let Some(i) = stack.pop() {
            if std::mem::replace(&mut seen[i], true) {
                continue;
            }
            out.push(i);
            stack.extend(self.nodes[i].children.iter().rev().filter(|&&c| c < seen.len()));
        }
        out
    }
}

#[cfg(test)]
mod tests {
    use super::{Animation, Channel, Interpolation, Node, Property, Rig, Trs};

    fn rig() -> Rig {
        let node = |name: &str, parent| Node {
            name: Some(name.into()),
            parent,
            children: Vec::new(),
            rest: Trs::IDENTITY,
            mesh: None,
            skin: None,
        };
        let channel = |node, property, interpolation, times: &[f32], values: &[f32]| Channel {
            node,
            property,
            interpolation,
            times: times.to_vec(),
            values: values.to_vec(),
        };
        Rig {
            nodes: vec![node("root", None), node("arm", Some(0))],
            skins: Vec::new(),
            animations: vec![Animation {
                name: None,
                frame_rate: None,
                channels: vec![
                    // Written twice too long at its first key.
                    channel(
                        0,
                        Property::Rotation,
                        Interpolation::Linear,
                        &[0.0, 1.0],
                        &[0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 1.0, 0.0],
                    ),
                    channel(
                        0,
                        Property::Translation,
                        Interpolation::Step,
                        &[0.0, 1.0],
                        &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
                    ),
                    channel(
                        1,
                        Property::Scale,
                        Interpolation::CubicSpline,
                        &[0.0, 1.0],
                        &[
                            0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3.0, 3.0, 3.0, 0.0, 0.0, 0.0,
                        ],
                    ),
                    channel(
                        1,
                        Property::Weights,
                        Interpolation::Linear,
                        &[0.0],
                        &[0.5, 0.5, 0.5, 0.5, 0.5],
                    ),
                ],
            }],
        }
    }

    #[test]
    fn pose_into_reuses_its_vector_and_poses_as_pose_does() {
        let rig = rig();
        let mut out = Vec::new();
        for t in [-1.0, 0.0, 0.25, 0.5, 1.0, 2.0] {
            rig.pose_into(Some(0), t, &mut out);
            assert_eq!(out, rig.pose(Some(0), t), "at {t}");
        }
        let at = out.as_ptr();
        rig.pose_into(Some(0), 0.5, &mut out);
        assert_eq!(out.as_ptr(), at, "allocated again");
        rig.pose_into(None, 0.5, &mut out);
        assert_eq!(out, vec![Trs::IDENTITY; 2]);
    }

    #[test]
    fn key_times_holds_every_channels_keys_once_in_order() {
        let mut rig = rig();
        assert_eq!(rig.animations[0].key_times(), [0.0, 1.0]);
        let channel = rig.animations[0].channels[0].clone();
        for times in [vec![0.5, 1.0, 3.0], vec![0.0, 1.0], vec![-1.0, 0.25]] {
            let values = channel.values[..4].repeat(times.len());
            rig.animations[0].channels.push(Channel {
                times,
                values,
                ..channel.clone()
            });
        }
        assert_eq!(rig.animations[0].key_times(), [-1.0, 0.0, 0.25, 0.5, 1.0, 3.0]);
        assert_eq!(
            Animation {
                name: None,
                channels: Vec::new(),
                frame_rate: None,
            }
            .key_times(),
            Vec::<f32>::new()
        );
    }

    #[test]
    fn a_poser_poses_as_pose_does_at_times_in_any_order() {
        let mut rig = rig();
        // A long channel, for steps of one key, several and many.
        let times: Vec<f32> = (0..40u8).map(|k| f32::from(k) * 0.05).collect();
        let values: Vec<f32> = (0..40u8).flat_map(|k| [f32::from(k), 0.0, -f32::from(k)]).collect();
        rig.animations[0].channels.push(Channel {
            node: 1,
            property: Property::Translation,
            interpolation: Interpolation::Linear,
            times,
            values,
        });
        let mut poser = rig.poser(0);
        let mut out = Vec::new();
        let mut check = |t: f32| {
            poser.pose_into(t, &mut out);
            assert_eq!(out, rig.pose(Some(0), t), "at {t}");
        };
        let forward = (-2..50i8).map(|k| f32::from(k) * 0.05);
        let jumps = [0.0, 0.01, 0.9, 0.9, 1.95, 2.5, 0.3, -1.0, 1.0, 0.05, 0.0];
        let backward = (-2..50i8).rev().map(|k| f32::from(k) * 0.037);
        for t in forward.chain(jumps).chain(backward) {
            check(t);
        }
    }

    #[test]
    fn rotations_come_out_unit_length_at_the_first_and_last_keys_too() {
        let rig = rig();
        for t in [-1.0, 0.0, 0.5, 1.0, 2.0] {
            let q = rig.pose(Some(0), t)[0].rotation;
            let len = q.iter().map(|c| c * c).sum::<f32>().sqrt();
            assert!((len - 1.0).abs() < 1e-6, "{q:?} at {t}");
        }
        assert_eq!(rig.pose(Some(0), 0.0)[0].rotation, [0.0, 0.0, 0.0, 1.0]);
        assert_eq!(rig.pose(Some(0), 0.5)[0].translation, [1.0, 2.0, 3.0]);
        assert_eq!(rig.pose(Some(0), 0.5)[1].scale, [2.0, 2.0, 2.0]);
    }

    fn close(a: &[f32], b: &[f32]) -> bool {
        a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-5)
    }

    #[test]
    fn a_transform_composes_into_a_column_major_matrix() {
        let half = std::f32::consts::FRAC_1_SQRT_2;
        let t = Trs {
            translation: [1.0, 2.0, 3.0],
            rotation: [0.0, 0.0, half, half], // 90° about +Z
            scale: [2.0, 2.0, 2.0],
        };
        let want = [
            0.0, 2.0, 0.0, 0.0, // +X goes to +Y, doubled
            -2.0, 0.0, 0.0, 0.0, // +Y goes to -X
            0.0, 0.0, 2.0, 0.0, //
            1.0, 2.0, 3.0, 1.0,
        ];
        assert!(close(&t.matrix(), &want), "{:?}", t.matrix());
        assert!(close(
            &Trs::IDENTITY.matrix(),
            &super::super::flatten::IDENTITY.map(crate::num::f32_of)
        ));
    }

    #[test]
    fn world_transforms_and_skin_matrices_follow_the_tree() {
        let mut rig = rig();
        rig.nodes[0].children = vec![1];
        let mut pose = vec![Trs::IDENTITY; 2];
        pose[0].translation = [1.0, 0.0, 0.0];
        pose[1].translation = [0.0, 1.0, 0.0];
        let world = rig.world(&pose);
        assert!(close(&world[1][12..15], &[1.0, 1.0, 0.0]), "{:?}", world[1]);
        // Inverse bind matrices that undo the pose: the joint matrices are the identity.
        let undo = |m: &[f32; 16]| {
            let mut i = Trs::IDENTITY.matrix();
            i[12] = -m[12];
            i[13] = -m[13];
            i[14] = -m[14];
            i
        };
        rig.skins.push(super::Skin {
            name: None,
            joints: vec![0, 1],
            inverse_bind: vec![undo(&world[0]), undo(&world[1])],
            skeleton: None,
        });
        for m in rig.skin_matrices(0, &world) {
            assert!(close(&m, &Trs::IDENTITY.matrix()), "{m:?}");
        }
        assert_eq!(rig.skin_matrices(5, &world), Vec::<[f32; 16]>::new());
        assert_eq!(rig.world(&[]).len(), 2, "nodes past the pose are at rest");
    }

    #[test]
    fn an_animation_that_is_not_there_poses_the_rest_pose() {
        let rig = rig();
        assert_eq!(rig.pose(Some(9), 0.5), rig.pose(None, 0.5));
        let mut out = Vec::new();
        rig.poser(9).pose_into(0.5, &mut out);
        assert_eq!(out, rig.pose(None, 0.5));
    }

    #[cfg(all(feature = "gltf", feature = "fs"))]
    #[test]
    fn an_animation_takes_its_own_frame_rate_before_the_files() {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus/gltf/skin_animated/skin.glb");
        let mut doc = crate::open(&path).unwrap();
        assert_eq!(
            doc.rig().unwrap().animations[0].frame_rate,
            None,
            "glTF has no frame rate"
        );
        doc.json_mut()["asset"]["extras"] = serde_json::json!({ "source": { "frameRate": 30.0 } });
        assert_eq!(doc.rig().unwrap().animations[0].frame_rate, Some(30.0));
        doc.json_mut()["animations"][0]["extras"] = serde_json::json!({ "frameRate": 24.0 });
        assert_eq!(doc.rig().unwrap().animations[0].frame_rate, Some(24.0));
    }
}