vrm-runtime 0.1.0

Renderer-agnostic VRM 1.0 loader, validator, animation system, and runtime
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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
use glam::{Quat, Vec3};
use std::collections::{BTreeMap, HashMap};

use crate::animation::VrmAnimation;
use crate::expressions::{MaterialColorType, MaterialColorUpdate, TextureTransformUpdate};
use crate::{Avatar, AvatarAsset, HumanBone, MorphTargetUpdate};

/// A per-node rotation delta (relative to the node's rest rotation), applied
/// as `initial_rotation * delta` when computing world matrices.
#[derive(Debug, Clone, PartialEq)]
pub struct BoneUpdate {
    node_index: u32,
    rotation: Quat,
    translation: Option<Vec3>,
}

impl BoneUpdate {
    /// Creates a rest-relative rotation update for a raw glTF node index.
    pub fn new(node_index: u32, rotation: Quat) -> Self {
        Self {
            node_index,
            rotation,
            translation: None,
        }
    }

    /// Creates a rest-relative rotation and local translation update.
    pub fn with_translation(node_index: u32, rotation: Quat, translation: Vec3) -> Self {
        Self {
            node_index,
            rotation,
            translation: Some(translation),
        }
    }

    /// Returns the raw glTF node index updated by this value.
    pub fn node_index(&self) -> u32 {
        self.node_index
    }

    /// Returns the rest-relative local rotation delta.
    pub fn rotation(&self) -> Quat {
        self.rotation
    }

    /// Returns the optional local translation override.
    pub fn translation(&self) -> Option<Vec3> {
        self.translation
    }
}

/// The renderer-ready result of evaluating one frame: accumulated morph
/// weights, material color / UV shifts, and per-node bone rotations.
#[derive(Debug, Default, Clone)]
pub struct AvatarEvaluation {
    /// Accumulated morph target weights.
    pub morph_updates: Vec<MorphTargetUpdate>,
    /// Accumulated material color changes.
    pub material_color_updates: Vec<MaterialColorUpdate>,
    /// Accumulated material UV transform changes.
    pub texture_transform_updates: Vec<TextureTransformUpdate>,
    /// Rest-relative local node transform changes.
    pub bone_updates: Vec<BoneUpdate>,
}

/// Mutable per-frame state of an avatar: expression weights, bone rotations
/// and the look-at target. Feed it to [`AvatarInstance::evaluate`] to produce
/// an [`AvatarEvaluation`].
#[derive(Debug, Default, Clone)]
pub struct AvatarInstance {
    expression_weights: HashMap<String, f32>,
    bone_rotations: HashMap<HumanBone, Quat>,
    bone_translations: HashMap<HumanBone, Vec3>,
    look_at_target: Option<Vec3>,
    look_at_rotation: Option<Quat>,
}

impl AvatarInstance {
    pub(crate) fn new() -> Self {
        Self::default()
    }

    /// Clears every expression weight, bone rotation and look-at target, so
    /// the inputs of the next frame fully define the instance state (frame-
    /// replace semantics). Without this, switching expressions/bones would
    /// accumulate the previous frames' inputs.
    pub fn reset_frame_state(&mut self) {
        self.expression_weights.clear();
        self.bone_rotations.clear();
        self.bone_translations.clear();
        self.look_at_target = None;
        self.look_at_rotation = None;
    }

    /// Sets the weight (clamped to `0..=1`) of an expression by name.
    pub fn set_expression(&mut self, name: impl Into<String>, weight: f32) {
        self.expression_weights
            .insert(name.into(), weight.clamp(0.0, 1.0));
    }

    /// Returns an expression input weight, or zero when it has not been set.
    pub fn expression_weight(&self, name: &str) -> f32 {
        self.expression_weights.get(name).copied().unwrap_or(0.0)
    }

    /// Removes one expression input by exact name.
    pub fn clear_expression(&mut self, name: &str) {
        self.expression_weights.remove(name);
    }

