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
use std::collections::HashMap;
use vrm_spec::vrmc_vrm_1_0::{HumanBoneName, Humanoid as SpecHumanoid};

use crate::NodeId;

/// The standard humanoid bone set of a VRM avatar.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum HumanBone {
    // Torso
    /// The pelvis and root of the humanoid skeleton.
    Hips,
    /// The lower spine.
    Spine,
    /// The chest above the spine.
    Chest,
    /// The optional upper chest above the chest.
    UpperChest,
    /// The neck below the head.
    Neck,
    // Head
    /// The head.
    Head,
    /// The left eye.
    LeftEye,
    /// The right eye.
    RightEye,
    /// The jaw.
    Jaw,
    // Leg
    /// The left thigh.
    LeftUpperLeg,
    /// The left lower leg.
    LeftLowerLeg,
    /// The left foot.
    LeftFoot,
    /// The left toes.
    LeftToes,
    /// The right thigh.
    RightUpperLeg,
    /// The right lower leg.
    RightLowerLeg,
    /// The right foot.
    RightFoot,
    /// The right toes.
    RightToes,
    // Arm
    /// The left shoulder.
    LeftShoulder,
    /// The left upper arm.
    LeftUpperArm,
    /// The left lower arm.
    LeftLowerArm,
    /// The left hand.
    LeftHand,
    /// The right shoulder.
    RightShoulder,
    /// The right upper arm.
    RightUpperArm,
    /// The right lower arm.
    RightLowerArm,
    /// The right hand.
    RightHand,

    // Finger
    /// The left thumb metacarpal.
    LeftThumbMetacarpal,
    /// The left thumb proximal phalanx.
    LeftThumbProximal,
    /// The left thumb distal phalanx.
    LeftThumbDistal,
    /// The left index proximal phalanx.
    LeftIndexProximal,
    /// The left index intermediate phalanx.
    LeftIndexIntermediate,
    /// The left index distal phalanx.
    LeftIndexDistal,
    /// The left middle proximal phalanx.
    LeftMiddleProximal,
    /// The left middle intermediate phalanx.
    LeftMiddleIntermediate,
    /// The left middle distal phalanx.
    LeftMiddleDistal,
    /// The left ring proximal phalanx.
    LeftRingProximal,
    /// The left ring intermediate phalanx.
    LeftRingIntermediate,
    /// The left ring distal phalanx.
    LeftRingDistal,
    /// The left little-finger proximal phalanx.
    LeftLittleProximal,
    /// The left little-finger intermediate phalanx.
    LeftLittleIntermediate,
    /// The left little-finger distal phalanx.
    LeftLittleDistal,
    /// The right thumb metacarpal.
    RightThumbMetacarpal,
    /// The right thumb proximal phalanx.
    RightThumbProximal,
    /// The right thumb distal phalanx.
    RightThumbDistal,
    /// The right index proximal phalanx.
    RightIndexProximal,
    /// The right index intermediate phalanx.
    RightIndexIntermediate,
    /// The right index distal phalanx.
    RightIndexDistal,
    /// The right middle proximal phalanx.
    RightMiddleProximal,
    /// The right middle intermediate phalanx.
    RightMiddleIntermediate,
    /// The right middle distal phalanx.
    RightMiddleDistal,
    /// The right ring proximal phalanx.
    RightRingProximal,
    /// The right ring intermediate phalanx.
    RightRingIntermediate,
    /// The right ring distal phalanx.
    RightRingDistal,
    /// The right little-finger proximal phalanx.
    RightLittleProximal,
    /// The right little-finger intermediate phalanx.
    RightLittleIntermediate,
    /// The right little-finger distal phalanx.
    RightLittleDistal,
}

