Skip to content

Instantly share code, notes, and snippets.

@matthewjberger
Created January 7, 2024 08:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewjberger/30dbd7e0d7facebcff4021d203fafcdd to your computer and use it in GitHub Desktop.
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)
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