# Screen to World coordinate: help needed

Hi, I have a simple function that returns the World coordinate when I click on a terrain mesh (a regular grid made of 4x4 quads), in the gl viewport:

``````
GLfloat wx, wy, wz;                     //Window coordinates
double cx, cy, cz;              //Object coordinates
GLdouble mv[16];                        //Modelview matrix
GLdouble proj[16];                      //Projection matrix
GLint vp[4];                            //Viewport
glGetDoublev( GL_MODELVIEW_MATRIX, mv );
glGetDoublev( GL_PROJECTION_MATRIX, proj );
glGetIntegerv( GL_VIEWPORT, vp );
wx = ( float ) event->x();
wy = ( float ) vp[3] - ( float ) event->y();            //To invert the y
glReadPixels(wx,wy, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &wz);
gluUnProject( wx, wy, wz, mv, proj, vp, &cx, &cy, &cz );

``````

The function works just fine returning the world coordinates.
However, I’d like to identify the actual point relative to the terrain, so that later I can, for example, put a tree on that specific point.

I suppose I have to take into account camera transformations and rotations, but I don’t know how.

Thanks

You’re already taking camera and world transformation into account (GL_MODELVIEW_MATRIX). As i can see, the code should do it already.

Thanks for the answer and sorry for my ignorance on this matter. So you say that even if I rotate or translate the terrain, the values should always be the same ?
My aim would be to gather the “local” point clicked on the terrain. So even if I rotate the camera, translate the terrain, if I click on the center of the terrain (regular quad grid ranging between -4,+4) it should always give 0,0, and -4->4 values at the corners.
As for now, I only get correct values if the camera is not moved.
Any idea ?

Hi,
Are you sure that the modelview matrix that u get from OpenGL is obtained after the camera transformation and not before it?
So in code it should be something like this,

``````
void Render() {
//clear back buffer and depth buffer (if any)

glMatrixMode(GL_MODELVIEW);
glMultMatrix(object.matrix);

//now get the modelview matrix and stuff here and do ur calculation
GLfloat wx, wy, wz;                     //Window coordinates
double cx, cy, cz;                      //Object coordinates
GLdouble mv[16];                        //Modelview matrix
GLdouble proj[16];                      //Projection matrix
GLint vp[4];                            //Viewport
glGetDoublev( GL_MODELVIEW_MATRIX, mv );
glGetDoublev( GL_PROJECTION_MATRIX, proj );
glGetIntegerv( GL_VIEWPORT, vp );
wx = ( float ) event->x();
wy = ( float ) vp[3] - ( float ) event->y();            //To invert the y
glReadPixels(wx,wy, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &wz);
gluUnProject( wx, wy, wz, mv, proj, vp, &cx, &cy, &cz );

See if this helps,
Mobeen

``````