<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Luc Momber on Medium]]></title>
        <description><![CDATA[Stories by Luc Momber on Medium]]></description>
        <link>https://medium.com/@Lucmomber?source=rss-acf5e25e8309------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZENKYvjfOt2uqrS_K5ObWQ.png</url>
            <title>Stories by Luc Momber on Medium</title>
            <link>https://medium.com/@Lucmomber?source=rss-acf5e25e8309------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 16:00:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Lucmomber/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Two-Pass Hierarchical Z-Buffer Occlusion Culling]]></title>
            <link>https://medium.com/@Lucmomber/two-pass-hierarchical-z-buffer-occlusion-culling-93171c5a9808?source=rss-acf5e25e8309------2</link>
            <guid isPermaLink="false">https://medium.com/p/93171c5a9808</guid>
            <category><![CDATA[game-programming]]></category>
            <category><![CDATA[graphics]]></category>
            <category><![CDATA[graphics-programming]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[real-time-rendering]]></category>
            <dc:creator><![CDATA[Luc Momber]]></dc:creator>
            <pubDate>Tue, 01 Apr 2025 22:56:44 GMT</pubDate>
            <atom:updated>2026-01-08T15:27:34.489Z</atom:updated>
            <content:encoded><![CDATA[<h4>Overview</h4><p>Two-pass Hierarchical Z-Buffer (HZB) culling is a rendering technique that leverages the power of indirect rendering to efficiently cull objects occluded by other geometry, enabling the rendering of significantly larger scenes. The two-pass variant utilizes two occlusion culling techniques; depth reprojection and hierarchical Z-buffer culling.</p><blockquote>UPDATE <br>Parts of my solution are now on GitHub, which can be seen below. Be aware that the solution is not uploaded to its full extent, as the private framework used is under NDA:<br><a href="https://github.com/LMomber/Code-Samples/tree/main/DirectX12%20HZB%20Occlusion%20Culling">https://github.com/LMomber/Code-Samples/tree/main/DirectX12%20HZB%20Occlusion%20Culling</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0fP9FUicsVqJ68npsaUKEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W6pnkisDKpO6xJCVhiu5Bw.png" /><figcaption>The left side shows the camera’s view, while the right side shows the back-view, demonstrating the culling of hidden objects</figcaption></figure><h4>First Pass</h4><p>As the name suggests, this technique consist of two passes. The first pass is the depth pre-pass. In this pass, a Z-buffer is created using the visible objects from the previous frame. These objects act as the occluders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*iqeeMBOo5LiZg8YxUMUvgg.png" /><figcaption>A visualization of the Z-buffer created by the depth pre-pass</figcaption></figure><h4>Hierarchical Z-Buffer</h4><p>From this depth buffer, a mipmap chain is created in a compute shader. Each mip samples the neighbouring texels of its parent, storing the sample farthest away from the camera.</p><pre>  // If either the width or height is odd, <br>  // extra samples are necessary to prevent artifacts<br>  switch (srcDimension)<br>    {<br>        case WIDTH_HEIGHT_EVEN:<br>        {<br>            const float2 UV = texelSize * (threadID.xy + float2(0.25, 0.25));<br>            const float2 off = texelSize * 0.5;<br>            <br>            const float2 offset1 = float2(0.0, 0.0);<br>            const float2 offset2 = float2(off.x, 0.0);<br>            const float2 offset3 = float2(0.0, off.y);<br>            const float2 offset4 = float2(off.x, off.y);<br>            <br>            src = max(SrcMip.SampleLevel(pointSampler, UV + offset1, srcMipLevel),<br>                   max(SrcMip.SampleLevel(pointSampler, UV + offset2, srcMipLevel),<br>                       max(SrcMip.SampleLevel(pointSampler, UV + offset3, srcMipLevel),<br>                           SrcMip.SampleLevel(pointSampler, UV + offset4, srcMipLevel))));<br>        }<br>        break;<br><br>        // Other cases<br>    }<br><br>  OutMip[threadID.xy] = Src;</pre><p>This creates a hierarchical Z-buffer where the objects closest to the camera slowly disappear in the lower mip levels:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Kiwzqe5uWiYeJO5QuLrXXQ.gif" /><figcaption>The different mip levels of the hierarchical Z-buffer</figcaption></figure><h4>Second Pass</h4><p>The second pass performs the hierarchical z-buffer culling. This compute pass is executed with as many threads as objects in the scene. <br>Frustum culling acts as an early-out test in this pass. This optional step saves extra time, especially in larger scenes where the majority of the geometry is frustum culled. <br>The result of the HZB culling is stored in the visibility buffer. This buffer has an index for each object in the scene, that holds either 0 or 1, depending on if the object is visible.</p><pre>    const uint index = threadID.x;<br><br>    // Early-out if the AABB is frustum culled<br>    if (index &gt;= numObjects || FrustumAABBIntersect(aabbBuffer[index]) == OUTSIDE)<br>    {<br>        visibilityBuffer[index] = OC_HIDDEN;<br>        return;<br>    }</pre><p>If the AABB is inside the frustum, its min &amp; max coordinates in the <br>Z-buffer’s UV-space are calculated.</p><pre>    const AABB aabb = aabbBuffer[index];<br>    <br>    const float3 aabb_min = aabb.min;<br>    const float3 aabb_max = aabb.max;<br>    const float4 aabb_size = float4(aabb_max - aabb_min, 0);<br>    <br>    float2 min_xy = float2(1.f, 1.f);<br>    float2 max_xy = float2(0.f, 0.f);<br>    float min_z = 1;<br><br>    // Converts the world-space coordinates of all 8 corners <br>    // to UV-space and returns the min/max<br>    CalculateMinMax(aabb_min, aabb_max, min_xy, max_xy, min_z);</pre><p>Using the min/max coordinates, the width &amp; height of the AABB are calculated in texels. With these values the correct mip sample level is calculated. This is the mip-level where the AABB covers 4 texels; That is important, since it allows the depth-sampling of the 4 AABB corners.</p><pre>    // Texture dimensions<br>    uint baseWidth, baseHeight;<br>    hzb.GetDimensions(baseWidth, baseHeight);<br>    <br>    const float2 boxWidth = float2(max_xy - min_xy);<br>    const float2 texelSize = boxWidth * float2(baseWidth, baseHeight);<br>    <br>    // The correct mip-level to test against<br>    const float mip = floor(log2(max(texelSize.x, texelSize.y)));</pre><p>The depth of the AABB’s corners in NDC-space are compared against the corresponding mip-level’s depth. If from the camera’s POV, the nearest corner of the AABB is further away than the furthest depth sampled from the mip, the object is not visible and can thus be culled.</p><pre>    // The AABB in the HZB&#39;s UV-space<br>    const float4 box = float4(min_xy, max_xy);<br>    <br>    // Sample each corner&#39;s depth value<br>    const float sample1 = hzb.SampleLevel(pointSampler, box.xy, mip);<br>    const float sample2 = hzb.SampleLevel(pointSampler, box.zy, mip);<br>    const float sample3 = hzb.SampleLevel(pointSampler, box.xw, mip);<br>    const float sample4 = hzb.SampleLevel(pointSampler, box.zw, mip);<br><br>    // Store the depth-value closest to the camera<br>    const float max_z = max(max(max(sample1, sample2), sample3), sample4);<br><br>    // If the min Z of the AABB &lt;= max Z of the mip, the object is visible.<br>    // A small delta is needed; the smaller the delta, the fewer cubes <br>    // are rendered. A small delta can cause visual artifacts.<br>    visibilityBuffer[index] = min_z &lt;= (max_z + 0.001f);</pre><p>Whether an object is visible or not is stored in the visibility buffer.<br>From this buffer an indirect draw buffer is created and executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zOwdguoP0mAfumGtGGsuNw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LQqMkBkB8WkryBLXsb0o4g.png" /><figcaption>Side view comparison: The left side shows rendering without culling, while the right side demonstrates two-pass HZB culling.</figcaption></figure><h4>Optimization</h4><p>Since the visibility buffer is a sparse buffer that can contain millions of indices, the indirect draw buffer can become quite large. In case of the scene above (30 million cubes), this resulted in a draw call of 50ms on a RTX 3070 Ti Laptop.<br>To reduce the size, the buffer is concatenated using a variation of <a href="https://medium.com/nerd-for-tech/understanding-implementation-of-work-efficient-parallel-prefix-scan-cca2d5335c9b">Blelloch’s algorithm (Work-Efficient Parallel Prefix Scan)</a>.</p><p>To fill the indirect draw buffer, each index of the visibility buffer is checked. If the index is 1, an indirect draw call is added to the indirect draw buffer. <br>One issue with this approach is that it needs an atomic counter to keep track of the next free index in the buffer. This is not ideal for performance. <br>To solve this, a new buffer that holds the <a href="https://en.wikipedia.org/wiki/Prefix_sum">exclusive prefix sum</a> “P” of the visibility buffer “V” is made. Every index in this buffer holds the sum of all indices that came before:</p><p><em>V = [0,1,1,0,1,0,0,1]<br>P = [0,0,1,2,2,3,3,3]</em></p><p>This is usefull, since for each index where the visibilty buffer stores a 1, the prefix sum buffer holds the index that the object’s draw command should be stored in.</p><p>This leads to another problem in GPU parallelization; With a standard prefix sum, each thread depends on the result of the last thread’s sum. I.e. the process is not parallel.<br>This is the problem that Blelloch’s algorithm solves, by using strided addition in the up-sweep phase and swapping the values to their right index in the down-sweep, lastly adding the previous strided value to the current index. Since it is an <em>exclusive </em>prefix sum, the first index of the down-sweep is always 0.</p><p>Here’s an example of a parallel prefix sum for <em>A = [3,1,7,0,4,1,6,3]</em> :</p><pre>Up-sweep:<br>Level 0: [3,1,7,0,4,1,6,3]      | Original array<br>Level 1: [4,7,5,9]              | [3+1,7+0,4+1,6+3]<br>Level 2: [11,14]                | [4+7,5+9]<br>Level 3: [25]                   | [11+14]<br><br>Down-sweep:<br>Level 3: [0]                    | Root set to 0<br>Level 2: [0,11]                 | Left child: 0, Right child: 11<br>Level 1: [0,4,11,16]            | Left subtree: [0,4] Right subtree: [11,16]<br>Level 0: [0,3,4,11,11,15,16,22] | Final sums</pre><p><strong>In code:</strong></p><pre>groupshared uint temp[256];<br><br>[numthreads(256, 1, 1)] <br>void main(uint3 threadID : SV_GroupThreadID, <br>          uint3 groupID : SV_GroupID)<br>{<br>    const uint i = threadID.x;<br>    const uint globalIndex = groupID.x * 256 + i;<br><br>    // Since it uses an &quot;exclusive&quot; prefix sum, <br>    // the first index should always be 0<br>    temp[i] = (globalIndex &lt; numInstances) ? visibilityBuffer[globalIndex] : 0;<br>    GroupMemoryBarrierWithGroupSync();<br><br>    // Up-sweep<br>    for (uint stride = 1; stride &lt; 256; stride *= 2)<br>    {<br>        const uint index = (i + 1) * stride * 2 - 1;<br>        if (index &lt; 256)<br>        {<br>            temp[index] += temp[index - stride];<br>        }<br>        GroupMemoryBarrierWithGroupSync();<br>    }<br><br>    ...<br>    <br>    ...<br><br>    // Down-sweep<br>    for (uint stride = 128; stride &gt; 0; stride /= 2)<br>    {<br>        const uint index = (i + 1) * stride * 2 - 1;<br>        if (index &lt; 256)<br>        {<br>            const uint tempValue = temp[index - stride];<br>            temp[index - stride] = temp[index];<br>            temp[index] += tempValue;<br>        }<br>        GroupMemoryBarrierWithGroupSync();<br>    }<br><br>    if (globalIndex &lt; numInstances)<br>    {<br>        scanResult[globalIndex] = temp[i];<br>    }<br>}</pre><p>Now the last challenge of this algorithm; Since the down-sweep depends on the results created by the up-sweep phase of multiple threads, the shader utilizes group-shared memory to temporarily store the data. But what if the number of objects in the scene is larger than 256 — the amount of threads in a group?</p><p>To solve this, a “group sum” buffer is used. This buffer stores the sums created by the up-sweep of the thread groups’ last indices.</p><pre>    // Up-sweep<br><br>    if (i == 255)<br>    {<br>        groupSums[groupID.x] = temp[255]; <br>        temp[255] = 0;<br>    }<br>    GroupMemoryBarrierWithGroupSync(); <br>    <br>    // Down-sweep</pre><p>If the group sum buffer itself is larger than 256, Blelloch’s algorithm is executed on this buffer as well. This is done recursively until the last group sum buffer is smaller than 256. The amount of group sum buffers necessary is calculated with:</p><pre>  // Since a thread group contains 256 threads,<br>  // amount is equal to log256(n) == log(n)/log(256)<br>  const uint numGroupSumBuffers = ceil(log(numObjectsInScene) / log(256)));</pre><p>At last a recursive pass that adds the group sum buffers’ results back into the original prefix sum buffer is required:</p><pre>    // Get the global thread index<br>    const uint threadGroupIndex = threadID.x;<br>    const uint globalIndex = groupID.x * 256 + threadGroupIndex;<br><br>    // Since the result is an &quot;exclusive&quot; prefix sum, <br>    // the first index should stay the same<br>    const uint offset = (groupID.x &gt; 0) ? groupSums[groupID.x] : 0;<br><br>    // Add the group sum value up to the output buffer&#39;s value<br>    result[globalIndex] += (globalIndex &lt; numInstances) ? offset : 0;</pre><h4>Future improvements</h4><p>To improve performance, a significant optimization involves using the pre-pass to not only render depth, but also output visible geometry directly to the scene. During the second draw pass, these previously rendered objects are excluded from the draw calls. This approach eliminates redundant rendering operations and reduces the overall rendering cost of the second pass.</p><p>Resources:</p><ul><li><a href="https://medium.com/@mil_kru/two-pass-occlusion-culling-4100edcad501">https://medium.com/@mil_kru/two-pass-occlusion-culling-4100edcad501</a></li><li><a href="https://www.youtube.com/watch?v=gCPgpvF1rUA&amp;t=523s">https://www.youtube.com/watch?v=gCPgpvF1rUA&amp;t=523s</a></li><li><a href="https://www.youtube.com/watch?v=EtX7WnFhxtQ">https://www.youtube.com/watch?v=EtX7WnFhxtQ</a></li><li><a href="https://www.realtimerendering.com/">Real Time Rendering — Tomas Akenine-Mo¨ller</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93171c5a9808" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>