//如果鼠标点中物体,则返回真,且选中的点在世界坐标系中的坐标为(x,y,z);否则返回假
bool MousePick_WndToWorld( double &x, double &y, double &z)
{
float depth ;//尝试值
POINT p;
GetCursorPos(&p);
::ScreenToClient(g_pGame ->Get_hwnd(), &p);
GLint viewport[4];
GLdouble modelview[16];
GLdouble projection[16];
GLfloat winX, winY;
GLdouble posX, posY, posZ;
glGetIntegerv(GL_VIEWPORT, viewport);
glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
glGetDoublev(GL_PROJECTION_MATRIX, projection);
winX = (float)p.x;
winY = viewport[3] - (float)p.y;
glReadPixels((int)winX, (int)winY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);//获取深度
gluUnProject(winX, winY, depth, modelview, projection, viewport, &x, &y, &z); //找到该点的3D坐标
CPT_3D vector;
vector.m_fX = (float)x;
vector.m_fY = (float)y;
vector.m_fZ = (float)z;
if ( fabs(depth- 1.0f) <= 1e-10)//depth为1表示帧缓存里没有数据,即表示鼠标没有点中任何物体
{
return false;
}
return true;
}