I am new to Opengl. I am working on a navigation application.
The map is displayed in perspective mode using glfrustum.
When the mouse is clicked on the map, I use glUnproject to map the window coordinate to the original object coordinate.
To get the z-coordinate for the click position (to pass it to glUnproject), I have tried the following methods. None of them worked propely for me.
- glReadPixels(x, height-y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &z);
int nResult = gluUnProject(x, height-y, z, m_pdModelMatrix, m_pdProjMatrix, m_pnViewport, &winx, &winy, &winz );
The value of z returned from glreadpixel is always 0 and hence i dont get the right coordinate
- I tried to the relative z coordinate using following method
gluProject(0,0,0,m_pdModelMatrix,m_pdProjMatrix, m_pnViewport, &winx, &winy, &z);
int nResult = gluUnProject(x, y, z, m_pdModelMatrix, m_pdProjMatrix, m_pnViewport, &winx, &winy, &winz );
I get a coordinate which is somewhere close to the object. But i dont get the accurate value.
Following are some patches i have used in code to get the expected perspective view. I am not sure if the problem is caused by any of these.
glFrustum (-width/40, width/40, -height/20, height/20, 1, 80 );
glTranslatef (0, 0, -21.0); /* viewing transformation /
glScalef (1, 1, 1); / modeling transformation */
As such the range of all the vertices is from -width/2 to width/2 and -height/2 to height/2.
But the value given in glfrustum is totally different.
The range of z value of all coordinates is from 1 to 20. I have calculated the value of z based on the value of y. I have just given the same value of y to z simply mapping it to suite the range of 1 to 20.
But the value given in glfrustum is 1 to 80.
Kindly tell me if there is a better way to do this and the reason for inaccurate results.
Thanks in advance.