Hey everyone. I am trying to use "gluUnProject" to get the mouse click coordinates in OpenGL coordinates. Well, I am using OpenGL in MFC, in a splitter-window pane. I am working on a 3D world editor, and I want to go ahead and get this part out of the way.
Anyhow, here is how I initialize OpenGL:
BOOL CWorldEditorView::InitGL()
{
// TODO: Initialize OpenGL for rendering
glShadeModel(GL_SMOOTH); // Set the shading model
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Set the default clear color
glClearDepth(1.0f); // Set the clearing depth
glFrontFace(GL_CW); // Set the culling face
glEnable(GL_CULL_FACE); // and set
glCullFace(GL_FRONT); // the culling mode
glEnable(GL_DEPTH_TEST); // Enable depth testing
glDepthFunc(GL_LEQUAL); // Set the depth-func.
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glMatrixMode(GL_PROJECTION); // Setup the
glLoadIdentity(); // projection matrix
gluPerspective(45.0f, m_fWHRatio, 1.0f, 100.0f); // Setup the perspective
return TRUE;
}
And here's the left-mouse button click handler:
void CWorldEditorView::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
int vp[4];
double mv[16], pm[16];
float winX, winY, winZ;
double x2, y2, z2;
double y;
CPoint cursor;
GetCursorPos(&cursor);
ScreenToClient(&cursor);
glGetIntegerv(GL_VIEWPORT, vp);
glGetDoublev(GL_MODELVIEW_MATRIX, mv);
glGetDoublev(GL_PROJECTION_MATRIX, pm);
winX = cursor.x;
winY = cursor.y;
y = (float) vp[3] - winY;
glReadPixels(winX, winY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);
gluUnProject(winX, y, 0.0f, mv, pm, vp, &glX, &glY, &glZ);
gluUnProject(winX, y, 1.0f, mv, pm, vp, &x2, &y2, &z2);
CString str;
str.Format("%f, %f, %f", glX-x2, glY-y2, glZ-z2);
AfxMessageBox(str);
bLines = TRUE;
CView::OnLButtonDown(nFlags, point);
}
BTW, I do this in the "OnSize" function:
CView::OnSize(nType, cx, cy);
// TODO: Add your message handler code here
if (cy == 0)
m_fWHRatio = (float) cx; // Set the width-height ratio
else
m_fWHRatio = (double) cx / (double) cy; // Same as above
glViewport(0, 0, cx, cy); // Setup the viewport
InitGL(); // Initialize OpenGL for rendering
Everything there is fine. But when I use the "OnLButtonDown" to display the clicked coordinates, even near the middle of the screen, I get values like "-3.04756, -1.08705, 93.73439". The "93" is coming from the z-value.
I have used "gluUnProject" before, without this problem. Can anyone tell me why it is doing this? Also, when I draw a line from 0.0f,0.0f to 1.0f,0.0f, it goes from the center of the screen all the way to the right side of the screen.
Thanks in advance,
Matt U. ("Waldo")