Blog
Apr
15


Often when working with 3D transformations in code, we are required to calculate a transform matrix to apply to every model in a scene. This transform matrix is usually comprised of three components: translate, rotate and scale.

For more information on the transformations please refer to the following wiki article:
http://en.wikipedia.org/wiki/Transformation_matrix

Working with affine transformations involve 4x4 matrices and matrix multiplications.

In OpenGL 1.1 these are easily accessible without knowing the ins and outs of the translate, rotate and scale matrices nor how to do matrix multiplications.

The following OpenGL 1.1 functions can let you do as such:

//OpenGL 1.1 Matrix Operations
glTranslatef(x,y,z);
glRotatef(x,1,0,0);
glRotatef(y,0,1,0);
glRotatef(z,0,0,1);
glScalef(x,y,z);

As easy as it is to use that sequence of OpenGL commands, you may run into the situation where you are not using OpenGL, or require a faster way to solve for the transform matrix.

Default Case Analysis:

 

  • If we used those functions above, each call would produce five 4x4 matrices
  • Multiplying two matrices together require 64 multiplications & 48 additions (4 multiplications & 3 additions for each element). A total of four matrix multiplications are required resulting in 256 multiplications and 192 additions.
  • What is common to most of the matrices is that many of the elements are 0.


Solution:

By combining the 4 matrix multiplcations together, we get the following:


    float cosX=cos(DEG_TO_RAD(rx));
    float cosY=cos(DEG_TO_RAD(ry));
    float cosZ=cos(DEG_TO_RAD(rz));
    float sinX=sin(DEG_TO_RAD(rx));
    float sinY=sin(DEG_TO_RAD(ry));
    float sinZ=sin(DEG_TO_RAD(rz));
    
    float m[16];

    m[0]=sx*cosY*cosZ;
    m[1]=sinZ*sx*cosY;
    m[2]=-sinY*sx;
    m[4]=-sinZ*cosX*sy + cosZ*sinY*sinX*sy;
    m[5]=cosX*sy*cosZ + sinZ*sinY*sinX*sy;
    m[6]=sinX*sy*cosY;
    m[8]=cosZ*sinY*cosX*sz + sinZ*sinX*sz;
    m[9]=-sinX*sz*cosZ + sinZ*sinY*cosX*sz;
    m[10]=cosX*sz*cosY;
    m[15]=1.f;
    m[12]=tx;
    m[13]=ty;
    m[14]=tz;
    m[3]=m[7]=m[11]=0.f;

Which totals to 6 trigonometry calculations, 30 multiplications, and 4 additions. Less than the number of operations in a matrix multiplication!

This can also be using for calculating bone transform in skeletal mesh deformations.

Use this to your heart's content. Courtesy of your friendly neighbourhood Supreme Heaven Internet Team.

 





© 2011 Supreme Heaven Internet Team. All Rights Reserved.
Powered By Supreme Heaven Internet Team