view vectors to matrix?

Started by
1 comment, last by InetRoadkill 15 years, 5 months ago
I have 3 vectors which describe a view: vecForward, vecUp, vecRight. I know these are in common use. What I would like to do is use these to create a rotation matrix that can be directly loaded in openGL without having to solve for the individual rotation angles (pitch,roll,yaw) and then doing a set of glRotates(). I did some sample rotations using glRotate() and downloaded the matrix from openGL and it looks like you can almost stuff the view vectors directly into a matrix and do a glMultMatrixf(). Is this the case? Does the matrix need inversion? (I know the rotations are 3x3 and the ogl matrix is 4x4. I assume you need to fill the remaining rows and columns with 0 except for a 1 in the lower corner.)
Advertisement
To create an OpenGL-ready matrix from three direction vectors and a position vector:
float m[16];m[0] = side.x;m[1] = side.y;m[2] = side.z;m[3] = 0.f;m[4] = up.x;m[5] = up.y;m[6] = up.z;m[7] = 0.f;m[8] = forward.x;m[9] = forward.y;m[10] = forward.z;m[11] = 0.f;m[12] = position.x;m[13] = position.y;m[14] = position.z;m[15] = 1.f;
Note that this layout works for DirectX/D3D as well.

If you're unsure of why the matrix must be laid out as shown above, let me know and I'll try to offer some clarification as to what's going on here.

Now, the above matrix represents a local-to-parent transform. If, however, you want to set up a view transform, you'll need a parent-to-local transform.

You can get the latter from the former by inverting the matrix. If you google '4x4 matrix inversion', you'll most likely be able to find some sample code showing how to invert a 4x4 matrix (if you're lucky, it might even use 1-d indexing, in which case you can just plug it right into your own code).

There's a shortcut you can take when inverting rigid body transforms which is both more efficient and easier to code than a general inversion, but to be honest I'm too lazy (or maybe just too tired) to type it out at the moment. A general inversion will work fine though, and since you'll only be doing it once per frame (presumably), efficiency shouldn't be an issue.
Oops. I was on the right track. I just had the side and front vectors swapped.

Thanks.

This topic is closed to new replies.

Advertisement