    /// Removes all expression inputs.
    pub fn clear_expressions(&mut self) {
        self.expression_weights.clear();
    }

    /// Sets the rotation delta of a humanoid bone (in addition to its rest
    /// rotation). Use [`AvatarInstance::set_bone_rotation`] for the common
    /// case; raw node updates go through the runtime output.
    pub fn set_bone_rotation(&mut self, bone: HumanBone, rotation: Quat) {
        self.bone_rotations.insert(bone, rotation);
    }

    /// Returns a humanoid bone's rotation delta, or identity when unset.
    pub fn bone_rotation(&self, bone: HumanBone) -> Quat {
        self.bone_rotations
            .get(&bone)
            .copied()
            .unwrap_or(Quat::IDENTITY)
    }

    /// Removes one humanoid bone rotation delta.
    pub fn clear_bone_rotation(&mut self, bone: HumanBone) {
        self.bone_rotations.remove(&bone);
    }

    /// Removes all humanoid bone rotation deltas.
    pub fn clear_bone_rotations(&mut self) {
        self.bone_rotations.clear();
    }

    /// Sets a local translation override for a humanoid bone.
    pub fn set_bone_translation(&mut self, bone: HumanBone, translation: Vec3) {
        self.bone_translations.insert(bone, translation);
    }

    /// Returns a humanoid bone's local translation, or zero when unset.
    pub fn bone_translation(&self, bone: HumanBone) -> Vec3 {
        self.bone_translations
            .get(&bone)
            .copied()
            .unwrap_or(Vec3::ZERO)
    }

    /// Removes one humanoid bone translation override.
    pub fn clear_bone_translation(&mut self, bone: HumanBone) {
        self.bone_translations.remove(&bone);
    }

    /// Removes all humanoid bone translation overrides.
    pub fn clear_bone_translations(&mut self) {
        self.bone_translations.clear();
    }

    /// Sets the world-space gaze target; `None` disables LookAt.
    pub fn set_look_at_target(&mut self, target: Option<Vec3>) {
        self.look_at_target = target;
        if target.is_some() {
            self.look_at_rotation = None;
        }
    }

    /// Returns the active world-space look-at target.
    pub fn look_at_target(&self) -> Option<Vec3> {
        self.look_at_target
    }

    /// Sets a direct rest-relative head rotation and clears any gaze target.
    pub fn set_look_at_rotation(&mut self, rotation: Option<Quat>) {
        self.look_at_rotation = rotation;
        if rotation.is_some() {
            self.look_at_target = None;
        }
    }

    pub(crate) fn overlay(&mut self, controls: &Self) {
        self.expression_weights
            .extend(controls.expression_weights.clone());
        self.bone_rotations.extend(controls.bone_rotations.clone());
        self.bone_translations
            .extend(controls.bone_translations.clone());
        if controls.look_at_target.is_some() {
            self.look_at_target = controls.look_at_target;
            self.look_at_rotation = None;
        } else if controls.look_at_rotation.is_some() {
            self.look_at_rotation = controls.look_at_rotation;
            self.look_at_target = None;
        }
    }

    /// Applies a clip to `avatar` at `time`, overwriting its animated controls.
    ///
    /// Programmatic rotations are target-local deltas. Loaded VRMA rotations
    /// are converted through normalized humanoid space, and their Hips
    /// translation is scaled by the ratio of target/source rest-pose heights.
    pub fn apply_animation(&mut self, animation: &VrmAnimation, time: f32, avatar: &AvatarAsset) {
        self.apply_animation_with_options(animation, time, avatar, true);
    }

