Getting the direction vector and up vector from the current model/view matrix.


I have recently made a camera class for my project. Although all the code has been written and it works perfectly, I still have some questions. The key code section in the class is from, and it looks like:

void glCamera::SetPrespective()
GLfloat Matrix[16];

glRotatef(m_HeadingDegrees, 0.0f, 1.0f, 0.0f);
glRotatef(m_PitchDegrees, 1.0f, 0.0f, 0.0f);

glGetFloatv(GL_MODELVIEW_MATRIX, Matrix);

m_DirectionVector.i = Matrix[8];
m_DirectionVector.k = Matrix[10];


glRotatef(m_PitchDegrees, 1.0f, 0.0f, 0.0f);

glGetFloatv(GL_MODELVIEW_MATRIX, Matrix);
m_DirectionVector.j = Matrix[9];

glRotatef(m_HeadingDegrees, 0.0f, 1.0f, 0.0f);

// Scale the direction by our speed.
m_DirectionVector *= m_ForwardVelocity;

// Increment our position by the vector
m_Position.x += m_DirectionVector.i;
m_Position.y += m_DirectionVector.j;
m_Position.z += m_DirectionVector.k;

// Translate to our new position.
glTranslatef(-m_Position.x, -m_Position.y, m_Position.z);


This code sets up the model/view matrix using the camera’s heading and pitch degrees. It works perfectly. What I do not get is the way it gets the direction vector from the model/view matrix using glGetFloat. Can anybody explain this a little bit or introduce some theoretic materials? Can I get the up vector in the similar way? Thanks a lot.

The upper-left 3x3 submatrix inside a 4x4 transformation matrix is really just 3 vectors. In the identity matrix you have this 3x3 submatrix:

1 0 0
0 1 0
0 0 1

which is really 3 vectors, one pointing straight down the x-axis, one pointing down the y-axis, and another pointing down the z-axis. If you apply rotations to this matrix, you end up with vectors that point in other directions.

Your code fragment is just using the z-axis component as the direction vector (components 8, 9 and 10). So the up vector would be the y-axis (components 4, 5, and 6).

Thanks for your reply.

However, I still wonder why it gets the direction vector in two steps:
1 construct the model/view matrix by heading and pitch, and get component i and k as the 8th and 10th element of the matrix;
2 construct the model/view matrix again, but this time by pitch ONLY! and get component j as the 9th element of the matrix.

Why doesn’t it get the direction vector from a grand matrix formed by heading and pitch or from two single matrice by heading and pitch respectively?

Any further explanations very welcome!