LearnOpenGL

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

Stencil-testing.html (16854B)


      1     <div id="content">
      2     <h1 id="content-title">Stencil testing</h1>
      3 <h1 id="content-url" style='display:none;'>Advanced-OpenGL/Stencil-testing</h1>
      4 <p>
      5   Once the fragment shader has processed the fragment a so called <def>stencil test</def> is executed that, just like the depth test, has the option to discard fragments. After that the remaining fragments are passed to the depth test where OpenGL could possibly discard even more fragments. The stencil test is based on the content of yet another buffer called the <def>stencil buffer</def> that we're allowed to update during rendering to achieve interesting effects.
      6 </p>
      7 
      8 <p>
      9   A stencil buffer (usually) contains <code>8</code> bits per <def>stencil value</def> that amounts to a total of <code>256</code> different stencil values per pixel. We can set these stencil values to values of our liking and we can discard or keep fragments whenever a particular fragment has a certain stencil value.
     10 </p>
     11 
     12 <note>
     13   Each windowing library needs to set up a stencil buffer for you. GLFW does this automatically so we don't have to tell GLFW to create one, but other windowing libraries may not create a stencil buffer by default so be sure to check your library's documentation.
     14 </note>
     15 
     16 <p>
     17   A simple example of a stencil buffer is shown below (pixels not-to-scale):
     18 </p>
     19 
     20 <img src="/img/advanced/stencil_buffer.png" class="clean" alt="A simple demonstration of a stencil buffer"/>
     21 
     22 <p>
     23   The stencil buffer is first cleared with zeros and then an open rectangle of <code>1</code>s is stored in the stencil buffer. The fragments of the scene are then only rendered (the others are discarded) wherever the stencil value of that fragment contains a <code>1</code>. 
     24 </p>
     25   
     26 <p>
     27 	Stencil buffer operations allow us to set the stencil buffer at specific values wherever we're rendering fragments. By changing the content of the stencil buffer while we're rendering,  we're <em>writing</em> to the stencil buffer. In the same (or following) frame(s) we can <em>read</em> these values to discard or pass certain fragments. When using stencil buffers you can get as crazy as you like, but the general outline is usually as follows:
     28 </p>
     29 
     30 <ul>
     31   <li>Enable writing to the stencil buffer.</li>
     32   <li>Render objects, updating the content of the stencil buffer.</li>
     33   <li>Disable writing to the stencil buffer.</li>
     34   <li>Render (other) objects, this time discarding certain fragments based on the content of the stencil buffer.</li>
     35 </ul>
     36 
     37 <p>
     38   By using the stencil buffer we can thus discard certain fragments based on the fragments of other drawn objects in the scene.
     39 </p>
     40   
     41 <p>
     42   You can enable stencil testing by enabling <var>GL_STENCIL_TEST</var>. From that point on, all rendering calls will influence the stencil buffer in one way or another.
     43 </p>
     44   
     45 <pre><code>
     46 <function id='60'>glEnable</function>(GL_STENCIL_TEST);    
     47 </code></pre>
     48 
     49 <p>
     50   Note that you also need to clear the stencil buffer each iteration just like the color and depth buffer:
     51 </p>
     52 
     53 <pre><code>
     54 <function id='10'>glClear</function>(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); 
     55 </code></pre>
     56   
     57 <p>
     58   Also, just like the depth testing's <fun><function id='65'>glDepthMask</function></fun> function, there is an equivalent function for the stencil buffer. The function <fun><function id='67'>glStencilMask</function></fun> allows us to set a bitmask that is <code>AND</code>ed with the stencil value about to be written to the buffer. By default this is set to a bitmask of all <code>1</code>s not affecting the output, but if we were to set this to <code>0x00</code> all the stencil values written to the buffer end up as <code>0</code>s. This is equivalent to depth testing's <fun><function id='65'>glDepthMask</function>(GL_FALSE)</fun>:
     59 </p>
     60   
     61 <pre><code>
     62 <function id='67'>glStencilMask</function>(0xFF); // each bit is written to the stencil buffer as is
     63 <function id='67'>glStencilMask</function>(0x00); // each bit ends up as 0 in the stencil buffer (disabling writes)
     64 </code></pre>
     65   
     66 <p>
     67   Most of the cases you'll only be using <code>0x00</code> or <code>0xFF</code> as the stencil mask, but it's good to know there are options to set custom bit-masks.
     68 </p>
     69   
     70 <h2>Stencil functions</h2>
     71 <p>
     72     Similar to depth testing, we have a certain amount of control over when a stencil test should pass or fail and how it should affect the stencil buffer. There are a total of two functions we can use to configure stencil testing: <fun><function id='68'>glStencilFunc</function></fun> and <fun><function id='69'>glStencilOp</function></fun>.
     73 </p>
     74   
     75 <p>
     76   The <fun><function id='68'>glStencilFunc</function>(GLenum func, GLint ref, GLuint mask)</fun> has three parameters:
     77 </p>
     78   
     79 <ul>
     80   <li><code>func</code>: sets the stencil test function that determines whether a fragment passes or is discarded. This test function is applied to the stored stencil value and the <fun><function id='68'>glStencilFunc</function></fun>'s <code>ref</code> value. Possible options are: <var>GL_NEVER</var>, <var>GL_LESS</var>, <var>GL_LEQUAL</var>, <var>GL_GREATER</var>, <var>GL_GEQUAL</var>, <var>GL_EQUAL</var>, <var>GL_NOTEQUAL</var> and <var>GL_ALWAYS</var>. The semantic meaning of these is similar to the depth buffer's functions.</li>
     81   <li><code>ref</code>: specifies the reference value for the stencil test. The stencil buffer's content is compared to this value.</li>
     82   <li><code>mask</code>: specifies a mask that is <code>AND</code>ed with both the reference value and the stored stencil value before the test compares them. Initially set to all <code>1</code>s.</li>
     83 </ul>
     84   
     85 <p>
     86    So in the case of the simple stencil example we've shown at the start, the function would be set to:
     87 </p>
     88 
     89 <pre class="cpp"><code>
     90 <function id='68'>glStencilFunc</function>(GL_EQUAL, 1, 0xFF)
     91 </code></pre>
     92 
     93 <p>
     94   This tells OpenGL that whenever the stencil value of a fragment is equal (<var>GL_EQUAL</var>) to the reference value <code>1</code>, the fragment passes the test and is drawn, otherwise discarded.  
     95 </p>
     96   
     97 <p>
     98   But <fun><function id='68'>glStencilFunc</function></fun> only describes whether OpenGL should pass or discard fragments based on the stencil buffer's content, not how we can actually update the buffer. That is where <fun><function id='69'>glStencilOp</function></fun> comes in.
     99 </p>
    100   
    101   <p>
    102     The <fun><function id='69'>glStencilOp</function>(GLenum sfail, GLenum dpfail, GLenum dppass)</fun> contains three options of which we can specify for each option what action to take:
    103   </p>
    104   
    105   <ul>
    106     <li><code>sfail</code>: action to take if the stencil test fails.</li>
    107     <li><code>dpfail</code>: action to take if the stencil test passes, but the depth test fails.</li>
    108     <li><code>dppass</code>: action to take if both the stencil and the depth test pass.</li>    
    109   </ul>
    110   
    111 <p>
    112   Then for each of the options you can take any of the following actions:
    113 </p>  
    114   
    115 <table>
    116   <tr>
    117   	<th>Action</th>
    118   	<th>Description</th>
    119   </tr>  
    120   <tr>
    121     <td><code>GL_KEEP</code></td>
    122  	<td>The currently stored stencil value is kept.</td>
    123   </tr>
    124   <tr>
    125     <td><code>GL_ZERO</code></td>
    126  	<td>The stencil value is set to <code>0</code>.</td>
    127   </tr>
    128   <tr>
    129     <td><code>GL_REPLACE</code></td>
    130  	<td>The stencil value is replaced with the reference value set with <fun><function id='68'>glStencilFunc</function></fun>.</td>
    131   </tr>
    132   <tr>
    133     <td><code>GL_INCR</code></td>
    134  	<td>The stencil value is increased by <code>1</code> if it is lower than the maximum value. </td>
    135   </tr><tr>
    136     <td><code>GL_INCR_WRAP</code></td>
    137  	<td>Same as <var>GL_INCR</var>, but wraps it back to <code>0</code> as soon as the maximum value is exceeded.</td>
    138   </tr> 
    139   <tr>
    140     <td><code>GL_DECR</code></td>
    141  	<td>The stencil value is decreased by <code>1</code> if it is higher than the minimum value.</td>
    142   </tr>
    143   <tr>
    144     <td><code>GL_DECR_WRAP</code></td>
    145  	<td>Same as <var>GL_DECR</var>, but wraps it to the maximum value if it ends up lower than <code>0</code>.</td>
    146   </tr>
    147   <tr>
    148     <td><code>GL_INVERT</code></td>
    149  	<td>Bitwise inverts the current stencil buffer value.</td>
    150   </tr>
    151 </table>
    152 
    153 <p>
    154   By default the <fun><function id='69'>glStencilOp</function></fun> function is set to <code>(GL_KEEP, GL_KEEP, GL_KEEP)</code> so whatever the outcome of any of the tests, the stencil buffer keeps its values. The default behavior does not update the stencil buffer, so if you want to write to the stencil buffer you need to specify at least one different action for any of the options.
    155 </p>
    156 
    157 <p>
    158   So using <fun><function id='68'>glStencilFunc</function></fun> and <fun><function id='69'>glStencilOp</function></fun> we can precisely specify when and how we want to update the stencil buffer and when to pass or discard fragments based on its content.
    159 </p>
    160   
    161 <h1>Object outlining</h1>
    162 <p>
    163    It would be unlikely if you completely understood how stencil testing works from the previous sections alone so we're going to demonstrate a particular useful feature that can be implemented with stencil testing alone called <def>object outlining</def>.
    164 </p>
    165 
    166 <img src="/img/advanced/stencil_object_outlining.png" class="clean" alt="An object outlined using stencil testing/buffer"/>
    167   
    168 <p>
    169   Object outlining does exactly what it says it does. For each object (or only one) we're creating a small colored border around the (combined) objects. This is a particular useful effect when you want to select units in a strategy game for example and need to show the user which of the units were selected. The routine for outlining your objects is as follows:
    170 </p>
    171 
    172 <ol>
    173   <li>Enable stencil writing.</li>
    174   <li>Set the stencil op to <var>GL_ALWAYS</var> before drawing the (to be outlined) objects, updating the stencil buffer with <code>1</code>s wherever the objects' fragments are rendered.</li>
    175   <li>Render the objects.</li>
    176   <li>Disable stencil writing and depth testing.</li>
    177   <li>Scale each of the objects by a small amount.</li>
    178   <li>Use a different fragment shader that outputs a single (border) color.</li>
    179   <li>Draw the objects again, but only if their fragments' stencil values are not equal to <code>1</code>.</li>
    180   <li>Enable depth testing again and restore stencil func to <var>GL_KEEP</var>.</li>
    181 </ol>
    182 
    183 <p>
    184   This process sets the content of the stencil buffer to <code>1</code>s for each of the object's fragments and when it's time to draw the borders, we draw scaled-up versions of the objects only where the stencil test passes. We're effectively discarding all the fragments of the scaled-up versions that are part of the original objects' fragments using the stencil buffer. 
    185 </p>
    186 
    187 <p>
    188   So we're first going to create a very basic fragment shader that outputs a border color. We simply set a hardcoded color value and call the shader <var>shaderSingleColor</var>:
    189 </p>
    190 
    191 <pre><code>
    192 void main()
    193 {
    194     FragColor = vec4(0.04, 0.28, 0.26, 1.0);
    195 }
    196 </code></pre>
    197 
    198 <p>
    199   Using the scene from the <a href="https://learnopengl.com/Advanced-OpenGL/Depth-testing" target="_blank">previous</a> chapter we're going to add object outlining to the two containers, so we'll leave the floor out of it. We want to first draw the floor, then the two containers (while writing to the stencil buffer), and then draw the scaled-up containers (while discarding the fragments that write over the previously drawn container fragments). 
    200 </p>
    201 
    202 <p>
    203   We first need to enable stencil testing: 
    204 </p>
    205 
    206 <pre class="cpp"><code>
    207 <function id='60'>glEnable</function>(GL_STENCIL_TEST);
    208 </code></pre>
    209 
    210 <p>
    211   And then in each frame we want to specify the action to take whenever any of the stencil tests succeed or fail:
    212 </p>
    213 
    214 <pre class="cpp"><code>
    215 <function id='69'>glStencilOp</function>(GL_KEEP, GL_KEEP, GL_REPLACE);  
    216 </code></pre>
    217 
    218 <p>
    219   If any of the tests fail we do nothing; we simply keep the currently stored value that is in the stencil buffer. If both the stencil test and the depth test succeed however, we want to replace the stored stencil value with the reference value set via <fun><function id='68'>glStencilFunc</function></fun> which we later set to <code>1</code>.
    220 </p>
    221 
    222 <p>
    223   We clear the stencil buffer to <code>0</code>s at the start of the frame and for the containers we update the stencil buffer to <code>1</code> for each fragment drawn:
    224 </p>
    225 
    226 <pre><code>
    227 <function id='69'>glStencilOp</function>(GL_KEEP, GL_KEEP, GL_REPLACE);  
    228 <function id='68'>glStencilFunc</function>(GL_ALWAYS, 1, 0xFF); // all fragments should pass the stencil test
    229 <function id='67'>glStencilMask</function>(0xFF); // enable writing to the stencil buffer
    230 normalShader.use();
    231 DrawTwoContainers();
    232 </code></pre>
    233 
    234 <p>
    235   By using <var>GL_REPLACE</var> as the stencil op function we make sure that each of the containers' fragments update the stencil buffer with a stencil value of <code>1</code>. Because the fragments always pass the stencil test, the stencil buffer is updated with the reference value wherever we've drawn them.
    236 </p>
    237 
    238 <p>
    239   Now that the stencil buffer is updated with <code>1</code>s where the containers were drawn we're going to draw the upscaled containers, but this time with the appropriate test function and disabling writes to the stencil buffer:
    240 </p>
    241 
    242 <pre><code>
    243 <function id='68'>glStencilFunc</function>(GL_NOTEQUAL, 1, 0xFF);
    244 <function id='67'>glStencilMask</function>(0x00); // disable writing to the stencil buffer
    245 glDisable(GL_DEPTH_TEST);
    246 shaderSingleColor.use(); 
    247 DrawTwoScaledUpContainers();
    248 </code></pre>
    249 
    250 <p>
    251   We set the stencil function to <var>GL_NOTEQUAL</var> to make sure that we're only drawing parts of the containers that are not equal to <code>1</code>. This way we only draw the part of the containers that are outside the previously drawn containers. Note that we also disable depth testing so the scaled up containers (e.g. the borders) do not get overwritten by the floor. Make sure to enable the depth buffer again once you're done.
    252 </p>
    253 
    254 <p>
    255   The total object outlining routine for our scene looks something like this:
    256 </p>
    257 
    258 <pre><code>
    259 <function id='60'>glEnable</function>(GL_DEPTH_TEST);
    260 <function id='69'>glStencilOp</function>(GL_KEEP, GL_KEEP, GL_REPLACE);  
    261   
    262 <function id='10'>glClear</function>(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); 
    263 
    264 <function id='67'>glStencilMask</function>(0x00); // make sure we don't update the stencil buffer while drawing the floor
    265 normalShader.use();
    266 DrawFloor()  
    267   
    268 <function id='68'>glStencilFunc</function>(GL_ALWAYS, 1, 0xFF); 
    269 <function id='67'>glStencilMask</function>(0xFF); 
    270 DrawTwoContainers();
    271   
    272 <function id='68'>glStencilFunc</function>(GL_NOTEQUAL, 1, 0xFF);
    273 <function id='67'>glStencilMask</function>(0x00); 
    274 glDisable(GL_DEPTH_TEST);
    275 shaderSingleColor.use(); 
    276 DrawTwoScaledUpContainers();
    277 <function id='67'>glStencilMask</function>(0xFF);
    278 <function id='68'>glStencilFunc</function>(GL_ALWAYS, 1, 0xFF);   
    279 <function id='60'>glEnable</function>(GL_DEPTH_TEST);  
    280 </code></pre>
    281 
    282 <p>
    283   As long as you understand the general idea behind stencil testing this shouldn't be too hard to understand. Otherwise try to carefully read the previous sections again and try to completely understand what each of the functions does now that you've seen an example of it can be used.
    284 </p>
    285 
    286 <p>
    287   The result of the outlining algorithm then looks like this:
    288 </p>
    289 
    290 
    291 <img src="/img/advanced/stencil_scene_outlined.png" class="clean" alt="3D scene with object outlining using a stencil buffer"/>
    292 
    293 <p>
    294   Check the source code <a href="/code_viewer_gh.php?code=src/4.advanced_opengl/2.stencil_testing/stencil_testing.cpp" target="_blank">here</a> to see the complete code of the object outlining algorithm.
    295 </p>
    296 
    297 <note>
    298   You can see that the borders overlap between both containers which is usually the effect that we want (think of strategy games where we want to select 10 units; merging borders is generally preferred). If you want a complete border per object you'd have to clear the stencil buffer per object and get a little creative with the depth buffer.
    299 </note>
    300 
    301 <p>
    302   The object outlining algorithm you've seen is commonly used in games to visualize selected objects (think of strategy games) and an algorithm like this can easily be implemented within a model class. You could set a boolean flag within the model class to draw either with borders or without. If you want to be creative you could even give the borders a more natural look with the help of post-processing filters like Gaussian Blur.
    303 </p>
    304 
    305 <p>
    306   Stencil testing has many more purposes (beside outlining objects) like drawing textures inside a rear-view mirror so it neatly fits into the mirror shape, or rendering real-time shadows with a stencil buffer technique called <def>shadow volumes</def>. Stencil buffers give us with yet another nice tool in our already extensive OpenGL toolkit.
    307 </p>       
    308 
    309     </div>
    310