LearnOpenGL

Translation in progress of learnopengl.com.
git clone https://git.mtkn.jp/LearnOpenGL
Log | Files | Refs

Depth-testing.html (19014B)


      1     <h1 id="content-title">Depth testing</h1>
      2 <h1 id="content-url" style='display:none;'>Advanced-OpenGL/Depth-testing</h1>
      3 <p>
      4   In the <a href="https://learnopengl.com/Getting-started/Coordinate-Systems" target="_blank">coordinate systems</a> chapter we've rendered a 3D container and made use of a <def>depth buffer</def> to prevent triangles rendering in the front while they're supposed to be behind other triangles. In this chapter we're going to elaborate a bit more on those <def>depth values</def> the depth buffer (or z-buffer) stores and how it actually determines if a fragment is in front. 
      5 </p>
      6 
      7 <p>
      8   The depth-buffer is a buffer that, just like the <def>color buffer</def> (that stores all the fragment colors: the visual output), stores information per fragment and has the same width and height as the color buffer. The depth buffer is automatically created by the windowing system and stores its depth values as <code>16</code>, <code>24</code> or <code>32</code> bit floats. In most systems you'll see a depth buffer with a precision of <code>24</code> bits. 
      9 </p>
     10 
     11 <p>
     12   When depth testing is enabled, OpenGL tests the depth value of a fragment against the content of the depth buffer. OpenGL performs a depth test and if this test passes, the fragment is rendered and the depth buffer is updated with the new depth value. If the depth test fails, the fragment is discarded.
     13 </p>
     14 
     15 <p>
     16   Depth testing is done in screen space after the fragment shader has run (and after the stencil test which we'll get to in the <a href="https://learnopengl.com/Advanced-OpenGL/Stencil-testing" target="_blank">next</a> chapter). The screen space coordinates relate directly to the viewport defined by OpenGL's <fun><function id='22'>glViewport</function></fun> function and can be accessed via GLSL's built-in <var>gl_FragCoord</var> variable in the fragment shader. The x and y components of <var>gl_FragCoord</var> represent the fragment's screen-space coordinates (with (0,0) being the bottom-left corner). The <var>gl_FragCoord</var> variable also contains a z-component which contains the depth value of the fragment. This z value is the value that is compared to the depth buffer's content. 
     17 </p>
     18 
     19 <note>
     20   Today most GPUs support a hardware feature called <def>early depth testing</def>. Early depth testing allows the depth test to run before the fragment shader runs. Whenever it is clear a fragment isn't going to be visible (it is behind other objects) we can prematurely discard the fragment. 
     21 <br/><br/>
     22 Fragment shaders are usually quite expensive so wherever we can avoid running them we should. A restriction on the fragment shader for early depth testing is that you shouldn't write to the fragment's depth value. If a fragment shader would write to its depth value, early depth testing is impossible;  OpenGL won't be able to figure out the depth value beforehand. 
     23 </note>
     24 
     25 <p>
     26   Depth testing is disabled by default so to enable depth testing we need to enable it with the <var>GL_DEPTH_TEST</var> option:
     27 </p>
     28 
     29 <pre><code>
     30 <function id='60'>glEnable</function>(GL_DEPTH_TEST);  
     31 </code></pre>
     32 
     33 <p>
     34   Once enabled, OpenGL automatically stores fragments their z-values in the depth buffer if they passed the depth test and discards fragments if they failed the depth test accordingly. If you have depth testing enabled you should also clear the depth buffer before each frame using <var>GL_DEPTH_BUFFER_BIT</var>; otherwise you're stuck with the depth values from last frame:
     35 </p>
     36 
     37 <pre><code>
     38 <function id='10'>glClear</function>(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  
     39 </code></pre>
     40 
     41 <p>
     42   There are certain scenarios imaginable where you want to perform the depth test on all fragments and discard them accordingly, but <strong>not</strong> update the depth buffer. Basically, you're (temporarily) using a <def>read-only</def> depth buffer. OpenGL allows us to disable writing to the depth buffer by setting its depth mask to <code>GL_FALSE</code>:
     43 </p>
     44 
     45 <pre><code>
     46 <function id='65'>glDepthMask</function>(GL_FALSE);  
     47 </code></pre>
     48 
     49 <p>
     50   Note that this only has effect if depth testing is enabled. 
     51 </p>
     52 
     53 <h2>Depth test function</h2>
     54 <p>
     55   OpenGL allows us to modify the comparison operators it uses for the depth test. This allows us to control when OpenGL should pass or discard fragments and when to update the depth buffer. We can set the comparison operator (or depth function) by calling <fun><function id='66'>glDepthFunc</function></fun>:
     56 </p>
     57 
     58 <pre><code>
     59 <function id='66'>glDepthFunc</function>(GL_LESS);  
     60 </code></pre>
     61 
     62 <p>
     63   The function accepts several comparison operators that are listed in the table below:
     64 </p>
     65 
     66 <table>
     67   <tr>
     68   	<th>Function</th>
     69   	<th>Description</th>
     70   </tr>  
     71   <tr>
     72     <td><code>GL_ALWAYS</code></td>
     73  	<td>The depth test always passes.</td>
     74   </tr>
     75   <tr>
     76     <td><code>GL_NEVER</code></td>
     77  	<td>The depth test never passes.</td>
     78   </tr>
     79   <tr>
     80     <td><code>GL_LESS</code></td>
     81  	<td>Passes if the fragment's depth value is less than the stored depth value.</td>
     82   </tr>
     83   <tr>
     84     <td><code>GL_EQUAL</code></td>
     85  	<td>Passes if the fragment's depth value is equal to the stored depth value.</td>
     86   </tr><tr>
     87     <td><code>GL_LEQUAL</code></td>
     88  	<td>Passes if the fragment's depth value is less than or equal to the stored depth value.</td>
     89   </tr> 
     90   <tr>
     91     <td><code>GL_GREATER</code></td>
     92  	<td>Passes if the fragment's depth value is greater than the stored depth value.</td>
     93   </tr>
     94   <tr>
     95     <td><code>GL_NOTEQUAL</code></td>
     96  	<td>Passes if the fragment's depth value is not equal to the stored depth value.</td>
     97   </tr>
     98   <tr>
     99     <td><code>GL_GEQUAL</code></td>
    100  	<td>Passes if the fragment's depth value is greater than or equal to the stored depth value.</td>
    101   </tr>
    102 </table>
    103 
    104 <p>
    105   By default the depth function <var>GL_LESS</var> is used that discards all the fragments that have a depth value higher than or equal to the current depth buffer's value.
    106 </p>
    107 
    108 <p>
    109   Let's show the effect that changing the depth function has on the visual output. We'll use a fresh code setup that displays a basic scene with two textured cubes sitting on a textured floor with no lighting. You can find the source code <a href="/code_viewer_gh.php?code=src/4.advanced_opengl/1.1.depth_testing/depth_testing.cpp" target="_blank">here</a>.
    110 </p>
    111 
    112 <p>
    113   Within the source code we changed the depth function to <var>GL_ALWAYS</var>:
    114 </p>
    115 
    116 <pre><code>
    117 <function id='60'>glEnable</function>(GL_DEPTH_TEST);
    118 <function id='66'>glDepthFunc</function>(GL_ALWAYS); 
    119 </code></pre>
    120 
    121 <p>
    122   This simulates the same behavior we'd get if we didn't enable depth testing. The depth test always passes so the fragments that are drawn last are rendered in front of the fragments that were drawn before, even though they should've been at the front. Since we've drawn the floor plane last, the plane's fragments overwrite each of the container's previously written fragments:
    123 </p>
    124 
    125 <img src="/img/advanced/depth_testing_func_always.png" class="clean" alt="Depth testing in OpenGL with GL_ALWAYS as depth function"/>
    126 
    127 <p>
    128   Setting it all back to <var>GL_LESS</var> gives us the type of scene we're used to:
    129 </p>
    130 
    131 <img src="/img/advanced/depth_testing_func_less.png" class="clean" alt="Depth testing in OpenGL with GL_LESS as depth function"/>
    132 
    133 <h2>Depth value precision</h2>
    134 <p>
    135   The depth buffer contains depth values between <code>0.0</code> and <code>1.0</code> and it compares its content with the z-values of all the objects in the scene as seen from the viewer. These z-values in view space can be any value between the projection-frustum's <code>near</code> and <code>far</code> plane. We thus need some way to transform these view-space z-values to the range of <code>[0,1]</code> and one way is to linearly transform them. The following (linear) equation transforms the z-value to a depth value between <code>0.0</code> and <code>1.0</code>:
    136 </p>
    137 
    138 \begin{equation} F_{depth} = \frac{z - near}{far - near} \end{equation}
    139 
    140 <p>
    141   Here \(near\) and \(far\) are the <em>near</em> and <em>far</em> values we used to provide to the projection matrix to set the visible frustum (see <a href="https://learnopengl.com/Getting-started/Coordinate-Systems" target="_blank">coordinate Systems</a>). The equation takes a depth value \(z\) within the frustum and transforms it to the range <code>[0,1]</code>. The relation between the z-value and its corresponding depth value is presented in the following graph:
    142 </p>
    143 
    144 <img src="/img/advanced/depth_linear_graph.png" class="clean" alt="Graph of depth values in OpenGL as a linear function"/>
    145 
    146 <note>
    147   Note that all equations give a depth value close to <code>0.0</code> when the object is close by  and a depth value close to <code>1.0</code> when the object is close to the far plane.
    148 </note>
    149 
    150 <p>
    151   In practice however, a <def>linear depth buffer</def> like this is almost never used. Because of projection properties a non-linear depth equation is used that is proportional to 1/z. The result is that we get enormous precision when z is small and much less precision when z is far away.
    152 </p>
    153 
    154 <p>
    155   Since the non-linear function is proportional to 1/z, z-values between <code>1.0</code> and <code>2.0</code> would result in depth values between <code>1.0</code> and <code>0.5</code> which is half of the [0,1] range, giving us enormous precision at small z-values. Z-values between <code>50.0</code> and <code>100.0</code> would account for only 2% of the [0,1] range. Such an equation, that also takes near and far distances into account, is given below:
    156 </p>
    157 
    158 \begin{equation} F_{depth} = \frac{1/z - 1/near}{1/far - 1/near} \end{equation}
    159 
    160 <p>
    161   Don't worry if you don't know exactly what is going on with this equation. The important thing to remember is that the values in the depth buffer are not linear in clip-space (they are linear in view-space before the projection matrix is applied). A value of <code>0.5</code> in the depth buffer does not mean the pixel's z-value is halfway in the frustum; the z-value of the vertex is actually quite close to the near plane! You can see the non-linear relation between the z-value and the resulting depth buffer's value in the following graph:
    162 </p>
    163 
    164 <img src="/img/advanced/depth_non_linear_graph.png" class="clean" alt="Graph of depth values in OpenGL as a non-linear function"/>
    165 
    166 <p>
    167   As you can see, the depth values are greatly determined by the small z-values giving us large depth precision to the objects close by. The equation to transform z-values (from the viewer's perspective) is embedded within the projection matrix so when we transform vertex coordinates from view to clip, and then to screen-space the non-linear equation is applied. 
    168 </p>  
    169 
    170 <p>
    171   The effect of this non-linear equation quickly becomes apparent when we try to visualize the depth buffer.
    172 </p>
    173 
    174 <h2>Visualizing the depth buffer</h2>
    175 <p>
    176   We know that the z-value of the built-in <var>gl_FragCoord</var> vector in the fragment shader contains the depth value of that particular fragment. If we were to output this depth value of the fragment as a color we could display the depth values of all the fragments in the scene:
    177 </p>
    178 
    179 <pre><code>
    180 void main()
    181 {             
    182     FragColor = vec4(vec3(gl_FragCoord.z), 1.0);
    183 }  
    184 </code></pre>
    185 
    186 <p>
    187   If you'd then run the program you'll probably notice that everything is white, making it look like all of our depth values are the maximum depth value of <code>1.0</code>. So why aren't any of the depth values closer to <code>0.0</code> and thus darker?
    188 </p>
    189 
    190 <p>
    191   In the previous section we described that depth values in screen space are non-linear e.g. they have a very high precision for small z-values and a low precision for large z-values. The depth value of the fragment increases rapidly over distance so almost all the vertices have values close to <code>1.0</code>. If we were to carefully move really close to an object you may eventually see the colors getting darker, their z-values becoming smaller:
    192 </p>
    193 
    194 <img src="/img/advanced/depth_testing_visible_depth.png" class="clean" alt="Depth buffer visualized in OpenGL and GLSL"/>
    195 
    196 <p>
    197   This clearly shows the non-linearity of the depth value. Objects close by have a much larger effect on the depth value than objects far away. Only moving a few inches can result in the colors going from dark to completely white.
    198 </p>
    199 
    200 <p>
    201   We can however, transform the non-linear depth values of the fragment back to its linear sibling. To achieve this we basically need to reverse the process of projection for the depth values alone. This means we have to first re-transform the depth values from the range <code>[0,1]</code> to normalized device coordinates in the range <code>[-1,1]</code>. Then we want to reverse the non-linear equation (equation 2) as done in the projection matrix and apply this inversed equation to the resulting depth value. The result is then a linear depth value. 
    202 </p>
    203 
    204 <p>
    205   First we transform the depth value to NDC which is not too difficult:
    206 </p>
    207 
    208 <pre><code>
    209 float ndc = depth * 2.0 - 1.0; 
    210 </code></pre>
    211 
    212 <p>
    213   We then take the resulting <var>ndc</var> value and apply the inverse transformation to retrieve its linear depth value:
    214 </p>
    215 
    216 <pre><code>
    217 float linearDepth = (2.0 * near * far) / (far + near - ndc * (far - near));	
    218 </code></pre>
    219 
    220 <p>
    221   This equation is derived from the projection matrix for non-linearizing the depth values, returning depth values between <var>near</var> and <var>far</var>. This <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html" target="_blank">math-heavy article</a> explains the projection matrix in enormous detail for the interested reader; it also shows where the equations come from.
    222 </p>
    223 
    224 <p>
    225   The complete fragment shader that transforms the non-linear depth in screen-space to a linear depth value is then as follows:
    226 </p>
    227 
    228 <pre><code>
    229 #version 330 core
    230 out vec4 FragColor;
    231 
    232 float near = 0.1; 
    233 float far  = 100.0; 
    234   
    235 float LinearizeDepth(float depth) 
    236 {
    237     float z = depth * 2.0 - 1.0; // back to NDC 
    238     return (2.0 * near * far) / (far + near - z * (far - near));	
    239 }
    240 
    241 void main()
    242 {             
    243     float depth = LinearizeDepth(gl_FragCoord.z) / far; // divide by far for demonstration
    244     FragColor = vec4(vec3(depth), 1.0);
    245 }
    246 </code></pre>
    247 
    248 <p>
    249   Because the linearized depth values range from <var>near</var> to <var>far</var> most of its values will be above <code>1.0</code> and displayed as completely white. By dividing the linear depth value by <var>far</var> in the <fun>main</fun> function we convert the linear depth value to the range [<code>0</code>, <code>1</code>]. This way we can gradually see the scene become brighter the closer the fragments are to the projection frustum's far plane, which works better for visualization purposes.
    250 </p>
    251 
    252 <p>
    253   If we'd now run the application we get depth values that are linear over distance. Try moving around the scene to see the depth values change in a linear fashion.
    254 </p>
    255 
    256 <img src="/img/advanced/depth_testing_visible_linear.png" class="clean" alt="Depth buffer visualized in OpenGL and GLSL as linear values"/>
    257 
    258 <p>
    259   The colors are mostly black because the depth values range linearly from the <code>near</code> plane (<code>0.1</code>) to the <code>far</code> plane (<code>100</code>) which is still quite far away from us. The result is that we're relatively close to the near plane and therefore get lower (darker) depth values.
    260 </p>
    261 
    262 <h2>Z-fighting</h2>
    263 <p>
    264   A common visual artifact may occur when two planes or triangles are so closely aligned to each other that the depth buffer does not have enough precision to figure out which one of the two shapes is in front of the other. The result is that the two shapes continually seem to switch order which causes weird glitchy patterns. This is called <def>z-fighting</def>, because it looks like the shapes are fighting over who gets on top.
    265 </p>
    266 
    267 <p>
    268   In the scene we've been using so far there are a few spots where z-fighting can be noticed. The containers were placed at the exact height of the floor which means the bottom plane of the container is coplanar with the floor plane. The depth values of both planes are then the same so the resulting depth test has no way of figuring out which is the right one. 
    269 </p>
    270 
    271 <p>
    272   If you move the camera inside one of the containers the effects are clearly visible, the bottom part of the container is constantly switching between the container's plane and the floor's plane in a zigzag pattern:
    273 </p>
    274 
    275 <img src="/img/advanced/depth_testing_z_fighting.png" class="clean" alt="Demonstration of Z-fighting in OpenGL"/>
    276 
    277 <p>
    278   Z-fighting is a common problem with depth buffers and it's generally more noticeable when objects are further away (because the depth buffer has less precision at larger z-values). Z-fighting can't be completely prevented, but there are a few tricks that will help to mitigate or completely prevent z-fighting in your scene.
    279 </p>
    280 
    281 <h3>Prevent z-fighting</h3>
    282 <p>
    283   The first and most important trick is <em>never place objects too close to each other in a way that some of their triangles closely overlap</em>. By creating a small offset between two objects you can completely remove z-fighting between the two objects. In the case of the containers and the plane we could've easily moved the containers slightly upwards in the positive y direction. The small change of the container's positions would probably not be noticeable at all and would completely reduce the z-fighting. However, this requires manual intervention of each of the objects and thorough testing to make sure no objects in a scene produce z-fighting.
    284 </p>
    285 
    286 <p>
    287   A second trick is to <em>set the near plane as far as possible</em>. In one of the previous sections we've discussed that precision is extremely large when close to the <code>near</code> plane so if we move the <code>near</code> plane away from the viewer, we'll have significantly greater precision over the entire frustum range. However, setting the <code>near</code> plane too far could cause clipping of near objects so it is usually a matter of tweaking and experimentation to figure out the best <code>near</code> distance for your scene. 
    288 </p>
    289 
    290 <p>
    291   Another great trick at the cost of some performance is to <em>use a higher precision depth buffer</em>. Most depth buffers have a precision of <code>24</code> bits, but most GPUs nowadays support <code>32</code> bit depth buffers, increasing the precision by a significant amount. So at the cost of some performance you'll get much more precision with depth testing, reducing z-fighting.
    292 </p>
    293 
    294 <p>
    295   The 3 techniques we've discussed are the most common and easy-to-implement anti z-fighting techniques. There are some other techniques out there that require a lot more work and still won't completely disable z-fighting. Z-fighting is a common issue, but if you use the proper combination of the listed techniques you probably won't need to deal with z-fighting that much.
    296 </p>       
    297 
    298     </div>
    299