在windows API搭建的OpenGL窗口中使用模板缓冲,需要在像素格式描述表中设置stencil buffer位宽为8,这样窗口会自动生成stencil buffer,然后可以在opengl环境下使用模板缓冲了。
一个渲染物体轮廓的示例,绿色为小长方体的边框
void Display() { glEnable(GL_DEPTH_TEST); glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glStencilMask(0x00); // 绘制地板时确保关闭模板缓冲的写入 shader_gym->use(); shader_gym->setMat4("model", glm::mat4(1)); shader_gym->setMat4("view", phc.getViewMatrix()); shader_gym->setMat4("projection", phc.getProjectionMatrix()); gym->Draw(shader_gym->programId); glStencilFunc(GL_ALWAYS, 1, 0xFF); glStencilMask(0xFF); cube->scale(5); cube->Draw(*shader_cube1, phc); glStencilFunc(GL_NOTEQUAL, 1, 0xFF); glStencilMask(0x00); glDisable(GL_DEPTH_TEST); cube->scale(5.4); cube->Draw(*shader_cube2, phc); glStencilMask(0xFF); glEnable(GL_DEPTH_TEST); movement(); }