写一个函数方法在MFC中对OPENGL进行初始化,,在GLAD初始化之前不进行GLFW创建,而是基于当前客户区DC:
#include<glad.h>
BOOL CSTLView::InitializeOpenGL()
{
m_pDC = new CClientDC(this);
if (m_pDC == NULL)
{
MessageBox(_T("Error Obtaining DC"));
return FALSE;
}
if (!SetupPixelFormat())
{
return FALSE;
}\
CreateModernOpenGLContext();
if (!gladLoadGL())
{
MessageBox(_T("Failed to initialize GLAD"));
return FALSE;
}
::glClearColor(0.95f, 0.95f, 0.95f, 0.95f);
glClear(GL_COLOR_BUFFER_BIT);
::glClearDepth(1.0f);
::glEnable(GL_DEPTH_TEST);
return TRUE;
}
其中SetupPixelFormat
是像素格式:
BOOL CSTLView::SetupPixelFormat()
{
static PIXELFORMATDESCRIPTOR pfd =
{
sizeof(PIXELFORMATDESCRIPTOR), // pfd的尺寸
1, // 版本号
PFD_DRAW_TO_WINDOW | // 支持窗口
PFD_SUPPORT_OPENGL | // 支持OpenGL
PFD_DOUBLEBUFFER, // 双缓冲
PFD_TYPE_RGBA, // RGBA类型
32, // 24位颜色深度
0, 0, 0, 0, 0, 0, // 颜色位被忽略
0, // 无缓冲
0, // 移位位被忽略
0, // 无累加缓冲
0, 0, 0, 0, // accum 位被忽略
16, // 16位z缓冲
24, // 无模具缓冲
0, // 无辅助缓冲区
PFD_MAIN_PLANE, // 主层
0, // 保留
0, 0, 0 // 图层蒙版
};
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;
}
CreateModernOpenGLContext
基于WGL扩展:
#include <wglext.h>
BOOL CSTLView::CreateModernOpenGLContext()
{
int attribs[] =
{
WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
WGL_CONTEXT_MINOR_VERSION_ARB, 3,
WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
0
};
HGLRC hTempContext = wglCreateContext(m_pDC->GetSafeHdc());
wglMakeCurrent(m_pDC->GetSafeHdc(), hTempContext);
PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = NULL;
wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB");
if (wglCreateContextAttribsARB)
{
m_hRC = wglCreateContextAttribsARB(m_pDC->GetSafeHdc(), 0, attribs);
wglMakeCurrent(NULL, NULL);
wglDeleteContext(hTempContext);
}
if (!m_hRC) return FALSE;
return wglMakeCurrent(m_pDC->GetSafeHdc(), m_hRC);
}
具体根据你的使用,再做修改。