Window coordinates - simple question

Hi,
If I have a pair of (x,y) window coordinates (where the mouse clicked in an opengl view) how do I find the corresponding coordinates of that click in terms of the opengl world space? I’m using gluPerspective for a 3d perspective projection matrix.

I’ve looked around but I’m not sure what the official name for this is, which makes it hard to search.

Thanks

You can’t get 3D coordinates from 2D coordinates because the projection loses information. However if you have the depth as well then you can use:
glReadPixels(x,y,GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
gluUnProject(x,y,depth, model_view, projection, viewport, &outX, &outY, &outZ);
See documentation for explanation of the function.

Typically this sort of thing is called “picking” because when user clicks somewhere inside a window, you project a ray into 3D and return the intersection with the first object. That’s kind of what the code above does - the depth component will contain the z for the closest object.