调用glut函数前,要初始化glut,即调用glutInit();
例如:
int argc=1;
char* argv[]={"MFC_GLUT"};
glutInit(&argc, argv);
再写一下MFC中添加OpenGL配置和glut初始化
1、view.h中添加成员
HGLRC m_hRC; //Rendering Context CDC* m_pDC; //Device Context
BOOL CXXXView::SetupPixelFormat() { static PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), // size of this pfd 1, // version number PFD_DRAW_TO_WINDOW | // support window PFD_SUPPORT_OPENGL | // support OpenGL PFD_DOUBLEBUFFER, // double buffered PFD_TYPE_RGBA, // RGBA type 24, // 24-bit color depth 0, 0, 0, 0, 0, 0, // color bits ignored 0, // no alpha buffer 0, // shift bit ignored 0, // no accumulation buffer 0, 0, 0, 0, // accum bits ignored 16, // 16-bit z-buffer 0, // no stencil buffer 0, // no auxiliary buffer PFD_MAIN_PLANE, // main layer 0, // reserved 0, 0, 0 // layer masks ignored }; int m_nPixelFormat = ::ChoosePixelFormat(m_pDC->GetSafeHdc(), &pfd); if ( m_nPixelFormat == 0 ) { return FALSE; } if ( ::SetPixelFormat(m_pDC->GetSafeHdc(), m_nPixelFormat, &pfd) == FALSE) { return FALSE; } return TRUE; } BOOL CXXXView::InitializeOpenGL() { //Get a DC for the Client Area m_pDC = new CClientDC(this); //Failure to Get DC if(m_pDC == NULL) { MessageBox("Error Obtaining DC"); return FALSE; } //Failure to set the pixel format if(!SetupPixelFormat()) { return FALSE; } //Create Rendering Context m_hRC = ::wglCreateContext (m_pDC->GetSafeHdc ()); //Failure to Create Rendering Context if(m_hRC == 0) { MessageBox("Error Creating RC"); return FALSE; } //Make the RC Current if(::wglMakeCurrent (m_pDC->GetSafeHdc (), m_hRC)==FALSE) { MessageBox("Error making RC Current"); return FALSE; } //Specify Black as the clear color ::glClearColor(0.0f,0.0f,0.0f,0.0f); //Specify the back of the buffer as clear depth ::glClearDepth(1.0f); //Enable Depth Testing ::glEnable(GL_DEPTH_TEST); return TRUE; }
// TODO: 在此添加您专用的创建代码 if( !InitializeOpenGL() ) { TRACE0( "InitializeOpenGL failed !"); return -1; } //初始化glut int argc=1; char* argv[]={"<span style="font-size: 13.3333339691162px;">MFC_GLUT</span>"}; glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
// TODO: 在此处添加消息处理程序代码 if(::wglMakeCurrent (0,0) == FALSE) { MessageBox("Could not make RC non-current"); } //Delete the rendering context if(::wglDeleteContext (m_hRC)==FALSE) { MessageBox("Could not delete RC"); } //Delete the DC if(m_pDC) { delete m_pDC; } //Set it to NULL m_pDC = NULL;5、在CXXXView::OnDraw()中添加以下代码
// TODO: 在此处为本机数据添加绘制代码 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); //RenderScene();//添加自己的绘制函数 // Tell OpenGL to flush its pipeline ::glFinish(); // Now Swap the buffers ::SwapBuffers( m_pDC->GetSafeHdc() );6、在CXXXView::OnEraseBkgnd()中,修改返回值为TRUE,来消除闪屏问题
BOOL CXXXView::OnEraseBkgnd(CDC* pDC) { // TODO: 在此添加消息处理程序代码和/或调用默认值 return TRUE; return CView::OnEraseBkgnd(pDC); }