    pub(crate) fn apply_animation_with_options(
        &mut self,
        animation: &VrmAnimation,
        time: f32,
        avatar: &Avatar,
        scale_hips_translation: bool,
    ) {
        let rest_world = avatar.compute_world_matrices(&[]);
        let hips_scale = if scale_hips_translation {
            animation
                .source_hips_height()
                .filter(|height| height.is_finite() && height.abs() > f32::EPSILON)
                .and_then(|source_height| {
                    let hips = avatar.humanoid().bone(HumanBone::Hips)?;
                    let target_height = rest_world.get(hips.0 as usize)?.w_axis.y;
                    target_height
                        .is_finite()
                        .then_some(target_height / source_height)
                })
                .unwrap_or(1.0)
        } else {
            1.0
        };

        for (&bone, target) in avatar.humanoid().bones() {
            let rotation = if animation.has_source_rest_pose() {
                retargeted_rotation_with_missing_ancestors(
                    animation,
                    time,
                    avatar,
                    &rest_world,
                    bone,
                    target.0 as usize,
                )
            } else {
                animation.sample_programmatic_bone_rotation_delta(bone, time)
            };
            if let Some(rotation) = rotation {
                self.set_bone_rotation(bone, rotation);
            }
        }

        for (bone, track) in animation.bone_tracks() {
            if track.translation().is_none() || avatar.humanoid().bone(bone).is_none() {
                continue;
            }
            if let Some(mut translation) = animation.sample_bone_translation_delta(bone, time) {
                if bone == HumanBone::Hips {
                    translation *= hips_scale;
                }
                self.set_bone_translation(bone, translation);
            }
        }

        self.set_look_at_rotation(animation.sample_look_at_rotation(time));
        for (name, _) in animation.expression_tracks() {
            self.set_expression(name, animation.sample_expression_weight(name, time));
        }
    }

