Created
January 7, 2024 08:11
-
-
Save matthewjberger/30dbd7e0d7facebcff4021d203fafcdd to your computer and use it in GitHub Desktop.
Decompose a nalgebra_glm 4x4 transformation matrix into translation, rotation, and scaling (accounts for non-uniform scaling)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub fn decompose_matrix( | |
matrix: &nalgebra_glm::Mat4, | |
) -> (nalgebra_glm::Vec3, nalgebra_glm::Quat, nalgebra_glm::Vec3) { | |
let translation = nalgebra_glm::Vec3::new(matrix.m14, matrix.m24, matrix.m34); | |
let (scale_x, scale_y, scale_z) = ( | |
nalgebra_glm::length(&nalgebra_glm::Vec3::new(matrix.m11, matrix.m12, matrix.m13)), | |
nalgebra_glm::length(&nalgebra_glm::Vec3::new(matrix.m21, matrix.m22, matrix.m23)), | |
nalgebra_glm::length(&nalgebra_glm::Vec3::new(matrix.m31, matrix.m32, matrix.m33)), | |
); | |
let scale = nalgebra_glm::Vec3::new(scale_x, scale_y, scale_z); | |
// Normalize the matrix to extract rotation | |
let rotation_matrix = nalgebra_glm::mat3( | |
matrix.m11 / scale_x, | |
matrix.m12 / scale_y, | |
matrix.m13 / scale_z, | |
matrix.m21 / scale_x, | |
matrix.m22 / scale_y, | |
matrix.m23 / scale_z, | |
matrix.m31 / scale_x, | |
matrix.m32 / scale_y, | |
matrix.m33 / scale_z, | |
); | |
let rotation = nalgebra_glm::mat3_to_quat(&rotation_matrix); | |
(translation, rotation, scale) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment