I’m modelling a room -in which I’d like to be able to obtain the exact position that I click with the mouse in that room. How do I go about doing this?Any code?


If you mean the exact position in world coordinates, you can do it like this.

Save the screen coordinates (in pixels) when you click (as winx and winy). Then read the depth buffer to get the depth value (this will be winz) at that point (with glReadPixels). Then use gluUnProject to obtain the world coordinates.

proto of gluUnProject:
int gluUnProject(GLdouble winx, GLdouble winy, GLdouble winz, const GLdouble modelMatrix[16], const GLdouble projMatrix[16], const GLint viewport[4], GLdouble *objx, GLdouble *objy, GLdouble *objz);
Map the specified window coordinates (winx, winy, winz) into object coordinates, using transformations defined by a modelview matrix (modelMatrix), projection matrix (projMatrix), and viewport (viewport). The resulting object coordinates are returned in objx, objy, and objz. The function returns GL_TRUE, indicating success, or GL_FALSE, indicating failure (such as an noninvertible matrix). This operation does not attempt to clip the coordinates to the viewport or eliminate depth values that fall outside of glDepthRange().
Taken from…/OpenGL_PG/6635


void WhenIClick(int button, int state, int winx, int winy)
// Check here if it’s the event you waited for, i.e. the right button and state.

GLdouble winz;
GLdouble objx, objy, objz;
GLint viewport[4];
GLdouble modelMatrix[16];
GLdouble projMatrix[16];

glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winz);

glGetIntegerv(GL_VIEWPORT, viewport);
glGetFloatv(GL_MODELVIEW_MATRIX, modelMatrix);
glGetFloatv(GL_PROJECTION_MATRIX, projMatrix);

gluUnproject((GLdouble)winx, (GLdouble)winy, winz, modelMatrix, projMatrix, viewport, &objx, &objy, &objz);

This is an example of a callback function that you can use with glut. Register it like this:
When you click, objx, objy and objz will hold the world coordinates of the point you clicked.