    /// Evaluates this instance against `avatar`, folding LookAt, expression
    /// overrides/accumulation and bone rotations into one [`AvatarEvaluation`].
    ///
    /// This is pure: the instance is only read, the caller keeps control of
    /// the shared state.
    pub fn evaluate(&self, avatar: &Avatar) -> AvatarEvaluation {
        // Work on copies so this method is pure: nothing is written back into
        // the instance, the caller keeps full control of the shared state.
        let mut expression_weights = self.expression_weights.clone();
        let mut bone_rotations = self.bone_rotations.clone();

        // Phase 1 / LookAt: turn the gaze target into eye state before any
        // expression math runs (matches the VRM recommended update order).
        // The result is fused into the working state below as if the user had
        // set those expressions/rotations themselves.
        if let Some(look_at) = avatar.look_at() {
            let controlled_bones: std::collections::HashSet<_> = bone_rotations
                .keys()
                .chain(self.bone_translations.keys())
                .copied()
                .collect();
            let pre_look_at_updates: Vec<BoneUpdate> = controlled_bones
                .into_iter()
                .filter_map(|bone| {
                    let node = avatar.humanoid().bone(bone)?;
                    let rotation = bone_rotations.get(&bone).copied().unwrap_or(Quat::IDENTITY);
                    Some(match self.bone_translations.get(&bone) {
                        Some(&translation) => {
                            BoneUpdate::with_translation(node.0, rotation, translation)
                        }
                        None => BoneUpdate::new(node.0, rotation),
                    })
                })
                .collect();
            let current_world = avatar.compute_world_matrices(&pre_look_at_updates);
            let rest_world = avatar.compute_world_matrices(&[]);
            let local_target = if let Some(target) = self.look_at_target {
                avatar.humanoid().bone(HumanBone::Head).and_then(|head| {
                    let current_head = current_world.get(head.0 as usize)?;
                    let rest_head = rest_world.get(head.0 as usize)?;
                    let (_, rest_rotation, _) = rest_head.to_scale_rotation_translation();
                    let look_at_world = *current_head
                        * glam::Mat4::from_translation(look_at.offset_from_head_bone)
                        * glam::Mat4::from_quat(rest_rotation.inverse());
                    Some(look_at_world.inverse().transform_point3(target))
                })
            } else {
                self.look_at_rotation.map(|rotation| rotation * Vec3::Z)
            };

            if let Some(local_target) = local_target {
                // Convert the head-local direction into horizontal (yaw) and
                // vertical (pitch) angles for the eye rig.
                let (yaw, pitch) = crate::look_at::calc_yaw_pitch(local_target);

                match look_at.look_at_type {
                    // Bone mode: the eye bones are rotated directly...
                    crate::LookAtType::Bone => {
                        let (left_rot, right_rot) = look_at.apply_bone(yaw, pitch);
                        bone_rotations.insert(HumanBone::LeftEye, left_rot);
                        bone_rotations.insert(HumanBone::RightEye, right_rot);
                    }
                    // Expression mode: write the look* expression weights, which
                    // the override/accumulation steps below will then process.
                    crate::LookAtType::Expression => {
                        let (l_left, l_right, l_down, l_up) = look_at.apply_expression(yaw, pitch);
                        if l_left > 0.0 {
                            expression_weights.insert("lookLeft".to_string(), l_left);
                        }
                        if l_right > 0.0 {
                            expression_weights.insert("lookRight".to_string(), l_right);
                        }
                        if l_down > 0.0 {
                            expression_weights.insert("lookDown".to_string(), l_down);
                        }
                        if l_up > 0.0 {
                            expression_weights.insert("lookUp".to_string(), l_up);
                        }
                    }
                }
            }
        }

        // Phase 2 / Override collection: an expression may suppress the
        // procedural expressions of a whole category (mouth / blink / gaze)
        // while it is active, either fully (block) or proportionally (blend).
        // Here we only aggregate that intent per category — nothing is modified.
        // The override authority uses the expression's output value: for
        // isBinary expressions that is the quantized 0/1 value.
        let mut mouth_block = false;
        let mut blink_block = false;
        let mut look_at_block = false;

        // Blend is accumulative: 1 - saturate(Σ blend weights).
        let mut mouth_blend_sum = 0.0f32;
        let mut blink_blend_sum = 0.0f32;
        let mut look_at_blend_sum = 0.0f32;

        for (name, &input_weight) in &self.expression_weights {
            // Inactive or unknown expressions have no override authority.
            if input_weight <= 0.0 {
                continue;
            }
            let Some(expr) = avatar.expressions().get(name) else {
                continue;
            };

            // isBinary expressions affect other expressions through their
            // binary output (0 or 1), not their raw input weight.
            let output_weight = if expr.is_binary() {
                if input_weight >= 0.5 { 1.0 } else { 0.0 }
            } else {
                input_weight
            };

            match expr.override_mouth() {
                crate::expressions::ExpressionOverrideType::Block => {
                    mouth_block |= output_weight > 0.0;
                }
                crate::expressions::ExpressionOverrideType::Blend => {
                    mouth_blend_sum += output_weight;
                }
                _ => {}
            }
            match expr.override_blink() {
                crate::expressions::ExpressionOverrideType::Block => {
                    blink_block |= output_weight > 0.0;
                }
                crate::expressions::ExpressionOverrideType::Blend => {
                    blink_blend_sum += output_weight;
                }
                _ => {}
            }
            match expr.override_look_at() {
                crate::expressions::ExpressionOverrideType::Block => {
                    look_at_block |= output_weight > 0.0;
                }
                crate::expressions::ExpressionOverrideType::Blend => {
                    look_at_blend_sum += output_weight;
                }
                _ => {}
            }
        }

        // Phase 3 / Apply overrides: touch only the procedural expressions of the
        // three categories. block zeroes them out; blend scales them by
        // 1 - saturate(Σ blend weights).
        let mouth_names = ["aa", "ih", "ou", "ee", "oh"];
        let blink_names = ["blink", "blinkLeft", "blinkRight"];
        let look_at_names = ["lookUp", "lookDown", "lookLeft", "lookRight"];

        let attenuation = |sum: f32| (1.0 - sum.min(1.0)).max(0.0);
        let overridden_load =
            |name: &str, avatar: &Avatar, block: bool, sum: f32, weight: &mut f32| {
                if block {
                    *weight = 0.0;
                } else if sum > 0.0 {
                    // An isBinary expression that receives any override effect
                    // is completely suppressed.
                    let binary_target = avatar
                        .expressions()
                        .get(name)
                        .map(|e| e.is_binary())
                        .unwrap_or(false);
                    *weight = if binary_target {
                        0.0
                    } else {
                        *weight * attenuation(sum)
                    };
                }
            };

        for (name, weight) in expression_weights.iter_mut() {
            if mouth_names.contains(&name.as_str()) {
                overridden_load(name, avatar, mouth_block, mouth_blend_sum, weight);
            }
            if blink_names.contains(&name.as_str()) {
                overridden_load(name, avatar, blink_block, blink_blend_sum, weight);
            }
            if look_at_names.contains(&name.as_str()) {
                overridden_load(name, avatar, look_at_block, look_at_blend_sum, weight);
            }
        }

        // Phase 4 / Accumulation: evaluate every (already overridden) expression
        // and fold its output into per-target accumulators. Only the accumulated
        // values reach the GPU — combined first so the order quirks of blendshape
        // APIs (e.g. wgpu) stay hidden from the caller.
        let mut weights = BTreeMap::<(u32, u32), f32>::new();
        // VRM expression evaluation starts every morph target at zero. The
        // glTF node or mesh weights are not an expression baseline.
        let mut material_colors = BTreeMap::<(u32, MaterialColorType), [f32; 4]>::new();
        let mut texture_transforms = BTreeMap::<u32, ([f32; 2], [f32; 2])>::new();

        for (name, input_weight) in &expression_weights {
            let Some(expression) = avatar.expressions().get(name) else {
                continue;
            };

            // Quantize binary expressions at the accumulation point, so their
            // morph output is strictly 0 or 1 (never an in-between value).
            let final_weight = if expression.is_binary() {
                if *input_weight >= 0.5 { 1.0 } else { 0.0 }
            } else {
                *input_weight
            };

            let expr_eval = expression.evaluate(final_weight);

            // Morph deltas: same (node, target) may be touched by several
            // expressions, so weights add up across them.
            for update in expr_eval.morph_updates {
                let key = (update.node_index(), update.target_index());
                *weights.entry(key).or_insert(0.0) += update.weight();
            }

            // Color deltas are accumulated as offsets from the base color,
            // which each bind already defines (see avatar.base_color).
            for update in expr_eval.material_color_updates {
                let key = (update.material_index(), update.color_type());
                let base = avatar.base_color(update.material_index(), update.color_type());
                let target = update.target_value();
                let weight = update.weight();
                let entry = material_colors.entry(key).or_insert([0.0; 4]);
                for i in 0..4 {
                    entry[i] += (target[i] - base[i]) * weight;
                }
            }

            // Texture transform deltas are accumulated relative to the
            // identity scale (1) and offset (0).
            for update in expr_eval.texture_transform_updates {
                let key = update.material_index();
                let scale = update.scale();
                let offset = update.offset();
                let weight = update.weight();
                let entry = texture_transforms
                    .entry(key)
                    .or_insert(([0.0; 2], [0.0; 2]));
                for i in 0..2 {
                    entry.0[i] += (scale[i] - 1.0) * weight;
                    entry.1[i] += (offset[i] - 0.0) * weight;
                }
            }
        }

        // Phase 5 / Emit updates: turn the accumulators into the final, renderer-ready
        // lists of the returned AvatarEvaluation.
        // Morph weights are clamped to [0, 1] — a blendshape only accepts that.
        let morph_updates = weights
            .into_iter()
            .map(|((node_index, target_index), weight)| {
                MorphTargetUpdate::new(node_index, target_index, weight.clamp(0.0, 1.0))
            })
            .collect();

        // Material color: accumulated delta is re-applied on top of the base color
        // to recover the final target value before handing it to the renderer.
        let material_color_updates = material_colors
            .into_iter()
            .map(|((material_index, color_type), delta)| {
                let base = avatar.base_color(material_index, color_type);
                let mut target_value = [0.0; 4];
                for i in 0..4 {
                    target_value[i] = base[i] + delta[i];
                }
                MaterialColorUpdate::new(material_index, color_type, target_value, 1.0)
            })
            .collect();

        let texture_transform_updates = texture_transforms
            .into_iter()
            .map(|(material_index, (scale_delta, offset_delta))| {
                let scale = [1.0 + scale_delta[0], 1.0 + scale_delta[1]];
                let offset = [offset_delta[0], offset_delta[1]];
                TextureTransformUpdate::new(material_index, scale, offset, 1.0)
            })
            .collect();

        // Bone updates: translate high-level HumanBone rotations into low-level node
        // indices so the renderer can feed them straight into compute_world_matrices.
        let bone_updates = bone_rotations
            .iter()
            .filter_map(|(bone, &rotation)| {
                let node = avatar.humanoid().bone(*bone)?;
                Some(match self.bone_translations.get(bone) {
                    Some(&translation) => {
                        BoneUpdate::with_translation(node.0, rotation, translation)
                    }
                    None => BoneUpdate::new(node.0, rotation),
                })
            })
            .chain(
                self.bone_translations
                    .iter()
                    .filter_map(|(bone, &translation)| {
                        if bone_rotations.contains_key(bone) {
                            return None;
                        }
                        let node = avatar.humanoid().bone(*bone)?;
                        Some(BoneUpdate::with_translation(
                            node.0,
                            Quat::IDENTITY,
                            translation,
                        ))
                    }),
            )
            .collect();

        AvatarEvaluation {
            morph_updates,
            material_color_updates,
            texture_transform_updates,
            bone_updates,
        }
    }
}

