Skip to main content

three_rs/objects/
skeleton.rs

1//! Port of `three.js/src/objects/Skeleton.js`.
2//!
3//! `boneTexture` is the renderer's business (Three allocates a `DataTexture`
4//! from `boneMatrices` in `Skeleton.computeBoneTexture`), so it is left as the
5//! [`Skeleton::bone_matrices`] hook; the
6//! renderer fills it in at rung 10.
7
8use crate::core::ObjectRef;
9use crate::math::Matrix4;
10
11/// `class Skeleton`.
12#[derive(Debug, Default)]
13pub struct Skeleton {
14    /// `Skeleton.bones`.
15    pub bones: Vec<ObjectRef>,
16    /// `Skeleton.boneInverses`.
17    pub bone_inverses: Vec<Matrix4>,
18    /// `Skeleton.boneMatrices` — `new Float32Array( bones.length * 16 )`,
19    /// filled by [`Skeleton::update`].
20    pub bone_matrices: Vec<f32>,
21    /// `Skeleton.frame`, the renderer's "did the texture change" counter.
22    pub frame: i64,
23}
24
25impl Skeleton {
26    /// `new Skeleton( bones, boneInverses )`. `None` for the inverses is
27    /// three.js' `boneInverses === undefined` branch, which calls
28    /// `calculateInverses()`.
29    pub fn new(bones: Vec<ObjectRef>, bone_inverses: Option<Vec<Matrix4>>) -> Self {
30        let mut skeleton = Self {
31            bones,
32            bone_inverses: Vec::new(),
33            bone_matrices: Vec::new(),
34            frame: -1,
35        };
36
37        skeleton.init(bone_inverses);
38        skeleton
39    }
40
41    /// `Skeleton.init()`.
42    pub fn init(&mut self, bone_inverses: Option<Vec<Matrix4>>) {
43        self.bone_matrices = vec![0.0; self.bones.len() * 16];
44
45        match bone_inverses {
46            None => self.calculate_inverses(),
47            Some(inverses) => {
48                if inverses.len() == self.bones.len() {
49                    self.bone_inverses = inverses;
50                } else {
51                    // `THREE.Skeleton: Number of inverse bone matrices does not
52                    // match amount of bones.`
53                    self.bone_inverses = vec![Matrix4::identity(); self.bones.len()];
54                }
55            }
56        }
57    }
58
59    /// `Skeleton.calculateInverses()`.
60    pub fn calculate_inverses(&mut self) {
61        self.bone_inverses.clear();
62
63        for bone in &self.bones {
64            let mut inverse = bone.borrow().matrix_world;
65            inverse.invert();
66            self.bone_inverses.push(inverse);
67        }
68    }
69
70    /// `Skeleton.pose()` — put the skeleton back into its bind pose.
71    pub fn pose(&mut self) {
72        // recover the bind-time world matrices
73        for (bone, inverse) in self.bones.iter().zip(self.bone_inverses.iter()) {
74            let mut world = *inverse;
75            world.invert();
76            bone.borrow_mut().matrix_world = world;
77        }
78
79        // compute the local matrices, positions, rotations and scales
80        for bone in &self.bones {
81            let parent_world = bone.parent().map(|parent| parent.borrow().matrix_world);
82
83            let matrix = match parent_world {
84                Some(parent_world) => {
85                    let mut inverse = parent_world;
86                    inverse.invert();
87                    let mut matrix = Matrix4::identity();
88                    let world = bone.borrow().matrix_world;
89                    matrix.multiply_matrices(&inverse, &world);
90                    matrix
91                }
92                None => bone.borrow().matrix_world,
93            };
94
95            let mut object = bone.borrow_mut();
96            object.matrix.copy(&matrix);
97            let matrix = object.matrix;
98            let (mut position, mut quaternion, mut scale) =
99                (object.position, object.quaternion, object.scale);
100            matrix.decompose(&mut position, &mut quaternion, &mut scale);
101            object.position = position;
102            object.quaternion = quaternion;
103            object.scale = scale;
104            object.sync_rotation_from_quaternion();
105        }
106    }
107
108    /// `Skeleton.update()` — flatten `boneMatrix = boneWorld * boneInverse`
109    /// into `boneMatrices`.
110    pub fn update(&mut self) {
111        let mut offset = 0;
112
113        for (bone, inverse) in self.bones.iter().zip(self.bone_inverses.iter()) {
114            // `// compute the offset between the current and the original
115            // transformation`
116            let world = bone.borrow().matrix_world;
117            let mut matrix = Matrix4::identity();
118            matrix.multiply_matrices(&world, inverse);
119
120            for (i, value) in matrix.elements.iter().enumerate() {
121                self.bone_matrices[offset + i] = *value as f32;
122            }
123
124            offset += 16;
125        }
126    }
127
128    /// `Skeleton.getBoneByName( name )`.
129    pub fn get_bone_by_name(&self, name: &str) -> Option<ObjectRef> {
130        self.bones
131            .iter()
132            .find(|bone| bone.borrow().name == name)
133            .cloned()
134    }
135}