各位老师们,我们现在实现的是用模板测试的特性实现的一个物体物体轮廓(Object Outlining)的一个效果。
实现思路:
1.渲染地板:不写入模板缓冲区。
2.渲染cube:写入模板缓冲区,设置像素模板值为1。
3.渲染边框:修改cube模型矩阵,微微放大cube模板,用GL_NOTEQUAL将模板值不为1的像素渲染出来。
我们来看看核心代码叭!
//1.地板的绘制:不写入模板缓冲区
glStencilMask(0x00);
// floor
glBindVertexArray(planeVAO);
glBindTexture(GL_TEXTURE_2D, floorTexture);
shader.setMat4("model", glm::mat4(1.0f));
glDrawArrays(GL_TRIANGLES, 0, 6);
glBindVertexArray(0);
//2.cube的绘制:写入模板缓冲区
glStencilFunc(GL_ALWAYS, 1, 0xFF);
glStencilMask(0xFF);//所有这些单元都将被考虑,并且它们都将被写入或读取。
// cubes
glBindVertexArray(cubeVAO);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, cubeTexture);
model = glm::translate(model, glm::vec3(-1.0f, 0.0f, -1.0f));
shader.setMat4("model", model);
glDrawArrays(GL_TRIANGLES, 0, 36);
model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(2.0f, 0.0f, 0.0f));
shader.setMat4("model", model);
glDrawArrays(GL_TRIANGLES, 0, 36);
// 3.这段代码的目的是使用模板测试来绘制对象的边界,并且禁用深度测试以确保所有的像素都被绘制
glStencilFunc(GL_NOTEQUAL, 1, 0xFF);//GL_NOTEQUAL表示模板测试将检查像素的模板值是否不等于1。如果等于1,则该像素将被视为失败。
glStencilMask(0x00);//模板掩码被设置为0,意味着模板缓冲区中的这些单元不会被读取或写入。
glDisable(GL_DEPTH_TEST);//禁用了深度测试:禁用深度测试意味着所有的像素都会被绘制,不考虑它们的深度值
shaderSingleColor.use();
float scale = 1.1f;//将立方体稍微放大一些
//之前cube已经被渲染出现了这里渲染边框,我们用glStencilFunc函数中GL_NOTEQUAL来将模板值等于1的的像素排除在外,然后这一次我们用的模型矩阵会使得立方体稍微放大一些,
// 且用GL_NOTEQUAL来将模板值等于1的的像素排除在外,然后模板掩码被设置为0,模板缓冲区不会写入读取,加上又禁用了深度测试,其实就能刚刚好将立方体的边框完全渲染出来
// cubes
glBindVertexArray(cubeVAO);
glBindTexture(GL_TEXTURE_2D, cubeTexture);
model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(-1.0f, 0.0f, -1.0f));
model = glm::scale(model, glm::vec3(scale, scale, scale));
shaderSingleColor.setMat4("model", model);
glDrawArrays(GL_TRIANGLES, 0, 36);
model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(2.0f, 0.0f, 0.0f));
model = glm::scale(model, glm::vec3(scale, scale, scale));
shaderSingleColor.setMat4("model", model);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
glStencilMask(0xFF);
glStencilFunc(GL_ALWAYS, 0, 0xFF);
glEnable(GL_DEPTH_TEST);
我猜肯定有老师想看看原代码叭?以下是全部的代码o!
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
//#include <learnopengl/filesystem.h>
#include <learnopengl/shader_m.h>
#include <learnopengl/camera.h>
#include <learnopengl/model.h>
#include <iostream>
#include "ResLoad.h"
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset);
void processInput(GLFWwindow* window);
unsigned int loadTexture(const char* path);
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
Camera camera(glm::vec3(0.0f, 0.0f, 3.0f));
float lastX = SCR_WIDTH / 2.0f;
float lastY = SCR_HEIGHT / 2.0f;
bool firstMouse = true;
float deltaTime = 0.0f;
float lastFrame = 0.0f;
int main()
{
glfwInit();
//OpenGL上下文的主要版本为3,应用程序将使用OpenGL 3.x的特性
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
//OpenGL上下文的次要版本为3,应用程序将使用OpenGL 3.3的特性
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
//OpenGL上下文的核心模式(核心模式意味着OpenGL将使用最新的、没有废弃的特性,并且不包含任何的扩展或遗留功能)
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "OpenGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();//终止GLFW库的实例,因为在某些平台上,如果不调用这个函数,程序可能无法正常退出。
return -1;//由于窗口创建失败,这行代码将返回-1,表示程序出错
}
glfwMakeContextCurrent(window);//指定的窗口的上下文设置为当前线程的主上下文
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); //当帧缓冲(把颜色缓冲、深度缓冲和模板缓冲结合起来就是帧缓冲)大小改变时,该回调函数将被调用
glfwSetCursorPosCallback(window, mouse_callback);//当鼠标位置改变时,该回调函数将被调用
glfwSetScrollCallback(window, scroll_callback);//处理滚动事件
//告诉GLFW库捕获鼠标输入,GLFW_CURSOR:使用鼠标光标
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR/*GLFW_CURSOR_DISABLED*/);
//使用GLAD库来加载所有的OpenGL函数指针
// (GLADloadproc)glfwGetProcAddress 是一个函数指针,它指向一个用于获取OpenGL函数地址的函数
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
//如果GLAD库无法初始化(即无法加载OpenGL函数指针),这行代码会输出一个错误消息
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
//表示在加载模型时垂直翻转纹理,这在某些3D模型中是必要的,因为纹理的坐标可能与模型的坐标不同步。
stbi_set_flip_vertically_on_load(true);
//启用深度测试:深度测试是OpenGL中用于确定哪些像素应该被绘制在前面的其他像素之上的过程
glEnable(GL_DEPTH_TEST);//深度缓冲中的值在屏幕空间中不是线性的(在透视矩阵应用之前在观察空间中是线性的)
glEnable(GL_ALWAYS);// 永远通过深度测试
//启用模板测试
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_NOTEQUAL, 1, 0xFF);//GL_NOTEQUAL当模板缓冲中的值不等于给定的值(在这里是1)时,0xFF(所有的像素都会进行模板测试):模板测试才会通过 哪个像素或哪些像素应用模板测试
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);//当模板测试通过时,用指定的值替换当前值
//Shader ourShader("D:/OpenGL/OpenGLearn/OpenGLearn/resources/Shader/8.modelloading/8.modelloading.vs", "D:/OpenGL/OpenGLearn/OpenGLearn/resources/Shader/8.modelloading/8.modelloading.fs");
//Model ourModel(/*FileSystem::getPath(*/"D:/OpenGL/OpenGLearn/OpenGLearn/resources/objects/cyborg/cyborg.obj"/*)*/);
Shader shader(Res::ResLoad::GetShaderPath("8.modelloading/8.modelloading.vs").c_str(), Res::ResLoad::GetShaderPath("8.modelloading/8.modelloading.fs").c_str());
Shader shaderSingleColor(Res::ResLoad::GetShaderPath("9.stencil_testing/9.stencil_testing.vs").c_str(), Res::ResLoad::GetShaderPath("9.stencil_testing/shaderSingleColor.fs").c_str());
float cubeVertices[] = {
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f
};
float planeVertices[] = {
5.0f, -0.5f, 5.0f, 2.0f, 0.0f,
-5.0f, -0.5f, 5.0f, 0.0f, 0.0f,
-5.0f, -0.5f, -5.0f, 0.0f, 2.0f,
5.0f, -0.5f, 5.0f, 2.0f, 0.0f,
-5.0f, -0.5f, -5.0f, 0.0f, 2.0f,
5.0f, -0.5f, -5.0f, 2.0f, 2.0f
};
// cube VAO
unsigned int cubeVAO, cubeVBO;
glGenVertexArrays(1, &cubeVAO);
glGenBuffers(1, &cubeVBO);
glBindVertexArray(cubeVAO);
glBindBuffer(GL_ARRAY_BUFFER, cubeVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), &cubeVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
glBindVertexArray(0);
// plane VAO
unsigned int planeVAO, planeVBO;
glGenVertexArrays(1, &planeVAO);
glGenBuffers(1, &planeVBO);
glBindVertexArray(planeVAO);
glBindBuffer(GL_ARRAY_BUFFER, planeVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), &planeVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
glBindVertexArray(0);
unsigned int cubeTexture = loadTexture(Res::ResLoad::GetTexturePath("marble.jpg").c_str());
unsigned int floorTexture = loadTexture(Res::ResLoad::GetTexturePath("metal.png").c_str());
shader.use();
shader.setInt("texture1", 0);
//这是一个while循环,它将持续执行,直到用户关闭GLFW窗口
while (!glfwWindowShouldClose(window))
{
//获取当前时间,并将其转换为浮点数。这个时间将用于计算帧之间的时间差
float currentFrame = static_cast<float>(glfwGetTime());
//计算当前帧与上一帧之间的时间差。这对于实现平滑动画和物理模拟非常重要。
deltaTime = currentFrame - lastFrame;
//更新lastFrame为当前时间,以便在下一次循环中计算新的deltaTime。
lastFrame = currentFrame;
// 处理用户输入。这可能包括处理键盘和鼠标事件,例如移动相机或选择对象
processInput(window);
//设置背景颜色
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);//清除颜色和深度缓冲区和模板缓冲区,为新的渲染帧做准备。
// set uniforms
shaderSingleColor.use();
glm::mat4 model = glm::mat4(1.0f);
glm::mat4 view = camera.GetViewMatrix();
glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
shaderSingleColor.setMat4("view", view);
shaderSingleColor.setMat4("projection", projection);
shader.use();
shader.setMat4("view", view);
shader.setMat4("projection", projection);
//1.地板的绘制:不写入模板缓冲区
glStencilMask(0x00);
// floor
glBindVertexArray(planeVAO);
glBindTexture(GL_TEXTURE_2D, floorTexture);
shader.setMat4("model", glm::mat4(1.0f));
glDrawArrays(GL_TRIANGLES, 0, 6);
glBindVertexArray(0);
//2.cube的绘制:写入模板缓冲区
glStencilFunc(GL_ALWAYS, 1, 0xFF);
glStencilMask(0xFF);//所有这些单元都将被考虑,并且它们都将被写入或读取。
// cubes
glBindVertexArray(cubeVAO);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, cubeTexture);
model = glm::translate(model, glm::vec3(-1.0f, 0.0f, -1.0f));
shader.setMat4("model", model);
glDrawArrays(GL_TRIANGLES, 0, 36);
model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(2.0f, 0.0f, 0.0f));
shader.setMat4("model", model);
glDrawArrays(GL_TRIANGLES, 0, 36);
// 3.这段代码的目的是使用模板测试来绘制对象的边界,并且禁用深度测试以确保所有的像素都被绘制
glStencilFunc(GL_NOTEQUAL, 1, 0xFF);//GL_NOTEQUAL表示模板测试将检查像素的模板值是否不等于1。如果等于1,则该像素将被视为失败。
glStencilMask(0x00);//模板掩码被设置为0,意味着模板缓冲区中的这些单元不会被读取或写入。
glDisable(GL_DEPTH_TEST);//禁用了深度测试:禁用深度测试意味着所有的像素都会被绘制,不考虑它们的深度值
shaderSingleColor.use();
float scale = 1.1f;//将立方体稍微放大一些
//之前cube已经被渲染出现了这里渲染边框,我们用glStencilFunc函数中GL_NOTEQUAL来将模板值等于1的的像素排除在外,然后这一次我们用的模型矩阵会使得立方体稍微放大一些,
// 且用GL_NOTEQUAL来将模板值等于1的的像素排除在外,然后模板掩码被设置为0,模板缓冲区不会写入读取,加上又禁用了深度测试,其实就能刚刚好将立方体的边框完全渲染出来
//物体轮廓渲染效果总结:1.渲染地板:不写入模板缓冲区
// 2.渲染cube:写入模板缓冲区,设置像素模板值为1
// 3.渲染边框:修改cube模型矩阵,微微放大cube模板,用GL_NOTEQUAL将模板值不为1的像素渲染出来
// cubes
glBindVertexArray(cubeVAO);
glBindTexture(GL_TEXTURE_2D, cubeTexture);
model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(-1.0f, 0.0f, -1.0f));
model = glm::scale(model, glm::vec3(scale, scale, scale));
shaderSingleColor.setMat4("model", model);
glDrawArrays(GL_TRIANGLES, 0, 36);
model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(2.0f, 0.0f, 0.0f));
model = glm::scale(model, glm::vec3(scale, scale, scale));
shaderSingleColor.setMat4("model", model);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
glStencilMask(0xFF);
glStencilFunc(GL_ALWAYS, 0, 0xFF);
glEnable(GL_DEPTH_TEST);
// 交换前后缓冲区,显示渲染的结果。这使得新的一帧能够显示在屏幕上。
glfwSwapBuffers(window);
glfwPollEvents();//轮询事件,如按键、鼠标移动等。这对于确保程序响应用户输入非常重要
}
// optional: de-allocate all resources once they've outlived their purpose:
glDeleteVertexArrays(1, &cubeVAO);
glDeleteVertexArrays(1, &planeVAO);
glDeleteBuffers(1, &cubeVBO);
glDeleteBuffers(1, &planeVBO);
//终止GLFW库,释放之前分配的所有资源。这是程序结束时应该做的清理工作。
glfwTerminate();
return 0;
}
void processInput(GLFWwindow* window)
{
//如果用户按下了“Escape”键(其GLFW键码是GLFW_KEY_ESCAPE),那么这个函数会告诉GLFW关闭当前窗口
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
camera.ProcessKeyboard(FORWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
camera.ProcessKeyboard(BACKWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
camera.ProcessKeyboard(LEFT, deltaTime);
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
camera.ProcessKeyboard(RIGHT, deltaTime);
}
// 用于处理窗口大小改变的事件,当窗口大小发生变化时(无论是由于操作系统还是用户调整大小),这个回调函数就会被执行。
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
//用来确保视口的大小与新的窗口大小相匹配
glViewport(0, 0, width, height);//第一个和第二个参数(0, 0)定义了视口的左下角位置。
}
// 处理鼠标移动事件,当鼠标在窗口中移动时,这个回调函数就会被执行。
void mouse_callback(GLFWwindow* window, double xposIn, double yposIn)
{
float xpos = static_cast<float>(xposIn);
float ypos = static_cast<float>(yposIn);
if (firstMouse)//是否是第一次移动鼠标。如果是第一次移动鼠标,则初始化lastX和lastY为当前鼠标的位置。
{
lastX = xpos;
lastY = ypos;
firstMouse = false;
}
//计算鼠标的x和y偏移量。
float xoffset = xpos - lastX;
float yoffset = lastY - ypos; //y偏移量的计算是反向的,因为y坐标从窗口的底部开始计数而不是顶部。
lastX = xpos;
lastY = ypos;
camera.ProcessMouseMovement(xoffset, yoffset);//调用camera对象的ProcessMouseMovement方法,并传递x和y偏移量作为参数。这通常用于旋转或平移相机视图。
}
//调用camera对象的ProcessMouseScroll方法,并传递y方向的滚动偏移量作为参数。
void scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
//调用camera对象的ProcessMouseScroll方法,并传递y方向的滚动偏移量作为参数。
camera.ProcessMouseScroll(static_cast<float>(yoffset));
}
unsigned int loadTexture(char const* path)
{
unsigned int textureID;
glGenTextures(1, &textureID);//生成一个新的纹理对象,并将其ID存储在textureID中
int width, height, nrComponents;
unsigned char* data = stbi_load(path, &width, &height, &nrComponents, 0);//STB图像库的stbi_load函数加载图像文件,并且更新w,h,n的值
if (data)//检查图像是否成功加载
{
GLenum format;//存储纹理格式
if (nrComponents == 1)
format = GL_RED;
else if (nrComponents == 3)
format = GL_RGB;
else if (nrComponents == 4)
format = GL_RGBA;
glBindTexture(GL_TEXTURE_2D, textureID);//绑定之前生成的2D纹理对象
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);//使用OpenGL的glTexImage2D函数将图像数据上传到纹理对象
glGenerateMipmap(GL_TEXTURE_2D);//生成mipmap,这是一种用于平滑纹理在不同缩放级别之间过渡的技术。
//设置纹理的环绕和过滤方式
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_image_free(data);
}
else
{
std::cout << "Texture failed to load at path: " << path << std::endl;
stbi_image_free(data);
}
return textureID;
}
以下是效果图o!