I want to obtain a mouselook effect.
Omitting mouse coords acquisition and other things, the gist of the problem is that:
using fixed opengl function, this can be made doing
glRotate(angley,0,1,0);
glRotate(anglex,1,0,0);
using my matrix class, the result is not as above:
mat4 cammtx;
cammtx.rotate(angley,0,1,0);
cammtx.rotate(anglex,1,0,0);
because camera not still holding the y axis, that is, also z axis seems to rotate...
How can i achieve the same glRotate behaviour with my matrix::rotate implementation?
struct mat4
{
float m[16];
mat4(){identity();}
.
.
void rotate(float angle,float x,float y,float z){float res[16];matrix::rotate(res,m,a,x,y,z);memcpy(m,res,sizeof(float)*16);}
};
here is my rotate function (input vector is not normalized, i know, but i pass only unit vectors)
void rotate(float* mr,float* m,float angle,float x,float y,float z)
{
float a=angle*PI_OVER_180;
float m2[16] = {0};
float c=cos(a);
float s=sin(a);
float xx=x*x,
yy=y*y,
zz=z*z;
m2[0] = xx+(1.0f-xx)*c;
m2[4] = (1.0f-c)*x*y-s*z;
m2[8] = (1.0f-c)*x*z+s*y;
m2[3] = 0.0f;
m2[1] = (1.0f-c)*y*x+s*z;
m2[5] = yy+(1.0f-yy)*c;
m2[9] = (1.0f-c)*y*z-s*x;
m2[7] = 0.0f;
m2[2] = (1.0f-c)*z*x-s*y;
m2[6] = (1.0f-c)*z*y+s*x;
m2[10] = zz+(1.0f-zz)*c;
m2[11] = 0.0f;
m2[12] = 0;
m2[13] = 0;
m2[14] = 0;
m2[15] = 1.0f;
multiply(mr,m2,m);
}
And this is the multiply function
float* multiply(float* c,float* aa,float* bb)
{
for(int i = 0; i < 4; i++)
{
c[i*4] = bb[i*4] * aa[0] + bb[i*4+1] * aa[4] + bb[i*4+2] * aa[8] + bb[i*4+3] * aa[12];
c[i*4+1] = bb[i*4] * aa[1] + bb[i*4+1] * aa[5] + bb[i*4+2] * aa[9] + bb[i*4+3] * aa[13];
c[i*4+2] = bb[i*4] * aa[2] + bb[i*4+1] * aa[6] + bb[i*4+2] * aa[10] + bb[i*4+3] * aa[14];
c[i*4+3] = bb[i*4] * aa[3] + bb[i*4+1] * aa[7] + bb[i*4+2] * aa[11] + bb[i*4+3] * aa[15];
}
return c;
}
Using
multiply (...)
the way it is written, you are currently pre-multiplyingm2
andm
. Because OpenGL uses (more importantly, because your rotation code is producing) column-major matrices, in order to perform a series of matrix multiplications in the proper order you need to post-multiply the operands.This can be accomplished simply by changing the end of your
rotate (...)
function to read:Keep in mind you need to do this for all matrix operations you decide to implement yourself. Translation, scaling, etc. Assuming you stick to column-major notation you need to post-multiply.