OpenGL核心技术之深度测试

发表于2017-04-04
评论0 3.3k浏览

本篇文章要给大家讲的是OpenGL核心技术中的深度测试。深度测试在游戏引擎中使用的非常多,比如在Unity3D引擎中,在UI之间的遮挡设置可以通过其深度值进行设置,在3D场景中也会根据其Z值进行设置其前后关系。这些都会用到深度测试技术,由于Unity3D引擎是跨平台的,它在移动端的渲染使用的是OpenGL,所以后面的系列文章就介绍关于OpenGL使用的核心技术。

深度测试需要一个存储区域,这个存储区域就称为深度缓冲,它就像颜色缓冲用于存储所有的片段颜色,深度缓冲和颜色缓冲区有相同的宽度和高度。深度缓冲由窗口系统自动创建并将其深度值存储为 16、 24 或 32 位浮点数,在大多数系统中深度缓冲区为24位。

使用深度测试就必须要启用它,当深度测试启用的时候, OpenGL 测试深度缓冲区内的深度值。OpenGL 执行深度测试的时候,如果此测试通过,深度缓冲内的值将被设为新的深度值。如果深度测试失败,则丢弃该片段。深度测试在片段着色器运行之后,它是在屏幕空间中执行的。屏幕空间坐标直接有关的视区,由OpenGL的glViewport函数给定,并且可以通过GLSL的片段着色器中内置的 gl_FragCoord变量访问。gl_FragCoord 的 X 和 y 表示该片段的屏幕空间坐标 ((0,0) 在左下角)。gl_FragCoord 还包含一个 z 坐标,它包含了片段的实际深度值。此 z 坐标值是与深度缓冲区的内容进行比较的值。

深度测试默认是关闭的,要启用深度测试的话,我们需要用GL_DEPTH_TEST选项来打开它,函数如下:

  1. glEnable(GL_DEPTH_TEST);  
一旦启用深度测试,如果片段通过深度测试,OpenGL自动在深度缓冲区存储片段的 z 值,如果深度测试失败,那么相应地丢弃该片段。如果启用深度测试,那么在每个渲染之前还应使用GL_DEPTH_BUFFER_BIT清除深度缓冲区,否则深度缓冲区将保留上一次进行深度测试时所写的深度值。函数如下:

  1. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  

        有时,我们也不需要深度测试,那就关闭它,就是禁止缓冲区写入,函数如下:

  1. glDepthMask(GL_FALSE);  
        在OpenGL中经常使用的深度测试函数为可以通过调用glDepthFunc

它包含很多参数:

  1. GL_ALWAYS   永远通过测试  
  2. GL_NEVER    永远不通过测试  
  3. GL_LESS 在片段深度值小于缓冲区的深度时通过测试  
  4. GL_EQUAL    在片段深度值等于缓冲区的深度时通过测试  
  5. GL_LEQUAL   在片段深度值小于等于缓冲区的深度时通过测试  
  6. GL_GREATER  在片段深度值大于缓冲区的深度时通过测试  
  7. GL_NOTEQUAL 在片段深度值不等于缓冲区的深度时通过测试  
  8. GL_GEQUAL   在片段深度值大于等于缓冲区的深度时通过测试  

         其中默认使用GL_LESS,它的含义是这将丢弃深度值高于或等于当前深度缓冲区的值的片段。

接下来仔介绍深度值的计算,深度缓冲主要是通过计算深度值来比较大小,在深度缓冲区中包含深度值介于0.01.0之间,从观察者看到其内容与场景中的所有对象的 z 值进行了比较。这些视图空间中的 z 值可以在投影平头截体的近平面和远平面之间的任何值。我们因此需要一些方法来转换这些视图空间 z 值到 [0,1] 的范围内,下面的 (线性) 方程把 z 值转换为 0.0 和 1.0 之间的值 :


这里far和near是我们用来提供到投影矩阵设置可见视图截锥的远近值。关于这方面技术的讲解,可以查看我之前写的博客,方程带内锥截体的深度值 z,并将其转换到 [0,1] 范围。在下面的图给出 z 值和其相应的深度值的关系:


然而,在实践中是几乎从来不使用这样的线性深度缓冲区。正确的投影特性的非线性深度方程是和1/z成正比的 ,由于非线性函数是和 1/z 成正比,例如1.0 和 2.0 之间的 z 值,将变为 1.0 到 0.5之间, 这样在z非常小的时候给了我们很高的精度。方程如下所示:


要记住的重要一点是在深度缓冲区的值不是线性的屏幕空间 (它们在视图空间投影矩阵应用之前是线性)。值为 0.5 在深度缓冲区并不意味着该对象的 z 值是投影平头截体的中间;顶点的 z 值是实际上相当接近近平面!你可以看到 z 值和产生深度缓冲区的值在下列图中的非线性关系:


         正如你所看到,一个附近的物体的小的 z 值因此给了我们很高的深度精度。变换 (从观察者的角度) 的 z 值的方程式被嵌入在投影矩阵,所以当我们变换顶点坐标从视图到裁剪,然后到非线性方程应用了的屏幕空间中。关于投影矩阵,读者可以查看之前写的博客。

        屏幕空间的深度值是非线性的,这个读者可以自己测试,在这里我把原理说一下:屏幕空间的深度值是非线性如他们在z很小的时候有很高的精度,较大的 z 值有较低的精度。该片段的深度值会迅速增加,所以几乎所有顶点的深度值接近 1.0。如果我们小心的靠近物体,你最终可能会看到的色彩越来越暗,意味着它们的 z 值越来越小,这清楚地表明深度值的非线性特性。近的物体相对远的物体对的深度值比对象较大的影响。只移动几英寸就能让暗色完全变亮。

        但是我们可以让深度值变换回线性。要实现这一目标我们需要让点应用投影变换逆的逆变换,成为单独的深度值的过程。这意味着我们必须首先重新变换范围 [0,1] 中的深度值为单位化的设备坐标(normalized device coordinates)范围内 [-1,1] (裁剪空间(clip space))。然后,我们想要反转非线性方程 :


 就像在投影矩阵做的那样并将此反转方程应用于所得到的深度值。然后,结果是一个线性的深度值。

         首先,我们需要 NDC 深度值转换:

  1. float z = depth * 2.0 - 1.0;  
         然后把我们所得到的 z 值应用逆转换来检索的线性深度值:

  1. float linearDepth = (2.0 * near) / (far + near - z * (far - near));  

         注意在转换上述方程是并不是从方程:



        精确的逆方程,这个方程从投影矩阵中导出,可以从新使用等式2将他转换为非线性深度值。这个方程也会考虑使用[0,1] 而不是 [near,far]范围内的 z 值 。

这不是从投影矩阵推导出的准确公式;这个方程是除以far的结果。深度值的范围一直到far,这作为一个介于 0.0 和 1.0 之间的颜色值并不合适。除以far的值把深度值映射到介于 0.0 和 1.0,更适合用于演示目的。

        这个能够将屏幕空间的非线性深度值转变为线性深度值的完整的片段着色器如下所示:

  1. #version 330 core  
  2.   
  3. out vec4 color;  
  4.   
  5. float LinearizeDepth(float depth)  
  6. {  
  7.     float near = 0.1;  
  8.     float far = 100.0;  
  9.     float z = depth * 2.0 - 1.0; // Back to NDC  
  10.     return (2.0 * near) / (far + near - z * (far - near));  
  11. }  
  12.   
  13. void main()  
  14. {  
  15.     float depth = LinearizeDepth(gl_FragCoord.z);  
  16.     color = vec4(vec3(depth), 1.0f);  
  17. }  

接下来介绍在程序中经常遇到的问题,深度冲突,就是在物体前后关系设置时会出现重叠现象,导致前后不分,在引擎中通常的做法有几种:

1、也是最重要的技巧是让物体之间不要离得太近,以至于他们的三角形重叠。

2、是尽可能把近平面设置得远一些。

3、是放弃一些性能来得到更高的深度值的精度。大多数的深度缓冲区都是24位。但现在显卡支持32位深度值,这让深度缓冲区的精度提高了一大节。所以牺牲一些性能你会得到更精确的深度测试,减少深度冲突。

最后把实现深度测试的Shader代码给读者展示一下:

首先展示的是片段着色器:

  1. #version 330 core  
  2. out vec4 color;  
  3.   
  4. float near = 1.0;   
  5. float far = 100.0;   
  6. float LinearizeDepth(float depth)   
  7. {  
  8.     float z = depth * 2.0 - 1.0; // Back to NDC   
  9.     return (2.0 * near * far) / (far + near - z * (far - near));      
  10. }  
  11.   
  12. void main()  
  13. {               
  14.     float depth = LinearizeDepth(gl_FragCoord.z) / far; // divide by far to get depth in range [0,1] for visualization purposes.  
  15.     color = vec4(vec3(depth), 1.0f);  
  16. }  

