|
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. //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.
Solution:
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!
|