Using gluUnProjectgluUnProject converts Windows screen coordinates to OpenGL coordinates. This means that you can get the position of your mouse on an OpenGL Window and use this method to find the x, y and z coordinate of where you clicked. You need to pass several variables to the function, these are: 1. Viewport Origin And Extent So how do you get them? We need to grab the current viewport. The information we need is the starting X and Y position of our GL viewport along with the viewport width and height. Once we get this information using glGetIntegerv(GL_VIEWPORT, viewport), viewport will hold the following information: viewport[0]=x
Once we have the viewport information, we can grab the Modelview information. The Modelview Matrix determines how the vertices of OpenGL primitives are transformed to eye coordinates.
After that, we need to get the Projection Matrix. The Projection Matrix transforms vertices in eye coordinates to clip coordinates.
4. The Windows Screen Coordinates After we have done all of that, we can grab the Windows screen coordinates. We are interested in the current mouse position.
Now Windows coordinates start with (0, 0) being at the top left whereas OpenGL coords start at the lower left. To convert to OpenGL coordinates we do the following:
You may have noticed the missing z coordinate, well here is how to get it:
5. Variables Where The Output OpenGL Coords Will Be Stored All that is left to do is calculate our final OpenGL coordinates.
Now here is the completed C code that will return the correct OpenGL coordinates if you pass it the mouse coordinates:
Also here is the Delphi code for the same function, donated by Sander Koopmans:
If you are rendering to a window, use the ScreenToClient method (before passing to the method) to convert the mouse co-ordinates given by GetCursorPos to window co-ordinates. Very special thanks to Sander for pointing out and fixing some bugs in the code and the addition of a Delphi version. Additional info for Delphi users from Sander: In the Delphi example the fullscreen / window bug isn't fixed, because it will cost a lot of extra code if you don't use the normal Delphi window TForm. If you want to fix this bug your self then Delphi has the exact same command. The command is stored in the class TControl from the VCL library. * Additional Commenting By NeHe |