[英]MFC with Opengl get 3d coordinate from 2d coordinate of mouse
我在基於鼠標的MFC應用程序中使用NEHE教程中的代碼
void CRightOGL::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
GLint viewport[4];
GLdouble modelview[16]={0};
GLdouble projection[16];
GLfloat winX, winY, winZ;
GLdouble posX, posY, posZ;
GLfloat mv[16];
glGetFloatv( GL_MODELVIEW_MATRIX, mv );
glGetDoublev( GL_MODELVIEW_MATRIX, modelview );
glGetDoublev( GL_PROJECTION_MATRIX, projection );
glGetIntegerv( GL_VIEWPORT, viewport );
winX = (float)point.x;
winY = (float)viewport[3] - (float)point.y;
glReadPixels(point.x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ );
gluUnProject( winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);
COpenGLControl::OnLButtonDown(nFlags, point);
}
但是問題是每次posX,&posY,&posZ ...我都會得到不正確的值,並且值始終出現在-9.25555,-9.255555,-9.255555中。 不僅如此,而且Modelview矩陣每次都返回相同的-9.555值。
如果我將所有內容都初始化為0,則posX,posY和PosZ僅返回0而不是正確的坐標。 鼠標的x和y值非常合適,因此從鼠標的角度來看沒有問題。
我做錯了什么?
我的opengl初始化代碼如下
void COpenGLControl::oglInitialize(void)
{
// Initial Setup:
//
static PIXELFORMATDESCRIPTOR pfd =
{
sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
32, // bit depth
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
16, // z-buffer depth
0, 0, 0, 0, 0, 0, 0,
};
// Get device context only once.
hdc = GetDC()->m_hDC;
// Pixel format.
m_nPixelFormat = ChoosePixelFormat(hdc, &pfd);
SetPixelFormat(hdc, m_nPixelFormat, &pfd);
// Create the OpenGL Rendering Context.
hrc = wglCreateContext(hdc);
wglMakeCurrent(hdc, hrc);
// Basic Setup:
//
// Set color to use when clearing the background.
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClearDepth(1.0f);
// Turn on backface culling
glFrontFace(GL_CCW);
glCullFace(GL_BACK);
// Turn on depth testing
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_DEPTH);
//glEnable(GL_TEXTURE_2D); // Enable 2D textures
// Send draw request
GLenum a = glGetError();
OnDraw(NULL);
}
好的,我發現由於以下情況而產生的問題
我在兩個不同的hdc的設置之間使用繪圖功能,因為我有兩個不同的mfc圖片控制窗口,並且兩者都有不同的繪圖。 這就是為什么當我使用上述gl代碼時,在鼠標按下或鼠標單擊事件內部,總是通過s = glGetError()給我帶來錯誤1282的原因。
因此,要使其正常工作,我剛剛在
wglMakeCurrent(hdc, hrc);
//my code
wglMakeCurrent(NULL, NULL);
它起作用了,現在所有xy和z值都在屏幕上
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.