fn retargeted_rotation_with_missing_ancestors(
    animation: &VrmAnimation,
    time: f32,
    avatar: &Avatar,
    rest_world: &[glam::Mat4],
    bone: HumanBone,
    target_node: usize,
) -> Option<Quat> {
    let own_rotation = animation.sample_normalized_source_bone_rotation(bone, time);
    let mut missing_ancestors = Vec::new();
    let mut ancestor = bone.parent();
    while let Some(parent) = ancestor {
        if avatar.humanoid().bone(parent).is_some() {
            break;
        }
        if animation.bone_track(parent).is_some()
            && let Some(rotation) = animation.sample_normalized_source_bone_rotation(parent, time)
        {
            missing_ancestors.push(rotation);
        }
        ancestor = parent.parent();
    }

    if own_rotation.is_none() && missing_ancestors.is_empty() {
        return None;
    }
    let normalized = missing_ancestors
        .into_iter()
        .rev()
        .fold(Quat::IDENTITY, |rotation, next| rotation * next)
        * own_rotation.unwrap_or(Quat::IDENTITY);
    let target_world_rotation = rest_world
        .get(target_node)?
        .to_scale_rotation_translation()
        .1;
    Some((target_world_rotation.inverse() * normalized * target_world_rotation).normalize())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        Avatar, AvatarNode, Expression, Expressions, Humanoid, LookAt, LookAtRangeMap, LookAtType,
        MorphTargetBind,
    };

    fn look_at_avatar(head_translation: Vec3) -> Avatar {
        Avatar::new()
            .with_humanoid(
                Humanoid::default()
                    .with_bone(HumanBone::Head, 0)
                    .with_bone(HumanBone::LeftEye, 1)
                    .with_bone(HumanBone::RightEye, 2),
            )
            .with_nodes(vec![
                AvatarNode {
                    index: 0,
                    name: Some("head".to_string()),
                    parent: None,
                    children: vec![1, 2],
                    initial_translation: head_translation,
                    initial_rotation: Quat::IDENTITY,
                    initial_scale: Vec3::ONE,
                },
                AvatarNode {
                    index: 1,
                    name: Some("leftEye".to_string()),
                    parent: Some(0),
                    children: vec![],
                    initial_translation: Vec3::ZERO,
                    initial_rotation: Quat::IDENTITY,
                    initial_scale: Vec3::ONE,
                },
                AvatarNode {
                    index: 2,
                    name: Some("rightEye".to_string()),
                    parent: Some(0),
                    children: vec![],
                    initial_translation: Vec3::ZERO,
                    initial_rotation: Quat::IDENTITY,
                    initial_scale: Vec3::ONE,
                },
            ])
            .with_look_at(LookAt {
                look_at_type: LookAtType::Bone,
                offset_from_head_bone: Vec3::ZERO,
                range_map_horizontal_inner: LookAtRangeMap::default(),
                range_map_horizontal_outer: LookAtRangeMap::default(),
                range_map_vertical_down: LookAtRangeMap::default(),
                range_map_vertical_up: LookAtRangeMap::default(),
            })
    }

    #[test]
    fn instance_stores_expression_weight() {
        let mut instance = AvatarInstance::new();

        assert_eq!(instance.expression_weight("happy"), 0.0);

        instance.set_expression("happy", 0.7);

        assert_eq!(instance.expression_weight("happy"), 0.7);
    }

    #[test]
    fn instance_evaluates_happy_expression() {
        let happy = Expression::new("happy")
            .with_morph_target_binds(vec![MorphTargetBind::new(91, 3, 1.0)]);

        let expressions = Expressions::new(vec![happy]);

        let avatar = Avatar::new().with_expressions(expressions);

        let mut instance = avatar.instantiate();
        instance.set_expression("happy", 0.7);

        let eval = instance.evaluate(&avatar);

        assert_eq!(eval.morph_updates.len(), 1);
        assert_eq!(eval.morph_updates[0].node_index(), 91);
        assert_eq!(eval.morph_updates[0].target_index(), 3);
        assert_eq!(eval.morph_updates[0].weight(), 0.7);
        assert!(eval.bone_updates.is_empty());
    }

    #[test]
    fn look_at_uses_the_head_node_when_the_head_has_no_mesh() {
        let avatar = look_at_avatar(Vec3::new(10.0, 0.0, 0.0));
        let mut instance = AvatarInstance::new();
        instance.set_look_at_target(Some(Vec3::new(10.0, 0.0, 5.0)));

        let evaluation = instance.evaluate(&avatar);

        for eye in [1, 2] {
            let rotation = evaluation
                .bone_updates
                .iter()
                .find(|update| update.node_index() == eye)
                .unwrap()
                .rotation();
            assert!(rotation.abs_diff_eq(Quat::IDENTITY, 1.0e-5));
        }
    }

    #[test]
    fn look_at_space_follows_the_current_head_rotation() {
        let avatar = look_at_avatar(Vec3::ZERO);
        let mut instance = AvatarInstance::new();
        instance.set_bone_rotation(
            HumanBone::Head,
            Quat::from_rotation_y(90.0_f32.to_radians()),
        );
        instance.set_look_at_target(Some(Vec3::new(5.0, 0.0, 0.0)));

        let evaluation = instance.evaluate(&avatar);

        for eye in [1, 2] {
            let rotation = evaluation
                .bone_updates
                .iter()
                .find(|update| update.node_index() == eye)
                .unwrap()
                .rotation();
            assert!(rotation.abs_diff_eq(Quat::IDENTITY, 1.0e-5));
        }
    }

    #[test]
    fn look_at_space_follows_the_current_head_translation() {
        let avatar = look_at_avatar(Vec3::ZERO);
        let mut instance = AvatarInstance::new();
        instance.set_bone_translation(HumanBone::Head, Vec3::new(10.0, 0.0, 0.0));
        instance.set_look_at_target(Some(Vec3::new(10.0, 0.0, 5.0)));

        let evaluation = instance.evaluate(&avatar);

        for eye in [1, 2] {
            let rotation = evaluation
                .bone_updates
                .iter()
                .find(|update| update.node_index() == eye)
                .expect("LookAt must update each eye")
                .rotation();
            assert!(rotation.abs_diff_eq(Quat::IDENTITY, 1.0e-5));
        }
    }
}