其次展示的是顶点着色器:

  1. #version 330 core  
  2. layout (location = 0) in vec3 position;  
  3. layout (location = 1) in vec2 texCoords;  
  4.   
  5. out vec2 TexCoords;  
  6.   
  7. uniform mat4 model;  
  8. uniform mat4 view;  
  9. uniform mat4 projection;  
  10.   
  11. void main()  
  12. {  
  13.     gl_Position = projection * view * model * vec4(position, 1.0f);  
  14.     TexCoords = texCoords;  
  15. }  

下面就是处理Shader脚本的C++代码,在这里把核心代码接口展示一下,代码如下所示:

  1. // 定义视口大小  
  2. glViewport(0, 0, screenWidth, screenHeight);  
  3.   
  4. // 启用深度测试  
  5. glEnable(GL_DEPTH_TEST);  
  6. // glDepthFunc(GL_ALWAYS); // Set to always pass the depth test (same effect as glDisable(GL_DEPTH_TEST))  
  7.   
  8. // 编译shader脚本  
  9. Shader shader("depth_testing.vs""depth_testing.frag");  
在后面就是对Shader进行传值操作:

  1. "white-space:pre">  // 清空缓存  
  2.         glClearColor(0.1f, 0.1f, 0.1f, 1.0f);  
  3.         glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  
  4.   
  5.         // 绘制物体以及传值  
  6.         shader.Use();   
  7.         glm::mat4 model;  
  8.         glm::mat4 view = camera.GetViewMatrix();  
  9.         glm::mat4 projection = glm::perspective(camera.Zoom, (float)screenWidth/(float)screenHeight, 0.1f, 100.0f);  
  10.         glUniformMatrix4fv(glGetUniformLocation(shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view));  
  11.         glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));  

在这里把Shader类代码展示如下:

  1. #ifndef SHADER_H  
  2. #define SHADER_H  
  3.   
  4. #include   
  5.   
  6. #include   
  7. #include   
  8. #include   
  9. #include   
  10.   
  11. class Shader  
  12. {  
  13. public:  
  14.     GLuint Program;  
  15.     // Constructor generates the shader on the fly  
  16.     Shader(const GLchar* vertexPath, const GLchar* fragmentPath, const GLchar* geometryPath = nullptr)  
  17.     {  
  18.         // 1. Retrieve the vertex/fragment source code from filePath  
  19.         std::string vertexCode;  
  20.         std::string fragmentCode;  
  21.         std::string geometryCode;  
  22.         std::ifstream vShaderFile;  
  23.         std::ifstream fShaderFile;  
  24.         std::ifstream gShaderFile;  
  25.         // ensures ifstream objects can throw exceptions:  
  26.         vShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);  
  27.         fShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);  
  28.         gShaderFile.exceptions (std::ifstream::failbit | std::ifstream::badbit);  
  29.         try   
  30.         {  
  31.             // Open files  
  32.             vShaderFile.open(vertexPath);  
  33.             fShaderFile.open(fragmentPath);  
  34.             std::stringstream vShaderStream, fShaderStream;  
  35.             // Read file's buffer contents into streams  
  36.             vShaderStream << vShaderFile.rdbuf();  
  37.             fShaderStream << fShaderFile.rdbuf();       
  38.             // close file handlers  
  39.             vShaderFile.close();  
  40.             fShaderFile.close();  
  41.             // Convert stream into string  
  42.             vertexCode = vShaderStream.str();  
  43.             fragmentCode = fShaderStream.str();           
  44.             // If geometry shader path is present, also load a geometry shader  
  45.             if(geometryPath != nullptr)  
  46.             {  
  47.                 gShaderFile.open(geometryPath);  
  48.                 std::stringstream gShaderStream;  
  49.                 gShaderStream << gShaderFile.rdbuf();  
  50.                 gShaderFile.close();  
  51.                 geometryCode = gShaderStream.str();  
  52.             }  
  53.         }  
  54.         catch (std::ifstream::failure e)  
  55.         {  
  56.             std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl;  
  57.         }  
  58.         const GLchar* vShaderCode = vertexCode.c_str();  
  59.         const GLchar * fShaderCode = fragmentCode.c_str();  
  60.         // 2. Compile shaders  
  61.         GLuint vertex, fragment;  
  62.         GLint success;  
  63.         GLchar infoLog[512];  
  64.         // Vertex Shader  
  65.         vertex = glCreateShader(GL_VERTEX_SHADER);  
  66.         glShaderSource(vertex, 1, &vShaderCode, NULL);  
  67.         glCompileShader(vertex);  
  68.         checkCompileErrors(vertex, "VERTEX");  
  69.         // Fragment Shader  
  70.         fragment = glCreateShader(GL_FRAGMENT_SHADER);  
  71.         glShaderSource(fragment, 1, &fShaderCode, NULL);  
  72.         glCompileShader(fragment);  
  73.         checkCompileErrors(fragment, "FRAGMENT");  
  74.         // If geometry shader is given, compile geometry shader  
  75.         GLuint geometry;  
  76.         if(geometryPath != nullptr)  
  77.         {  
  78.             const GLchar * gShaderCode = geometryCode.c_str();  
  79.             geometry = glCreateShader(GL_GEOMETRY_SHADER);  
  80.             glShaderSource(geometry, 1, &gShaderCode, NULL);  
  81.             glCompileShader(geometry);  
  82.             checkCompileErrors(geometry, "GEOMETRY");  
  83.         }  
  84.         // Shader Program  
  85.         this->Program = glCreateProgram();  
  86.         glAttachShader(this->Program, vertex);  
  87.         glAttachShader(this->Program, fragment);  
  88.         if(geometryPath != nullptr)  
  89.             glAttachShader(this->Program, geometry);  
  90.         glLinkProgram(this->Program);  
  91.         checkCompileErrors(this->Program, "PROGRAM");  
  92.         // Delete the shaders as they're linked into our program now and no longer necessery  
  93.         glDeleteShader(vertex);  
  94.         glDeleteShader(fragment);  
  95.         if(geometryPath != nullptr)  
  96.             glDeleteShader(geometry);  
  97.   
  98.     }  
  99.     // Uses the current shader  
  100.     void Use() { glUseProgram(this->Program); }  
  101.   
  102. private:  
  103.     void checkCompileErrors(GLuint shader, std::string type)  
  104.     {  
  105.         GLint success;  
  106.         GLchar infoLog[1024];  
  107.         if(type != "PROGRAM")  
  108.         {  
  109.             glGetShaderiv(shader, GL_COMPILE_STATUS, &success);  
  110.             if(!success)  
  111.             {  
  112.                 glGetShaderInfoLog(shader, 1024, NULL, infoLog);  
  113.                 std::cout << "| ERROR::::SHADER-COMPILATION-ERROR of type: " << type << "|n" << infoLog << "n| -- --------------------------------------------------- -- |" << std::endl;  
  114.             }  
  115.         }  
  116.         else  
  117.         {  
  118.             glGetProgramiv(shader, GL_LINK_STATUS, &success);  
  119.             if(!success)  
  120.             {  
  121.                 glGetProgramInfoLog(shader, 1024, NULL, infoLog);  
  122.                 std::cout << "| ERROR::::PROGRAM-LINKING-ERROR of type: " << type << "|n" << infoLog << "n| -- --------------------------------------------------- -- |" << std::endl;  
  123.             }  
  124.         }  
  125.     }  
  126. };  
  127.   
  128. #endif  

