Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Quaternion rotation to rotation matrix?

Tags:

Basically, given a quaterion (qx, qy, qz, qw)... How can i convert that to an OpenGL rotation matrix? I'm also interested in which matrix row is "Up", "Right", "Forward" etc... I have a camera rotation in quaternion that I need in vectors...

like image 431
Polaris878 Avatar asked Oct 12 '09 18:10

Polaris878


People also ask

How do you create a rotation matrix using quaternion?

Combine the quaternion rotations into a single representation, then apply the quaternion rotation to arbitrarily initialized Cartesian points. Combine the rotation matrices into a single representation, then apply the rotation matrix to the same initial Cartesian points.

How do you convert a rotation vector to a rotation matrix?

The formula for finding the rotation matrix corresponding to an angle-axis vector is called Rodrigues' formula, which is now derived. Let r be a rotation vector. If the vector is (0,0,0), then the rotation is zero, and the corresponding matrix is the identity matrix: r = 0 → R = I . such that p = r.

How do you convert quaternion to DCM?

Description. dcm = quat2dcm( q ) calculates the direction cosine matrix, n , for a given quaternion, q . Aerospace Toolbox uses quaternions that are defined using the scalar-first convention.

How do you reverse a quaternion rotation?

Inverting or conjugating a rotation quaternion has the effect of reversing the axis of rotation, which modifies it to rotate in the opposite direction from the original. That is, if a point is rotated to a new position using q, then rotating it again using q−1 or q* will return it to its original location.


1 Answers

The following code is based on a quaternion (qw, qx, qy, qz), where the order is based on the Boost quaternions:

boost::math::quaternion<float> quaternion;
float qw = quaternion.R_component_1();
float qx = quaternion.R_component_2();
float qy = quaternion.R_component_3();
float qz = quaternion.R_component_4();

First you have to normalize the quaternion:

const float n = 1.0f/sqrt(qx*qx+qy*qy+qz*qz+qw*qw);
qx *= n;
qy *= n;
qz *= n;
qw *= n;

Then you can create your matrix:

Matrix<float, 4>(
    1.0f - 2.0f*qy*qy - 2.0f*qz*qz, 2.0f*qx*qy - 2.0f*qz*qw, 2.0f*qx*qz + 2.0f*qy*qw, 0.0f,
    2.0f*qx*qy + 2.0f*qz*qw, 1.0f - 2.0f*qx*qx - 2.0f*qz*qz, 2.0f*qy*qz - 2.0f*qx*qw, 0.0f,
    2.0f*qx*qz - 2.0f*qy*qw, 2.0f*qy*qz + 2.0f*qx*qw, 1.0f - 2.0f*qx*qx - 2.0f*qy*qy, 0.0f,
    0.0f, 0.0f, 0.0f, 1.0f);

Depending on your matrix class, you might have to transpose it before passing it to OpenGL.

like image 140
Malte Clasen Avatar answered Oct 18 '22 07:10

Malte Clasen