Advanced Rendering Techniques and Optimizations
local graph
Chapter 11 — Advanced Rendering Techniques and Optimizations
Section titled “Chapter 11 — Advanced Rendering Techniques and Optimizations”In this chapter, we’ll scratch the surface of more advanced rendering topics and optimizations. We’ll also show how to combine multiple effects and techniques into a single graphical application.
This chapter covers the following recipes:
- Refactoring indirect rendering
- Doing frustum culling on the CPU
- Doing frustum culling on the GPU with compute shaders
- Implementing shadows for directional lights
- Implementing order-independent transparency
- Loading texture assets asynchronously
- Putting it all together into a Vulkan demo
Technical requirements
Section titled “Technical requirements”To run the examples in this chapter, you will need a computer with a graphics card supporting Vulkan 1.3. Read Chapter 1, for guidance on how to build demo applications from this book.
This chapter depends on the geometry loading code discussed in Chapter 8, and the post-processing effects covered in the previous chapter, Chapter 10. Be sure to review both chapters before continuing.
The source code for the examples in this chapter is available on GitHub at https://github.com/PacktPublishing/3D-Graphics-Rendering-Cookbook-Second-Edition/tree/main/Chapter11.
Refactoring indirect rendering
Section titled “Refactoring indirect rendering”In Chapter 8, we introduced the VKMesh helper class, which provided a straightforward way to encapsulate scene geometry, GPU buffers, and rendering pipelines. This class has been useful in simplifying rendering tasks throughout Chapters 8 to 10. However, its simplicity comes with a trade-off: it tightly couples scene data, rendering pipelines, and buffers.
This strong coupling poses challenges when attempting to render the same scene data with different pipelines or when selectively rendering parts of a scene. To address these limitations, let’s introduce a new class, VKMesh11, designed to resolve these issues and enable more flexible rendering setups. With VKMesh11, we will have the new foundation needed to implement more advanced and complex algorithms in this chapter.
Getting ready
Section titled “Getting ready”As we build on top of the old VKMesh class, ensure you’ve reviewed all the recipes in Chapter 8 to understand how the old VKMesh class works.
The source code for this recipe can be found in Chapter11/VKMesh11.h.
How to do it…
Section titled “How to do it…”In this recipe, we aim to address two main issues with the existing VKMesh implementation. The first is to allow the use of custom shaders, depth states, and push constants within the VKMesh11 rendering pipeline. The second issue is to enable the rendering of specific parts of the mesh by using a custom modified indirect commands buffer. This approach will decouple rendering operations from the default buffer, allowing us to implement frustum culling. Let’s go through the steps required to do it:
- First, we introduce a new helper class,
VKIndirectBuffer11, designed to manage an indirect commands buffer along with an array ofDrawIndexedIndirectCommandstructures:class VKIndirectBuffer11 final {public:const std::unique_ptr<lvk::IContext>& ctx_;Holder<BufferHandle> bufferIndirect_;vector<DrawIndexedIndirectCommand> drawCommands_; - We can define the maximum number of draw commands,
maxDrawCommands, this buffer can store, though the actual number of commands may be smaller. Additionally, we can specify the buffer’s storage type, which will be important later when making the indirect buffer host-visible in the next recipe, Performing frustum culling on the CPU:VKIndirectBuffer11(const std::unique_ptr<lvk::IContext>& ctx,size_t maxDrawCommands,lvk::StorageType indirectBufferStorage = lvk::StorageType_Device): ctx_(ctx), drawCommands_(maxDrawCommands) { - We allocate the buffer and include a
uint32_tinteger to store the number of commands. It can be used withvkCmdDrawIndexedIndirectCount()to enable GPU-side modification of the command count:
Note
Our indirect buffer layout is as follows:
uint32_t numCommands;DrawIndexedIndirectCommand cmd0;DrawIndexedIndirectCommand cmd1;…DrawIndexedIndirectCommand cmdMaxDrawCommands;bufferIndirect_ = ctx->createBuffer( { .usage = lvk::BufferUsageBits_Indirect | lvk::BufferUsageBits_Storage, .storage = indirectBufferStorage, .size = sizeof(uint32_t) + sizeof(DrawIndexedIndirectCommand) * maxDrawCommands, .debugName = "Buffer: indirect" });}- Here’s a helper function to upload the updated contents of the indirect buffer using the modified
drawCommands_array. We store the number of draw commands at the very beginning of the buffer:void uploadIndirectBuffer() {const uint32_t numCommands = drawCommands_.size();ctx_->upload(bufferIndirect_, &numCommands, sizeof(uint32_t));ctx_->upload(bufferIndirect_,drawCommands_.data(),sizeof(VkDrawIndexedIndirectCommand) * numCommands, sizeof(uint32_t));}; - Let’s introduce another helper function,
selectTo(), which populates a separateVKIndirectBuffer11object with draw commands filtered by a predicate functor,pred. This is useful for separating subsets of a scene based on specific criteria. In the Implementing order-independent transparency recipe, we’ll use it to create separate indirect buffers for opaque and transparent objects:void selectTo(VKIndirectBuffer11& buf,const std::function<bool(const DrawIndexedIndirectCommand&)>& pred){buf.drawCommands_.clear();for (const auto& c : drawCommands_)if (pred(c)) buf.drawCommands_.push_back(c);buf.uploadIndirectBuffer();} - This helper function creates a pointer to a memory-mapped indirect buffer. This will be used in the next recipe, Performing frustum culling on the CPU, to modify the indirect buffer before rendering:
DrawIndexedIndirectCommand*getDrawIndexedIndirectCommandPtr() const {return std::launder(reinterpret_cast<DrawIndexedIndirectCommand*>(ctx_->getMappedPtr(bufferIndirect_) + sizeof(uint32_t)));}};
Now, let’s introduce another class, VKPipeline11, to encapsulate the functionality for creating the graphics pipeline.
- Our pipeline will include vertex and fragment shaders, along with two rendering pipelines: one for standard rendering and one for wireframe rendering, similar to how the old
VKMeshclass handled it:class VKPipeline11 final {public:Holder<ShaderModuleHandle> vert_;Holder<ShaderModuleHandle> frag_;Holder<RenderPipelineHandle> pipeline_;Holder<RenderPipelineHandle> pipelineWireframe_; - The constructor takes some mental load off the old
VKMeshconstructor. Everything related to the graphics pipeline creation is here:VKPipeline11(const std::unique_ptr<lvk::IContext>& ctx,const lvk::VertexInput& streams,lvk::Format colorFormat,lvk::Format depthFormat,uint32_t numSamples = 1,Holder<ShaderModuleHandle>&& vert = {},Holder<ShaderModuleHandle>&& frag = {}) { - Custom shaders are optional. By default, we use the shaders from Chapter 8:
vert_ = vert.valid() ?std::move(vert) : loadShaderModule(ctx, "Chapter08/02_SceneGraph/src/main.vert");frag_ = frag.valid() ?std::move(frag) : loadShaderModule(ctx, "Chapter08/02_SceneGraph/src/main.frag");
- Last but not least, two rendering pipelines are created: one for standard rendering and one for wireframe rendering:
pipeline_ = ctx->createRenderPipeline({.vertexInput = streams,.smVert = vert_,.smFrag = frag_,.color = {{ .format = colorFormat }},.depthFormat = depthFormat,.cullMode = lvk::CullMode_None,.samplesCount = numSamples,.minSampleShading = numSamples>1 ? 0.25f : 0.f});pipelineWireframe_ = ctx->createRenderPipeline({.vertexInput = streams,.smVert = vert_,.smFrag = frag_,.color = { { .format = colorFormat } },.depthFormat = depthFormat,.cullMode = lvk::CullMode_None,.polygonMode = lvk::PolygonMode_Line,.samplesCount = numSamples });}};
Now, we can use two helper classes, VKIndirectBuffer11 and VKPipeline11, to streamline our new mesh class, VKMesh11. Let’s see how it works.
How it works…
Section titled “How it works…”The VKMesh11 class is almost a direct drop-in replacement for the old VKMesh, with the main difference being that the graphics pipelines are now entirely separate and should be stored elsewhere:
- All the buffers, except for the indirect command buffer, are still managed directly within this class:
class VKMesh11 {public:const std::unique_ptr<lvk::IContext>& ctx;uint32_t numIndices_ = 0;uint32_t numMeshes_ = 0;Holder<BufferHandle> bufferIndices_;Holder<BufferHandle> bufferVertices_;Holder<BufferHandle> bufferTransforms_;Holder<BufferHandle> bufferDrawData_;Holder<BufferHandle> bufferMaterials_;std::vector<DrawData> drawData_;VKIndirectBuffer11 indirectBuffer_;
- The texture cache is identical to the one in
VKMesh. We won’t discuss it here, so please refer to Chapter 8 for details. The member fields,materialsCPU_andmaterialsGPU_, are used to store the corresponding materials. We will utilize them later, in the Loading texture assets asynchronously recipe:TextureFiles textureFiles_;mutable TextureCache textureCache_;std::vector<Material> materialsCPU_;std::vector<GLTFMaterialDataGPU> materialsGPU_;VKMesh11(const std::unique_ptr<lvk::IContext>& ctx,const MeshData& meshData,const Scene& scene,lvk::StorageType indirectBufferStorage = lvk::StorageType_Device,bool preloadMaterials = true): ctx(ctx), numIndices_((uint32_t)meshData.indexData.size()), numMeshes_((uint32_t)meshData.meshes.size()), indirectBuffer_(ctx,meshData.getMeshFileHeader().meshCount,indirectBufferStorage), textureFiles_(meshData.textureFiles){const MeshFileHeader header = meshData.getMeshFileHeader();const uint32_t* indices = meshData.indexData.data();const uint8_t* vertexData = meshData.vertexData.data(); - Here, we skip the code for creating GPU buffers for materials, vertices, indices, and model-to-world transformation matrices. For details, refer to Chapter 8. The materials initialization is now slightly different and can be entirely skipped using the
preloadMaterialsflag. We will use this in the Loading texture assets asynchronously recipe:materialsCPU_ = meshData.materials;materialsGPU_.reserve(meshData.materials.size());for (const auto& mat : meshData.materials) {materialsGPU_.push_back(preloadMaterials ?convertToGPUMaterial(ctx, mat, textureFiles_, textureCache_) :GLTFMaterialDataGPU{});} - Draw commands are now stored in the default
VKIndirectBuffer11object. The content is populated in the same way as in the oldVKMesh, using the sameDrawDatastructure. We skip most of that code here for the sake of brevity:const uint32_t numCommands = header.meshCount;indirectBuffer_.drawCommands_.resize(numCommands);drawData_.resize(numCommands);DrawIndexedIndirectCommand* cmd =indirectBuffer_.drawCommands_.data();DrawData* dd = drawData_.data();uint32_t ddIndex = 0;// … prepare indirect commands buffer - skippedfor (auto& i : scene.meshForNode) { … }indirectBuffer_.uploadIndirectBuffer();bufferDrawData_ = ctx->createBuffer({ .usage = lvk::BufferUsageBits_Storage,.storage = lvk::StorageType_Device,.size = sizeof(DrawData) * numCommands,.data = drawData_.data(),.debugName = "Buffer: drawData" });} - The
draw()functions have changed, and there are now two of them. The first one takes a mandatoryVKPipeline11object and uses default push constants to pass data into GLSL shaders, including the familiarview,proj, andtexSkyboxIrradianceparameters fromVKMesh. Note the additional, optionalVKIndirectBuffer11parameter:void draw(lvk::ICommandBuffer& buf,const VKPipeline11& pipeline,const mat4& view, const mat4& proj,TextureHandle texSkyboxIrradiance = {},bool wireframe = false,const VKIndirectBuffer11* indirectBuffer = nullptr){buf.cmdBindIndexBuffer(bufferIndices_, lvk::IndexFormat_UI32);buf.cmdBindVertexBuffer(0, bufferVertices_); - We use the standard or wireframe pipeline from the provided
VKPipeline11object:buf.cmdBindRenderPipeline(wireframe ?pipeline.pipelineWireframe_:pipeline.pipeline_);buf.cmdBindDepthState({ .compareOp = lvk::CompareOp_Less,.isDepthWriteEnabled = true }); - These push constants are exactly the same as in the old
VKMeshclass:const struct {mat4 viewProj;uint64_t bufferTransforms;uint64_t bufferDrawData;uint64_t bufferMaterials;uint32_t texSkyboxIrradiance;} pc = {.viewProj = proj * view,.bufferTransforms = ctx->gpuAddress(bufferTransforms_),.bufferDrawData = ctx->gpuAddress(bufferDrawData_),.bufferMaterials = ctx->gpuAddress(bufferMaterials_),.texSkyboxIrradiance = texSkyboxIrradiance.index(),};buf.cmdPushConstants(pc); - The last step in the first
draw()method is to use the optional indirect commands buffer, if provided, or replace it with the default buffer if not. Then, we callvkCmdDrawIndexedIndirectCount(), specifying the location of our draw commands counter, which is at the very beginning of the indirect buffer:if (!indirectBuffer)indirectBuffer = &indirectBuffer_;buf.cmdDrawIndexedIndirectCount(indirectBuffer->bufferIndirect_,sizeof(uint32_t),indirectBuffer->bufferIndirect_, 0, numMeshes_,sizeof(DrawIndexedIndirectCommand));} - The second
draw()function is designed to take custom push constants and depth state, which are populated externally. Everything else remains the same. We will use this function to render our scene with custom shaders in the Implementing shadows for directional lights recipe:void draw(lvk::ICommandBuffer& buf,const VKPipeline11& pipeline,const void* pushConstants, size_t pcSize,const lvk::DepthState depthState = {.compareOp = lvk::CompareOp_Less,.isDepthWriteEnabled = true }bool wireframe = false,const VKIndirectBuffer11* indirectBuffer =nullptr){buf.cmdBindIndexBuffer(bufferIndices_, lvk::IndexFormat_UI32);buf.cmdBindVertexBuffer(0, bufferVertices_);buf.cmdBindRenderPipeline(wireframe ?pipeline.pipelineWireframe_:pipeline.pipeline_);buf.cmdBindDepthState(depthState);buf.cmdPushConstants(pushConstants, pcSize);if (!indirectBuffer)indirectBuffer = &indirectBuffer_;buf.cmdDrawIndexedIndirectCount(indirectBuffer->bufferIndirect_,sizeof(uint32_t),indirectBuffer->bufferIndirect_, 0, numMeshes_,sizeof(DrawIndexedIndirectCommand));} - One last helper function is
getDrawIndexedIndirectCommandPtr(). It simply returns the corresponding pointer value from our default indirect commands buffer:DrawIndexedIndirectCommand*getDrawIndexedIndirectCommandPtr() const {return indirectBuffer_.getDrawIndexedIndirectCommandPtr();};};
That’s it! Now, let’s put the VKMesh11 class to use in the next recipe and learn how to perform frustum culling on the CPU.
Doing frustum culling on the CPU
Section titled “Doing frustum culling on the CPU”Frustum culling is a technique used to determine whether a part of the scene is visible within the viewing frustum. While many tutorials online explain how to implement it, most have a significant drawback.
As Inigo Quilez highlighted in his blog http://www.iquilezles.org/www/articles/frustumcorrect/frustumcorrect.htm, many frustum culling examples determine whether a mesh is outside the viewing frustum by comparing the mesh’s axis-aligned bounding box (AABB) against the 6 planes of the frustum. They reject any AABB that lies entirely outside any of these planes.
This approach will result in false positives when a large AABB, which is not actually visible, intersects some of the frustum planes. The naïve method will incorrectly classify these AABBs as visible, reducing culling efficiency. For individual meshes, addressing these cases may not be worth the performance cost. However, when culling large bounding boxes that serve as containers, such as sections of an octree, false positives can become a significant issue. The solution is to incorporate a reverse culling test, where the 8 corner points of the viewing frustum are checked against the 6 planes of the AABB.
In this recipe, we will provide self-contained frustum culling code in C++ and show you how to use it to render the Bistro scene.
Getting ready
Section titled “Getting ready”Make sure you’ve reviewed all the recipes in Chapter 8 to understand how the VKMesh class works. The example source code for this demo is located in Chapter11/01_CullingCPU.
How to do it…
Section titled “How to do it…”To implement both box-in-frustum and frustum-in-box tests, we need to extract 6 frustum planes and 8 frustum corner points from the view matrix. Here’s the code to do that, located in shared/UtilsMath.h:
- By default, GLM uses a right-handed coordinate system. In this case, the 6 frustum planes are extracted from the transposed, premultiplied view-projection matrix,
vp:void getFrustumPlanes(mat4 vp, vec4* planes) {vp = glm::transpose(vp);planes[0] = vec4(vp[3] + vp[0]); // leftplanes[1] = vec4(vp[3] - vp[0]); // rightplanes[2] = vec4(vp[3] + vp[1]); // bottomplanes[3] = vec4(vp[3] - vp[1]); // topplanes[4] = vec4(vp[3] + vp[2]); // nearplanes[5] = vec4(vp[3] - vp[2]); // far} - The
8frustum corner points can be generated by taking a unit cube, transforming it with the inverse of the premultiplied view-projection matrix, and then performing perspective division. In this way, the unit cube effectively warps into the frustum:void getFrustumCorners(glm::mat4 vp, glm::vec4* points) {const vec4 corners[] = {vec4(-1, -1, -1, 1), vec4( 1, -1, -1, 1),vec4( 1, 1, -1, 1), vec4(-1, 1, -1, 1),vec4(-1, -1, 1, 1), vec4( 1, -1, 1, 1),vec4( 1, 1, 1, 1), vec4(-1, 1, 1, 1)};const glm::mat4 invVP = glm::inverse(vp);for (int i = 0; i != 8; i++) {const vec4 q = invVP * corners[i];points[i] = q / q.w;}} - The AABB culling code is now straightforward. Simply check whether the bounding box is entirely outside any of the 6 frustum planes:
bool isBoxInFrustum(glm::vec4* frPlanes,glm::vec4* frCorners, const BoundingBox& b) {using glm::dot;for ( int i = 0; i < 6; i++ ) {int r = 0;r +=(dot(frPlanes[i],vec4(b.min_.x,b.min_.y,b.min_.z,1.f)) < 0) ? 1 : 0;r +=(dot(frPlanes[i],vec4(b.max_.x,b.min_.y,b.min_.z,1.f)) < 0) ? 1 : 0;r +=(dot(frPlanes[i],vec4(b.min_.x,b.max_.y,b.min_.z,1.f)) < 0) ? 1 : 0;r +=(dot(frPlanes[i],vec4(b.max_.x,b.max_.y,b.min_.z,1.f)) < 0) ? 1 : 0;r +=(dot(frPlanes[i],vec4(b.min_.x,b.min_.y,b.max_.z,1.f)) < 0) ? 1 : 0;r +=(dot(frPlanes[i],vec4(b.max_.x,b.min_.y,b.max_.z,1.f)) < 0) ? 1 : 0;r +=(dot(frPlanes[i],vec4(b.min_.x,b.max_.y,b.max_.z,1.f)) < 0) ? 1 : 0;r +=(dot(frPlanes[i],vec4(b.max_.x,b.max_.y,b.max_.z,1.f)) < 0) ? 1 : 0;if (r == 8) return false;}
Note
Here, the terms “inside” and “outside” of a plane are defined by the direction of its normal vector: “inside” lies in the direction of the normal vector, while “outside” is in the opposite direction.
- Next, invert the test and check whether the frustum is entirely inside the bounding box:
int r = 0;r = 0; for (int i = 0; i<8; i++)r+=((frCorners[i].x>b.max_.x) ? 1 : 0);if (r == 8) return false;r = 0; for (int i = 0; i<8; i++)r+=((frCorners[i].x<b.min_.x) ? 1 : 0);if (r == 8) return false;r = 0; for (int i = 0; i<8; i++)r+=((frCorners[i].y>b.max_.y) ? 1 : 0);if (r == 8) return false;r = 0; for (int i = 0; i<8; i++)r+=((frCorners[i].y<b.min_.y) ? 1 : 0);if (r == 8) return false;r = 0; for (int i = 0; i<8; i++)r+=((frCorners[i].z>b.max_.z) ? 1 : 0);if (r == 8) return false;r = 0; for (int i = 0; i<8; i++)r+=((frCorners[i].z<b.min_.z) ? 1 : 0);if (r == 8) return false;return true;}
Let’s take a look at how this culling code can be used in our demos.
How it works…
Section titled “How it works…”The main driving code for this demo is located in the Chapter11/01_CullingCPU/src/main.cpp file. It is based on the Bistro MSAA rendering example, Chapter10/03_MSAA, from Chapter 10. Let’s now go over the new sections of the code that handle frustum culling:
- First, we need to add a few parameters to control culling. The
cullingViewmatrix represents the view matrix of the culling frustum, which can be detached from the camera view to allow observation of the culling process from an external perspective. ThefreezeCullingViewflag enables this functionality. The Boolean flags can be controlled from the ImGui UI:mat4 cullingView = mat4(1.0f);bool freezeCullingView = false;bool drawMeshes = true;bool drawBoxes = true;bool drawWireframe = false; - The remaining setup before the rendering loop is almost identical to the demo in
Chapter10/03_MSAA, so we’ll skip it here. There are two additions. One addition is a keyboard callback that toggles the culling frustum freezing state using the P key:// …app.addKeyCallback( {const bool pressed = action != GLFW_RELEASE;if (key == GLFW_KEY_P && pressed &&!ImGui::GetIO().WantCaptureKeyboard)freezeCullingView = !freezeCullingView;}); - Another change is passing the
StorageType_HostVisibleparameter toVKMesh11, ensuring it allocates the indirect commands buffer as host-visible. Check the previous Refactoring indirect rendering recipe to understand how theVKMesh11class works:
Note
This is necessary for our CPU culling approach. Later, we will evaluate each mesh’s visibility using AABB-to-frustum culling and then directly modify the indirect commands buffer to set the number of instances for that mesh to either 1 or 0, based on visibility.
const VKMesh11 mesh(ctx, meshData, scene, lvk::StorageType_HostVisible);const VKPipeline11 pipeline(ctx, meshData.streams, ctx->getSwapchainFormat(), app.getDepthFormat(), kNumSamples);- Let’s examine the rendering loop to understand how the culling process is implemented:
app.run([&](uint32_t width, uint32_t height,float aspectRatio, float deltaSeconds){const mat4 view = app.camera_.getViewMatrix();const mat4 proj = glm::perspective(45.f, aspectRatio, 0.1f, 200.f);lvk::ICommandBuffer& buf =ctx->acquireCommandBuffer();
- We update the
cullingViewmatrix using the camera’s view matrix and create a combined view-projection matrix to extract the 6 frustum planes and 8 frustum corners from it using the helper functions defined earlier:if (!freezeCullingView)cullingView = app.camera_.getViewMatrix();vec4 frustumPlanes[6];getFrustumPlanes(proj * cullingView, frustumPlanes);vec4 frustumCorners[8];getFrustumCorners(proj * cullingView, frustumCorners); - With all the data ready, the actual culling takes place in this
forloop. We obtain a pointer to the indirect commands buffer fromVKMeshand iterate through all the meshes. For each mesh, we callisBoxInFrustum()for its world-space AABB and set the number of instances to render to either1or0, depending on its visibility. ThenumVisibleMeshesvariable is used to display the number of visible meshes in the UI:int numVisibleMeshes = 0;DrawIndexedIndirectCommand* cmd =mesh.getDrawIndexedIndirectCommandPtr();for (auto& p : scene.meshForNode) {const BoundingBox box = meshData.boxes[p.second].getTransformed(scene.globalTransform[p.first]);const uint32_t count = isBoxInFrustum(frustumPlanes, frustumCorners, box) ? 1 : 0;(cmd++)->instanceCount = count;numVisibleMeshes += count;}
Note
As you can see, we transform AABBs from model space to world space in every frame. However, since our Bistro scene is completely static, this extra work is unnecessary. In the next recipe, Doing frustum culling on the GPU with compute shaders, we will optimize this process by pre-transforming the bounding boxes, eliminating the need for per-frame transformations.
- Since our indirect buffer is host-visible and memory-mapped, we need to call
flushMappedMemory()after updating it to ensure the changes are visible to the GPU. Internally, this function will callvmaFlushAllocation()if the Vulkan Memory Allocator is used, orvkFlushMappedMemoryRanges()otherwise:ctx->flushMappedMemory(mesh.indirectBuffer_.bufferIndirect_, 0,mesh.numMeshes_ * sizeof(DrawIndexedIndirectCommand)); - The culling is complete. The remaining code handles drawing the debugging UI. We render the culling frustum (in yellow) so that we can fly around with the camera and observe it from the outside:
canvas3d.clear();canvas3d.setMatrix(proj * view);if (freezeCullingView)canvas3d.frustum(cullingView, proj, vec4(1, 1, 0, 1));
- Next, we render all the bounding boxes. If a mesh is visible, we draw its bounding box in green; otherwise, we draw it in red:
if (drawBoxes) {const DrawIndexedIndirectCommand* cmd =mesh.getDrawIndexedIndirectCommandPtr();for (auto& p : scene.meshForNode) {const BoundingBox box = meshData.boxes[p.second];canvas3d.box(scene.globalTransform[p.first],box, (cmd++)->instanceCount ?vec4(0, 1, 0, 1) : vec4(1, 0, 0, 1));}}// …if (drawMeshes) {mesh.draw(buf, pipeline, view, proj,skyBox.texSkyboxIrradiance, drawWireframe);}
The remaining scene rendering code is exactly the same as in Chapter10/03_MSAA. Indeed, we only modified the content of the indirect buffer, which controls GPU rendering inside the VKMesh11 class. There’s a small ImGui UI rendering snippet in Chapter11/01_CullingCPU/src/main.cpp, which we leave for you to explore.
The running demo application should render something similar to the following screenshot:

Figure 11.1: Bistro with CPU frustum culling
The culling frustum, rendered with yellow lines, is frozen to allow us to observe its orientation. The green boxes represent visible meshes, while the red boxes indicate invisible ones. Next time the P key is pressed, the culling frustum is reattached to the camera view.
There’s more…
Section titled “There’s more…”One might argue that this type of culling is inefficient because modern GPUs can render small meshes much faster than we can cull them on the CPU, and this is mostly true. It doesn’t make sense to cull very small objects such as bottles or individual leaves this way. However, the CPU culling pipeline is still extremely useful when culling large objects or even clusters of objects. For instance, if we create a 3D grid that covers the entire Bistro scene with reasonably large cells, we can assign each mesh to the cells that intersect it. This way, CPU culling can be applied to each cell rather than individual meshes, allowing us to skip over entire sections of the scene. On platforms where bandwidth consumption increases power usage and heat—such as mobile phones and handheld consoles—performing culling on the CPU may prevent the costly transfer of uncompressed vertex data from RAM to tile memory, only for it to be discarded.
Another improvement could be to perform this type of CPU culling using multithreading, often referred to as the parallel-brute-force approach. We leave these enhancements as moderately complex exercises for you.
For now, let’s port this simple culling technique to the GPU using a compute pipeline and perform some performance measurements.
Doing frustum culling on the GPU with compute shaders
Section titled “Doing frustum culling on the GPU with compute shaders”In the previous recipe, we explored how to cull invisible meshes on the CPU using the classic AABB-to-frustum method. However, this CPU-based approach has its limitations. Now, let’s learn how to use Vulkan compute shaders to implement a basic frustum culling pipeline on the GPU.
The goal of this recipe is to demonstrate what can be achieved on modern GPUs using compute pipelines and indirect rendering, rather than to create an efficient culling system. Once you are comfortable with the basics, we can explore the limitations and discuss potential directions for improvement.
Getting ready
Section titled “Getting ready”Be sure to read the previous recipe, Doing frustum culling on the CPU, to familiarize yourself with the basics of frustum culling.
The source code for this recipe is available in Chapter11/02_CullingGPU.
How to do it…
Section titled “How to do it…”The concept behind this recipe is simple. We’ll take the C++ isAABBinFrustum() helper function from the previous recipe, Doing frustum culling on the CPU, and port it to GLSL. Next, we’ll transform the culling for loop from C++ into the body of the main() function in our compute shader. In the updated C++ code, we’ll retain both the old CPU culling code and the new GPU culling implementation, allowing us to switch between them and compare their performance.
Let’s explore how to port the C++ culling code to a GLSL compute shader that is located in Chapter11/02_CullingGPU/src/FrustumCulling.comp:
- Before porting the culling function to GLSL, we need to define some data structures and declare shader inputs. We’ll create an
AABBstructure to represent our bounding boxes, corresponding to theBoundingBoxtype in C++. In this structure,6floats are used to store thevec3min and max values, ensuring we avoid scalar alignment issues in the shader:struct AABB {float pt[6];}; - The GLSL
DrawIndexedIndirectCommandstructure corresponds to the C++ VulkanVkDrawIndexedIndirectCommandstruct. This structure will be used to modify the content of the indirect commands buffer and adjust the number of instances based on AABB visibility:struct DrawIndexedIndirectCommand {uint count;uint instanceCount;uint firstIndex;int baseVertex;uint baseInstance;}; - The
DrawDatastruct is used to access thetransformIdfor each draw call. To recap how it works, refer to theVKMeshclass and the Implementing indirect rendering with Vulkan recipe in Chapter 8. TheVKMesh11class uses the sameDrawDatastructure:struct DrawData {uint transformId;uint materialId;}; - The
BoundingBoxesbuffer, managed inChapter11/02_CullingGPU/src/main.cpp, is used to pass the bounding boxes to the shader, while the other 2 buffers are managed within theVkMeshclass:layout(std430, buffer_reference)readonly buffer BoundingBoxes {AABB boxes[];};layout(std430, buffer_reference)readonly buffer DrawDataBuffer {DrawData dd[];};layout(std430, buffer_reference) buffer DrawCommands {uint numDraws; // unused in this compute shaderDrawIndexedIndirectCommand dc[];}; - A small
CullingDatabuffer is used to pass per-frame data to the compute shader. This includes6frustum planes,8frustum corners, and the number of meshes to cull. ThenumVisibleMeshesfield is initially set to0and is atomically incremented for each visible mesh. It will be read back in C++ and displayed in the ImGui UI:layout(std430, buffer_reference) buffer CullingData {vec4 planes[6];vec4 corners[8];uint numShapesToCull;uint numVisibleMeshes;}; - Push constants are used to pass the GPU addresses of all 4 aforementioned buffers to the compute shader:
layout(std430, push_constant) uniform PushConstants {DrawCommands commands;DrawDataBuffer drawData;BoundingBoxes AABBs;CullingData frustum;};
- Here’s the
isAABBinFrustum()frustum culling function, which is largely copied from its C++ implementation. It follows the same two-phase approach used in the previous recipe, Doing frustum culling on the CPU. In this case, we use macros to provide mnemonic names for the floating-point values in the AABB structure:#define min_x box.pt[0]#define min_y box.pt[1]#define min_z box.pt[2]#define max_x box.pt[3]#define max_y box.pt[4]#define max_z box.pt[5]bool isAABBinFrustum(AABB box) {for (int i = 0; i < 6; i++) {int r = 0;r += (dot( frustum.planes[i],vec4(min_x, min_y, min_z, 1.0f)) < 0) ? 1 : 0;r += (dot( frustum.planes[i],vec4(max_x, min_y, min_z, 1.0f)) < 0) ? 1 : 0;r += (dot( frustum.planes[i],vec4(min_x, max_y, min_z, 1.0f)) < 0) ? 1 : 0;r += (dot( frustum.planes[i],vec4(max_x, max_y, min_z, 1.0f)) < 0) ? 1 : 0;r += (dot( frustum.planes[i],vec4(min_x, min_y, max_z, 1.0f)) < 0) ? 1 : 0;r += (dot( frustum.planes[i],vec4(max_x, min_y, max_z, 1.0f)) < 0) ? 1 : 0;r += (dot( frustum.planes[i],vec4(min_x, max_y, max_z, 1.0f)) < 0) ? 1 : 0;r += (dot( frustum.planes[i],vec4(max_x, max_y, max_z, 1.0f)) < 0) ? 1 : 0;if (r == 8) return false;}int r = 0;r = 0; for ( int i = 0; i < 8; i++ )r += ( (frustum.corners[i].x > max_x) ? 1 : 0 );if ( r == 8 ) return false;r = 0; for ( int i = 0; i < 8; i++ )r += ( (frustum.corners[i].x < min_x) ? 1 : 0 );if ( r == 8 ) return false;r = 0; for ( int i = 0; i < 8; i++ )r += ( (frustum.corners[i].y > max_y) ? 1 : 0 );if ( r == 8 ) return false;r = 0; for ( int i = 0; i < 8; i++ )r += ( (frustum.corners[i].y < min_y) ? 1 : 0 );if ( r == 8 ) return false;r = 0; for ( int i = 0; i < 8; i++ )r += ( (frustum.corners[i].z > max_z) ? 1 : 0 );if ( r == 8 ) return false;r = 0; for ( int i = 0; i < 8; i++ )r += ( (frustum.corners[i].z < min_z) ? 1 : 0 );if ( r == 8 ) return false;return true;} - With the culling helper function in place, we can implement the shader’s
main()function as follows. The shader operates on workgroups of 64 elements, so we need to skip any meshes beyond the value ofnumMeshesToCull. ThebaseInstanceparameter is extracted from theDrawCommandsbuffer and then used to get an AABB object. Since everything runs in parallel, we use the atomic operationatomicAdd()to increment the count of visible meshes:void main() {const uint idx = gl_GlobalInvocationID.x;if (idx < frustum.numMeshesToCull) {uint baseInstance = commands.dc[idx].baseInstance;AABB box = AABBs.boxes[drawData.dd[baseInstance].transformId];uint numInstances = isAABBinFrustum(box) ? 1 : 0;commands.dc[idx].instanceCount = numInstances;atomicAdd(frustum.numVisibleMeshes, numInstances);}}
Note
Instead of checking against numMeshesToCull, we can pad the underlying buffers to 64 meshes. This will require modifying the VkMesh11 class, and we leave it as an exercise for you.
More information
In a real application, instead of calling atomicAdd() for each value, we should use subgroup memory along with the GLSL commands subgroupBallot() and subgroupBallotBitCount() to perform a single atomic operation per shader workgroup. Refer to the Khronos Vulkan subgroup tutorial https://www.khronos.org/blog/vulkan-subgroup-tutorial to learn more about this approach.
Now, let’s take a look at the C++ code to understand how everything works.
How it works…
Section titled “How it works…”The C++ code is located in Chapter11/02_CullingGPU/src/main.cpp. It is built on the example from the previous recipe, Doing frustum culling on the CPU, so here we will focus only on the newly added sections:
- We need a new
CullingModeenum to select between different culling modes in ImGui:enum CullingMode {CullingMode_None = 0,CullingMode_CPU = 1,CullingMode_GPU = 2,};mat4 cullingView = mat4(1.0f);int cullingMode = CullingMode_GPU;// … - Let’s load our culling compute shader and create a pipeline for it:
Holder<ShaderModuleHandle> compCulling = loadShaderModule(ctx,"Chapter11/02_CullingGPU/src/FrustumCulling.comp");Holder<ComputePipelineHandle> pipelineCulling =ctx->createComputePipeline({ .smComp = compCulling } );
- In the previous recipe, Doing frustum culling on the CPU, we did a lot of extra work by transforming mesh bounding boxes from model space to world space in each frame. Since the scene is static, let’s pretransform and reorder all the bounding boxes. The
reorderedBoxescontainer can now be indexed by theDrawData::transformId, as we saw earlier in the compute shader code. Let’s upload it into a GPU buffer:std::vector<BoundingBox> reorderedBoxes;reorderedBoxes.resize(scene.globalTransform.size());for (auto& p : scene.meshForNode)reorderedBoxes[p.first] = meshData.boxes[p.second].getTransformed(scene.globalTransform[p.first]);Holder<BufferHandle> bufferAABBs = ctx->createBuffer({.usage = lvk::BufferUsageBits_Storage,.storage = lvk::StorageType_Device,.size = reorderedBoxes.size() * sizeof(BoundingBox),.data = reorderedBoxes.data() }); - Here’s a C++ struct that corresponds to the
CullingDatabuffer we declared in GLSL. TheCullingData::numVisibleMeshesmember field is used to transfer data to and from the GPU, while thenumVisibleMeshesvariable is used to display this value through ImGui. We will see how to update both of these in a moment:struct CullingData {vec4 frustumPlanes[6];vec4 frustumCorners[8];uint32_t numMeshesToCull = 0;uint32_t numVisibleMeshes = 0; // GPU};int numVisibleMeshes = 0; // CPU - The update of
CullingData::numVisibleMesheshappens on the GPU, and we need to read it back. If we wait for the GPU to finish before reading the value, it will cause the CPU to stall. Instead, let’s read back the value that was updated a frame earlier. To achieve this, we can create multiple buffers to holdCullingDatafor 2 consecutive frames and use them in a round-robin fashion:const lvk::BufferDesc cullingDataDesc = {.usage = lvk::BufferUsageBits_Storage,.storage = lvk::StorageType_HostVisible,.size = sizeof(CullingData) };Holder<BufferHandle> bufferCullingData[] = {ctx->createBuffer(cullingDataDesc),ctx->createBuffer(cullingDataDesc),}; - We also need 2 corresponding Vulkan fences to wait for each of these previously submitted frames. Each
SubmitHandlewraps aVkFenceobject, as described in the Using Vulkan command buffers recipe from Chapter 2. ThecurrentBufferIdvariable ranges from0to1and is used to track the current buffer ID:vk::SubmitHandle submitHandle[LVK_ARRAY_NUM_ELEMENTS(bufferCullingData)] = {};uint32_t currentBufferId = 0; - Here’s a structure representing push constants. The first 3 buffers are persistent, while the last buffer,
frustum, holdsCullingDataand is updated each frame in a round-robin fashion:struct {uint64_t commands;uint64_t drawData;uint64_t AABBs;uint64_t frustum;} pcCulling = {.commands = ctx->gpuAddress(mesh.bufferIndirect_),.drawData = ctx->gpuAddress(mesh.bufferDrawData_),.AABBs = ctx->gpuAddress(bufferAABBs),}; - Let’s now take a look at the rendering loop. In addition to the previously implemented CPU culling, we now have two new code paths: one for GPU culling and one where culling is completely disabled:
app.run([&](uint32_t width, uint32_t height,float aspectRatio, float deltaSeconds) {const mat4 view = app.camera_.getViewMatrix();const mat4 proj = glm::perspective(45.f, aspectRatio, 0.1f, 200.f);ICommandBuffer& buf = ctx->acquireCommandBuffer();if (!freezeCullingView)cullingView = app.camera_.getViewMatrix();CullingData cullingData = {.numMeshesToCull = static_cast<uint32_t>(scene.meshForNode.size()),};getFrustumPlanes(proj * cullingView, cullingData.frustumPlanes);getFrustumCorners(proj * cullingView, cullingData.frustumCorners);
- The no-culling code path simply sets the number of instances to
1for all meshes and updatesnumVisibleMeshesaccordingly. Don’t forget to flush the mapped indirect commands GPU buffer:if (cullingMode == CullingMode_None) {numVisibleMeshes = scene.meshForNode.size();DrawIndexedIndirectCommand* cmd =mesh.getDrawIndexedIndirectCommandPtr();for (auto& p : scene.meshForNode)(cmd++)->instanceCount = 1;ctx->flushMappedMemory(mesh.indirectBuffer_.bufferIndirect_, 0,mesh.numMeshes_ * sizeof(DrawIndexedIndirectCommand));} - The CPU culling code path is very similar to the one in the previous recipe, Doing frustum culling on the CPU. The main difference here is that we use the pretransformed bounding boxes we calculated earlier:
else if (cullingMode == CullingMode_CPU) {numVisibleMeshes = 0;DrawIndexedIndirectCommand* cmd =mesh.getDrawIndexedIndirectCommandPtr();for (auto& p : scene.meshForNode) {const BoundingBox box = reorderedBoxes[p.first];const uint32_t count = isBoxInFrustum(cullingData.frustumPlanes,cullingData.frustumCorners, box) ? 1 : 0;(cmd++)->instanceCount = count;numVisibleMeshes += count;;}ctx->flushMappedMemory(mesh.indirectBuffer_.bufferIndirect_, 0,mesh.numMeshes_ * sizeof(DrawIndexedIndirectCommand));}
- The GPU culling code path is straightforward. We assign the GPU pointer of the current
CullingDatabuffer to push constants, bind them, update the contents of theCullingDatabuffer, and dispatch our compute shader. We must specify the dependency to the indirect buffer to ensure a proper Vulkan buffer memory barrier is issued. Our compute shader processes work groups of size64, which is why we perform the division and round the result up:else if (cullingMode == CullingMode_GPU) {buf.cmdBindComputePipeline(pipelineCulling);pcCulling.meshes = ctx->gpuAddress(bufferCullingData[bufferId]);buf.cmdPushConstants(pcCulling);buf.cmdUpdateBuffer(bufferCullingData[bufferId], cullingData);buf.cmdDispatchThreadGroups({ 1 + cullingData.numMeshesToCull / 64 },{ .buffers = { BufferHandle(mesh.bufferIndirect_) } });} - After the compute shader, we can begin rendering our culled scene. We need to specify the indirect buffer as a dependency to ensure proper compute-to-graphics buffer memory barriers:
// …buf.cmdBeginRendering(lvk::RenderPass{.color = {{ .loadOp = lvk::LoadOp_Clear,.storeOp = lvk::StoreOp_MsaaResolve,.clearColor = {1, 1, 1, 1}}},.depth = { .loadOp = lvk::LoadOp_Clear,.clearDepth = 1.0f } },framebufferMSAA,{ .buffers ={ BufferHandle(mesh.bufferIndirect_) } });// …
Note
The cmdBeginRendering() and cmdDispatchThreadGroups() functions are located in deps/src/lightweightvk/lvk/vulkan/VulkanClasses.cpp. Refer to this file to review which specific Vulkan memory barriers are inserted based on the buffer usage flags.
While the C++ code mentioned above is sufficient to drive our GPU-based culling, there’s one more interesting detail worth mentioning.
In the previous recipe, Doing frustum culling on the CPU, all culling was performed on the CPU, making it straightforward to compute the number of visible meshes. With GPU-based culling, this becomes a bit more complex, as we need to retrieve the visible mesh count from the GPU buffer back to the CPU. This value is already calculated and stored in the CullingData GPU buffer, in the CullingData::numVisibleMeshes field.
To read this value back efficiently, we access one of the previously used buffers where the compute shader has already finished execution. To achieve this, we created arrays of bufferCullingData[] round-robin buffers and submitHandle[] fences, which are wrapped into lvk::SubmitHandle. Let’s take a look at the code that uses them.
- After recording all the compute and rendering commands, we submit the command buffer, store the
SubmitHandleassociated with it, and advance to the nextcurrentBufferId:// …buf.cmdEndRendering();submitHandle[currentBufferId] = ctx->submit(buf, ctx->getCurrentSwapchainTexture());currentBufferId = (currentBufferId + 1) %LVK_ARRAY_NUM_ELEMENTS(bufferCullingData); - Next, we wait on the
SubmitHandlethat follows the submittedcurrentBufferIdcommand buffer. In other words, we check the Vulkan fence corresponding to a command buffer submitted one frame ago. By this point, the GPU has most likely finished processing that buffer, so the fence resolves quickly, allowing us to read the data back. TheVulkanContext::download()function copies the data from the mapped GPU buffer into anumVisibleMeshesvariable in RAM, while also properly invalidating non-coherent mapped memory if necessary. You can find its implementation in thedeps/src/lightweightvk/lvk/vulkan/VulkanClasses.cppfile:if (cullingMode == CullingMode_GPU &&app.fpsCounter_.numFrames_ > 1){ctx->wait(submitHandle[currentBufferId]);ctx->download(bufferCullingData[currentBufferId],&numVisibleMeshes, sizeof(uint32_t),offsetof(CullingData, numVisibleMeshes));}
Once the numVisibleMeshes value is updated, we can use it with ImGui to display the number of visible meshes computed on the GPU.
Note
It is important to highlight a significant inefficiency here. While the compute shader completes its task before rendering begins, we wait for the entire submitted command buffer, which includes both the compute and rendering stages. This could be optimized using Vulkan timeline semaphores, a feature that became core in Vulkan 1.2. However, at the time of writing this book, the LightweightVK framework does not yet support timeline semaphores.
Let’s now run the demo application. It should produce an image similar to the one shown in the following screenshot:

Figure 11.2: Bistro with GPU frustum culling
The culling frustum is frozen, and only the visible geometry is rendered. The visible AABBs are displayed in red, while the invisible ones are shown in green. You can fly around the scene and toggle the frustum freezing state using the P key.
You can switch between different culling modes using ImGui. If you run the sample app in a Release build and disable Vulkan validation layers using the Vulkan Configurator tool, you can perform basic performance measurements and compare the different culling modes. In most cases, the CPU culling outperforms the non-culled rendering. However, this naïve GPU culling implementation is typically slower than CPU culling. Our isAABBinFrustum() function has a lot of branching and is not optimized for SIMD, making it inefficient on the GPU. It is mainly for demonstration purposes, showing how to port C++ code to GLSL. However, performance can be significantly improved by either rewriting the code in a SIMD-friendly way or replacing AABB culling with simpler bounding sphere culling, which can be much more easily calculated using dot products in a branchless fashion. We leave it as an advanced exercise for you.
There’s more…
Section titled “There’s more…”Another optimization for frustum culling, apart from making the code SIMD-friendly, is to use multithreading on the CPU. This approach, often referred to as parallel-brute-force, can lead to significant performance improvements. For more details on this technique, check out the GDC 2011 Culling the Battlefield presentation by Daniel Collin.
It is important to note that the assumption in our GPU culling pipeline—that setting the number of instances in VkDrawIndexedIndirectCommand to 0 completely eliminates the penalty of rendering a mesh—is not accurate. In reality, simply setting the number of instances to 0 does not completely remove the associated GPU performance cost. To optimize this, one should consider compacting the indirect buffer by removing culled items or creating a new indirect buffer directly in the compute shader, using the atomic value of numVisibleMeshes as an index. This approach is particularly beneficial when culling is not performed every frame, and the buffer is reused across multiple frames.
There is an excellent SIGGRAPH 2015 presentation titled GPU-Driven Rendering Pipelines by Ulrich Haar and Sebastian Aaltonen, which provides an in-depth exploration of the use of compute functionality in rendering pipelines. It dives into various strategies and optimizations for efficient GPU-based rendering techniques: http://advances.realtimerendering.com/s2015/aaltonenhaar_siggraph2015_combined_final_footer_220dpi.pdf.
Implementing shadows for directional lights
Section titled “Implementing shadows for directional lights”In the previous chapter, we explored setting up a shadow mapping pipeline, focusing primarily on the API and the overall implementation process rather than achieving good shadow accuracy or versatility. In the Implementing shadow maps recipe from Chapter 10, we learned how to render shadows from spotlights using perspective projection for the shadow-casting light source. For directional light sources, which are often used to simulate sunlight, a single light source can illuminate the entire scene. Implementing shadows for such a light source requires constructing a projection matrix that accounts for the scene’s bounds. This recipe will explore how to implement this basic approach and incorporate shadows into our Bistro scene.
Getting ready
Section titled “Getting ready”Ensure you revisit the Implementing shadow maps recipe from Chapter 10 as we move forward into the shadow mapping topic.
The demo for this recipe can be found in Chapter11/03_DirectionalShadows.
How to do it…
Section titled “How to do it…”To construct a projection matrix for a directional light, we calculate the axis-aligned bounding box of the entire scene, transform it into light-space using the light’s view matrix, and then use the bounds of the transformed box to construct an orthographic frustum that fully encloses this box.
We calculate the scene bounding box in two simple steps:
- First, we pretransform the bounding boxes of individual meshes into world space. This step uses the same approach as outlined earlier for frustum culling in the Doing frustum culling on the GPU with compute shaders recipe:
std::vector<BoundingBox> reorderedBoxes;reorderedBoxes.resize(scene.globalTransform.size());for (auto& p : scene.meshForNode)reorderedBoxes[p.first] = meshData.boxes[p.second].getTransformed(scene.globalTransform[p.first]);
- Next, we combine all the pretransformed bounding boxes into one single large world-space bounding box:
BoundingBox bigBoxWS = reorderedBoxes.front();for (const auto& b : reorderedBoxes) {bigBoxWS.combinePoint(b.min_);bigBoxWS.combinePoint(b.max_);}
Since our scene is static, we do it just once, outside of the main rendering loop.
Now we can construct a projection matrix for our directional light source.
- The light’s direction can be adjusted in real time via ImGui controls, using two angles: the azimuthal angle,
theta, and the elevation angle,phi:struct LightParams {float theta = +90.0f;float phi = -26.0f;float depthBiasConst = 1.1f;float depthBiasSlope = 2.0f;bool operator==(const LightParams&) const = default;} light; - To construct the light’s view matrix, we first create two rotation matrices based on the
thetaandphiangles. These matrices are used to rotate a top-down light direction vector,(0, -1, 0), into the desired orientation. Using the resulting light direction, we build the light’s view matrix using theglm::lookAt()helper function. Since the light source encompasses the entire scene, its origin can be conveniently set to(0, 0, 0):const mat4 rot1 = glm::rotate(mat4(1.f),glm::radians(light.theta), vec3(0, 1, 0));const mat4 rot2 = glm::rotate(rot1,glm::radians(light.phi), vec3(1, 0, 0));const vec3 lightDir = glm::normalize(vec3(rot2 * vec4(0.0f, -1.0f, 0.0f, 1.0f)));const mat4 lightView =glm::lookAt(vec3(0, 0, 0), lightDir, vec3(0, 0, 1)); - With the light’s view matrix,
lightView, ready, we transform the scene’s world-space bounding box into light-space. Since Vulkan uses a clip coordinate space where the z axis ranges from0to1, we use theglm::orthoLH_ZO()helper function to create the projection matrix. However, this function follows the DirectX clip coordinate convention, so we must flip the z axis to match Vulkan’s expectations:const BoundingBox boxLS = bigBoxWS.getTransformed(lightView);const mat4 lightProj = glm::orthoLH_ZO(boxLS.min_.x, boxLS.max_.x,boxLS.min_.y, boxLS.max_.y,boxLS.max_.z, boxLS.min_.z); - The light’s view and projection matrices can be premultiplied and stored in a GPU buffer using the
LightDatastructure. The associated shadow map texture and sampler are set up similarly to the approach outlined in the Implementing shadow maps recipe from Chapter 10:struct LightData {mat4 viewProjBias;vec4 lightDir;uint32_t shadowTexture;uint32_t shadowSampler;};Holder<BufferHandle> bufferLight = ctx->createBuffer({.usage = lvk::BufferUsageBits_Storage,.storage = lvk::StorageType_Device,.size = sizeof(LightData),.debugName = "Buffer: light" }); - We create our
VKMesh11object for the scene and two pipelines: one for rendering the scene into the shadow map and another for rendering the scene normally into a swapchain image. Note that the shadow map pipeline is not multisampled:const VKMesh11 mesh(ctx, meshData, scene);const VKPipeline11 pipelineMesh(ctx, meshData.streams, ctx->getSwapchainFormat(),app.getDepthFormat(), kNumSamples,loadShaderModule(ctx,"Chapter11/03_DirectionalShadows/src/main.vert"),loadShaderModule(ctx,"Chapter11/03_DirectionalShadows/src/main.frag"));const VKPipeline11 pipelineShadow(ctx, meshData.streams, lvk::Format_Invalid,ctx->getFormat(shadowMap), 1,loadShaderModule(ctx,"Chapter11/03_DirectionalShadows/src/shadow.vert"),loadShaderModule(ctx,"Chapter11/03_DirectionalShadows/src/shadow.frag")); - The remaining shadow map rendering logic follows the same structure as in the previous Implementing shadow maps spotlight recipe from Chapter 10. The main difference is that the shadow map is updated only when the light parameters, direction angles, or depth bias, are changed via the ImGui UI, instead of being updated every frame. This is possible because our scene is static:
ICommandBuffer& buf = ctx->acquireCommandBuffer();if (prevLight != light) {prevLight = light;// … render Bistro into the shadow map here…mesh.draw(buf, pipelineShadow, lightView, lightProj);// …buf.cmdUpdateBuffer(bufferLight, LightData{.viewProjBias = scaleBias * lightProj * lightView,.lightDir = vec4(lightDir, 0.0f),.shadowTexture = shadowMap.index(),.shadowSampler = samplerShadow.index() });}
Here’s what a shadow map for the entire scene should look like when the theta and phi angles are set to 0:

Figure 11.3: A shadow map for a top-down directional light
Note how the light’s viewing frustum is fit to the scene bounds. If you start changing the light direction, it will still be fit to the transformed scene bounding box, but it won’t be tightly fit to the scene itself. This is because a transformed axis-aligned bounding box can contain more empty space, as the axes of the original box may no longer be aligned with the axes of the new coordinate system. One simple improvement for this can be calculating the combined scene bounding box directly in light space, from the individual AABBs of meshes transformed to light space, instead of first calculating the scene AABB in world space and then transforming it to light space. We leave this as a simple exercise for you.
The demo application for this recipe should render the following image.

Figure 11.4: The Bistro scene rendered with shadows from a directional light
Try changing the light direction and adjusting the depth bias parameters to observe how these changes affect the shadow quality and help mitigate artifacts. The directional light frustum is rendered in yellow to visualize the bounds of the light’s influence on the scene.
There’s more…
Section titled “There’s more…”The preceding screenshot uses an orthographic projection for the shadow map, which leads to aliasing issues despite a high shadow map resolution of 8192x8192. To improve shadow map quality, you can apply techniques such as Perspective Shadow Maps (PSMs), introduced by Stamminger and Drettakis at SIGGRAPH 2002. PSMs use post-projective space, causing nearby objects to occupy more space in the shadow map, reducing aliasing for objects close to the camera. Another advanced technique is Light Space Perspective Shadow Maps (https://www.cg.tuwien.ac.at/research/vr/lispsm), which further refines the concept to achieve better shadow quality across different depths.
To further reduce aliasing in shadow maps, a more generic technique is to divide the light frustum into multiple frustums or cascades, each covering a different range of distances from the camera. This method, known as Cascaded Shadow Maps (CSMs), involves rendering multiple shadow maps for different depth ranges and then applying the appropriate shadow map based on the viewer’s distance. Parallel Split Shadow Maps (PSSMs) are a variation of this approach, where the split of the frustum is more evenly distributed.
Moreover, perspective shadow maps and cascades can be combined into a single shadow mapping pipeline producing the best results. We recommend the book Real-Time Shadows https://www.realtimeshadows.com, which, despite its age, remains one of the best “all-in-one-place” references for shadow techniques.
Now, let’s move on to the next recipe, where we will explore an interesting technique for rendering transparent objects to improve the visual quality of our Bistro scene.
Implementing order-independent transparency
Section titled “Implementing order-independent transparency”Until now, we’ve rendered transparent objects using a basic punch-through transparency method, as described in the Rendering large scenes recipe from Chapter 8. While this approach was limited in quality, it allowed transparent and opaque objects to be rendered together without any additional care or sorting, greatly simplifying the rendering pipeline. Now, let’s take it a step further and implement a method that enables correctly blended transparent objects.
Alpha blending of multiple surfaces requires sorting all transparent surfaces back-to-front, which can be achieved through various methods. These include sorting scene objects back-to-front, using multi-pass depth peeling techniques, as described in https://matthewwellings.com/blog/depth-peeling-order-independent-transparency-in-vulkan, and employing order-independent approximations such as http://casual-effects.blogspot.com/2014/03/weighted-blended-order-independent.html and a more recent work, Phenomenological Transparency, by Morgan McGuire and Michael Mara (https://research.nvidia.com/publication/phenomenological-transparency).
In Vulkan, it is possible to implement order-independent transparency (OIT) using per-pixel linked lists via atomic counters and load-store-atomic read-modify-write operations on textures. This method is order-independent, meaning it eliminates the need to sort transparent geometry before rendering. Instead, all necessary sorting is performed in a fragment shader at the pixel level after the scene has been rendered. The algorithm works by constructing a linked list of fragments for each screen pixel, with each node storing color and depth values. Once these per-pixel lists are constructed, they can be sorted and blended using a fullscreen fragment shader. Essentially, this is a two-pass algorithm. Our implementation is inspired by https://fr.slideshare.net/hgruen/oit-and-indirect-illumination-using-dx11-linked-lists. Let’s take a closer look at how it works.
Getting ready
Section titled “Getting ready”We recommend revisiting the Implementing a material system recipe from Chapter 8 to refresh your understanding of the material system’s data structures. This example utilizes multiple indirect buffers with the VKMesh11 class, as described earlier in this chapter, in the Refactoring indirect rendering recipe.
The source code for this recipe is available in Chapter11/04_OIT.
How to do it…
Section titled “How to do it…”The rendering pipeline for this example proceeds as follows: first, we render opaque objects with standard shading, as done in the previous recipe. Next, we render transparent objects, adding shaded fragments to linked lists instead of rendering them directly to the framebuffer. Finally, we sort the linked lists and overlay the blended image onto the opaque framebuffer. To keep things simple, we omit shadows in this example and focus solely on transparency rendering and MSAA. We will combine OIT with shadows and other effects in the Putting it all together into a Vulkan demo recipe.
Let’s walk through the C++ code to implement this technique:
- The
main()function is similar to the one from theChapter10/03_MSAAexample and the Implementing MSAA in Vulkan recipe from Chapter 10. We use aVKMesh11object and two pipelines with two sets of shaders: the first set,main.vertandopaque.frag, is for opaque objects, while the second set,main.vertandtransparent.frag, is for transparent objects:const VKMesh11 mesh(ctx, meshData, scene);const VKPipeline11 pipelineOpaque(ctx, meshData.streams, ctx->getSwapchainFormat(),app.getDepthFormat(), kNumSamples,loadShaderModule(ctx, "Chapter11/04_OIT/src/main.vert"),loadShaderModule(ctx, "Chapter11/04_OIT/src/opaque.frag"));const VKPipeline11 pipelineTransparent(ctx, meshData.streams, ctx->getSwapchainFormat(),app.getDepthFormat(), kNumSamples,loadShaderModule(ctx, "Chapter11/04_OIT/src/main.vert"),loadShaderModule(ctx, "Chapter11/04_OIT/src/transparent.frag")); - A fullscreen post-processing pass is handled in
GL03_OIT.frag. We will examine the shaders after reviewing the C++ code:Holder<ShaderModuleHandle> vertOIT =loadShaderModule(ctx, "data/shaders/QuadFlip.vert");Holder<ShaderModuleHandle> fragOIT =loadShaderModule(ctx, "Chapter11/04_OIT/src/oit.frag");Holder<RenderPipelineHandle> pipelineOIT = ctx->createRenderPipeline({.smVert = vertOIT,.smFrag = fragOIT,.color ={ { .format = ctx->getSwapchainFormat() } } }); - Let’s create two
VKIndirectBuffer11objects, as described in the Refactoring indirect rendering recipe: one for opaque meshes and another for transparent ones. A simple C++isTransparent()lambda can be used to filter draw commands based on thesMaterialFlags_Transparentflag in the material flags. This flag was set by theconvertAIMaterial()helper function from Chapter 8 during the import of the Bistro mesh:VKIndirectBuffer11 meshesOpaque(ctx, mesh.numMeshes_);VKIndirectBuffer11 meshesTransparent(ctx, mesh.numMeshes_);auto isTransparent = [&meshData, &mesh](const DrawIndexedIndirectCommand& c) -> bool {const uint32_t mtlIndex = mesh.drawData_[c.baseInstance].materialId;const Material& mtl = meshData.materials[mtlIndex];return (mtl.flags & sMaterialFlags_Transparent) > 0;};mesh.indirectBuffer_.selectTo(meshesOpaque,[&isTransparent](const DrawIndexedIndirectCommand& c) -> bool {return !isTransparent(c);});mesh.indirectBuffer_.selectTo(meshesTransparent,[&isTransparent](const DrawIndexedIndirectCommand& c) -> bool {return isTransparent(c);}); - In addition to multiple indirect buffers, we need a few other buffers to store linked list data. The C++
TransparentFragmentstructure will mirror the same structure in our GLSL shaders, representing a single node of a per-pixel linked list. We need a floating-point color value with an alpha channel to support HDR reflections on transparent objects, along with a depth value and an index for the next node. The RGBA color is stored as auint64_t, which corresponds to the four-componentf16vec4half-float vector in GLSL. In the C++ code, we don’t actually need to worry about these member fields; we only need to know the structure’s size in order to allocate a buffer for it:Note In real-world applications, 16-bit floats for color channels are often replaced with 10-bit packed formats, such asstruct TransparentFragment {uint64_t rgba;float depth;uint32_t next;};VK_FORMAT_A2R10G10B10_UNORM_PACK32, to save memory bandwidth. In C++, this can be mimicked usinguint32_t. However, we avoid using this approach here to simplify our HDR rendering code. - The buffer allocation proceeds as follows: we allocate storage to accommodate
kMaxOITFragmentstransparent fragments, which corresponds to4overdraw layers. This totals roughly225Mbof memory in 4K resolution. Any fragments beyond this limit will be discarded by our fragment shader, which performs bounds checking:const uint32_t kMaxOITFragments =sizeFb.width * sizeFb.height * 4;Holder<BufferHandle> bufferTransparencyLists = ctx->createBuffer({.usage = lvk::BufferUsageBits_Storage,.storage = lvk::StorageType_Device,.size = sizeof(TransparentFragment) * kMaxOITFragments,.debugName = "Buffer: transparency lists",});
The textureHeadsOIT texture is a fullscreen uint32_t texture that contains integer indices (which index into the bufferTransparencyLists buffer) for the head elements of the per-pixel linked lists corresponding to each screen pixel. Note that this image does not have either the Sampled or Attachment usage flags, as it is only accessed with image load-store operations:
Holder<TextureHandle> textureHeadsOIT = ctx->createTexture({ .format = lvk::Format_R_UI32, .dimensions = sizeFb, .usage = lvk::TextureUsageBits_Storage, .debugName = "oitHeads" });The bufferAtomicCounter contains a single 32-bit integer that tracks the total number of allocated transparent fragments so far and acts as an atomic counter in a linear memory allocator implemented in the GLSL shader. The bufferTransparencyLists is the actual memory pool used to store linked lists created by our allocator:
Holder<BufferHandle> bufferAtomicCounter = ctx->createBuffer({ .usage = lvk::BufferUsageBits_Storage, .storage = lvk::StorageType_Device, .size = sizeof(uint32_t), .debugName = "Buffer: atomic counter" });- Each frame, we should reset the atomic counter to
0and clear the heads buffer with the value0xFFFFFFFF, which acts as an end-of-list guard value to signal that there are no more transparent fragments for that pixel. Here is a C++ lambda to accomplish this:auto clearTransparencyBuffers = [&bufferAtomicCounter,&textureHeadsOIT, sizeFb](lvk::ICommandBuffer& buf){buf.cmdClearColorImage(textureHeadsOIT, { .uint32 = { 0xffffffff } });buf.cmdFillBuffer(bufferAtomicCounter, 0, sizeof(uint32_t), 0);}; - With all the preparations complete, we can now enter the rendering loop and clear the transparency buffers:
app.run([&](uint32_t width, uint32_t height,float aspectRatio, float deltaSeconds){const mat4 view = app.camera_.getViewMatrix();const mat4 proj = glm::perspective(45.f, aspectRatio, 0.1f, 200.f);ICommandBuffer& buf = ctx->acquireCommandBuffer();clearTransparencyBuffers(buf);
- Scene rendering can proceed as usual by first drawing the skybox, followed by the opaque meshes of the Bistro scene using the corresponding indirect buffer:
const lvk::Framebuffer framebufferMSAA = {.color = { { .texture = msaaColor,.resolveTexture = offscreenColor } },.depthStencil = { .texture = msaaDepth },};buf.cmdBeginRendering(lvk::RenderPass{.color = {{.loadOp = lvk::LoadOp_Clear,.storeOp = lvk::StoreOp_MsaaResolve,.clearColor = {1.f, 1.f, 1.f, 1.f}}},.depth = { .loadOp = lvk::LoadOp_Clear,.clearDepth = 1.0f } },framebufferMSAA);skyBox.draw(buf, view, proj);
- Push constants are shared between the opaque and transparent pipelines:
const struct {mat4 viewProj;vec4 cameraPos;uint64_t bufferTransforms;uint64_t bufferDrawData;uint64_t bufferMaterials;uint64_t bufferAtomicCounter;uint64_t bufferTransparencyLists;uint32_t texSkybox;uint32_t texSkyboxIrradiance;uint32_t texHeadsOIT;uint32_t maxOITFragments;} pc = {.viewProj = proj * view,.cameraPos = vec4(app.camera_.getPosition(), 1.f),.bufferTransforms = ctx->gpuAddress(mesh.bufferTransforms_),.bufferDrawData = ctx->gpuAddress(mesh.bufferDrawData_),.bufferMaterials = ctx->gpuAddress(mesh.bufferMaterials_),.bufferAtomicCounter = ctx->gpuAddress(bufferAtomicCounter),.bufferTransparencyLists = ctx->gpuAddress(bufferTransparencyLists),.texSkybox = skyBox.texSkybox.index(),.texSkyboxIrradiance = skyBox.texSkyboxIrradiance.index(),.texHeadsOIT = textureHeadsOIT.index(),.maxOITFragments = kMaxOITFragments,};
- Opaque and transparent meshes use different depth states. The opaque meshes update the depth buffer, while the transparent meshes output everything with overdraw. Later, we will see how to sort them in the fragment shader. The key point is that transparent objects need to be properly depth-culled against opaque objects:
if (drawMeshesOpaque)mesh.draw(buf, pipelineOpaque, &pc, sizeof(pc),{ .compareOp = lvk::CompareOp_Less,.isDepthWriteEnabled = true },drawWireframe, &meshesOpaque);if (drawMeshesTransparent)mesh.draw(buf, pipelineTransparent, &pc, sizeof(pc),{ .compareOp = lvk::CompareOp_Less,.isDepthWriteEnabled = false },drawWireframe, &meshesTransparent);
- The grid can be rendered normally after all objects, as the transparent objects don’t modify the color and depth buffers; they simply store their output in per-pixel lists:
app.drawGrid(buf, proj, vec3(0, -1.0f, 0), kNumSamples);buf.cmdEndRendering();
Now, after the first render pass, we have the MSAA color values resolved in the offscreenColor texture and our OIT buffers populated with transparent fragments. Next, we run the second pass, a fullscreen post-processing step, which sorts transparent fragments and blends them together. Here, we combine and render everything directly into a swapchain image:
const lvk::Framebuffer framebufferMain = { .color = { { .texture = ctx->getCurrentSwapchainTexture() } },};buf.cmdBeginRendering( lvk::RenderPass{ .color = {{ .loadOp = lvk::LoadOp_Load, .storeOp = lvk::StoreOp_Store }} }, framebufferMain,- We need barriers for textures and buffers. The
offscreenColortexture will be transitioned fromVK_IMAGE_LAYOUT_ATTACHMENT_OPTIMALtoVK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL. ThetextureHeadsOITtexture has theVK_IMAGE_LAYOUT_GENERALimage layout and will only require an image memory barrier without any layout transition to ensure execution dependency between the two passes. ThebufferTransparencyListsstorage buffer requires a memory barrier to ensure that subsequent reads from the linked lists stored in it can correctly access the data written by the first render pass. ThebufferAtomicCounterbuffer is not used in the fullscreen pass, so we can skip it:{ .textures = { TextureHandle(textureHeadsOIT),TextureHandle(offscreenColor) },.buffers = { BufferHandle(bufferTransparencyLists) }}); - The fullscreen pass shader uses a different set of push constants. We’ve added a useful debugging feature—a blinking opacity heatmap overlay—to show how many transparent pixels are drawn at each screen pixel. To implement this, we pass the current time to the shader:
const struct {uint64_t bufferTransparencyLists;uint32_t texColor;uint32_t texHeadsOIT;float time;float opacityBoost;uint32_t showHeatmap;} pcOIT = {.bufferTransparencyLists = ctx->gpuAddress(bufferTransparencyLists),.texColor = offscreenColor.index(),.texHeadsOIT = textureHeadsOIT.index(),.time = static_cast<float>(glfwGetTime()),.opacityBoost = opacityBoost,.showHeatmap = showHeatmap ? 1u : 0u,};
- Next, we can draw our fullscreen triangle and render the ImGui UI on top. We’ll skip the UI code here for brevity:
buf.cmdBindRenderPipeline(pipelineOIT);buf.cmdPushConstants(pcOIT);buf.cmdBindDepthState({});buf.cmdDraw(3);app.imgui_->beginFrame(framebufferMain);app.drawFPS();app.drawMemo();// … we skip all the ImGui UI rendering hereapp.imgui_->endFrame(buf);buf.cmdEndRendering();}ctx->submit(buf, ctx->getCurrentSwapchainTexture());
That’s it for the C++ part. Now, let’s switch to the GLSL code and examine how it works to handle transparent objects.
How it works…
Section titled “How it works…”There are some shared GLSL declarations in the common_oit.sp and common.sp files, which are used across our shaders. Let’s take a look at them.
- The
Chapter11/04_OIT/src/common_oit.spfile is shared between both transparent shaders: the one for rendering transparent meshes and the fullscreen one. It declares theTransparentFragmentstructure, similar to the C++ version, along with a buffer to hold it:struct TransparentFragment {f16vec4 color;float depth;uint next;};layout(std430, buffer_reference)buffer TransparencyListsBuffer {TransparentFragment frags[];}; - The
Chapter11/04_OIT/src/common.spfile is shared between the shaders for rendering both opaque and transparent meshes. It uses theDrawDatastructure, which is maintained by theVKMesh11class. If you want to recap how these buffers work, refer to the Refactoring indirect rendering recipe and Chapter 8:#include <data/shaders/gltf/common_material.sp>#include <Chapter11/04_OIT/src/common_oit.sp>struct DrawData {uint transformId;uint materialId;};layout(std430, buffer_reference) readonly buffer TransformBuffer {mat4 model[];};layout(std430, buffer_reference) readonly buffer DrawDataBuffer {DrawData dd[];};layout(std430, buffer_reference) readonly buffer MaterialBuffer {MetallicRoughnessDataGPU material[];};layout(std430, buffer_reference) buffer AtomicCounter {uint numFragments;};layout(push_constant) uniform PerFrameData {mat4 viewProj;vec4 cameraPos;TransformBuffer transforms;DrawDataBuffer drawData;MaterialBuffer materials;AtomicCounter atomicCounter;TransparencyListsBuffer oitLists;uint texSkybox;uint texSkyboxIrradiance;uint texHeadsOIT;uint maxOITFragments;} pc;
Now, let’s take a look at the actual GLSL shaders used for rendering. The first fragment shader, Chapter11/04_OIT/src/transparent.frag, is responsible for rendering transparent meshes and populating the per-pixel linked lists. Let’s go through the source code to clarify how it works:
- The
early_fragment_testslayout specifier ensures that the fragment shader is not executed unnecessarily if the fragment is discarded based on the depth test. This is crucial because any redundant invocation of this shader could result in corrupted transparency lists. ThekTextures2DInOut[]array is needed to access ourtextureHeadsOITstorage image in a bindless fashion:#include <Chapter11/04_OIT/src/common.sp>#include <data/shaders/UtilsPBR.sp>layout (early_fragment_tests) in;layout (set = 0, binding = 2, r32ui) uniform uimage2D kTextures2DInOut[];layout (location=0) in vec2 uv;layout (location=1) in vec3 normal;layout (location=2) in vec3 worldPos;layout (location=3) in flat uint materialId; - Here’s a helper function to slightly improve the ad hoc reflections in the glass. Its sole purpose is to make things a bit shinier. If you want to make reflections more realistic, refer to Chapter 6:
vec3 fresnelSchlickRoughness(float cosTheta, vec3 F0, float roughness) {return F0 +(max(vec3(1.0 - roughness), F0) - F0) *pow(clamp(1.0 - cosTheta, 0.0, 1.0), 5.0);}void main() {MetallicRoughnessDataGPU mat = pc.materials.material[materialId];vec4 emissiveColor =vec4(mat.emissiveFactorAlphaCutoff.rgb, 0) *textureBindless2D(mat.emissiveTexture, 0, uv);vec4 baseColor = mat.baseColorFactor *(mat.baseColorTexture > 0 ?textureBindless2D(mat.baseColorTexture, 0, uv) :vec4(1.0));
- This includes some simple normal mapping, as described in the Implementing the glTF 2.0 metallic-roughness shading model recipe from Chapter 6 along with two hardcoded directional lights. We will replace these with a proper light source and shadows later, in the Putting it all together into a Vulkan demo recipe:
vec3 n = normalize(normal);vec3 normalSample = textureBindless2D(mat.normalTexture, 0, uv).xyz;if (length(normalSample) > 0.5)n = perturbNormal(n, worldPos, normalSample, uv);float NdotL1 = clamp(dot(n, normalize(vec3(-1, 1,+0.5))), 0.1, 1.0);float NdotL2 = clamp(dot(n, normalize(vec3(+1, 1,-0.5))), 0.1, 1.0);float NdotL = 0.2 * (NdotL1+NdotL2);
- Similarly, we use hacky IBL diffuse lighting here and environment reflections for transparent objects. We’re not aiming for any kind of PBR accuracy, but rather keeping it simple and shiny while focusing on transparency:
const vec4 f0 = vec4(0.04);vec3 sky = vec3(-n.x, n.y, -n.z); // rotate skyboxvec4 diffuse = baseColor * (vec4(1.0) - f0) * (textureBindlessCube(pc.texSkyboxIrradiance,0,sky) + vec4(NdotL) );vec3 v = normalize(pc.cameraPos.xyz - worldPos);vec3 reflection = reflect(v, n);reflection = vec3(reflection.x, -reflection.y,reflection.z); // rotate reflectionvec3 colorRefl = textureBindlessCube(pc.texSkybox, 0, reflection).rgb;vec3 kS = fresnelSchlickRoughness(clamp(dot(n, v), 0.0, 1.0), vec3(f0), 0.1);vec3 color = emissiveColor.rgb + diffuse.rgb + colorRefl * kS;
- The
colorvalue we calculated represents the color of our transparent fragment. Now, let’s insert it into the corresponding per-pixel linked list based on its transparency. We clamp the alpha value between0.01and0.99to reduce the number of transparent fragments stored in the transparency lists:float alpha = clamp(baseColor.a * mat.clearcoatTransmissionThickness.z,0.0, 1.0);bool isTransparent = (alpha > 0.01) && (alpha < 0.99); - Here comes the interesting part. Our transparent mesh rendering shader runs on an MSAA render target. Instead of storing all multisampled fragments in the transparency lists, which would increase memory consumption and bandwidth for our
8xMSAA, we store only those samples fully covered by this fragment shader invocation. To do this, we construct the current sample mask using the built-in GLSLgl_SampleIDvariable and compare it with thegl_SampleMaskIn[0]array element, which contains the computed sample coverage mask for the current fragment.
Note
A sample bit is set in this mask if and only if the sample is considered covered for this fragment shader invocation. Bit B of mask gl_SampleMask[M] corresponds to sample 32 * M + B. The array has ceil(s/32) elements, where s is the maximum number of color samples supported by the implementation. We use 8x MSAA, so we can take only the gl_SampleMaskIn[0] element.
The gl_HelperInvocation value indicates whether the fragment shader invocation is considered a helper invocation. We don’t want to modify our transparency lists for these helper fragment shader invocations:
Note
A helper invocation is a fragment shader invocation created solely for evaluating derivatives. These derivatives are computed implicitly in the built-in texture() GLSL function and explicitly in the dFdx() and dFdy() derivative functions.
if ( isTransparent && !gl_HelperInvocation && gl_SampleMaskIn[0] == (1 << gl_SampleID) ) {- Once we decide to add a new element to a per-pixel list corresponding to the current fragment, we need to allocate memory for it. To do this, we use the
bufferAtomicCounter, which holds a singleuint32_tvalue. This value is atomically incremented to obtain the index of the next available slot in the transparent fragments buffer:uint index =atomicAdd(pc.atomicCounter.numFragments, 1); - If the index we obtained is still within the max bounds of the buffer, we proceed with the write. To do this, we extract the old head of the
prevIndexlinked list and atomically replace it with the new head, which is now stored in the transparency buffer at the location of the index. TheprevIndexvalue will become the next pointer of our list:if (index < pc.maxOITFragments) {uint prevIndex = imageAtomicExchange(kTextures2DInOut[pc.texHeadsOIT], ivec2(gl_FragCoord.xy), index);TransparentFragment frag;frag.color = f16vec4(color, alpha);frag.depth = gl_FragCoord.z;frag.next = prevIndex;pc.oitLists.frags[index] = frag;}}}
Now the per-pixel list is constructed. Note that this shader performs only image load-store operations without modifying any of the color and depth buffers directly.
Once we have populated the linked lists, let’s learn how to sort and blend them to combine everything into the resulting image. This is done in a fullscreen pass in the Chapter11/04_OIT/src/oit.frag shader.
- The fragment shader inputs contain the
texColorcolor texture, which holds all opaque objects rendered. ThetexHeadsOITtexture contains the heads of per-pixel lists, andoitListsis our transparency buffer:#include <Chapter11/04_OIT/src/common_oit.sp>layout (set = 0, binding = 2, r32ui)uniform uimage2D kTextures2DIn[];layout (location=0) in vec2 uv;layout (location=0) out vec4 out_FragColor;layout (push_constant) uniform PushConstants {TransparencyListsBuffer oitLists;uint texColor;uint texHeadsOIT;float time;float opacityBoost;uint showHeatmap;} pc; - The
main()function starts by extracting the linked list for the current pixel into a local array. This is done in a loop until we reach the0xFFFFFFFFguard marker or the maximal number of overlapping transparent fragments,MAX_FRAGMENTS. The number of extracted fragments is stored innumFragments:#define MAX_FRAGMENTS 64void main() {TransparentFragment frags[MAX_FRAGMENTS];uint numFragments = 0;uint idx = imageLoad(kTextures2DIn[pc.texHeadsOIT], ivec2(gl_FragCoord.xy)).r;while (idx != 0xFFFFFFFF && numFragments < MAX_FRAGMENTS) {frags[numFragments] = pc.oitLists.frags[idx];numFragments++;idx = pc.oitLists.frags[idx].next;} - Let’s sort the array by depth using insertion sort from largest to smallest. This is efficient, given that we have a relatively small number of overlapping fragments:
for (int i = 1; i < numFragments; i++) {TransparentFragment toInsert = frags[i];uint j = i;while (j > 0 && toInsert.depth > frags[j-1].depth) {frags[j] = frags[j-1];j--;}frags[j] = toInsert;}
- Now we can blend the sorted fragments together. First, retrieve the color of the closest non-transparent object from the framebuffer. Then, traverse the array, blending the colors based on their alpha values. Clamping to the range
0…1is necessary to prevent any HDR values from leaking into the alpha channel:vec4 color = textureBindless2D(pc.texColor, 0, uv);for (uint i = 0; i < numFragments; i++) {color = mix( color, vec4(frags[i].color),clamp(float(frags[i].color.a+pc.opacityBoost),0.0, 1.0) );} - Lastly, we can apply our debugging transparency heatmap to visualize the overdraw level for each pixel. This heatmap helps demonstrate how many transparent fragments are being processed at each pixel location:
if (pc.showHeatmap > 0 && numFragments > 0)color = (1.0+sin(5.0*pc.time)) * vec4(vec3(numFragments, numFragments, 0), 0) / 16.0;out_FragColor = color;}
That’s all the shader code necessary to implement order-independent transparency using per-pixel linked lists. The running demo application should render an image similar to the one shown in the following screenshot.

Figure 11.5: Looking inside the Bistro with order-independent transparency
Make sure you move the camera inside the bar to check the bottles and glasses on the tables and the windows and observe how all of these objects can overlay each other.
There’s more…
Section titled “There’s more…”While this transparency method gives pixel-perfect blending results, it requires a staggering amount of memory to handle large resolutions and the depth complexity of overlapping transparent objects. This makes it very unfriendly for rendering on mobile and power-limited devices, where other methods involving transparency approximations are more commonly used. For alternative methods to optimize OIT on mobile, search for Per-Fragment Layered Sorting (PLS) and Layered Depth Images (LDI).
Loading texture assets asynchronously
Section titled “Loading texture assets asynchronously”All our demos so far preload all texture assets at startup, which works fine for applications with small data sizes that can be loaded instantly. Indeed, we downscaled all the Bistro textures to 512x512. However, as content size enters the gigabyte range, it becomes desirable to implement lazy-loading or streaming mechanisms to load assets as needed. Let’s enhance our demos with basic lazy-loading functionality that allows textures to load while the application continues rendering the scene. Multithreading will leverage the Taskflow library along with standard C++20 capabilities. To make the example more relevant and the graphics more visually appealing, we’ll also increase the dimensions of our compressed textures to 2048x2048.
Getting ready
Section titled “Getting ready”We recommend revisiting the Multithreading with Taskflow recipe from Chapter 1.
The source code for this recipe is located in Chapter11/05_LazyLoading.
How to do it…
Section titled “How to do it…”To simplify the implementation, our approach is to replace the VKMesh11 class, which handled all texture loading synchronously, with a new VKMesh11Lazy class, capable of loading textures asynchronously. This new class will subclass VKMesh11, replacing the texture loading logic in the constructor with an asynchronous mechanism. It will also include helper functions to create Vulkan textures from the loaded texture data. The new VKMesh11Lazy class is designed as a drop-in replacement for VKMesh11. Let’s examine the declaration of this new scene-loading class in the Chapter11/VKMesh11Lazy.h file:
- First, we need to divide our monolith texture creation process into two distinct parts: loading the texture data and creating a Vulkan texture from it. This separation is essential because textures can only be created on the main thread. To facilitate this, we introduce a data container to store the loaded
.ktxtexture data:struct LoadedTextureData {uint32_t index = 0;ktxTexture1* ktxTex = nullptr;lvk::TextureDesc desc;}; - We introduce a
loadTextureData()helper function, which loads a.ktxfile using the KTX-Software library and returns the loaded data. Since we precompressed all Bistro textures into BC7 and stored them into theKTXformat, this KTX-only approach is sufficient for our needs. This function closely resembles theloadTexture()function fromshared/Utils.h, with the key difference being that it does not create a Vulkan texture:LoadedTextureData loadTextureData(const char* fileName){ktxTexture1* ktxTex = nullptr;ktxTexture1_CreateFromNamedFile(fileName,KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT, &ktxTex);const lvk::Format format = {switch (glInternalFormat) {case GL_COMPRESSED_RGBA_BPTC_UNORM:return lvk::Format_BC7_RGBA;case GL_RGBA8:return lvk::Format_RGBA_UN8;// … handle other formats here}return lvk::Format_Invalid;}(ktxTex->glInternalformat);return LoadedTextureData{.ktxTex = ktxTex,.desc = { .type = lvk::TextureType_2D,.format = format,.dimensions = { ktxTex->baseWidth,ktxTex->baseHeight, 1 },.usage = lvk::TextureUsageBits_Sampled,.numMipLevels = ktxTex->numLevels,.data = ktxTex->pData,.dataNumMipLevels = ktxTex->numLevels,.debugName = fileName} };}
The Lo adedTextureData structure encapsulates all the information needed to create a texture, as it includes an lvk::TextureDesc object—an argument for the VulkanContext::createTexture() function, which handles the creation of all necessary Vulkan objects for a texture. This operation will be performed on the main thread.
- Let’s introduce another helper function,
convertToGPUMaterialLazy(), which will run on the loader thread. This function closely mirrors the existingconvertToGPUMaterial()function from Chapter 8. However, it usesloadTextureData()instead ofloadTexture(). All parameters remain unchanged, except forloadedTextureDataandloadingMutex, which serves as a mutex to safeguard multithreaded access to theTextureCacheandLoadedTextureDataobjects:GLTFMaterialDataGPU convertToGPUMaterialLazy(const std::unique_ptr<lvk::IContext>& ctx,const Material& mat,const TextureFiles& files,TextureCache& cache,std::vector<LoadedTextureData>& loadedTextureData,std::mutex& loadingMutex){ - Populate the
GLTFMaterialDataGPUstructure similarly to how it was handled inconvertToGPUMaterial(). For brevity, we omit the detailed parameter conversions as there’s no value in duplicating them here. By default, the fields ofGLTFMaterialDataGPUare initialized to0. This setup ensures that any textures not yet loaded will be automatically rendered as white textures, thanks to the0index, which corresponds to a white dummy texture. This behavior simplifies the rendering process, as no additional checks or logic are needed to handle textures that haven’t been loaded yet:GLTFMaterialDataGPU result = {.baseColorFactor = mat.baseColorFactor,// …}; - The local
startLoadingTexture()lambda function ensures that texture data is loaded only if it isn’t already present in the texture cache and isn’t currently waiting in theloadedTextureDataqueue:auto startLoadingTexture = [&cache, &ctx, &files,&loadedTextureData, &loadingMutex](int textureId){if (textureId == -1) return;if (cache.size() <= textureId)cache.resize(textureId+1);const bool notInCache = cache[textureId].empty();const bool notInQueue = notInCache ?std::find_if(loadedTextureData.cbegin(),loadedTextureData.cend(),[textureId](const LoadedTextureData& d) {return d.index == textureId;}) == loadedTextureData.end() : false;if (notInCache && notInQueue) {loadedTextureData.push_back(loadTextureData(files[textureId].c_str()));loadedTextureData.back().index = textureId;}}; - All manipulations on the texture cache and the list of loaded textures should be performed while holding a locked mutex:
std::lock_guard lock(loadingMutex);startLoadingTexture(mat.baseColorTexture);startLoadingTexture(mat.emissiveTexture);startLoadingTexture(mat.normalTexture);startLoadingTexture(mat.opacityTexture);return result;}
Now that we have all the necessary functions, let’s take a look at how the new VKMesh11Lazy class works to implement asynchronous loading.
How it works…
Section titled “How it works…”The new VKMesh11Lazy class is derived from VKMesh11 and adds new data members, along with changes to the constructor and a new member function. Let’s take a closer look:
- The new data members handle multithreading. The mutex protects the entire asynchronous loading process. The
loadedTextureData_vector holds texture data that has been loaded and is waiting to be processed on the main thread, where the actual textures will be created. Thetf::Taskflowobject drives the Taskflow library, and thetf::Executorobject is a thread pool with2loader threads:class VKMesh11Lazy final : public VKMesh11 {public:std::mutex loadingMutex_;std::vector<LoadedTextureData> loadedTextureData_;tf::Taskflow taskflow_;tf::Executor executor_{ size_t(2) };
Note
For simplicity, we store an instance of tf::Executor here. However, when there are many instances of VKMesh11Lazy, it is better to use an external executor shared by all mesh instances.
- The constructor has the same parameters as
VKMesh11, except for the last one – thepreloadMaterialsBoolean flag. This flag is not used here, and the one in the base class constructor is set tofalseto disable any texture loading in the base class:VKMesh11Lazy(const std::unique_ptr<lvk::IContext>& ctx,const MeshData& meshData, const Scene& scene,lvk::StorageType indirectBufferStorage = lvk::StorageType_Device): VKMesh11(ctx, meshData, scene,indirectBufferStorage, false){materialsGPU_.resize(materialsCPU_.size()); - Instead of loading the materials along with all the textures, let’s populate the
Taskflowobject using thefor_each_index()algorithm for all available materials. For each material, we will call theconvertToGPUMaterialLazy()function we defined earlier:taskflow_.for_each_index(0u,static_cast<uint32_t>(materialsCPU_.size()), 1u,[&](int i) {materialsGPU_[i] = convertToGPUMaterialLazy(ctx, materialsCPU_[i], textureFiles_,textureCache_, loadedTextureData_, loadingMutex_);}); - At the end of the constructor, we can begin the multithreaded execution:
executor_.run(taskflow_);}
- To process the loaded texture data, we need to call the
processLoadedTextures()method from the main thread. This method processes one loaded texture at a time to avoid stuttering when handling too many textures per frame:bool processLoadedTextures() {LoadedTextureData tex; - Note the extra C++ scope here, which controls the duration of the mutex lock. We want to extract the loaded texture data while the mutex is locked, but we avoid calling any heavy methods from the main thread while the mutex is locked. Since the order of texture loading doesn’t matter, we simply use
pop_back()instead of managing a proper queue:{std::lock_guard lock(loadingMutex_);if (loadedTextureData_.empty()) return false;tex = loadedTextureData_.back();loadedTextureData_.pop_back();} - Let’s create the actual texture and then destroy the loaded texture data, as it is no longer needed:
Holder<TextureHandle> texture = ctx->createTexture(tex.desc);ktxTexture_Destroy(ktxTexture(tex.ktxTex));
- To update our texture cache and texture IDs in GPU materials, we need to lock the mutex again. This helper
getTextureFromCache()local lambda is used to make the code cleaner:std::lock_guard lock(loadingMutex_);textureCache_[tex.index] = std::move(texture);auto getTextureFromCache = [this](int textureId) -> uint32_t {return textureCache_.size() > textureId ?textureCache_[textureId].index() : 0;}; - Next, we go through all the materials and update them using the texture IDs from the cache. This is necessary because a single loaded texture can be referenced by multiple materials. Since we don’t track their relationships, the simplest approach is to update them all—there’s not much work involved:
for (size_t i = 0; i != materialsCPU_.size(); i++) {const Material& mtl = materialsCPU_[i];GLTFMaterialDataGPU& m = materialsGPU_[i];m.baseColorTexture = getTextureFromCache(mtl.baseColorTexture);m.emissiveTexture = getTextureFromCache(mtl.emissiveTexture);m.normalTexture = getTextureFromCache(mtl.normalTexture);m.transmissionTexture = getTextureFromCache(mtl.opacityTexture);}
- Once the
std::vectormaterialsGPU_container with GPU materials is updated, it can be uploaded into the corresponding GPU buffer, which is managed in theVKMesh11base class:ctx->upload(bufferMaterials_,materialsGPU_.data(),materialsGPU_.size() *sizeof(decltype(materialsGPU_)::value_type));return true;}};
As mentioned at the beginning, the new VKMesh11Lazy class is a drop-in replacement for VKMesh11. In fact, we only need to change two lines of C++ code:
- The first line is to replace the mesh declaration as follows:
VKMesh11Lazy mesh(ctx, meshData, scene);
- The second line, added at the very beginning of the rendering loop, is needed to poll
processLoadedTextures()every frame to check for loaded textures:app.run([&](uint32_t width, uint32_t height,float aspectRatio, float deltaSeconds){mesh.processLoadedTextures();// …
And that’s it. By changing just a few lines of code, our demo now supports asynchronous texture loading. All the code is complete and ready to be tested. Let’s run the Chapter11/05_LazyLoading demo application to see how the Bistro scene can be rendered with lazy-loaded textures. When you run the demo, the geometry data will be loaded and rendered almost instantly, producing an image like the one in the following screenshot:

Figure 11.6: The Bistro scene rendered with asynchronous texture loading
You can navigate the demo with the keyboard and mouse while all the textures are streamed in within a few moments. This functionality, while essential for any serious rendering engine, is also very useful for smaller-scale applications, as the ability to quickly rerun the app significantly improves debugging capabilities.
There’s more…
Section titled “There’s more…”The asynchronous texture loading approach presented here offers much better responsiveness compared to preloading the entire texture pool at startup. However, a better approach might be to precreate empty textures and load images directly into these memory regions, especially since our data is already compressed into the BC7 format. This could be an interesting exercise for you.
Another improvement could be made in the main loop. Instead of polling the processLoadedTextures() method every frame, texture updates could be integrated into the events system of your rendering engine. Additionally, rather than loading just one texture per iteration, a “load balancer” could be implemented to upload multiple textures to the GPU, with the number of textures determined by their sizes using heuristics. We recommend increasing the max texture size of the demo app to 4096x4096 so you can experiment with this approach on a much heavier dataset.
One important thing to note is that our asynchronous loading mechanism only loads preprocessed, compressed textures in the .ktx format. This means that during the first run of the demo, you’ll need to wait until all the textures are compressed. This can be avoided by integrating texture compression with asynchronous loading. You can try this as an exercise, or refer to the LightweightVK samples to see how it is done: https://github.com/corporateshark/lightweightvk/tree/master/samples.
Putting it all together into a Vulkan demo
Section titled “Putting it all together into a Vulkan demo”To wrap up our minimalist Vulkan rendering engine, we’ll bring together the techniques covered in Chapters 8, 10, and 11 into one demo application.
Our final Vulkan demo application showcases the Lumberyard Bistro scene with the following techniques and effects:
- Multisample anti-aliasing (MSAA)
- Screen-space ambient occlusion (SSAO)
- HDR rendering with light adaptation
- Directional shadow mapping with percentage-closer filtering (PCF)
- GPU frustum culling using compute shaders
- Order-independent transparency (OIT)
- Asynchronous loading of textures
In this recipe, we’ll focus on the details of how to integrate all these effects rather than on the individual techniques.
Getting ready
Section titled “Getting ready”Ensure you have a solid understanding of all the recipes from this and previous chapters.
The demo application for this recipe is located in the Chapter11/06_FinalDemo folder.
How to do it…
Section titled “How to do it…”Since we are already familiar with all the rendering techniques used in this recipe, we can quickly review the C++ source code and highlight the key sections that enable these techniques to work together. Different techniques and effects are implemented via different compute and graphics pipeline objects, accessing and modifying various buffers and textures. The following image illustrates an almost complete directed graph of our entire frame, known as a frame graph. Buffers are represented as ovals, textures as white rectangles, graphics pipelines as dark rectangles, and compute pipelines as dark rectangles with a folder icon. The textual labels on the diagram correspond to the names of the variables in the C++ code.

Figure 11.7: Our final demo frame graph
- We define all the parameters that can be adjusted through the ImGui UI. These should already be familiar to you, but we have made slight tweaks to improve the final appearance of the rendered image:
bool drawMeshesOpaque = true;bool drawMeshesTransparent = true;bool drawWireframe = false;bool drawBoxes = false;bool drawLightFrustum = false;// SSAObool ssaoEnable = true;bool ssaoEnableBlur = true;int ssaoNumBlurPasses = 1;float ssaoDepthThreshold = 30.0f;// OITbool oitShowHeatmap = false;float oitOpacityBoost = 0.0f;// HDRbool hdrDrawCurves = false;bool hdrEnableBloom = true;float hdrBloomStrength = 0.01f;int hdrNumBloomPasses = 2;float hdrAdaptationSpeed = 1.0f;// Cullingenum CullingMode {CullingMode_None = 0,CullingMode_CPU = 1,CullingMode_GPU = 2,};mat4 cullingView = mat4(1.0f);int cullingMode = CullingMode_CPU;bool freezeCullingView = false;struct LightParams {float theta = +90.0f;float phi = -26.0f;float depthBiasConst = 1.1f;float depthBiasSlope = 2.0f;} light;
- We need to resolve both the MSAA color and depth textures, as the depth buffer will be used for computing SSAO. Since the entire demo uses an HDR rendering pipeline, the offscreen pixel format is set to
Format_RGBA_F16:std::unique_ptr<lvk::IContext> ctx(app.ctx_.get());const lvk::Dimensions sizeFb =ctx->getDimensions(ctx->getCurrentSwapchainTexture());const uint32_t kNumSamples = 8;const lvk::Format kOffscreenFormat = lvk::Format_RGBA_F16;Holder<TextureHandle> msaaColor = ctx->createTexture({.format = kOffscreenFormat,.dimensions = sizeFb,.numSamples = kNumSamples,.usage = lvk::TextureUsageBits_Attachment,.storage = lvk::StorageType_Memoryless });Holder<TextureHandle> msaaDepth = ctx->createTexture({.format = app.getDepthFormat(),.dimensions = sizeFb,.numSamples = kNumSamples,.usage = lvk::TextureUsageBits_Attachment,.storage = lvk::StorageType_Memoryless }); - We apply MSAA only when rendering opaque objects, as described in the Implementing order-independent transparency recipe, which is why our resolved textures are named
texOpaqueDepthandtexOpaqueColor:Holder<TextureHandle> texOpaqueDepth = ctx->createTexture({.format = app.getDepthFormat(),.dimensions = sizeFb,.usage = lvk::TextureUsageBits_Attachment |lvk::TextureUsageBits_Sampled |lvk::TextureUsageBits_Storage });Holder<TextureHandle> texOpaqueColor = ctx->createTexture({.format = kOffscreenFormat,.dimensions = sizeFb,.usage = lvk::TextureUsageBits_Attachment |lvk::TextureUsageBits_Sampled |lvk::TextureUsageBits_Storage }); - Two additional HDR color attachments are needed later, closer to the end-of-frame rendering. The first,
texOpaqueColorWithSSAO, stores the opaque objects with the SSAO effect applied. The second,texSceneColor, holds the final HDR-rendered scene just before tone mapping is applied:Holder<TextureHandle> texOpaqueColorWithSSAO = ctx->createTexture({.format = kOffscreenFormat,.dimensions = sizeFb,.usage = lvk::TextureUsageBits_Attachment |lvk::TextureUsageBits_Sampled |lvk::TextureUsageBits_Storage });Holder<TextureHandle> texSceneColor = ctx->createTexture({.format = kOffscreenFormat,.dimensions = sizeFb,.usage = lvk::TextureUsageBits_Attachment |lvk::TextureUsageBits_Sampled |lvk::TextureUsageBits_Storage }); - Let’s create textures for HDR and light adaptation, as described in the Implementing HDR rendering and tone mapping and Implementing HDR light adaptation recipes of Chapter 10:
const lvk::Dimensions sizeBloom = { 512, 512 };Holder<TextureHandle> texBrightPass = ctx->createTexture({.format = kOffscreenFormat,.dimensions = sizeBloom,.usage = lvk::TextureUsageBits_Sampled |lvk::TextureUsageBits_Storage });Holder<TextureHandle> texBloomPass = ctx->createTexture({.format = kOffscreenFormat,.dimensions = sizeBloom,.usage = lvk::TextureUsageBits_Sampled |lvk::TextureUsageBits_Storage });Holder<TextureHandle> texBloom[] = {ctx->createTexture({.format = kOffscreenFormat,.dimensions = sizeBloom,.usage = lvk::TextureUsageBits_Sampled |lvk::TextureUsageBits_Storage}),ctx->createTexture({.format = kOffscreenFormat,.dimensions = sizeBloom,.usage = lvk::TextureUsageBits_Sampled |lvk::TextureUsageBits_Storage})};const lvk::ComponentMapping swizzle = {.r = lvk::Swizzle_R, .g = lvk::Swizzle_R,.b = lvk::Swizzle_R, .a = lvk::Swizzle_1 };Holder<TextureHandle> texLumViews[10] = {ctx->createTexture({.format = lvk::Format_R_F16,.dimensions = sizeBloom,.usage = lvk::TextureUsageBits_Sampled |lvk::TextureUsageBits_Storage,.numMipLevels = lvk::calcNumMipLevels(sizeBloom.width,sizeBloom.height),.swizzle = swizzle }) };for (uint32_t v = 1; v != LVK_ARRAY_NUM_ELEMENTS(texLumViews); v++) {texLumViews[v] = ctx->createTextureView(texLumViews[0], { .mipLevel = v, .swizzle = swizzle });}
- The ping-pong textures for HDR light adaptation are preinitialized with a very bright color value, as explained in the Implementing HDR light adaptation recipe from Chapter 10:
const uint16_t brightPixel = glm::packHalf1x16(50.0f);const lvk::TextureDesc luminanceTextureDesc{.format = lvk::Format_R_F16,.dimensions = {1, 1},.usage = lvk::TextureUsageBits_Sampled |lvk::TextureUsageBits_Storage,.swizzle = swizzle };Holder<TextureHandle> texAdaptedLum[2] = {ctx->createTexture(luminanceTextureDesc),ctx->createTexture(luminanceTextureDesc) };
- A large 16-bit shadow map is created with a resolution of
4096x4096, along with a depth-comparison sampler that clamps values to the border texels. To render the shadow map in shades of gray, we use texture swizzling functionality. A single value from the R-channel is duplicated across all three RGB channels:Holder<TextureHandle> texShadowMap = ctx->createTexture({.type = lvk::TextureType_2D,.format = lvk::Format_Z_UN16,.dimensions = { 4096, 4096 },.usage = lvk::TextureUsageBits_Attachment |lvk::TextureUsageBits_Sampled,.swizzle = { .r = lvk::Swizzle_R,.g = lvk::Swizzle_R,.b = lvk::Swizzle_R, .a = lvk::Swizzle_1 } });Holder<SamplerHandle> samplerShadow = ctx->createSampler({.wrapU = lvk::SamplerWrap_Clamp,.wrapV = lvk::SamplerWrap_Clamp,.depthCompareOp = lvk::CompareOp_LessEqual,.depthCompareEnabled = true }); - A separate buffer is used to pass light data to the shaders, as described in the Implementing shadows for directional lights recipe:
struct LightData {mat4 viewProjBias;vec4 lightDir;uint32_t shadowTexture;uint32_t shadowSampler;};Holder<BufferHandle> bufferLight = ctx->createBuffer({.usage = lvk::BufferUsageBits_Storage,.storage = lvk::StorageType_Device,.size = sizeof(LightData) });
- Another set of textures and a sampler are required for the SSAO effect, as outlined in the Implementing screen space ambient occlusion recipe from Chapter 10:
Holder<TextureHandle> texSSAO = ctx->createTexture({.format = ctx->getSwapchainFormat(),.dimensions = ctx->getDimensions(ctx->getCurrentSwapchainTexture()),.usage = lvk::TextureUsageBits_Sampled |lvk::TextureUsageBits_Storage });Holder<TextureHandle> texBlur[] = {ctx->createTexture({.format = ctx->getSwapchainFormat(),.dimensions = ctx->getDimensions(ctx->getCurrentSwapchainTexture()),.usage = lvk::TextureUsageBits_Sampled |lvk::TextureUsageBits_Storage }),ctx->createTexture({.format = ctx->getSwapchainFormat(),.dimensions = ctx->getDimensions(ctx->getCurrentSwapchainTexture()),.usage = lvk::TextureUsageBits_Sampled |lvk::TextureUsageBits_Storage })};Holder<SamplerHandle> samplerClamp = ctx->createSampler({.wrapU = lvk::SamplerWrap_Clamp,.wrapV = lvk::SamplerWrap_Clamp,.wrapW = lvk::SamplerWrap_Clamp });
- The OIT setup code is identical to the code from the Implementing order-independent transparency recipe. The only difference is the floating-point pixel format used for HDR rendering. For brevity, we skip the C++ lambda code here; refer to the recipe for details:
const Skybox skyBox(ctx, "data/immenstadter_horn_2k_prefilter.ktx","data/immenstadter_horn_2k_irradiance.ktx",kOffscreenFormat, app.getDepthFormat(), kNumSamples);VKMesh11Lazy mesh(ctx, meshData, scene);const VKPipeline11 pipelineOpaque(ctx, meshData.streams, kOffscreenFormat,app.getDepthFormat(), kNumSamples,loadShaderModule(ctx, "Chapter11/06_FinalDemo/src/main.vert"),loadShaderModule(ctx, "Chapter11/06_FinalDemo/src/opaque.frag"));const VKPipeline11 pipelineTransparent(ctx, meshData.streams, kOffscreenFormat,app.getDepthFormat(), kNumSamples,loadShaderModule(ctx, "Chapter11/06_FinalDemo/src/main.vert"),loadShaderModule(ctx, "Chapter11/06_FinalDemo/src/transparent.frag"));const VKPipeline11 pipelineShadow(ctx, meshData.streams, lvk::Format_Invalid,ctx->getFormat(texShadowMap), 1,loadShaderModule(ctx, "Chapter11/03_DirectionalShadows/src/shadow.vert"),loadShaderModule(ctx, "Chapter11/03_DirectionalShadows/src/shadow.frag"));VKIndirectBuffer11 meshesOpaque(ctx,mesh.numMeshes_, lvk::StorageType_HostVisible);VKIndirectBuffer11 meshesTransparent(ctx,mesh.numMeshes_, lvk::StorageType_HostVisible);// … skipped populating indirect buffers here
We skip the rest of the initialization code that loads GLSL shaders and creates the corresponding graphics and compute pipelines, and some buffers. Refer to the relevant recipes for instructions on how to do this. Instead, let’s focus on some new details in the main rendering loop:
- We poll
processLoadedTextures()to handle lazy-loaded textures, as described in the Loading texture assets asynchronously recipe, and extract the viewing frustum planes for culling, as explained in the Doing frustum culling on the GPU with compute shaders recipe:app.run([&](uint32_t width, uint32_t height,float aspectRatio, float deltaSeconds) {mesh.processLoadedTextures();const mat4 view = app.camera_.getViewMatrix();const mat4 proj = glm::perspective(45.0f, aspectRatio, pcSSAO.zNear, pcSSAO.zFar);if (!freezeCullingView)cullingView = app.camera_.getViewMatrix();CullingData cullingData = {.numMeshesToCull = meshesOpaque.drawCommands_.size() };getFrustumPlanes(proj * cullingView, cullingData.frustumPlanes);getFrustumCorners(proj * cullingView, cullingData.frustumCorners); - We update the light view matrix and calculate the scene’s AABB in light space to calculate the light projection matrix, as described in the Implementing shadows for directional lights recipe:
const glm::mat4 rot1 = glm::rotate(mat4(1.f),glm::radians(light.theta), glm::vec3(0, 1, 0));const glm::mat4 rot2 = glm::rotate(rot1,glm::radians(light.phi), glm::vec3(1, 0, 0));const vec3 lightDir = glm::normalize(vec3(rot2 * vec4(0.0f, -1.0f, 0.0f, 1.0f)));const mat4 lightView = glm::lookAt(glm::vec3(0.0f), lightDir, vec3(0, 0, 1));const BoundingBox boxLS = bigBoxWS.getTransformed(lightView);const mat4 lightProj = glm::orthoLH_ZO(boxLS.min_.x, boxLS.max_.x,boxLS.min_.y, boxLS.max_.y,boxLS.max_.z, boxLS.min_.z);
- Now we’re ready to start filling the command buffer. The first tasks are to clear the OIT buffers, as described in the Implementing order-independent transparency recipe, and cull the scene:
ICommandBuffer& buf = ctx->acquireCommandBuffer();clearTransparencyBuffers(buf);
- The culling code here is slightly different. First, we take a shortcut and perform frustum culling only for opaque meshes, as transparent meshes are always rendered due to their low number and very low polygon count. Since we’re culling only part of the scene, we can’t use the
VKMesh11indirect buffer directly as we did in the Doing frustum culling on the GPU with compute shaders recipe. Instead, we use the indirect buffer from theVKIndirectBuffer11objectmeshOpaque, which contains only opaque meshes. Since all transparent meshes are visible, we initialize ournumVisibleMeshescounter with the number of transparent meshes:if (cullingMode == CullingMode_CPU) {numVisibleMeshes =meshesTransparent.drawCommands_.size());DrawIndexedIndirectCommand* cmd = meshesOpaque.getDrawIndexedIndirectCommandPtr();for (size_t i = 0; i != meshesOpaque.drawCommands_.size(); i++) {const BoundingBox box = reorderedBoxes[mesh.drawData_[cmd->baseInstance].transformId];const uint32_t count =isBoxInFrustum(cullingData.frustumPlanes,cullingData.frustumCorners, box) ? 1 : 0;(cmd++)->instanceCount = count;numVisibleMeshes += count;}ctx->flushMappedMemory(meshesOpaque.bufferIndirect_, 0,meshesOpaque.drawCommands_.size() *sizeof(DrawIndexedIndirectCommand));} else - The GPU culling code path is similar. We run the compute shader to patch the contents of the
meshesOpaque.bufferIndirect_buffer. Note the buffer dependency incmdDispatchThreadGroups(), which is necessary to issue proper Vulkan buffer memory barriers:if (cullingMode == CullingMode_GPU) {buf.cmdBindComputePipeline(pipelineCulling);pcCulling.meshes = ctx->gpuAddress(bufferCullingData[currentBufferId]);pcCulling.commands = ctx->gpuAddress(meshesOpaque.bufferIndirect_);cullingData.numVisibleMeshes =meshesTransparent.drawCommands_.size());buf.cmdPushConstants(pcCulling);buf.cmdUpdateBuffer(bufferCullingData[currentBufferId], cullingData);buf.cmdDispatchThreadGroups({ 1 + cullingData.numMeshesToCull / 64 },{ .buffers = { BufferHandle(meshesOpaque.bufferIndirect_) } });} - After culling is complete, we update the shadow map if necessary, as described in the Implementing shadows for directional lights recipe. The shadow mapping code renders the entire scene using
mesh.draw()and does not rely on the culling code, so there is no dependency between the two, allowing them to run in parallel, at least in theory:if (prevLight != light) {prevLight = light;buf.cmdBeginRendering(lvk::RenderPass{.depth = {.loadOp = lvk::LoadOp_Clear,.clearDepth = 1.0f} },lvk::Framebuffer{.depthStencil = {.texture = texShadowMap} });buf.cmdSetDepthBias(light.depthBiasConst, light.depthBiasSlope);buf.cmdSetDepthBiasEnable(true);mesh.draw(buf, pipelineShadow, lightView, lightProj);buf.cmdSetDepthBiasEnable(false);buf.cmdEndRendering();buf.cmdUpdateBuffer(bufferLight, LightData{.viewProjBias = scaleBias * lightProj * lightView,.lightDir = vec4(lightDir, 0.0f),.shadowTexture = texShadowMap.index(),.shadowSampler = samplerShadow.index(),});} - Now we can render the scene using our MSAA render target and resolve it:
const lvk::Framebuffer framebufferMSAA = {.color = {{.texture = msaaColor,.resolveTexture = texOpaqueColor }},.depthStencil = {.texture = msaaDepth,.resolveTexture = texOpaqueDepth } };buf.cmdBeginRendering(lvk::RenderPass{.color = { {.loadOp = lvk::LoadOp_Clear,.storeOp = lvk::StoreOp_MsaaResolve,.clearColor = { 1.f, 1.f, 1.f, 1.f } } },.depth = {.loadOp = lvk::LoadOp_Clear,.storeOp = lvk::StoreOp_MsaaResolve,.clearDepth = 1.0f } },framebufferMSAA, { .buffers = {BufferHandle(meshesOpaque.bufferIndirect_)}});
- We draw the skybox and all the meshes, as described in the Implementing order-independent transparency recipe. For brevity, we’ve skipped the code that populates the push constants struct
pc:skyBox.draw(buf, view, proj);// … skipped push constantsif (drawMeshesOpaque) mesh.draw(buf, pipelineOpaque, &pc, sizeof(pc),{ .compareOp = lvk::CompareOp_Less,.isDepthWriteEnabled = true },drawWireframe, &meshesOpaque);if (drawMeshesTransparent)mesh.draw(buf, pipelineTransparent, &pc, sizeof(pc),{ .compareOp = lvk::CompareOp_Less,.isDepthWriteEnabled = false },drawWireframe, &meshesTransparent);app.drawGrid(buf, proj, vec3(0, -1.0f, 0),kNumSamples, kOffscreenFormat);buf.cmdEndRendering(); - At this point, we have our color and depth buffers resolved into the textures
texOpaqueColorandtexOpaqueDepth. Next, let’s calculate the SSAO effect using the depth buffer, as described in the Implementing screen space ambient occlusion recipe from Chapter 10. Note the texture dependencies here:if (ssaoEnable) {buf.cmdBindComputePipeline(pipelineSSAO);buf.cmdPushConstants(pcSSAO);buf.cmdDispatchThreadGroups({ .width = 1 + sizeFb.width / 16,.height = 1 + sizeFb.height / 16 },{ .textures = {TextureHandle(texOpaqueDepth),TextureHandle(texSSAO) } });if (ssaoEnableBlur) {// … the blur code is skipped} - Now, we can combine the SSAO texture
texSSAOwithtexOpaqueColorand render the result intotexOpaqueColorWithSSAO. Note the additional dependency ontexOpaqueColorfor proper Vulkan image layout transition fromVK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMALtoVK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:buf.cmdBeginRendering({ .color={{.loadOp = lvk::LoadOp_Load,.clearColor={1.f, 1.f, 1.f, 1.f}}},},{ .color = { {.texture = texOpaqueColorWithSSAO } },},{ .textures = {TextureHandle(texSSAO),TextureHandle(texOpaqueColor) } });buf.cmdBindRenderPipeline(pipelineCombineSSAO);buf.cmdPushConstants(pcCombineSSAO);buf.cmdBindDepthState({});buf.cmdDraw(3);buf.cmdEndRendering();} - Now, we can take
texOpaqueColorWithSSAOand combine it with transparent objects, as described in the Implementing order-independent transparency recipe. The result is rendered intotexSceneColor, which is our fully rendered HDR scene, ready to be tone-mapped:const lvk::Framebuffer framebufferOffscreen = {.color = { { .texture = texSceneColor } },};buf.cmdBeginRendering(lvk::RenderPass{.color = {{ .loadOp = lvk::LoadOp_Load,.storeOp = lvk::StoreOp_Store }},},framebufferOffscreen,{ .textures = {TextureHandle(texHeadsOIT),TextureHandle(texOpaqueColor),TextureHandle(texOpaqueColorWithSSAO) },.buffers = { BufferHandle(bufferListsOIT) }});// … skipped push constants hereconst struct { … } pcOIT = { … };buf.cmdBindRenderPipeline(pipelineOIT);buf.cmdPushConstants(pcOIT);buf.cmdBindDepthState({});buf.cmdDraw(3);buf.cmdEndRendering();// … skipped tone mapping code} - The skipped tone mapping code depends on
texSceneColor, but otherwise, it is identical to the code used in the Implementing HDR light adaptation recipe from Chapter 10. We skip it here, along with the extensive ImGui rendering code, and then submit the following command:submitHandle[currentBufferId] = ctx->submit(buf, ctx->getCurrentSwapchainTexture()); - The following code fragment, which waits for the previous frame, is necessary to retrieve the results of GPU culling for display in ImGui. You can read about it in the Doing frustum culling on the GPU with compute shaders recipe:
currentBufferId = (currentBufferId + 1) %LVK_ARRAY_NUM_ELEMENTS(bufferCullingData);if (cullingMode == CullingMode_GPU &&app.fpsCounter_.numFrames_ > 1) {ctx->wait(submitHandle[currentBufferId]);ctx->download(bufferCullingData[currentBufferId],&numVisibleMeshes, sizeof(uint32_t),offsetof(CullingData, numVisibleMeshes));}// swap ping-pong texturesstd::swap(texAdaptedLum[0], texAdaptedLum[1]);});
Now, we can run the demo application, and it should render the Lumberyard Bistro scene with all the aforementioned effects, as shown in the following screenshot:

Figure 11.8: The final Vulkan demo
Try running the demo, moving the camera around, and experimenting with the various UI controls. Every single tweak from the previous recipes should be here.
Note
If you’d like to render high-quality shadows as in the screenshot, set the shadow map resolution to 16384x16384.
With this example, we conclude Vulkan 3D Graphics Rendering Cookbook, and we hope you enjoyed it!
There’s more…
Section titled “There’s more…”The possibilities here are endless. You can use this framework to experiment with more advanced rendering techniques. Adding more screen-space effects, such as temporal antialiasing or screen-space reflections, should be relatively simple. Another easy next step could be replacing the basic SSAO effect implemented here with ray-traced ambient occlusion using Vulkan’s raytracing capabilities. The LightweightVK framework is fully capable of handling that.
Adding multiple light sources can be done by storing their parameters in a buffer and iterating over it in the fragment shader. Various optimizations are possible, such as tile deferred shading or clustered shading: http://www.cse.chalmers.se/~uffe/clustered_shading_preprint.pdf. The easiest way to incorporate shadows from multiple light sources into this demo would be to use separate per-light shadow maps and access them all via bindless textures. It could be especially cool to implement omnidirectional shadows for light sources inside the Bistro interior.
Going deeper into complex materials rendering could be another exciting direction to explore. A good starting point might be converting the Bistro scene materials to PBR and using our glTF2 rendering code from Chapter 6 to render them correctly. If you decide to pursue this and dive into the practical side of PBR rendering, the Filament engine documentation is an excellent resource to explore: https://google.github.io/filament/Filament.html.
One last thing to mention is the complexity of manual resource allocation here. As shown in the frame graph diagram (Figure 11.7), the number of buffers and textures used in the demo increases rapidly with each new effect added. This makes it tedious and error-prone to maintain and extend the frame graph manually. If you’re interested in writing a generic 3D rendering engine, there are many generalized approaches to automating frame graph construction. A frame graph helps plan and schedule all required operations on the GPU and CPU for a frame, along with all the necessary resources, in the most efficient way. It’s a complex topic, and to learn more, we recommend reading the GDC presentation FrameGraph: Extensible Rendering Architecture in Frostbite by Yuriy O’Donnell and the book Mastering Graphics Programming with Vulkan by Marco Castorina and Gabriel Sassone, published by Packt.