impl HumanBone {
    /// Returns the canonical humanoid parent from the VRM 1.0 bone hierarchy.
    pub(crate) const fn parent(self) -> Option<Self> {
        use HumanBone::*;

        Some(match self {
            Hips => return None,
            Spine => Hips,
            Chest => Spine,
            UpperChest => Chest,
            Neck => UpperChest,
            Head => Neck,
            LeftEye | RightEye | Jaw => Head,
            LeftUpperLeg => Hips,
            LeftLowerLeg => LeftUpperLeg,
            LeftFoot => LeftLowerLeg,
            LeftToes => LeftFoot,
            RightUpperLeg => Hips,
            RightLowerLeg => RightUpperLeg,
            RightFoot => RightLowerLeg,
            RightToes => RightFoot,
            LeftShoulder => UpperChest,
            LeftUpperArm => LeftShoulder,
            LeftLowerArm => LeftUpperArm,
            LeftHand => LeftLowerArm,
            RightShoulder => UpperChest,
            RightUpperArm => RightShoulder,
            RightLowerArm => RightUpperArm,
            RightHand => RightLowerArm,
            LeftThumbMetacarpal | LeftIndexProximal | LeftMiddleProximal | LeftRingProximal
            | LeftLittleProximal => LeftHand,
            LeftThumbProximal => LeftThumbMetacarpal,
            LeftThumbDistal => LeftThumbProximal,
            LeftIndexIntermediate => LeftIndexProximal,
            LeftIndexDistal => LeftIndexIntermediate,
            LeftMiddleIntermediate => LeftMiddleProximal,
            LeftMiddleDistal => LeftMiddleIntermediate,
            LeftRingIntermediate => LeftRingProximal,
            LeftRingDistal => LeftRingIntermediate,
            LeftLittleIntermediate => LeftLittleProximal,
            LeftLittleDistal => LeftLittleIntermediate,
            RightThumbMetacarpal | RightIndexProximal | RightMiddleProximal | RightRingProximal
            | RightLittleProximal => RightHand,
            RightThumbProximal => RightThumbMetacarpal,
            RightThumbDistal => RightThumbProximal,
            RightIndexIntermediate => RightIndexProximal,
            RightIndexDistal => RightIndexIntermediate,
            RightMiddleIntermediate => RightMiddleProximal,
            RightMiddleDistal => RightMiddleIntermediate,
            RightRingIntermediate => RightRingProximal,
            RightRingDistal => RightRingIntermediate,
            RightLittleIntermediate => RightLittleProximal,
            RightLittleDistal => RightLittleIntermediate,
        })
    }

    /// Reports whether the VRM 1.0 table marks the parent bone as mandatory.
    pub(crate) const fn requires_direct_parent(self) -> bool {
        use HumanBone::*;

        matches!(
            self,
            UpperChest
                | LeftThumbProximal
                | LeftThumbDistal
                | LeftIndexIntermediate
                | LeftIndexDistal
                | LeftMiddleIntermediate
                | LeftMiddleDistal
                | LeftRingIntermediate
                | LeftRingDistal
                | LeftLittleIntermediate
                | LeftLittleDistal
                | RightThumbProximal
                | RightThumbDistal
                | RightIndexIntermediate
                | RightIndexDistal
                | RightMiddleIntermediate
                | RightMiddleDistal
                | RightRingIntermediate
                | RightRingDistal
                | RightLittleIntermediate
                | RightLittleDistal
        )
    }

    /// Returns the lower-camel-case identifier used by the VRM schemas.
    pub(crate) const fn spec_name(self) -> &'static str {
        use HumanBone::*;

