GluUnproject works, but only when the camera is not rotated

I am working on a very basic 3D program, my first one using OpenGL. What I am trying to do is trace a ray from the mouse's location on click which works, but only when the camera is not rotated. When the camera is rotated, the unproject treats it as if it was not.

What am I doing wrong?

The code for unproject:

Coord3<GLdouble> Display::GetOGLPos(uint16_t x, uint16_t y)
{
GLint viewport[4];
GLdouble modelview[16];
GLdouble projection[16];

Coord2<GLfloat> window_location;
Coord3<GLdouble> resultant_ray;

glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
glGetDoublev(GL_PROJECTION_MATRIX, projection);
glGetIntegerv(GL_VIEWPORT, viewport);

window_location.x = (float)x;
window_location.y = viewport[3] - (float)y;

gluUnProject(window_location.x , window_location.y, 1.0f, modelview, projection, viewport, &resultant_ray.x, &resultant_ray.y, &resultant_ray.z);

return resultant_ray;
}


The display code:

void Display::Render()
{
if(!dirty)
{
return;
}

glTranslatef(camera.location.x ,camera.location.y, camera.location.z);

glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

glRotatef(camera.angle.y, 1, 0, 0);
glRotatef(camera.angle.x, 0, 1, 0);

glCallList(cube);

glColor3ub(0, 0, 255);

glBegin(GL_LINES);
glVertex3f(0,0,0);
glVertex3f(mouse_click.x, mouse_click.y, mouse_click.z);
glEnd();

SDL_GL_SwapBuffers();

dirty = 0;

SDL_Delay(33);
}

• Try rotating first, then translating. – MichaelHouse Dec 31 '11 at 3:01
• Rotating then translating is the right case for this project, it rotates around a central object instead of using an FPS style camera. – Shawn Buckley Dec 31 '11 at 3:11
• I'm not too familiar with OpenGL, but when you do glGetDoublev(GL_MODELVIEW_MATRIX, modelview) try to output the content of modelview to the console, and start moving the camera around. It's supposed to change when the camera changes, and if it doesn't, that would explain the problem. – David Gouveia Dec 31 '11 at 3:19
• If rotating then translating is the right case... why aren't you doing it? – MichaelHouse Dec 31 '11 at 5:41
• I must have gotten mixed up trying variations, the one posted is the one that works as intended. – Shawn Buckley Dec 31 '11 at 5:43

It might be because you're clearing the modelview matrix at the end of draw() with glLoadIdentity(); Try doing the transformations again at the beginning of GetOGLPos before you call glGetDoublev() for the matrices, then loading the identity matrix afterwards.
• The projection matrix shouldn't change with rotation. That's what the modelview matrix is for. Unless you are switching the matrix mode to projection somewhere, it will remain unmodified. When you call glLoadIdentity() it undoes all your glRotate(), glTranslate(), and glScale() transformations. When you get the modelview matrix after that, you're getting an unmoved, unrotated matrix, which is why it works when you haven't moved or rotated yet. – Robert Rouhani Dec 31 '11 at 3:45