LearnOpenGL

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

CSM.html (23787B)


      1     <div id="content">
      2     <h1 id="content-title">CSM</h1>
      3 <h1 id="content-url" style='display:none;'>Guest-Articles/2021/CSM</h1>
      4 <p>
      5 		<a href="https://learnopengl.com/Advanced-Lighting/Shadows/Shadow-Mapping" target="_blank">Shadow mapping</a> as described on LearnOpenGL is a powerful, and relatively simple technique. However, if implemented as-is from the above referred tutorial, the avid OpenGL student will notice a few shortcomings.
      6 	</p>
      7 	<ul>
      8 		<li>The shadow map is always created around the origin, and not on the area the camera is actually looking at. It would be best of course if we could shadow map the whole scene, with sufficient resolution, but on current hardware this is not feasible. In reality we want the shadow maps to be created on objects that are in view, saving our precious GPU memory for things that matter. </li>
      9 		<li>The shadow map orthographic projection matrix is not properly fitted onto the view frustum. To achieve the best possible resolution for our shadow maps, the ortho matrix needs to be as tightly fit to the camera frustum as possible, because again: if it’s larger that means that less detail is spent on the objects that are actually visible.</li>
     10 		<li>The shadow maps (even with advanced PCF functions) are blurry if we want the shadow rendering distance to be large, as we would in a game with a first-person camera. We can increase the resolution of the shadow maps to mitigate this, but GPU memory is a resource we should be conservative of.</li>
     11 	</ul>
     12 	<p>
     13 		Cascaded shadow mapping is a direct answer to the third point, however while implementing it we will solve the first two points, too. The core insight in cascaded shadow mapping is, that we don’t need the same amount of shadow detail for things that are far from us. We want crisp shadows for stuff that’s near to the near plane, and we are absolutely fine with blurriness for objects that are hundreds of units away: it’s not going to be noticeable at all. How can we achieve this? The answer is beautiful in its simplicity: just render different shadow maps for things that are close and for those that are far away, and sample from them according to the depth of the fragment in the fragment shader. The high-level algorithm is as follows:
     14 	</p>
     15 	<ul>
     16 		<li>Divide our ordinary view frustum into n subfrusta, where the far plane of the <code>i</code>-th frustum is the near plane of the <code>(i+1)</code>-th frustum</li>
     17 		<li>Compute the tightly fitting ortho matrix for each frustum</li>
     18 		<li>For each frustum render a shadow map as if seen from our directional light</li>
     19 		<li>Send all shadow maps to our fragment shader</li>
     20 		<li>Render the scene, and according to the fragment’s depth value sample from the correct shadow map</li>
     21 	</ul>
     22 	<p>
     23 		Sounds simple right? Well, it is, but as it often is when it comes to our friend OpenGL: the devil is in the details.
     24 	</p>
     25 	<img src="/img/guest/2021/CSM/cs_go.png" width="800px">
     26 	<p>
     27 		In the above image we can see the edges of shadow cascades in Counter-Strike: Global Offensive. The image was captured on low graphics settings.
     28 	</p>
     29       
     30 	<h2>World coordinates of the view frustum</h2>
     31 	<p>
     32 		Before getting our hands dirty with shadows, we need to tackle a more abstract problem: making our projection matrix fit nicely onto a generic frustum. To be able to do this, we need to know the world space coordinates of the frustum in question. While this might sound daunting at first, we already have all the tools necessary in our repertoire.  If we think back on the excellent <a href="https://learnopengl.com/Getting-started/Coordinate-Systems" target="_blank"> coordinate systems</a> tutorial, the beheaded pyramid of the frustum only looks that way in world coordinates, and our view and projection matrices do the job of transforming this unusual shape into the NDC cube. And we know the coordinates of the corners of the NDC cube: the coordinates are in the range <code>[-1,1]</code>  on the three axes. Because matrix multiplication is a reversible process, we can apply the inverse of the view and projection matrices on the corner points of the NDC cube to get the frustum corners in world space.
     33 	</p>
     34 	<math>
     35 		$$v_{NDC} = M_{proj} M_{view} v_{world}$$
     36 		$$v_{world} = (M_{proj} M_{view})^{-1} v_{NDC}$$
     37 	</math>
     38 
     39 <pre><code>
     40 std::vector&lt;glm::vec4&gt; getFrustumCornersWorldSpace(const glm::mat4& proj, const glm::mat4& view)
     41 {
     42     const auto inv = glm::inverse(proj * view);
     43     
     44     std::vector&lt;glm::vec4> frustumCorners;
     45     for (unsigned int x = 0; x &lt; 2; ++x)
     46     {
     47         for (unsigned int y = 0; y &lt; 2; ++y)
     48         {
     49             for (unsigned int z = 0; z &lt; 2; ++z)
     50             {
     51                 const glm::vec4 pt = 
     52                     inv * glm::vec4(
     53                         2.0f * x - 1.0f,
     54                         2.0f * y - 1.0f,
     55                         2.0f * z - 1.0f,
     56                         1.0f);
     57                 frustumCorners.push_back(pt / pt.w);
     58             }
     59         }
     60     }
     61     
     62     return frustumCorners;
     63 }
     64 </code></pre>
     65   
     66 	<p>
     67 		The projection matrix described here is a perspective matrix, using the camera’s aspect ratio and fov, and using the near and far plane of the current frustum being analyzed. The view matrix is the view matrix of our camera.
     68 	</p>
     69       
     70 <pre><code>
     71 const auto proj = <function id='58'>glm::perspective</function>(
     72     <function id='63'>glm::radians</function>(camera.Zoom),
     73     (float)SCR_WIDTH / (float)SCR_HEIGHT,
     74     nearPlane,
     75     farPlane
     76 );
     77 </code></pre>
     78       
     79 	<img src="/img/guest/2021/CSM/frustum_fitting.png">
     80 	<br>
     81       
     82 	<h2>The light view-projection matrix</h2>
     83 	<p>
     84 		This matrix - as in ordinary shadow mapping – is the product of the view and projection matrix that transforms the scene as if it were seen by the light. Calculating the view matrix is simple, we know the direction our light is coming from, and we know a point in world space that it definitely is looking at: the center of the frustum. The position of the frustum center can be obtained by averaging the coordinates of the frustum corners. (This is so because averaging the coordinates of the near and far plane gives us the center of those rectangles, and taking the midpoint of these two points gives us the center of the frustum.)
     85 	</p>
     86 	<pre><code>
     87 glm::vec3 center = glm::vec3(0, 0, 0);
     88 for (const auto& v : corners)
     89 {
     90     center += glm::vec3(v);
     91 }
     92 center /= corners.size();
     93     
     94 const auto lightView = <function id='62'>glm::lookAt</function>(
     95     center + lightDir,
     96     center,
     97     glm::vec3(0.0f, 1.0f, 0.0f)
     98 );
     99     </code></pre>
    100 	<p>
    101 		The projection matrix is bit more complex. Because the light in question is a directional light, the matrix needs to be an orthographic projection matrix, this much is clear. To understand how we determine the left, right, top etc. parameters of the matrix imagine the scene you are drawing from the perspective of the light. From this viewpoint the shadow map we are trying to render is going to be an axis aligned rectangle, and this rectangle – as we established before – needs to fit on the frustum tightly. So we need to obtain the coordinates of the frustum in this space, and take the maximum and minimum of the coordinates along the coordinate axes. While this might sound daunting at first, this perspective is exactly what our light view matrix transformation gives us. We need to transform the frustum corner points in the light view space, and find the maximum and minimum coordinates.
    102 	</p>
    103       
    104 	<pre><code>
    105 float minX = std::numeric_limits&lt;float>::max();
    106 float maxX = std::numeric_limits&lt;float>::min();
    107 float minY = std::numeric_limits&lt;float>::max();
    108 float maxY = std::numeric_limits&lt;float>::min();
    109 float minZ = std::numeric_limits&lt;float>::max();
    110 float maxZ = std::numeric_limits&lt;float>::min();
    111 for (const auto& v : corners)
    112 {
    113     const auto trf = lightView * v;
    114     minX = std::min(minX, trf.x);
    115     maxX = std::max(maxX, trf.x);
    116     minY = std::min(minY, trf.y);
    117     maxY = std::max(maxY, trf.y);
    118     minZ = std::min(minZ, trf.z);
    119     maxZ = std::max(maxZ, trf.z);
    120 }
    121 	</code></pre>
    122       
    123 	<p>
    124 		We are going to create our projection matrix from the product of two matrices. First, we are going to create an ortho projection matrix, with the left, right, top, bottom parameters set to <code>-1</code> or <code>1</code>, and the z values set to <var>minZ</var> and <var>maxZ</var>. This creates a 3D rectangle sitting on the origin with width and height of <code>2</code>, and depth of (<var>maxZ</var> – <var>minZ</var>). In the code we increase the amount of space covered by <var>minZ</var> and <var>maxZ</var> by multiplying or dividing them with a <var>zMult</var>. This is because we want to include geometry which is behind or in front of our frustum in camera space. Think about it: not only geometry which is in the frustum can cast shadows on a surface in the frustum!
    125 	</p>
    126       
    127 <pre><code>
    128 // Tune this parameter according to the scene
    129 constexpr float zMult = 10.0f;
    130 if (minZ &lt; 0)
    131 {
    132     minZ *= zMult;
    133 }
    134 else
    135 {
    136     minZ /= zMult;
    137 }
    138 if (maxZ &lt; 0)
    139 {
    140     maxZ /= zMult;
    141 }
    142 else
    143 {
    144     maxZ *= zMult;
    145 }
    146    
    147 const glm::mat4 lpMatrix = <function id='59'>glm::ortho</function>(-1.0f, 1.0f, -1.0f, 1.0f, minZ, maxZ);
    148 </code></pre>
    149 	<p>
    150 		The other part of our projection matrix is going to be a crop matrix, which moves the rectangle onto the frustum in light view space. Starting from a unit matrix, we need to set the x and y scaling components, and the x and y offset components of the matrix. 
    151 	</p>
    152       
    153 	<math>
    154 		$$S_x = {2 \over M_x - m_x}$$
    155 		$$S_y = {2 \over M_y - m_y}$$
    156 		$$O_x = -0.5(M_x + m_x)S_x$$
    157 		$$O_y = -0.5(M_y + m_y)S_y$$
    158 		$$C = \begin{bmatrix}S_x & 0 & 0 & O_x \\0 & S_y & 0 & O_y \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1\end{bmatrix}$$
    159 	</math>
    160 	
    161 	<p>
    162 		Let’s look at S<sub>x</sub>. It needs to shrink down the frustum bounding rectangle to a unit size, this is achieved by dividing by the width of the rectangle (M<sub>x</sub> – m<sub>x</sub>). However, we need to scale by <code>2</code>, because our 3D rectangle sitting on the origin has a width of <code>2</code>. S<sub>y</sub> is analogous to this.
    163 	</p>
    164 	<img src="/img/guest/2021/CSM/frustum_cropping.png" width="800px">
    165 	<p>
    166 		For the x offset, we need to multiply by the negative halfway point between M<sub>x</sub> and m<sub>x</sub>, and scale by S<sub>x</sub>. And the y offset is analogous.
    167 	</p>
    168 	
    169 <pre><code>
    170 const float scaleX = 2.0f / (maxX - minX);
    171 const float scaleY = 2.0f / (maxY - minY);
    172 const float offsetX = -0.5f * (minX + maxX) * scaleX;
    173 const float offsetY = -0.5f * (minY + maxY) * scaleY;
    174     
    175 glm::mat4 cropMatrix(1.0f);
    176 cropMatrix[0][0] = scaleX;
    177 cropMatrix[1][1] = scaleY;
    178 cropMatrix[3][0] = offsetX;
    179 cropMatrix[3][1] = offsetY;
    180     
    181 return cropMatrix * lpMatrix * lightView;
    182 </code></pre>
    183 	
    184 	<p>
    185 		Multiplying the view, projection and crop matrices together, we get the view-projection matrix of the light for the given frustum. We need to do this procedure for every frustum in our cascade.
    186 	</p>
    187       
    188 	<h2>2D array textures</h2>
    189 	<p>
    190 		While we let our stomachs digest what we learned about frustum fitting we should figure out how to store our shadow maps. In principle there is no limit on how many cascades we can do, so hardcoding an arbitrary value doesn’t seem like a wise idea. Also, it quickly becomes tiresome typing out and binding sampler2Ds for our shaders. OpenGL has a good solution to this problem in the form of <def>2D array textures</def>. This object is an array of textures, which have the same dimensions. To use them in shaders declare them like this:
    191 	</p>
    192       
    193 <pre><code>
    194 uniform sampler2DArray shadowMap;
    195 </code></pre>
    196       
    197 	<p>
    198 		To sample from them we can use the regular texture function with a vec3 parameter for texture coordinates, the third dimension specifying which layer to sample from, starting from <code>0</code>.
    199 	</p>
    200       
    201 <pre><code>
    202 texture(depthMap, vec3(TexCoords, currentLayer))
    203 </code></pre>
    204       
    205 	<p>
    206 		Creating our array texture is slightly different than creating a regular old texture2D. Instead of <function id='52'>glTexImage2D</function> we use glTexImage3D to allocate memory, and when binding the texture to the framebuffer we use glFramebufferTexture instead of <function id='81'>glFramebufferTexture2D</function>. The parameters of these functions are somewhat self-explanatory if we know the old versions. When calling the OpenGL functions, we need to pass <var>GL_TEXTURE_2D_ARRAY</var> instead of <var>GL_TEXTURE_2D</var> as the target, to tell OpenGL what kind of texture we are dealing with.
    207 	</p>
    208 	
    209 <pre><code>
    210 <function id='76'>glGenFramebuffers</function>(1, &lightFBO);
    211     
    212 <function id='50'>glGenTextures</function>(1, &lightDepthMaps);
    213 <function id='48'>glBindTexture</function>(GL_TEXTURE_2D_ARRAY, lightDepthMaps);
    214 glTexImage3D(
    215     GL_TEXTURE_2D_ARRAY,
    216     0,
    217     GL_DEPTH_COMPONENT32F,
    218     depthMapResolution,
    219     depthMapResolution,
    220     int(shadowCascadeLevels.size()) + 1,
    221     0,
    222     GL_DEPTH_COMPONENT,
    223     GL_FLOAT,
    224     nullptr);
    225     
    226 <function id='15'>glTexParameter</function>i(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    227 <function id='15'>glTexParameter</function>i(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    228 <function id='15'>glTexParameter</function>i(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
    229 <function id='15'>glTexParameter</function>i(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
    230     
    231 constexpr float bordercolor[] = { 1.0f, 1.0f, 1.0f, 1.0f };
    232 <function id='15'>glTexParameter</function>fv(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_BORDER_COLOR, bordercolor);
    233     
    234 <function id='77'>glBindFramebuffer</function>(GL_FRAMEBUFFER, lightFBO);
    235 glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, lightDepthMaps, 0);
    236 glDrawBuffer(GL_NONE);
    237 glReadBuffer(GL_NONE);
    238     
    239 int status = <function id='79'>glCheckFramebufferStatus</function>(GL_FRAMEBUFFER);
    240 if (status != GL_FRAMEBUFFER_COMPLETE)
    241 {
    242     std::cout &lt;&lt; "ERROR::FRAMEBUFFER:: Framebuffer is not complete!";
    243     throw 0;
    244 }
    245     
    246 <function id='77'>glBindFramebuffer</function>(GL_FRAMEBUFFER, 0);
    247 </code></pre>
    248       
    249 	<p>
    250 		Take care when binding this texture to a sampler. Again: we need to use <var>GL_TEXTURE_2D_ARRAY</var> as the target parameter.
    251 	</p>
    252       
    253 <pre><code>
    254 <function id='49'>glActiveTexture</function>(GL_TEXTURE1);
    255 <function id='48'>glBindTexture</function>(GL_TEXTURE_2D_ARRAY, lightDepthMaps);
    256 </code></pre>
    257 	
    258 	<p>
    259 		So far so good, now we know the semantics of using a texture array. It all seems straightforward, but OpenGL has one more curveball to throw at us: we can’t render into this texture the ordinary way, we need to do something called <def>layered rendering</def>. This process is very similar to what we did with <a href="https://learnopengl.com/Advanced-Lighting/Shadows/Point-Shadows" target="_blank">cubemaps and pointlights</a> , we coax the <a href="https://learnopengl.com/Advanced-OpenGL/Geometry-Shader" target="_blank">geometry shader</a> into generating multiple layers of geometry for us at the same time. If we recall our depthmap shader is very simple: transform the vertices to light space in the vertex stage, and let the hardware do the rest with an empty fragment shader. In our new depthmap shader we are going to only do the world space transformation in the vertex shader.
    260 	</p>
    261       
    262 <pre><code>
    263 #version 460 core
    264 layout (location = 0) in vec3 aPos;
    265     
    266 uniform mat4 model;
    267     
    268 void main()
    269 {
    270     gl_Position = model * vec4(aPos, 1.0);
    271 }
    272 </code></pre>
    273   
    274 	<p>
    275 	The newly inserted geometry shader will look something like this:
    276 	</p>
    277       
    278 <pre><code>
    279 #version 460 core
    280     
    281 layout(triangles, invocations = 5) in;
    282 layout(triangle_strip, max_vertices = 3) out;
    283     
    284 layout (std140, binding = 0) uniform LightSpaceMatrices
    285 {
    286     mat4 lightSpaceMatrices[16];
    287 };
    288     
    289 void main()
    290 {          
    291     for (int i = 0; i &lt; 3; ++i)
    292     {
    293         gl_Position = 
    294             lightSpaceMatrices[gl_InvocationID] * gl_in[i].gl_Position;
    295         gl_Layer = gl_InvocationID;
    296         EmitVertex();
    297     }
    298     EndPrimitive();
    299 }  
    300 </code></pre>
    301       
    302 	<p>
    303 		The input declaration has a new member, specifying the <def>invocation count</def>. This number means, that this shader will be instanced, these instances running in parallel, and we can refer the current instance by the inbuilt variable <var>gl_InvocationID</var>. We will use this number in the shader code to reference which layer of the array texture we are rendering to, and which shadow matrix we are going to use to do the light space transform. We are iterating over all triangles, and setting <var>gl_Layer</var> and <var>gl_Position</var> accordingly. 
    304 	</p>
    305       
    306 	<note>
    307 		I strongly suggest modifying your Shader class in your engine to enable the possibility of inserting variables into the shader code before shader compilation, so that you can make the <i>invocations</i> parameter dynamic. This way if you modify the number of cascades in the C++ code you dont have to modify the shader itself, removing one cog from the complex machine that is your engine. I didn't include this in the tutorial for the sake of simplicity.
    308 	</note>
    309       
    310 	<p>
    311 		The fragment shader remains the same empty, passthrough shader.
    312 	</p>
    313       
    314 <pre><code>
    315 #version 460 core
    316     
    317 void main()
    318 {             
    319 }
    320 </code></pre>
    321       
    322 	<p>
    323 		Our draw call invoking the shader looks something like this:
    324 	</p>
    325       
    326 <pre><code>
    327 simpleDepthShader.use();
    328     
    329 <function id='77'>glBindFramebuffer</function>(GL_FRAMEBUFFER, lightFBO);
    330 glFramebufferTexture(GL_FRAMEBUFFER, GL_TEXTURE_2D_ARRAY, lightDepthMaps, 0);
    331 <function id='22'>glViewport</function>(0, 0, depthMapResolution, depthMapResolution);
    332 <function id='10'>glClear</function>(GL_DEPTH_BUFFER_BIT);
    333 <function id='74'>glCullFace</function>(GL_FRONT);  // peter panning
    334 renderScene(simpleDepthShader);
    335 <function id='74'>glCullFace</function>(GL_BACK);
    336 <function id='77'>glBindFramebuffer</function>(GL_FRAMEBUFFER, 0);
    337 </code></pre>
    338       
    339 	<img src="/img/guest/2021/CSM/cascades.png" width="800px">
    340 
    341 	<h2>Scene rendering</h2>
    342 	<p>
    343 		Now the only thing remaining is doing the actual shadow rendering. In our ordinary phong/deferred fragment shader where we calculate whether the current fragment is occluded or not, we need to insert some logic to decide which light space matrix to use, and which texture to sample from.
    344 	</p>
    345       
    346 <pre><code>
    347 // select cascade layer
    348 vec4 fragPosViewSpace = view * vec4(fragPosWorldSpace, 1.0);
    349 float depthValue = abs(fragPosViewSpace.z);
    350     
    351 int layer = -1;
    352 for (int i = 0; i &lt; cascadeCount; ++i)
    353 {
    354     if (depthValue &lt; cascadePlaneDistances[i])
    355     {
    356         layer = i;
    357         break;
    358     }
    359 }
    360 if (layer == -1)
    361 {
    362     layer = cascadeCount;
    363 }
    364     
    365 vec4 fragPosLightSpace = lightSpaceMatrices[layer] * vec4(fragPosWorldSpace, 1.0);
    366 </code></pre>
    367       
    368 	<p>
    369 		If you remember to prevent shadow acne we applied a depth bias to our image. We need to do the same here, but keep in mind that we are dealing with multiple shadow maps, and on each of them the pixels cover a widely different amount of space, and a unit increase in pixel value means  different depth increase in all of them. Because of this we need to apply a different bias depending on which shadow map we sample from. In my experience scaling the bias inversely proportionally with the far plane works nicely.
    370 	</p>
    371       
    372 <pre><code>
    373 // perform perspective divide
    374 vec3 projCoords = fragPosLightSpace.xyz / fragPosLightSpace.w;
    375 // transform to [0,1] range
    376 projCoords = projCoords * 0.5 + 0.5;
    377     
    378 // get depth of current fragment from light's perspective
    379 float currentDepth = projCoords.z;
    380 if (currentDepth  &gt; 1.0)
    381 {
    382     return 0.0;
    383 }
    384 // calculate bias (based on depth map resolution and slope)
    385 vec3 normal = normalize(fs_in.Normal);
    386 float bias = max(0.05 * (1.0 - dot(normal, lightDir)), 0.005);
    387 if (layer == cascadeCount)
    388 {
    389     bias *= 1 / (farPlane * 0.5f);
    390 }
    391 else
    392 {
    393     bias *= 1 / (cascadePlaneDistances[layer] * 0.5f);
    394 }
    395 </code></pre>
    396       
    397 	<note>
    398 		Please note that there are different strategies for applying bias when dealing with shadow maps. I will link to a few sources detailing these in the citations section.
    399 	</note>
    400       
    401 	<p>
    402 		The rest of the function is the same as before, the only difference is that we are sampling from a 2D array texture, hence we need to add a third parameter to the <fun>texture</fun> and the <fun>textureSize</fun> functions.
    403 	</p>
    404       
    405 <pre><code>
    406 // PCF
    407 float shadow = 0.0;
    408 vec2 texelSize = 1.0 / vec2(textureSize(shadowMap, 0));
    409 for(int x = -1; x &lt;= 1; ++x)
    410 {
    411     for(int y = -1; y &lt;= 1; ++y)
    412     {
    413         float pcfDepth = texture(
    414                     shadowMap,
    415                     vec3(projCoords.xy + vec2(x, y) * texelSize,
    416                     layer)
    417                     ).r; 
    418         shadow += (currentDepth - bias) > pcfDepth ? 1.0 : 0.0;        
    419     }    
    420 }
    421 shadow /= 9.0;
    422     
    423 // keep the shadow at 0.0 when outside the far_plane region of the light's frustum.
    424 if(projCoords.z &gt; 1.0)
    425 {
    426     shadow = 0.0;
    427 }
    428     	
    429 return shadow;
    430 </code></pre>
    431       
    432 	<p>
    433 		And that's it! If we did everything correctly we should see that the renderer switches between shadow maps based on the distance. Try setting some unreasonable cascade plane distances (for example only one, which is a few units from the camera) to see if the code really does work. You should see a noticable degradation in shadow quality between the two sides of the plane. If you see moire artifacts on the screen try changing around bias parameters a bit.
    434 	</p>
    435       
    436       <img src="/img/guest/2021/CSM/demoscene.png" width="800px">
    437         
    438         <p>
    439           You can find the full source code for the cascaded shadow mapping demo <a href="/code_viewer_gh.php?code=src/8.guest/2021/2.csm/shadow_mapping.cpp" target="_blank">here</a>.
    440         </p>
    441 
    442 	<h2>Closing thoughts</h2>
    443 	<p>
    444 		In the sample project provided you can toggle depthmap visualization by pressing <kbd>F</kbd>. When in depthmap visualization mode you can press the <kbd>+</kbd> key to swap between the different layers.
    445 	</p>
    446 	<p>
    447 		When browsing through the code you might wonder why is the UBO array length <code>16</code>. This is just an arbitrary choice, to me it seemed unlikely that anyone would use more than <code>16</code> shadow cascades, so this seemed like a nice number to allocate.
    448 	</p>
    449       
    450 	<h2>Additional Resources</h2>
    451 	<ul>
    452 		<li><a href="https://developer.download.nvidia.com/SDK/10.5/opengl/src/cascaded_shadow_maps/doc/cascaded_shadow_maps.pdf" target="_blank">NVIDIA paper on the subject:</a> incomprehensible in my opinion but has to be mentioned</li>
    453 		<li><a href="https://www.gamedev.net/forums/topic/672664-fitting-directional-light-in-view-frustum/?page=1" target="_blank">A series of incredibly helpful and useful forum posts</a></li>
    454 		<li><a href="https://ogldev.org/www/tutorial49/tutorial49.html" target="_blank">Another interesting tutorial from OGLDev</a></li>
    455 		<li><a href="https://docs.microsoft.com/en-us/windows/win32/dxtecharts/cascaded-shadow-maps" target="_blank">An article from Microsoft:</a> nice pictures illustrating some issues with CSM</li>
    456 		<li><a href="https://digitalrune.github.io/DigitalRune-Documentation/html/3f4d959e-9c98-4a97-8d85-7a73c26145d7.htm" target="_blank">An article about shadow bias</a></li>
    457 		<li><a href="http://c0de517e.blogspot.com/2011/05/shadowmap-bias-notes.html" target="_blank">Some informative drawings about shadow bias strategies</a></li>
    458 	</ul>
    459 	<br>
    460       
    461 <author>
    462   <strong>Article by: </strong>Márton Árbócz<br/>
    463   <!--<strong>Contact: </strong><a href="mailto:eklavyagames@gmail.com" target="_blank">e-mail</a>-->
    464 </author>       
    465 
    466     </div>
    467