1. Win32下基于DirectX的实现到处都可以找的到,我这里实现的是基于OpenGL的实现:
废话不多说,直接看代码:
1. 头文件中的部分代码:
class RendererOpenGL : public Renderer, public Singleton<RendererOpenGL>
{
public:
RendererOpenGL();
~RendererOpenGL();
public:
// 作用:更新一帧
// 参数:无
// 返回:无
void moveOneFrame(float pElapse);
// 作用:渲染一帧
// 参数:无
// 返回:无
void renderOneFrame(float pElapse);
private:
// 作用:渲染一帧(内部)
// 参数:无
// 返回:无
void _renderImpl(float pElapse);
// 作用:更新一帧(内部)
// 参数:无
// 返回:无
void _updateImpl(float pElapse);
private:
// 作用:初始化渲染器
// 参数:无
// 返回:无
bool _initRenderDevice();
// 作用:子类析构
// 参数:无
// 返回:无
void _childDestruct();
// 作用:初始化当前所使用的实例
// 参数:无
// 返回:初始化是否成功
bool _initCurrentInstance();
private:
// 作用:交换缓存
// 参数:无
// 返回:无
void _swapBuffers();
private:
HDC mDC;
HGLRC mRC;
};
2. .cpp中的代码(类中与OpenGL设备没有直接关系的接口,这里就不列出其实现)
RendererOpenGL::RendererOpenGL()
: mDC(0),
mRC(0)
{
}
RendererOpenGL::~RendererOpenGL()
{
_childDestruct();
}
// 渲染一帧
void RendererOpenGL::renderOneFrame(float pElapse)
{
// 清空后台缓存
glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
glClearDepth(1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
_renderImpl(pElapse);
// 强制刷新OpenGL命令
glFlush();
// 交换后台缓存
_swapBuffers(); ////---- 重要,不可缺少
}
// 初始化渲染器
bool RendererOpenGL::_initRenderDevice()
{
// 获取窗口句柄
HWND hWnd = reinterpret_cast<HWND>(WindowWin32::getSingleton().getHandle());
assert(NULL != hWnd);
// 设置像素描述结构
PIXELFORMATDESCRIPTOR pfd =
{
sizeof(PIXELFORMATDESCRIPTOR), // 像素描述结构的大小
1, // 版本号
PFD_DRAW_TO_WINDOW | // 缓存区的输出显示在一个窗口中
PFD_SUPPORT_OPENGL | // 缓存区支持OpenGL绘图
PFD_STEREO | // 颜色缓存区是立体缓存
PFD_DOUBLEBUFFER, // 颜色缓存区是双缓存
PFD_TYPE_RGBA, // 使用RGBA颜色格式
16, // 颜色缓存区中颜色值所占的位深
0, 0, 0, 0, 0, 0, // 使用默认的颜色设置
0, // 无Alpha缓存
0, // 颜色缓存区中Alpha成分的移位计数
0, // 无累计缓存区
0, 0, 0, 0, // 累计缓存区无移位
32, // 32位深度缓存
0, // 无蒙版缓存
0, // 无辅助缓存区
PFD_MAIN_PLANE, // 必须为PFD_MAIN_PLANE,设置为主绘制层
0, // 表示OpenGL实现所支持的上层或下层平面的数量
0, 0, 0 // 过时,已不再使用
};
// 获取设备上下文
mDC = GetDC(hWnd);
if (NULL == mDC)
{
Utils::error("Failed to Get Device Context in OpenGL.\n");
return false;
}
// 查找一个兼容的像素格式
GLuint pixelFormat = ChoosePixelFormat(mDC, &pfd);
if (0 == pixelFormat)
{
// 没找到
Utils::error("Failed to choose PixelFormat in OpenGL.\n");
return false;
}
// 设置像素格式
if (! SetPixelFormat(mDC, pixelFormat, &pfd))
{
// 设置失败
Utils::error("Failed to set PixelFormat in OpenGL.\n");
return false;
}
// 创建OpengGL渲染描述表
mRC = wglCreateContext(mDC);
if (NULL == mRC)
{
Utils::error("Failed to Create context.\n");
return false;
}
// 设置OpenGL的渲染窗口为当前窗口
if (! wglMakeCurrent(mDC, mRC))
{
// 设置失败
Utils::error("Failed to Make Current in OpenGL.\n");
return false;
}
return true;
}
// 子类析构
void RendererOpenGL::_childDestruct()
{
HWND hWnd = reinterpret_cast<HWND>(WindowWin32::getSingleton().getHandle());
assert(NULL != hWnd);
// 释放设备上下文
if (0 != mDC)
{
wglMakeCurrent(mDC, 0);
// 释放渲染描述表
if (0 != mRC)
{
wglDeleteContext(mRC);
mRC = 0;
}
ReleaseDC(hWnd, mDC);
mDC = 0;
}
}
// 交换缓存
void RendererOpenGL::_swapBuffers()
{
::SwapBuffers(mDC);
}