        match self {
            Hips => "hips",
            Spine => "spine",
            Chest => "chest",
            UpperChest => "upperChest",
            Neck => "neck",
            Head => "head",
            LeftEye => "leftEye",
            RightEye => "rightEye",
            Jaw => "jaw",
            LeftUpperLeg => "leftUpperLeg",
            LeftLowerLeg => "leftLowerLeg",
            LeftFoot => "leftFoot",
            LeftToes => "leftToes",
            RightUpperLeg => "rightUpperLeg",
            RightLowerLeg => "rightLowerLeg",
            RightFoot => "rightFoot",
            RightToes => "rightToes",
            LeftShoulder => "leftShoulder",
            LeftUpperArm => "leftUpperArm",
            LeftLowerArm => "leftLowerArm",
            LeftHand => "leftHand",
            RightShoulder => "rightShoulder",
            RightUpperArm => "rightUpperArm",
            RightLowerArm => "rightLowerArm",
            RightHand => "rightHand",
            LeftThumbMetacarpal => "leftThumbMetacarpal",
            LeftThumbProximal => "leftThumbProximal",
            LeftThumbDistal => "leftThumbDistal",
            LeftIndexProximal => "leftIndexProximal",
            LeftIndexIntermediate => "leftIndexIntermediate",
            LeftIndexDistal => "leftIndexDistal",
            LeftMiddleProximal => "leftMiddleProximal",
            LeftMiddleIntermediate => "leftMiddleIntermediate",
            LeftMiddleDistal => "leftMiddleDistal",
            LeftRingProximal => "leftRingProximal",
            LeftRingIntermediate => "leftRingIntermediate",
            LeftRingDistal => "leftRingDistal",
            LeftLittleProximal => "leftLittleProximal",
            LeftLittleIntermediate => "leftLittleIntermediate",
            LeftLittleDistal => "leftLittleDistal",
            RightThumbMetacarpal => "rightThumbMetacarpal",
            RightThumbProximal => "rightThumbProximal",
            RightThumbDistal => "rightThumbDistal",
            RightIndexProximal => "rightIndexProximal",
            RightIndexIntermediate => "rightIndexIntermediate",
            RightIndexDistal => "rightIndexDistal",
            RightMiddleProximal => "rightMiddleProximal",
            RightMiddleIntermediate => "rightMiddleIntermediate",
            RightMiddleDistal => "rightMiddleDistal",
            RightRingProximal => "rightRingProximal",
            RightRingIntermediate => "rightRingIntermediate",
            RightRingDistal => "rightRingDistal",
            RightLittleProximal => "rightLittleProximal",
            RightLittleIntermediate => "rightLittleIntermediate",
            RightLittleDistal => "rightLittleDistal",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum HumanoidHierarchyViolation {
    MissingRequiredParent {
        bone: HumanBone,
        required_parent: HumanBone,
    },
    InvalidParent {
        bone: HumanBone,
        expected_parent: Option<HumanBone>,
        actual_parent: Option<HumanBone>,
    },
}

impl HumanoidHierarchyViolation {
    pub(crate) const fn bone(self) -> HumanBone {
        match self {
            Self::MissingRequiredParent { bone, .. } | Self::InvalidParent { bone, .. } => bone,
        }
    }

    pub(crate) fn message(self) -> String {
        match self {
            Self::MissingRequiredParent {
                bone,
                required_parent,
            } => format!(
                "humanoid bone `{}` requires parent bone `{}`",
                bone.spec_name(),
                required_parent.spec_name()
            ),
            Self::InvalidParent {
                bone,
                expected_parent: Some(expected_parent),
                actual_parent,
            } => {
                let found = actual_parent
                    .map(|parent| format!("`{}`", parent.spec_name()))
                    .unwrap_or_else(|| "no mapped humanoid ancestor".to_string());
                format!(
                    "humanoid bone `{}` must be a descendant of `{}` with that bone as its nearest mapped humanoid ancestor; found {found}",
                    bone.spec_name(),
                    expected_parent.spec_name()
                )
            }
            Self::InvalidParent {
                bone,
                expected_parent: None,
                actual_parent,
            } => {
                let found = actual_parent
                    .map(|parent| format!("`{}`", parent.spec_name()))
                    .unwrap_or_else(|| "an unknown bone".to_string());
                format!(
                    "humanoid root bone `{}` must not have mapped humanoid ancestor {found}",
                    bone.spec_name()
                )
            }
        }
    }
}

/// Validates both mandatory optional-bone prerequisites and the nearest
/// humanoid ancestor. Non-humanoid nodes may still occur between two bones.
pub(crate) fn hierarchy_violations(
    bones: impl IntoIterator<Item = (HumanBone, usize)>,
    node_parents: &[Option<usize>],
) -> Vec<HumanoidHierarchyViolation> {
    let bone_nodes = bones.into_iter().collect::<HashMap<_, _>>();
    let node_bones = bone_nodes
        .iter()
        .map(|(&bone, &node)| (node, bone))
        .collect::<HashMap<_, _>>();
    let mut violations = Vec::new();

    for &bone in Humanoid::ALL_BONES {
        let Some(&node) = bone_nodes.get(&bone) else {
            continue;
        };

        let direct_parent = bone.parent();
        if bone.requires_direct_parent()
            && let Some(required_parent) = direct_parent
            && !bone_nodes.contains_key(&required_parent)
        {
            violations.push(HumanoidHierarchyViolation::MissingRequiredParent {
                bone,
                required_parent,
            });
        }

        let mut expected_parent = direct_parent;
        while let Some(parent) = expected_parent {
            if bone_nodes.contains_key(&parent) {
                break;
            }
            expected_parent = parent.parent();
        }

        let mut cursor = node_parents.get(node).copied().flatten();
        let mut actual_parent = None;
        for _ in 0..node_parents.len() {
            let Some(node) = cursor else {
                break;
            };
            if let Some(&parent_bone) = node_bones.get(&node) {
                actual_parent = Some(parent_bone);
                break;
            }
            cursor = node_parents.get(node).copied().flatten();
        }

        if actual_parent != expected_parent {
            violations.push(HumanoidHierarchyViolation::InvalidParent {
                bone,
                expected_parent,
                actual_parent,
            });
        }
    }

    violations
}

impl From<HumanBoneName> for HumanBone {
    fn from(name: HumanBoneName) -> Self {
        match name {
            HumanBoneName::Hips => Self::Hips,
            HumanBoneName::Spine => Self::Spine,
            HumanBoneName::Chest => Self::Chest,
            HumanBoneName::UpperChest => Self::UpperChest,
            HumanBoneName::Neck => Self::Neck,
            HumanBoneName::Head => Self::Head,
            HumanBoneName::LeftEye => Self::LeftEye,
            HumanBoneName::RightEye => Self::RightEye,
            HumanBoneName::Jaw => Self::Jaw,
            HumanBoneName::LeftUpperLeg => Self::LeftUpperLeg,
            HumanBoneName::LeftLowerLeg => Self::LeftLowerLeg,
            HumanBoneName::LeftFoot => Self::LeftFoot,
            HumanBoneName::LeftToes => Self::LeftToes,
            HumanBoneName::RightUpperLeg => Self::RightUpperLeg,
            HumanBoneName::RightLowerLeg => Self::RightLowerLeg,
            HumanBoneName::RightFoot => Self::RightFoot,
            HumanBoneName::RightToes => Self::RightToes,
            HumanBoneName::LeftShoulder => Self::LeftShoulder,
            HumanBoneName::LeftUpperArm => Self::LeftUpperArm,
            HumanBoneName::LeftLowerArm => Self::LeftLowerArm,
            HumanBoneName::LeftHand => Self::LeftHand,
            HumanBoneName::RightShoulder => Self::RightShoulder,
            HumanBoneName::RightUpperArm => Self::RightUpperArm,
            HumanBoneName::RightLowerArm => Self::RightLowerArm,
            HumanBoneName::RightHand => Self::RightHand,
            HumanBoneName::LeftThumbMetacarpal => Self::LeftThumbMetacarpal,
            HumanBoneName::LeftThumbProximal => Self::LeftThumbProximal,
            HumanBoneName::LeftThumbDistal => Self::LeftThumbDistal,
            HumanBoneName::LeftIndexProximal => Self::LeftIndexProximal,
            HumanBoneName::LeftIndexIntermediate => Self::LeftIndexIntermediate,
            HumanBoneName::LeftIndexDistal => Self::LeftIndexDistal,
            HumanBoneName::LeftMiddleProximal => Self::LeftMiddleProximal,
            HumanBoneName::LeftMiddleIntermediate => Self::LeftMiddleIntermediate,
            HumanBoneName::LeftMiddleDistal => Self::LeftMiddleDistal,
            HumanBoneName::LeftRingProximal => Self::LeftRingProximal,
            HumanBoneName::LeftRingIntermediate => Self::LeftRingIntermediate,
            HumanBoneName::LeftRingDistal => Self::LeftRingDistal,
            HumanBoneName::LeftLittleProximal => Self::LeftLittleProximal,
            HumanBoneName::LeftLittleIntermediate => Self::LeftLittleIntermediate,
            HumanBoneName::LeftLittleDistal => Self::LeftLittleDistal,
            HumanBoneName::RightThumbMetacarpal => Self::RightThumbMetacarpal,
            HumanBoneName::RightThumbProximal => Self::RightThumbProximal,
            HumanBoneName::RightThumbDistal => Self::RightThumbDistal,
            HumanBoneName::RightIndexProximal => Self::RightIndexProximal,
            HumanBoneName::RightIndexIntermediate => Self::RightIndexIntermediate,
            HumanBoneName::RightIndexDistal => Self::RightIndexDistal,
            HumanBoneName::RightMiddleProximal => Self::RightMiddleProximal,
            HumanBoneName::RightMiddleIntermediate => Self::RightMiddleIntermediate,
            HumanBoneName::RightMiddleDistal => Self::RightMiddleDistal,
            HumanBoneName::RightRingProximal => Self::RightRingProximal,
            HumanBoneName::RightRingIntermediate => Self::RightRingIntermediate,
            HumanBoneName::RightRingDistal => Self::RightRingDistal,
            HumanBoneName::RightLittleProximal => Self::RightLittleProximal,
            HumanBoneName::RightLittleIntermediate => Self::RightLittleIntermediate,
            HumanBoneName::RightLittleDistal => Self::RightLittleDistal,
        }
    }
}

/// The glTF node index that a [`HumanBone`] maps to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HumanBoneNode(pub u32);

/// The humanoid skeleton: the mapping from each [`HumanBone`] to a node.
#[derive(Debug, Clone, Default)]
pub struct Humanoid {
    bones: HashMap<HumanBone, HumanBoneNode>,
}

impl Humanoid {
    /// The full set of humanoid bones a VRM avatar can define.
    pub const ALL_BONES: &[HumanBone] = &[
        HumanBone::Hips,
        HumanBone::Spine,
        HumanBone::Chest,
        HumanBone::UpperChest,
        HumanBone::Neck,
        HumanBone::Head,
        HumanBone::LeftEye,
        HumanBone::RightEye,
        HumanBone::Jaw,
        HumanBone::LeftUpperLeg,
        HumanBone::LeftLowerLeg,
        HumanBone::LeftFoot,
        HumanBone::LeftToes,
        HumanBone::RightUpperLeg,
        HumanBone::RightLowerLeg,
        HumanBone::RightFoot,
        HumanBone::RightToes,
        HumanBone::LeftShoulder,
        HumanBone::LeftUpperArm,
        HumanBone::LeftLowerArm,
        HumanBone::LeftHand,
        HumanBone::RightShoulder,
        HumanBone::RightUpperArm,
        HumanBone::RightLowerArm,
        HumanBone::RightHand,
        HumanBone::LeftThumbMetacarpal,
        HumanBone::LeftThumbProximal,
        HumanBone::LeftThumbDistal,
        HumanBone::LeftIndexProximal,
        HumanBone::LeftIndexIntermediate,
        HumanBone::LeftIndexDistal,
        HumanBone::LeftMiddleProximal,
        HumanBone::LeftMiddleIntermediate,
        HumanBone::LeftMiddleDistal,
        HumanBone::LeftRingProximal,
        HumanBone::LeftRingIntermediate,
        HumanBone::LeftRingDistal,
        HumanBone::LeftLittleProximal,
        HumanBone::LeftLittleIntermediate,
        HumanBone::LeftLittleDistal,
        HumanBone::RightThumbMetacarpal,
        HumanBone::RightThumbProximal,
        HumanBone::RightThumbDistal,
        HumanBone::RightIndexProximal,
        HumanBone::RightIndexIntermediate,
        HumanBone::RightIndexDistal,
        HumanBone::RightMiddleProximal,
        HumanBone::RightMiddleIntermediate,
        HumanBone::RightMiddleDistal,
        HumanBone::RightRingProximal,
        HumanBone::RightRingIntermediate,
        HumanBone::RightRingDistal,
        HumanBone::RightLittleProximal,
        HumanBone::RightLittleIntermediate,
        HumanBone::RightLittleDistal,
    ];

    /// Returns the node index assigned to `bone`, if any.
    pub fn bone(&self, bone: HumanBone) -> Option<&HumanBoneNode> {
        self.bones.get(&bone)
    }

    /// Returns the type-safe asset node assigned to `bone`.
    pub fn bone_id(&self, bone: HumanBone) -> Option<NodeId> {
        self.bone(bone)
            .map(|node| NodeId::from_index(node.0 as usize))
    }

    /// Iterates over every mapped bone and its raw glTF node index.
    pub fn bones(&self) -> impl Iterator<Item = (&HumanBone, &HumanBoneNode)> {
        self.bones.iter()
    }

    /// Iterates over mapped bones using type-safe node identifiers.
    pub fn bone_ids(&self) -> impl Iterator<Item = (HumanBone, NodeId)> + '_ {
        self.bones
            .iter()
            .map(|(&bone, node)| (bone, NodeId::from_index(node.0 as usize)))
    }

    /// Builder method that maps a [`HumanBone`] to a glTF node index.
    pub fn with_bone(mut self, bone: HumanBone, node_index: u32) -> Self {
        self.bones.insert(bone, HumanBoneNode(node_index));
        self
    }

    pub(crate) fn load_humanoid(schema: &SpecHumanoid) -> Self {
        let mut bones = HashMap::new();

        for (bone_name, bone_spec) in &schema.human_bones.0 {
            let Some(node) = bone_spec.as_ref().and_then(|spec| spec.node.as_ref()) else {
                continue;
            };
            let human_bone = HumanBone::from(*bone_name);
            let node_index = node.value() as u32;
            bones.insert(human_bone, HumanBoneNode(node_index));
        }

        Self { bones }
    }
}