Search code examples
graphics3drotationquaternionsspherical-coordinate

Proper conversion between Quaternions and Spherical Rotation Coordinates?


I'm learning about more quaternion conversions and I have a question regarding quaternion to spherical rotation conversion code at the following section of this website:

http://web.archive.org/web/20041029003853/http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q59

What are angle and sin_angle in this code supposed to be? Angle is never used so I was guessing it's the rotation angle. Is sin_angle supposed to be sin_a?

If this was a function returning an array of float with the spherical rotation data, would [angle, latitude, longitude] be an appropriate representation of the converted quaternion?

cos_a  = W;
sin_a  = sqrt( 1.0 - cos_a * cos_a );
angle  = acos( cos_a ) * 2;
if ( fabs( sin_angle ) < 0.0005 ) sin_a = 1;
tx = X / sin_a;
ty = Y / sin_a;
tz = Z / sin_a;
latitude = -asin( ty );
if ( tx * tx + tz * tz < 0.0005 )
   longitude   = 0;
else
   longitude  = atan2( tx, tz );
if ( longitude < 0 )
   longitude += 360.0;

Solution

  • A quaternion is four numbers [X,Y,Z,W] that encode a rotation direction and an angle. The code extracts this information and converts the rotation axis into a latitude and longitude.

    • Quaternion construction from rotation axis [tx,ty,tz] and angle theta is
      • X = tx*SIN(theta/2)
      • Y = ty*SIN(theta/2)
      • Z = tz*SIN(theta/2)
      • W = COS(theta/2)

    This code does the reverse, since angle = 2*ACOS(W) = 2*(theta/2) = theta. So the variable angle stores the rotation angle.