Can some one tell me how to transform from Screen Coordinate to OpenGL coordinate?
I want to draw a 3d line,so i obtain the mouse position in screen coordinate before i draw the line ,i have to transform the screen coordinate to the OpenGL coordinate. However , the line’s position is not correct !why?
My transformation function
Vector3 GetOGLPos(int x, int y)
{
GLint viewport[4];
GLdouble modelview[16];
GLdouble projection[16];
GLfloat winX, winY, winZ;
GLdouble posX, posY, posZ;
Vector3 v;
glGetDoublev( GL_MODELVIEW_MATRIX, modelview );
glGetDoublev( GL_PROJECTION_MATRIX, projection );
glGetIntegerv( GL_VIEWPORT, viewport );winX = (float)x; winY = (float)viewport[3] - (float)y; glReadPixels( x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ ); gluUnProject( winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);
v.x=posX;
v.y=posY;
v.z=posZ;
return v;
}
My mouse message function: i found the position tranformed into OpenGL coordinate is not correct!!!why?
void MouseCallback(int button, int state, int x, int y)
{
Vector3 v;
v.x=GetOGLPos(x,y).x;
v.y=GetOGLPos(x,y).y;
switch ( button )
{
case GLUT_LEFT_BUTTON:
if ( state == GLUT_DOWN )
{
temp1.x = v.x;
temp1.y = v.y;
temp1.z=0;
}
else if ( state == GLUT_UP )
{
temp2.x = v.x;
temp2.y = v.y;
temp2.z=0;
glutPostRedisplay();
}
break;
}
}