另外在处理时需要用到摄像机代码,完整代码如下所示:

  1. #pragma once  
  2.   
  3. // Std. Includes  
  4. #include   
  5.   
  6. // GL Includes  
  7. #include   
  8. #include   
  9. #include   
  10.   
  11.   
  12.   
  13. // Defines several possible options for camera movement. Used as abstraction to stay away from window-system specific input methods  
  14. enum Camera_Movement {  
  15.     FORWARD,  
  16.     BACKWARD,  
  17.     LEFT,  
  18.     RIGHT  
  19. };  
  20.   
  21. // Default camera values  
  22. const GLfloat YAW        = -90.0f;  
  23. const GLfloat PITCH      =  0.0f;  
  24. const GLfloat SPEED      =  3.0f;  
  25. const GLfloat SENSITIVTY =  0.25f;  
  26. const GLfloat ZOOM       =  45.0f;  
  27.   
  28.   
  29. // An abstract camera class that processes input and calculates the corresponding Eular Angles, Vectors and Matrices for use in OpenGL  
  30. class Camera  
  31. {  
  32. public:  
  33.     // Camera Attributes  
  34.     glm::vec3 Position;  
  35.     glm::vec3 Front;  
  36.     glm::vec3 Up;  
  37.     glm::vec3 Right;  
  38.     glm::vec3 WorldUp;  
  39.     // Eular Angles  
  40.     GLfloat Yaw;  
  41.     GLfloat Pitch;  
  42.     // Camera options  
  43.     GLfloat MovementSpeed;  
  44.     GLfloat MouseSensitivity;  
  45.     GLfloat Zoom;  
  46.   
  47.     // Constructor with vectors  
  48.     Camera(glm::vec3 position = glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f), GLfloat yaw = YAW, GLfloat pitch = PITCH) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVTY), Zoom(ZOOM)  
  49.     {  
  50.         this->Position = position;  
  51.         this->WorldUp = up;  
  52.         this->Yaw = yaw;  
  53.         this->Pitch = pitch;  
  54.         this->updateCameraVectors();  
  55.     }  
  56.     // Constructor with scalar values  
  57.     Camera(GLfloat posX, GLfloat posY, GLfloat posZ, GLfloat upX, GLfloat upY, GLfloat upZ, GLfloat yaw, GLfloat pitch) : Front(glm::vec3(0.0f, 0.0f, -1.0f)), MovementSpeed(SPEED), MouseSensitivity(SENSITIVTY), Zoom(ZOOM)  
  58.     {  
  59.         this->Position = glm::vec3(posX, posY, posZ);  
  60.         this->WorldUp = glm::vec3(upX, upY, upZ);  
  61.         this->Yaw = yaw;  
  62.         this->Pitch = pitch;  
  63.         this->updateCameraVectors();  
  64.     }  
  65.   
  66.     // Returns the view matrix calculated using Eular Angles and the LookAt Matrix  
  67.     glm::mat4 GetViewMatrix()  
  68.     {  
  69.         return glm::lookAt(this->Position, this->Position + this->Front, this->Up);  
  70.     }  
  71.   
  72.     // Processes input received from any keyboard-like input system. Accepts input parameter in the form of camera defined ENUM (to abstract it from windowing systems)  
  73.     void ProcessKeyboard(Camera_Movement direction, GLfloat deltaTime)  
  74.     {  
  75.         GLfloat velocity = this->MovementSpeed * deltaTime;  
  76.         if (direction == FORWARD)  
  77.             this->Position += this->Front * velocity;  
  78.         if (direction == BACKWARD)  
  79.             this->Position -= this->Front * velocity;  
  80.         if (direction == LEFT)  
  81.             this->Position -= this->Right * velocity;  
  82.         if (direction == RIGHT)  
  83.             this->Position += this->Right * velocity;  
  84.     }  
  85.   
  86.     // Processes input received from a mouse input system. Expects the offset value in both the x and y direction.  
  87.     void ProcessMouseMovement(GLfloat xoffset, GLfloat yoffset, GLboolean constrainPitch = true)  
  88.     {  
  89.         xoffset *= this->MouseSensitivity;  
  90.         yoffset *= this->MouseSensitivity;  
  91.   
  92.         this->Yaw   += xoffset;  
  93.         this->Pitch += yoffset;  
  94.   
  95.         // Make sure that when pitch is out of bounds, screen doesn't get flipped  
  96.         if (constrainPitch)  
  97.         {  
  98.             if (this->Pitch > 89.0f)  
  99.                 this->Pitch = 89.0f;  
  100.             if (this->Pitch < -89.0f)  
  101.                 this->Pitch = -89.0f;  
  102.         }  
  103.   
  104.         // Update Front, Right and Up Vectors using the updated Eular angles  
  105.         this->updateCameraVectors();  
  106.     }  
  107.   
  108.     // Processes input received from a mouse scroll-wheel event. Only requires input on the vertical wheel-axis  
  109.     void ProcessMouseScroll(GLfloat yoffset)  
  110.     {  
  111.         if (this->Zoom >= 1.0f && this->Zoom <= 45.0f)  
  112.             this->Zoom -= yoffset;  
  113.         if (this->Zoom <= 1.0f)  
  114.             this->Zoom = 1.0f;  
  115.         if (this->Zoom >= 45.0f)  
  116.             this->Zoom = 45.0f;  
  117.     }  
  118.   
  119. private:  
  120.     // Calculates the front vector from the Camera's (updated) Eular Angles  
  121.     void updateCameraVectors()  
  122.     {  
  123.         // Calculate the new Front vector  
  124.         glm::vec3 front;  
  125.         front.x = cos(glm::radians(this->Yaw)) * cos(glm::radians(this->Pitch));  
  126.         front.y = sin(glm::radians(this->Pitch));  
  127.         front.z = sin(glm::radians(this->Yaw)) * cos(glm::radians(this->Pitch));  
  128.         this->Front = glm::normalize(front);  
  129.         // Also re-calculate the Right and Up vector  
  130.         this->Right = glm::normalize(glm::cross(this->Front, this->WorldUp));  // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement.  
  131.         this->Up    = glm::normalize(glm::cross(this->Right, this->Front));  
  132.     }  
  133. };  

以上就是关于深度测试的介绍,供参考

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引