Image-Based Techniques
local graph
Chapter 10 — Image-Based Techniques
Section titled “Chapter 10 — Image-Based Techniques”In this chapter, we will learn how to build a post-processing pipeline and implement various image-based effects in Vulkan using LightweightVK, and how to integrate them with our scene rendering code. We will examine LightweightVK ’s implementation and review the underlying Vulkan code. Many of these techniques (such as ambient occlusion, high dynamic range (HDR) rendering and tone mapping, light adaptation, and temporal anti-aliasing) are important pieces of any modern post-processing pipeline. The idea is to render the scene to an offscreen image and then apply these effects, which is why they are referred to as “image-based” techniques.
In addition to these techniques, projective shadow mapping relies on somewhat similar offscreen rendering machinery. We will implement a very basic projective shadow mapping algorithm as one of our first examples, and then revisit the topic of shadow mapping in the next chapter with a more advanced approach.
This chapter covers the post-processing pipeline and has the following recipes:
- Implementing offscreen rendering in Vulkan
- Implementing full-screen triangle rendering
- Implementing shadow maps
- Implementing MSAA in Vulkan
- Implementing screen space ambient occlusion
- Implementing HDR rendering and tone mapping
- Implementing HDR light adaptation
Technical requirements
Section titled “Technical requirements”To run the recipes from this chapter, you need a computer with a video card and drivers supporting Vulkan 1.3. Read Chapter 1, if you want to learn how to build and run demo applications from this book.
This chapter relies on the scene and geometry loading code explained in Chapter 8, so make sure you read it before proceeding any further.
Implementing offscreen rendering in Vulkan
Section titled “Implementing offscreen rendering in Vulkan”Before we dive into general post-processing effects, let’s learn how to implement some foundational Vulkan code for offscreen rendering. We will use this functionality throughout the rest of the book to implement various rendering and post-processing techniques.
In this recipe, we will learn how to render directly into specific mip levels of an image and access each mip level individually. As a demonstration, we will render a textured icosahedron where each mip level of the texture is painted in a different color, allowing us to clearly see how the GPU handles mip level transitions.
Getting ready
Section titled “Getting ready”It is recommended to review the recipe Using texture data in Vulkan from Chapter 3.
The demo app for this recipe is located in Chapter10/01_OffscreenRendering.
How to do it…
Section titled “How to do it…”Let’s start by examining the high-level code of our example app in Chapter10/01_OffscreenRendering/src/main.cpp.
-
First, we create our standard
VulkanAppapplication and vertex and index buffers for our icosahedron. Here,trepresents the golden ratio, as described at https://en.wikipedia.org/wiki/Regular_icosahedron. The following code to generate an icosahedron mesh might come in handy.struct VertexData { float pos[3]; };const float t = (1.0f + sqrtf(5.0f)) / 2.0f;const VertexData vertices[] = {{-1, t, 0}, {1, t, 0}, {-1, -t, 0}, { 1, -t, 0},{ 0,-1, t}, {0, 1, t}, { 0, -1,-t}, { 0, 1, -t},{ t, 0,-1}, {t, 0, 1}, {-t, 0,-1}, {-t, 0, 1} };const uint16_t indices[] = { 0, 11, 5, 0, 5, 1, 0, 1,7, 0, 7, 10, 0, 10, 11, 1, 5, 9, 5, 11, 4, 11, 10,2, 10, 7, 6, 7, 1, 8, 3, 9, 4, 3, 4, 2, 3, 2, 6,3, 6, 8, 3, 8, 9, 4, 9, 5, 2, 4, 11, 6, 2, 10,8, 6, 7, 9, 8, 1 };int main() {VulkanApp app({ … });std::unique_ptr<lvk::IContext> ctx(app.ctx_.get());Holder<BufferHandle> bufferIndices = ctx->createBuffer({.usage = lvk::BufferUsageBits_Index,.storage = lvk::StorageType_Device,.size = sizeof(indices),.data = indices });Holder<BufferHandle> bufferVertices = ctx->createBuffer({.usage = lvk::BufferUsageBits_Vertex,.storage = lvk::StorageType_Device,.size = sizeof(vertices),.data = vertices }); -
Here are the vertex and fragment shaders, along with a graphics pipeline to render the mesh.
Holder<ShaderModuleHandle> vert =loadShaderModule(ctx, "Chapter10/01_OffscreenRendering/src/main.vert");Holder<ShaderModuleHandle> frag =loadShaderModule(ctx, "Chapter10/01_OffscreenRendering/src/main.frag");const lvk::VertexInput vdesc = {.attributes = {{.location = 0,.format = VertexFormat::Float3 }},.inputBindings = {{.stride = sizeof(VertexData)}},};Holder<lvk::RenderPipelineHandle> pipeline =ctx->createRenderPipeline({.vertexInput = vdesc,.smVert = vert,.smFrag = frag,.color = { { .format = ctx->getSwapchainFormat() } },.depthFormat = app.getDepthFormat(),}); -
Let’s create a 512x512 texture with a full mipmap pyramid.
constexpr uint8_t numMipLevels = lvk::calcNumMipLevels(512, 512);Holder<TextureHandle> texture = ctx->createTexture({.type = lvk::TextureType_2D,.format = lvk::Format_RGBA_UN8,.dimensions = {512, 512},.usage = lvk::TextureUsageBits_Attachment |lvk::TextureUsageBits_Sampled,.numMipLevels = numMipLevels }); -
Now, let’s create a set of texture views, each targeting individual mip levels of this texture. As we learned in the recipe Using texture data in Vulkan from Chapter 3, a
TextureHandlein LightweightVK is simply a wrapper aroundVkImageandVkImageView, along with additional metadata. TheIContext::createTextureView()function creates a newVkImageViewobject while keeping the originalVkImagefrom the initial texture. We will take a closer look at its implementation in the How it works… section.Holder<TextureHandle> mipViews[numMipLevels];for (uint32_t mip = 0; mip != numMipLevels; mip++)mipViews[mip] = ctx->createTextureView(texture, { .mipLevel = mip });
This allows the newly created texture views to function seamlessly in any texture mapping process as if they were complete textures.
- Now, let’s fill each of these individual mip levels with data. For simplicity, we will clear each of the 10 mip levels with a distinct color from the following table:
const vec3 colors[10] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1},{1, 1, 0}, {0, 1, 1}, {1, 0, 1},{1, 0, 0}, {0, 1, 0}, {0, 0, 1}, {0, 0, 0} };
- We can use offscreen rendering to achieve this. Since we are not rendering any geometry, all we need to do is specify rendering for a specific mip level with
LoadOp_Clearand provide a color value from the table.ICommandBuffer& buf = ctx->acquireCommandBuffer();for (uint8_t i = 0; i != numMipLevels; i++) {buf.cmdBeginRendering(RenderPass{.color = { {.loadOp = lvk::LoadOp_Clear,.level = i,.clearColor = {colors[i].r, …, 1}}} },lvk::Framebuffer{.color = { { .texture = texture }} });buf.cmdEndRendering();}ctx->submit(buf);
Since the colors are essentially static, we only need to do this once, before entering the main application loop.
- The main application loop is quite standard. We rotate the icosahedron model and render it to the current swapchain image.
app.run([&](uint32_t width, uint32_t height,float aspectRatio, float deltaSeconds) {const mat4 view = app.camera_.getViewMatrix();const mat4 proj = glm::perspective(…);const mat4 model = glm::rotate(…);const lvk::Framebuffer framebuffer = {.color = {{ .texture = ctx->getCurrentSwapchainTexture() }},.depthStencil ={.texture=app.getDepthTexture()},};ICommandBuffer& buf = ctx->acquireCommandBuffer();buf.cmdBindVertexBuffer(0, bufferVertices);buf.cmdBindIndexBuffer(bufferIndices, lvk::IndexFormat_UI16);
- We don’t need any additional Vulkan image layout transitions or memory barriers here because our command buffer submissions are strictly ordered, as explained in Chapter 2. Moreover, the render-to-texture code in
cmdEndRendering()(step 6) has already transitioned the texture toVK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMALafter rendering.buf.cmdBeginRendering( lvk::RenderPass{.color = {{.loadOp = lvk::LoadOp_Clear,.clearColor = {1.0f, 1.0f, 1.0f, 1.0f}}},.depth = { .loadOp = lvk::LoadOp_Clear,.clearDepth = 1.0f } },framebuffer );buf.cmdBindRenderPipeline(pipeline);buf.cmdBindDepthState({ .compareOp = lvk::CompareOp_Less,.isDepthWriteEnabled = true }); - We specify the texture that we populated earlier with the custom mip pyramid of colored mip levels and draw the mesh.
const struct PushConstants {mat4 mvp;uint32_t texture;} pc = {.mvp = proj * view * model,.texture = texture.index(),};buf.cmdPushConstants(pc);buf.cmdDrawIndexed(LVK_ARRAY_NUM_ELEMENTS(indices));
- Next, we have our standard grid rendering along with UI elements, such as the FPS counter and the memo. The most interesting part here will be the ImGui UI. Here, we display the entire contents of the mip pyramid within the ImGui UI. We use the texture views we created to access the individual mip levels of the parent texture object.
// … skipped drawing the grid, FPS, memo…app.imgui_->beginFrame(framebuffer);const ImGuiViewport* v = ImGui::GetMainViewport();ImGui::Begin("Control", nullptr, ImGuiWindowFlags_AlwaysAutoResize);ImGui::Text("Mip-pyramid 512x512");const float windowWidth = v->WorkSize.x / 5;for (uint32_t l = 0; l != numMipLevels; l++)ImGui::Image(mipViews[l].index(),ImVec2((int)windowWidth >> l,((int)windowWidth >> l)));ImGui::End();app.imgui_->endFrame(buf);buf.cmdEndRendering();ctx->submit(buf, ctx->getCurrentSwapchainTexture());});// …}
We conclude the main loop by submitting our command buffer and presenting the swapchain image.
- Here is the GLSL vertex shader for our rendering. The key part here is that we use ad hoc cylindrical mapping to calculate the
uvcoordinates from the vertex positions.layout (location = 0) in vec3 pos;layout (location = 0) out vec2 uv;layout(push_constant) uniform PushConstants {mat4 mvp;};#define PI 3.1415926float atan2(float y, float x) {return x == 0.0 ? sign(y) * PI/2 : atan(y, x);}void main() {gl_Position = mvp * vec4(pos, 1.0);float theta = atan2(pos.y, pos.x) / PI + 0.5;uv = vec2(theta, pos.z);} - And here is the fragment shader, which is trivial. Note that the only color information applied here comes from the texture.
layout (location=0) in vec2 uv;layout (location=0) out vec4 out_FragColor;layout(push_constant) uniform PushConstants {mat4 mvp;uint texture;};void main() {out_FragColor = textureBindless2D(texture, 0, uv);}
The running demo application should display a colorful, rotating icosahedron, as shown in the following screenshot.

Figure 10.1: A textured, rotating icosahedron
While this rendering may seem extremely simple, and it is, let’s take a moment to step back and understand what’s happening here, as it is well worth it.
The color information comes from a single texture. Based on the distance from the camera and the angle of each triangle to the screen plane, we sample from different mip levels of that texture. Since our texture has a completely custom, and in some sense, unusual, mip pyramid, with each mip level containing independent color information, we can observe a distinctive color pattern on the mesh. Notice the smooth transitions between the different colors, which occur due to trilinear filtering, where the GPU linearly blends between the individual mip levels.
Note
Back in the days of early GPUs, in the late 1990s and early 2000s, this technique was used to visualize and compare the quality of trilinear filtering across different GPUs and drivers.
Try using a custom sampler with lvk::SamplerMip_Nearest to disable trilinear filtering and observe a completely different visual pattern.
For us, this approach will serve as a building block to render into offscreen textures and visualize intermediate data. We will utilize it in the subsequent recipes.
Now we’ll take a look at how the Vulkan code works under the hood.
How it works…
Section titled “How it works…”Let’s check deps/src/lightweightvk/lvk/vulkan/VulkanClasses.cpp. The function of interest is VulkanContext::createTextureView(), which is responsible for key work with texture views.
- It accepts a texture handle and a
TextureViewDescobject, which specifies the parameters of a view we want to create. In our example, we only used themipLevelfield to extract a single mip level.struct TextureViewDesc {TextureType type = TextureType_2D;uint32_t layer = 0;uint32_t numLayers = 1;uint32_t mipLevel = 0;uint32_t numMipLevels = 1;ComponentMapping swizzle = {};};Holder<TextureHandle> VulkanContext::createTextureView(TextureHandle texture,const TextureViewDesc& desc,const char* debugName,Result* outResult) { - The function creates a copy of the
VulkanImagewrapper object from the existing texture and marks it as non-owning. As a result, the texture view remains valid only as long as the original texture is still in place. Check the recipe Using texture data in Vulkan from Chapter 3 to recap how Vulkan objects are stored in pools in LightweightVK. In our copy ofVulkanImage, we erase all previously createdVkImageViewobjects because they belong to the parent texture.VulkanImage image = *texturesPool_.get(texture);image.isOwningVkImage_ = false;memset(&image.imageViewStorage_, 0, sizeof(image.imageViewStorage_));memset(&image.imageViewForFramebuffer_, 0,sizeof(image.imageViewForFramebuffer_)); - Let’s choose
VkImageAspectFlagsfor the new image view based on the image format. This can be done manually by providing the necessary aspect mask as part of ourTextureViewDesc. However, this is how it is currently handled in LightweightVK for simplicity.VkImageAspectFlags aspect = 0;if (image.isDepthFormat_||image.isStencilFormat_) {if (image.isDepthFormat_)aspect |= VK_IMAGE_ASPECT_DEPTH_BIT;else if (image.isStencilFormat_)aspect |= VK_IMAGE_ASPECT_STENCIL_BIT;} else {aspect = VK_IMAGE_ASPECT_COLOR_BIT;} - Let’s select the
VkImageViewTypebased on the providedTextureViewDesc::typevalue.VkImageViewType vkImageViewType = VK_IMAGE_VIEW_TYPE_MAX_ENUM;switch (desc.type) {case TextureType_2D:vkImageViewType = desc.numLayers > 1 ?VK_IMAGE_VIEW_TYPE_2D_ARRAY :VK_IMAGE_VIEW_TYPE_2D;break;case TextureType_3D:vkImageViewType = VK_IMAGE_VIEW_TYPE_3D;break;case TextureType_Cube:vkImageViewType = desc.numLayers > 1 ?VK_IMAGE_VIEW_TYPE_CUBE_ARRAY :VK_IMAGE_VIEW_TYPE_CUBE;break;} - One useful feature of Vulkan image views is the ability to swizzle the components of a texture before returning the samples to the shader. For example, it allows loading a
1-channel R texture as a4-channel RGBA texture without reordering the underlying data. The value of the R channel can be broadcasted into all three RGB channels, rendering it white instead of red, while the A channel can be explicitly set to1. This will be helpful later in this chapter, in the recipe Implementing HDR rendering and tone mapping, to visualize intermediate buffers with ImGui.const VkComponentMapping mapping = {.r = VkComponentSwizzle(desc.swizzle.r),.g = VkComponentSwizzle(desc.swizzle.g),.b = VkComponentSwizzle(desc.swizzle.b),.a = VkComponentSwizzle(desc.swizzle.a),}; - Let’s create the actual
VkImageViewobject. The functionVulkanImage::createImageView()was explained in the recipe Using texture data in Vulkan from Chapter 3.image.imageView_ = image.createImageView(vkDevice_,vkImageViewType, image.vkImageFormat_, aspect,desc.mipLevel, desc.numMipLevels,desc.layer, desc.numLayers,mapping, nullptr, debugName); - One important extra step: If the original
VkImageobject was created with the flagVK_IMAGE_USAGE_STORAGE_BITand we want it to be accessible as a storage image from a compute shader, the swizzle must be identity. Therefore, we need anotherVkImageViewobject to be packed into the descriptor set used for storage images. Let’s create it here. While this might seem like an ad hoc decision, it is a trade-off we make to simplify the high-level LightweightVK interface.if (image.vkUsageFlags_& VK_IMAGE_USAGE_STORAGE_BIT) {if (!desc.swizzle.identity()) {image.imageViewStorage_ = image.createImageView(vkDevice_, vkImageViewType,image.vkImageFormat_, aspect, 0,VK_REMAINING_MIP_LEVELS, 0, desc.numLayers,{}, nullptr, debugName);}}TextureHandle handle = texturesPool_.create(std::move(image));awaitingCreation_ = true;return {this, handle};} - As for offscreen rendering, there’s another set of
VkImageViewobjects maintained insideVulkanImage, as was explained in the recipe Using texture data in Vulkan from Chapter 3. These are lazily created from the member functionCommandBuffer::cmdBeginRendering()by callingVulkanImage::getOrCreateVkImageViewForFramebuffer(). OneVkImageViewobject is required for each mip level or layer that we intend to render into. Here’s the code:VkImageView VulkanImage::getOrCreateVkImageViewForFramebuffer(VulkanContext& ctx, uint8_t level, uint16_t layer){if (imageViewForFramebuffer_[level][layer])return imageViewForFramebuffer_[level][layer];imageViewForFramebuffer_[level][layer] = createImageView(ctx.getVkDevice(), VK_IMAGE_VIEW_TYPE_2D, vkImageFormat_,getImageAspectFlags(), level, 1u, layer, 1u);return imageViewForFramebuffer_[level][layer];} - Here’s a quick look at the relevant parts of the
VulkanImagestruct for your convenience. The full declaration was explained in the recipe Using texture data in Vulkan from Chapter 3. In this struct,imageView_is the view we created,imageViewStorage_is the image view with the identity swizzle required for storage images, andimageViewForFramebuffer_is a lazily allocated collection of image views for each level and layer we want to render into. We limit the number of framebuffer layers to6for rendering into cube maps —another tradeoff made for the sake of simplifying the high-level API:struct VulkanImage final {// …VkImageView imageView_ = VK_NULL_HANDLE;VkImageView imageViewStorage_ = VK_NULL_HANDLE;VkImageView imageViewForFramebuffer_[LVK_MAX_MIP_LEVELS][6]= {};};
This offscreen rendering functionality serves as a building block for all our subsequent offscreen rendering Vulkan demos. Before we apply it, however, let’s first learn how to render full-screen quads in the next recipe.
Implementing full-screen triangle rendering
Section titled “Implementing full-screen triangle rendering”In most of the post-processing techniques covered in this chapter, you’ll need to render a textured rectangle that spans the entire screen and apply a specific fragment shader to it. To make this easier, we can use a single vertex shader that works across all of these cases. While it is straightforward to render a quad using the traditional vertex and index buffers approach, managing this can become complex when you need to handle many shader combinations across different stages of the rendering pipeline. In this recipe, we will demonstrate how to render a full-screen quad by generating geometry directly in a vertex shader. Additionally, instead of using quad geometry, we will use a single triangle covering the entire screen. Let’s explore how this is done.
Getting ready
Section titled “Getting ready”Check out the recipe Implementing programmable vertex pulling from Chapter 5.
How to do it…
Section titled “How to do it…”Let’s go through the code for our full-screen triangle vertex shader. The GLSL shader is located in the data/shaders/Quad.vert file and is as follows:
- This shader has no inputs except the built-in GLSL variable
gl_VertexIndex, which ranges from0to2for a triangle. Instead of calculating vertex positions in world space, we define them directly in homogeneous clip-space coordinates, which Vulkan uses. These clip-space coordinates range from-1.0to+1.0, covering the entire screen. Simple arithmetic withgl_VertexIndexallows us to achieve this. Ouruvtexture coordinates range from0.0to1.0, from top to bottom and left to right.#version 460layout (location=0) out vec2 uv;void main() {uv = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2 );gl_Position = vec4(uv * 2.0 + -1.0, 0.0, 1.0);} - There is an alternate version of this vertex shader in
data/shaders/QuadFlip.vertthat generates vertically flippeduvcoordinates, as shown below:#version 460layout (location=0) out vec2 uv;void main() {uv = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2 );gl_Position = vec4(uv * vec2(2, -2) + vec2(-1, 1), 0.0, 1.0);} - Although rendering a full-screen quad is straightforward and useful for learning purposes, using a full-screen triangle can often be faster in many real-world scenarios. Here’s how a triangle can cover the entire screen: the top-right and bottom-left portions are clipped, leaving only the rectangular area visible.

Figure 10.2: A full-screen triangle
- Here’s how to set up a rendering pipeline using one of these vertex shaders. This code snippet is from
Chapter10/04_SSAO/src/main.cppin the recipe Implementing screen space ambient occlusion.Holder<ShaderModuleHandle> vertCombine =loadShaderModule(ctx, "data/shaders/QuadFlip.vert");Holder<ShaderModuleHandle> fragCombine =loadShaderModule(ctx, "Chapter10/04_SSAO/src/combine.frag");HolderRenderPipelineHandle> pipelineCombine =ctx->createRenderPipeline({.smVert = vertCombine,.smFrag = fragCombine,.color = { { .format = ctx->getSwapchainFormat()}} }); - To render our full-screen “quad” (actually a triangle), we can use the following commands, as shown in
Chapter10/04_SSAO/src/main.cpp. The content of the push constants depends entirely on the fragment shader in use, as they are not needed for our vertex shaders.buf.cmdBindRenderPipeline(pipelineCombine);buf.cmdPushConstants(pcCombine);buf.cmdBindDepthState({});buf.cmdDraw(3);
In the upcoming recipes, we’ll learn how to pair this vertex shader with various fragment shaders to create different post-processing effects. Now, let’s move on to another “basic” image-based technique: projective shadows.
There’s more…
Section titled “There’s more…”This technique was popularized by Sascha Willems in his blog post, Vulkan tutorial on rendering a fullscreen quad without buffers: https://www.saschawillems.de/blog/2016/08/13/vulkan-tutorial-on-rendering-a-fullscreen-quad-without-buffers.
An alternative to the full-screen quad rendering approach is to perform a full image compute pass. However, this method requires image load-store operations, and the compute shader must be aware of the output image format. We explored this technique in the recipe Generating textures in Vulkan using compute shaders in Chapter 5.
Implementing shadow maps
Section titled “Implementing shadow maps”As we’ve seen in previous chapters, we can render complex scenes with diverse materials, including physically based rendering (PBR) materials. While these techniques can create visually appealing images, the realism of our scenes was severely lacking. Adding shadows can significantly enhance the depth and authenticity of a scene, making it feel more grounded and believable. Shadow mapping, in particular, is a foundational technique for achieving realistic lighting and shading effects. In this recipe, we will go through the basics of projective shadow mapping techniques.
Getting ready
Section titled “Getting ready”The demo application for this recipe, located in Chapter10/02_ShadowMapping, implements all the essential steps for setting up a projective shadow mapping rendering pipeline. It is recommended to briefly review the code before reading this recipe.
Be sure to review the recipe Implementing offscreen rendering in Vulkan to refresh your understanding of rendering to offscreen images, as this technique is essential for the shadow mapping process.
How to do it…
Section titled “How to do it…”The idea behind projective shadow mapping is fairly straightforward: the scene is rendered from the light’s point of view. Objects closest to the light are illuminated, while everything else falls into shadow. To identify these closest objects, a depth buffer is used, storing the distance of each visible surface from the light. This requires rendering the scene into an offscreen depth framebuffer.
The rendering process has three main phases: calculating the light’s projection and view matrices; rendering the entire scene from the light’s perspective into an offscreen depth shadow map; and finally, rendering the scene again from the camera’s view, using the depth shadow map to apply shadows.
Let’s walk through the code in Chapter10/02_ShadowMapping/src/main.cpp to see how each step of this process is implemented:
- First, let’s set up our
VulkanAppand load some mesh data. We will need at least two objects: one to cast the shadow and a ground or surface to receive the shadow.int main() {VulkanApp app({ … });LineCanvas3D canvas3d;std::unique_ptr<lvk::IContext> ctx(app.ctx_.get());struct VertexData {vec3 pos;vec3 n;vec2 tc;}; - The first object is a duck model, loaded from a
.gltffile.std::vector<VertexData> vertices;std::vector<uint32_t> indices;const aiScene* scene = aiImportFile("data/rubber_duck/scene.gltf", aiProcess_Triangulate);const aiMesh* mesh = scene->mMeshes[0];for (uint32_t i = 0; i != mesh->mNumVertices; i++) {// … load vertices into \`vertices\` …}for (uint32_t i = 0; i != mesh->mNumFaces; i++) {for (uint32_t j = 0; j != 3; j++)indices.push_back(mesh->mFaces[i].mIndices[j]);}aiReleaseImport(scene); - The second object is a simple plane that will receive the shadow. This plane is created directly from vertices. We’ll store both models, the duck and the plane, in the same vertex and index buffers. So, we need to keep track of how many indices the duck mesh has and the offset where the plane mesh begins. Our quad plane is defined by
2triangles,4vertices, and6indices. We use themergeVectors()function, introduced in the recipe Rendering large scenes from Chapter 5 to combinestd::vectorcontainers.const uint32_t duckNumIndices = indices.size();const uint32_t planeVertexOffset = vertices.size();mergeVectors( indices, { 0, 1, 2, 2, 3, 0 } );mergeVectors( vertices, {{vec3(-4, -4, 0), vec3(0, 0, 1), vec2(0, 0)},{vec3(-4, +4, 0), vec3(0, 0, 1), vec2(0, 1)},{vec3(+4, +4, 0), vec3(0, 0, 1), vec2(1, 1)},{vec3(+4, -4, 0), vec3(0, 0, 1), vec2(1, 0)} } ); - This vertex and index data is immutable, meaning we can upload it into the GPU buffers and then forget about it for a while.
Holder<BufferHandle> bufferIndices = ctx->createBuffer({.usage = lvk::BufferUsageBits_Index,.storage = lvk::StorageType_Device,.size = sizeof(uint32_t) * indices.size(),.data = indices.data() });Holder<BufferHandle> bufferVertices = ctx->createBuffer({.usage = lvk::BufferUsageBits_Vertex,.storage = lvk::StorageType_Device,.size = sizeof(VertexData) * vertices.size(),.data = vertices.data() });
- Next, let’s load the textures for our 3D models.
Holder<TextureHandle> duckTexture = loadTexture(ctx,"data/rubber_duck/textures/Duck_baseColor.png");Holder<TextureHandle> planeTexture = loadTexture(ctx, "data/wood.jpg");
- We need some per-frame data for our shaders. The
viewandprojmatrices are the standard camera ones we’ve already used. Thelightmatrix will store the product of the light’s view and projection matrices, multiplied by the scale-bias matrix. We will explain how this is calculated shortly. For now, one light matrix is enough since we are using only a single light in this recipe. ThelightAnglesfield stores the cosines of our spotlight’s inner and outer angles, which we’ll discuss shortly.lightPosis a shortcut for the light’s position in world space. The shadow texture and sampler fields will be used in our GLSL fragment shader. Let’s allocate a GPU buffer to store this structure. We will populate the buffer later, inside the rendering loop.struct PerFrameData {mat4 view;mat4 proj;mat4 light;vec4 lightAngles; // cos(inner), cos(outer)vec4 lightPos;uint32_t shadowTexture;uint32_t shadowSampler;};Holder<BufferHandle> bufferPerFrame = ctx->createBuffer({.usage = lvk::BufferUsageBits_Uniform,.storage = lvk::StorageType_Device,.size = sizeof(PerFrameData) }); - Now, let’s create our 16-bit depth shadow map texture and a sampler. This sampler is slightly different from the one we used earlier. It enables the Vulkan depth compare operation, where the depth comparison is applied to the fetched texture data before filtering. As a result, the depth texture lookup will return
1.0if the comparison istrue, and0.0if it isfalse. This is what we will need in our fragment shader to apply shadows. We will revisit this when we discuss the GLSL shaders in a few moments.Holder<TextureHandle> shadowMap = ctx->createTexture({.type = lvk::TextureType_2D,.format = lvk::Format_Z_UN16,.dimensions = {1024, 1024},.usage = lvk::TextureUsageBits_Attachment |lvk::TextureUsageBits_Sampled });Holder<SamplerHandle> samplerShadow = ctx->createSampler({.wrapU = lvk::SamplerWrap_Clamp,.wrapV = lvk::SamplerWrap_Clamp,.depthCompareOp = lvk::CompareOp_LessEqual,.depthCompareEnabled = true }); - Now, we can create a graphics pipeline for our main render pass. Let’s load the shaders and set up the pipeline.
Holder<ShaderModuleHandle> vert =loadShaderModule(ctx, "Chapter10/02_ShadowMapping/src/main.vert");Holder<ShaderModuleHandle> frag =loadShaderModule(ctx, "Chapter10/02_ShadowMapping/src/main.frag");
- The
VertexInputformat corresponds to theVertexDatastructure declared earlier in step 1.const lvk::VertexInput vdesc = {.attributes ={{ .location = 0,.format = lvk::VertexFormat::Float3,.offset = offsetof(VertexData, pos) },{ .location = 1,.format = lvk::VertexFormat::Float3,.offset = offsetof(VertexData, n) },{ .location = 2,.format = lvk::VertexFormat::Float2,.offset = offsetof(VertexData, tc) }, },.inputBindings = {{.stride = sizeof(VertexData)}},};Holder<RenderPipelineHandle> pipeline =ctx->createRenderPipeline({.vertexInput = vdesc,.smVert = vert,.smFrag = frag,.color = { { .format = ctx->getSwapchainFormat() } },.depthFormat = app.getDepthFormat() }); - A separate graphics pipeline with its own set of shaders is required to render the scene into the shadow map. The
vertexInputfield here contains onlyvec3positions, as this is the only data our offscreen rendering vertex shader requires.Holder<ShaderModuleHandle> vertShadow =loadShaderModule(ctx, "Chapter10/02_ShadowMapping/src/shadow.vert");Holder<ShaderModuleHandle> fragShadow =loadShaderModule(ctx, "Chapter10/02_ShadowMapping/src/shadow.frag");Holder<RenderPipelineHandle> pipelineShadow =ctx->createRenderPipeline({.vertexInput = lvk::VertexInput{.attributes = {{ .location = 0,.format = lvk::VertexFormat::Float3,.offset = offsetof(VertexData, pos) } },.inputBindings = { { .stride = sizeof(VertexData) } } },.smVert = vertShadow,.smFrag = fragShadow,.depthFormat = ctx->getFormat(shadowMap)}); - We’re almost done with the setup. The light’s view and projection matrices can be calculated using the following variables. Here,
g_LightFOVrepresents the field-of-view angle of the light,g_LightInnerAngledefines the light’s inner cone, andg_LightNearandg_LightFarare the near and far clip planes for the light, respectively. All these variables are controlled from the ImGui UI.float g_LightFOV = 45.0f;float g_LightInnerAngle = 10.0f;float g_LightNear = 0.8f;float g_LightFar = 8.0f; - The value
g_LightDistrepresents the distance of the light from the origin, whileg_LightXAngleandg_LightYAngleare the rotation angles around the X and Y axes, respectively. The depth values of shadow fragments are adjusted by depth bias factors to reduce shadow acne artifacts that occur when self-shadowing scene objects, which are caused by Z-fighting. These parameters are somewhat ad hoc and tricky, requiring significant fine-tuning in real-world applications. You can tweak them from the ImGui UI.float g_LightDist = 4.0f;float g_LightXAngle = 240.0f;float g_LightYAngle = 0.0f;float g_LightDepthBiasConst = 1.5f;float g_LightDepthBiasSlope = 3.0f;
A few other parameters are needed to control the scene from the UI. We skip them here.
Now, we can enter the rendering loop. Let’s go through it step by step to understand how the entire rendering process unfolds.
- Rotate the scene and the light around the vertical axis in opposite directions.
app.run([&](uint32_t width, uint32_t height,float aspectRatio, float deltaSeconds){g_ModelAngle = fmodf(g_ModelAngle–50*deltaSeconds, 360);g_LightYAngle = fmodf(g_LightYAngle+50*deltaSeconds, 360);
- Calculate the light’s position, as well as its view and projection matrices.
mat4 rotY = glm::rotate(mat4(1.f),glm::radians(g_LightYAngle), vec3(0, 1, 0));mat4 rotX = glm::rotate(rotY,glm::radians(g_LightXAngle), vec3(1, 0, 0));vec4 lightPos = rotX * vec4(0, 0, g_LightDist, 1);const mat4 lightProj = glm::perspective(glm::radians(g_LightFOV), 1.0f, g_LightNear, g_LightFar);const mat4 lightView = glm::lookAt(vec3(lightPos), vec3(0), vec3(0, 1, 0));
- Calculate the main camera’s view and projection matrices. The main camera can be toggled via ImGui to switch between the regular view and the view from the light source.
const bool showLightCamera = cameraType == comboBoxItems[1];mat4 view = showLightCamera ? lightView : app.camera_.getViewMatrix();mat4 proj = showLightCamera ?glm::perspective(glm::radians(g_LightFOV),aspectRatio, g_LightNear, g_LightFar) :glm::perspective(glm::radians(60.0f), aspectRatio, 0.1f, 1000.0f);mat4 m1 = glm::rotate(mat4(1.0f), glm::radians(-90.0f), vec3(1, 0, 0));mat4 m2 = glm::rotate(mat4(1.0f),glm::radians(g_ModelAngle), vec3(0, 1, 0));
- Now, we can begin filling in the command buffer. The vertex and index buffers will be shared between both graphics pipelines, and the push constants will be the same for convenience.
ICommandBuffer& buf = ctx->acquireCommandBuffer();buf.cmdBindVertexBuffer(0, bufferVertices);buf.cmdBindIndexBuffer(bufferIndices, lvk::IndexFormat_UI32);struct PushConstants {mat4 model;uint64_t perFrameBuffer;uint32_t texture;};
- Let’s render the scene into the shadow map. The per-frame data buffer
bufferPerFrameneeds to be updated with the data corresponding to the light matrices. Our shadow rendering shaders consume onlyviewandprojmatrices.buf.cmdUpdateBuffer(bufferPerFrame, PerFrameData{.view = lightView, .proj = lightProj });buf.cmdBeginRendering(lvk::RenderPass{.depth = {.loadOp = LoadOp_Clear,.clearDepth = 1.f} },lvk::Framebuffer{.depthStencil = { .texture = shadowMap } }); - Note that we only draw the duck model into the shadow map. The
modelmatrix is passed via push constants. Depth bias factors are configured usingcmdSetDepthBias(). Theg_LightDepthBiasConstfactor determines the constant depth offset added to each fragment, whileg_LightDepthBiasSlopeis a scalar factor applied based on the fragment’s slope.buf.cmdBindRenderPipeline(pipelineShadow);buf.cmdPushConstants(PushConstants{.model = m2 * m1,.perFrameBuffer = ctx->gpuAddress(bufferPerFrame) });buf.cmdBindDepthState({ .compareOp = lvk::CompareOp_Less,.isDepthWriteEnabled = true });buf.cmdSetDepthBias(g_LightDepthBiasConst,g_LightDepthBiasSlope);buf.cmdSetDepthBiasEnable(true);buf.cmdDrawIndexed(duckNumIndices);buf.cmdEndRendering();
At this point, our shadow map texture should contain a view of the scene from the light’s perspective, which should resemble the following image.
Note
Here, the content of the single-channel shadow map is rendered as the R channel. You can change that to white by using texture views and swizzling, as described earlier in the recipe Implementing offscreen rendering in Vulkan.

Figure 10.3: A shadow map
Now we are ready to continue rendering and render the main camera view while applying the shadow map to the scene.
- The scale-bias matrix scales the UV texture coordinates by
0.5and then translates them byvec2(0.5, 0.5). This step is necessary because the light’s clip-spacexycoordinates are in the range-1…+1, while the texture coordinates are sampled using the range0…1. Therefore, we need to multiply them by0.5and add0.5.const mat4 scaleBias = mat4(0.5, 0.0, 0.0, 0.0,0.0, 0.5, 0.0, 0.0,0.0, 0.0, 1.0, 0.0,0.5, 0.5, 0.0, 1.0); - Our main rendering shaders require the entire set of values in the
bufferPerFramebuffer to be filled in. Notice how thescaleBiasmatrix is multiplied with thelightProjandlightViewmatrices to prebake all texture coordinate transformations into a singlemat4matrix.buf.cmdUpdateBuffer(bufferPerFrame,PerFrameData{.view = view,.proj = proj,.light = scaleBias * lightProj * lightView,.lightAngles = vec4(cosf(glm::radians(0.5f * g_LightFOV)),cosf(glm::radians(0.5f * (g_LightFOV - g_LightInnerAngle))),1.0f, 1.0f),.lightPos = lightPos,.shadowTexture = shadowMap.index(),.shadowSampler = samplerShadow.index() }); - When we begin rendering, we must specify the
shadowMaptexture as a dependency to ensure the necessary Vulkan image layout transitions are applied. This framebuffer is also reused later for ImGui rendering.const lvk::Framebuffer framebuffer = {.color = { { .texture = ctx->getCurrentSwapchainTexture() } },.depthStencil = { .texture = app.getDepthTexture() },};buf.cmdBeginRendering(lvk::RenderPass{.color ={{.loadOp = lvk::LoadOp_Clear,.clearColor = { 1.f, 1.f, 1.f, 1.f } }},.depth = { .loadOp = lvk::LoadOp_Clear,.clearDepth = 1.0f } },framebuffer,{ .textures = {{TextureHandle(shadowMap)}} }); - The scene rendering itself is straightforward. We bind the required pipeline and then render the duck mesh, followed by the plane. The push constants store the texture ID for each mesh, while the shadow map texture ID is stored in the
bufferPerFramebuffer.buf.cmdBindRenderPipeline(pipeline);buf.cmdBindDepthState({.compareOp = lvk::CompareOp_Less,.isDepthWriteEnabled = true });buf.cmdPushConstants(PushConstants{ // Duck.model = m2 * m1,.perFrameBuffer = ctx->gpuAddress(bufferPerFrame),.texture = duckTexture.index() });buf.cmdDrawIndexed(duckNumIndices);buf.cmdPushConstants(PushConstants{ // Plane.model = m1,.perFrameBuffer = ctx->gpuAddress(bufferPerFrame),.texture = planeTexture.index() });buf.cmdDrawIndexed(6, 1, 0, planeVertexOffset);
At this point, our shadow mapping code is complete. The remaining part of the C++ code handles drawing the traditional grid and FPS counter, followed by the ImGui UI to control various light and shadow mapping parameters. We’ll skip that section here.
- There’s one more thing to mention. When rendering the scene from a regular first-person camera, we can render the light frustum using the 3D drawing canvas introduced in the recipe Implementing immediate mode 3D drawing canvas from Chapter 5. This is incredibly useful for debugging various shadow mapping algorithms. You will see it in action while running the demo application.
if (!showLightCamera && g_DrawFrustum) {canvas3d.clear();canvas3d.setMatrix(proj * view);canvas3d.frustum(lightView, lightProj, vec4(1, 0, 0, 1));canvas3d.render(*ctx.get(), framebuffer, buf);}
Now, let’s take a look at both sets of GLSL shaders to understand how everything works.
How it works…
Section titled “How it works…”All of our GLSL shaders here share the same set of common declarations, Chapter10/02_ShadowMapping/src/common.sp, for the per-frame buffer and push constants, just for convenience.
layout(std430, buffer_reference) readonly buffer PerFrameData { mat4 view; mat4 proj; mat4 light; vec4 lightAngles; vec4 lightPos; uint shadowTexture; uint shadowSampler;};layout(push_constant) uniform PushConstants { mat4 model; PerFrameData perFrame; uint texture;} pc;struct PerVertex { vec2 uv; vec3 worldNormal; vec3 worldPos; vec4 shadowCoords;};The first set of GLSL shaders is necessary to render our scene into the shadow map.
- The vertex shader
Chapter10/02_ShadowMapping/src/shadow.verttakes theviewandprojmatrices from the buffer and themodelmatrix from the push constants.#include <Chapter10/02_ShadowMapping/src/common.sp>layout (location = 0) in vec3 pos;void main() {gl_Position = pc.perFrame.proj * pc.perFrame.view *pc.model * vec4(pos, 1.0);} - The fragment shader for shadow map rendering is just empty because we do not output any color information, only the depth values. The source code is located in
Chapter10/02_ShadowMapping/src/shadow.frag.void main() {}
The second set of GLSL shaders is where the actual projective texture mapping occurs. Let’s take a closer look.
- The vertex shader
Chapter10/02_ShadowMapping/src/main.vertdoes the same transformation forgl_Position.#include <Chapter10/02_ShadowMapping/src/common.sp>layout (location = 0) in vec3 pos;layout (location = 1) in vec3 normal;layout (location = 2) in vec2 uv;layout (location=0) out PerVertex vtx;void main() {gl_Position = pc.perFrame.proj * pc.perFrame.view *pc.model * vec4(pos, 1.0); - Next, we populate all the remaining data necessary for rendering. Notice how the vertex position is first transformed into the light’s coordinate system, then into normalized device coordinates, and finally, into texture coordinates. This is done using the model matrix and the combined light matrix we calculated in C++, which is the product of the light’s view and projection matrices, multiplied by the scale-bias matrix. The resulting
vec4value is stored inshadowCoordsand passed to the fragment shader, where we will perform the perspective division.mat3 normalMatrix = transpose( inverse(mat3(pc.model)) );vtx.uv = uv;vtx.worldNormal = normalMatrix * normal;vtx.worldPos = (pc.model * vec4(pos, 1.0)).xyz;vtx.shadowCoords = pc.perFrame.light * pc.model * vec4(pos, 1.0);} - The fragment shader
Chapter10/02_ShadowMapping/src/main.fragdoes several things. It implements a simple soft shadow effect using a technique called percentage-closer filtering (PCF). The helper functionPCF(), which is defined in the include filedata/shaders/Shadow.sp, performs a 3x3 averaging of 9 depth comparison operations. Note that we average not the results of depth map sampling at adjacent locations but the results of multiple comparisons between the depth value of the current fragment (in the light space) and the sampled depth values obtained from the shadow map. This is done automatically using the shadow sampler we created earlier in the C++ code.
Note
Naïve averaging of 9 depth comparison operations can lead to light leaking and soft shadows that are too blurry. Using more advanced PCF kernels or variance shadow mapping can achieve better results.
#include <Chapter10/02_ShadowMapping/src/common.sp>layout (location=0) in PerVertex vtx;layout (location=0) out vec4 out_FragColor;float PCF3x3(vec3 uvw, uint textureid, uint samplerid) { float size = 1.0 / textureBindlessSize2D(textureid).x; float shadow = 0.0; for (int v=-1 ; v<=+1 ; v++) for (int u=-1 ; u<=+1 ; u++) { shadow += textureBindless2DShadow(textureid, samplerid, uvw + size * vec3(u, v, 0)); } return shadow / 9;}- The helper function
shadow()encapsulates all the shadowing logic and returns a single shadow factor for the current fragment. TheshadowCoordvalue passed as the argumentsrepresents the position of the current fragment in the light’s clip space, interpolated from the vertex shader. We perform the perspective division by thewcomponent and check if the fragment lies within the-1.0…+1.0clip spaceZrange, then call thePCF3()function to evaluate the result. Our viewport is flipped to be similar to OpenGL, hence the flippedYcoordinate1.0-s.y.float shadow(vec4 s, uint textureid, uint samplerid) {s = s / s.w;if (s.z > -1.0 && s.z < 1.0) {float shadowSample = PCF3x3(vec3(s.x, 1.0-s.y, s.z), textureid, samplerid); - Note that the surface in full shadow receives an ad hoc factor of
0.3instead of0to prevent over-darkening of the shadowed areas.return mix(0.3, 1.0, shadowSample);}return 1.0;} - The
spotLightFactor()function calculates the spot light shadowing coefficient based on the inner and outer cone angles of the spot light. This allows for a gradual shadow falloff between these two angles.
Note
The inner angle is the angle within which the spotlight emits its maximum intensity. The light within this cone is bright and uniform. The outer angle is the angle at which the light completely fades out to zero intensity. The region between the inner and outer angles forms a gradual falloff zone, creating a smooth transition from bright light to darkness.
Both angles are controlled from our UI, so you can adjust them and observe the results. The values of outerAngle and innerAngle are actually the cosines of the angles, which we calculated earlier in C++ for performance reasons. The light direction dirSpot is calculated as -lightPos in this case because our spot light is always aimed at the origin (0, 0, 0).
float spotLightFactor(vec3 worldPos) { vec3 dirLight = normalize(worldPos - pc.perFrame.lightPos.xyz); vec3 dirSpot = normalize(-pc.perFrame.lightPos.xyz); float rho = dot(dirLight, dirSpot); float outerAngle = pc.perFrame.lightAngles.x; float innerAngle = pc.perFrame.lightAngles.y; if (rho > outerAngle) return smoothstep(outerAngle, innerAngle, rho); return 0.0;}- With all the helper functions in place, the
main()function becomes straightforward. We calculate the simple diffuse lighting contributionNdotLbased on the light position and surface normal, then multiply it by the results of theshadow()andspotLightFactor()function calls. The resulting value is then multiplied by a diffuse texture sample.void main() {vec3 n = normalize(vtx.worldNormal);vec3 l = normalize(pc.perFrame.lightPos.xyz);float NdotL = clamp(dot(n, l), 0.1, 1.0);float Ka = 0.1;float Kd = NdotL * shadow(vtx.shadowCoords,pc.perFrame.shadowTexture,pc.perFrame.shadowSampler) *spotLightFactor(vtx.worldPos);out_FragColor = textureBindless2D(pc.texture, 0, vtx.uv) * clamp(Ka + Kd, 0.3, 1.0);}
This is all the code necessary to implement simple PCF shadow mapping. The demo application should render a shadowed scene, as shown in the following screenshot. Make sure to experiment with all the ImGui controls to see how different light parameters affect the shadow mapping.

Figure 10.4: Rendering a shadow-mapped duck
This concludes our basic Vulkan shadow mapping example and the first use case of offscreen rendering. Let’s now shift focus back to the main topic of this chapter and continue exploring image-based rendering techniques by learning how to implement multisample anti-aliasing (MSAA) in Vulkan.
There’s more…
Section titled “There’s more…”The technique described in this recipe for calculating the light’s view and projection matrices is suitable only for spot lights and, to some extent, omni lights. For directional lights, which impact the entire visible scene, the view and projection matrices depend on the geometry of the scene and how it intersects the main camera’s frustum. We will cover this topic in Chapter 11, where we will create an outdoor shadow map for a directional light and the Bistro scene.
Implementing MSAA in Vulkan
Section titled “Implementing MSAA in Vulkan”Multisample anti-aliasing (MSAA) is an anti-aliasing technique used in computer graphics to reduce jagged edges and improve the visual quality of rendered images. Multisampling is a specialized form of supersampling where the fragment shader runs only once per pixel, with only the depth (and stencil) values being supersampled within a pixel. More precisely, with multisampling, the fragment shader only needs to be evaluated once per pixel for each triangle that covers at least one sample point.
Note
Although MSAA is gradually being replaced by more advanced anti-aliasing techniques like temporal anti-aliasing (TAA), it remains relevant on mobile GPUs. When paired with tiled rendering, its performance cost is minimal.
In Vulkan, multiple sample values can later be resolved into non-multisampled color and depth images. Let’s go over how to use MSAA and resolve multisampled attachments in Vulkan.
Getting ready
Section titled “Getting ready”Be sure to review the recipe Implementing offscreen rendering in Vulkan to refresh your knowledge on handling offscreen rendering.
To find the Bistro scene rendering code used here, refer to the recipe Rendering large scenes in Chapter 8. We placed the Bistro loading code into a helper function loadBistro(), located in Chapter10/Bistro.h, which will be used in all upcoming demo applications in this chapter and the next.
The sample app for this recipe is located in Chapter10/03_MSAA.
How to do it…
Section titled “How to do it…”In most of the previous recipes, we rendered the main scene, with some shaders applied, directly into a swapchain image, which holds only one sample per pixel. Multisample rendering in Vulkan works differently. Here, we need to create an offscreen render target capable of storing multiple samples per pixel and render our scene into that target. Before this multisampled image can be displayed or used in post-processing effects, it must first be resolved into a standard non-multisampled render target. Vulkan provides several ways to perform this resolution.
One option is to use the Vulkan command vkCmdResolveImage(), which takes a fully rendered multisampled image and resolves it into a non-multisampled image. While straightforward, this approach requires the multisampled image to be completely rendered and stored in memory before the resolve operation can begin. Storing multiple samples per pixel consumes a large amount of memory, putting significant pressure on memory bandwidth – a limited resource on power-constrained devices like smartphones. As a result, this approach has very limited practical use.
The Vulkan API offers another method that is well-suited for mobile devices with tiled GPUs. As covered in the recipe Initializing Vulkan pipelines in Chapter 2, the command vkCmdBeginRendering() requires a list of framebuffer attachments, each of which can include a resolve attachment, referred to as VkRenderingAttachmentInfo::resolveImageView in Vulkan. By specifying this resolve attachment and following some additional setup steps, the Vulkan driver can resolve multisampled images into non-multisampled images without storing intermediate multisampled data in memory. Let’s see how to implement this. We will first review the high-level LightweightVK wrapper code, then explore the Vulkan implementation details.
- We begin by examining the app’s
main()function, located in theChapter10/03_MSAA/src/main.cppfile. Here, we perform the usual setup and load the Bistro mesh using theloadBistro()helper function fromChapter10/Bistro.h. The full process was explained in the recipe Rendering large scenes in Chapter 8.int main() {MeshData meshData;Scene scene;loadBistro(meshData, scene);VulkanApp app({ … });// … - Next, we choose the number of MSAA samples to use and create an offscreen color render target with the specified number of samples. The dimensions of this render target should match those of our swapchain.
const uint32_t kNumSamples = 8;const lvk::Dimensions sizeFb = ctx->getDimensions(ctx->getCurrentSwapchainTexture());Holder<TextureHandle> msaaColor =ctx->createTexture({.format = ctx->getSwapchainFormat(),.dimensions = sizeFb,.numSamples = kNumSamples,.usage = lvk::TextureUsageBits_Attachment });
- The same applies to the depth buffer: we need a multisampled depth buffer, so we can no longer use the default one from
VulkanApp.Holder<TextureHandle> msaaDepth =ctx->createTexture({.format = app.getDepthFormat(),.dimensions = sizeFb,.numSamples = kNumSamples,.usage = lvk::TextureUsageBits_Attachment }); - We want to control rendering from the ImGui UI and create two
VKMeshobjects for our Bistro scene. Since Vulkan requires the number of samples to be specified when creating the graphics pipeline, these two separateVKMeshinstances are necessary. TheVKMeshclass is declared inChapter08/VKMesh08.hand was used in the recipe Rendering large scenes in Chapter 8.bool enableMSAA = true;const VKMesh mesh(ctx, meshData, scene,ctx->getSwapchainFormat(), app.getDepthFormat());const VKMesh meshMSAA(ctx, meshData, scene,ctx->getSwapchainFormat(), app.getDepthFormat(),kNumSamples);app.run([&](uint32_t width, uint32_t height,float aspectRatio, float deltaSeconds) {const mat4 view = app.camera_.getViewMatrix();const mat4 proj = glm::perspective( … );ICommandBuffer& buf = ctx->acquireCommandBuffer(); - Entering the rendering loop, we define a list of color and depth attachments for our framebuffer. We use the
enableMSAAflag to toggle between MSAA and non-MSAA rendering. When MSAA is enabled, we setmsaaColoras the offscreen texture and the current swapchain texture asresolveTexture. When MSAA is disabled, we use the current swapchain texture as the framebuffer texture, leaving the resolve texture empty. Note that we don’t need to resolve the depth texture, so we can skip filling in theresolveTexturefield for it.const lvk::Framebuffer framebufferOffscreen = {.color = { {.texture = enableMSAA ?msaaColor : ctx->getCurrentSwapchainTexture(),.resolveTexture = enableMSAA ?ctx->getCurrentSwapchainTexture() : {} } },.depthStencil = {.texture = enableMSAA ? msaaDepth : app.getDepthTexture() },}; - At the start of rendering, we need to set the render pass parameters and the appropriate load and store operations. For the color attachment, we use
StoreOp_MsaaResolve, while for the depth attachment, which we don’t need to resolve, we keep the implicit store operationStoreOp_DontCare.buf.cmdBeginRendering( lvk::RenderPass{.color = { { .loadOp = lvk::LoadOp_Clear,.storeOp = enableMSAA ?lvk::StoreOp_MsaaResolve : lvk::StoreOp_Store,.clearColor = {1, 1, 1, 1} } },.depth = { .loadOp = lvk::LoadOp_Clear,.clearDepth = 1.0f } },framebufferOffscreen); - During rendering, we must specify the number of MSAA samples for all our rendering helper functions. This is required so they can update their internal graphics pipelines, which are created lazily. We will look into the details shortly.
(enableMSAA ? meshMSAA : mesh).draw(buf, view, proj, texSkyboxIrradiance, drawWireframe);app.drawGrid(buf, proj, vec3(0, -1.0f, 0), enableMSAA ? kNumSamples : 1);canvas3d.render(*ctx.get(),framebufferOffscreen, buf, enableMSAA ? kNumSamples : 1);buf.cmdEndRendering();
- We use a separate framebuffer description for ImGui rendering because it is rendered on top of the resolved, non-multisampled swapchain image. Once the command buffer is submitted, we present the swapchain image.
const lvk::Framebuffer framebufferMain = {.color = { { .texture = ctx->getCurrentSwapchainTexture() } } };buf.cmdBeginRendering( lvk::RenderPass{.color = { { .loadOp = lvk::LoadOp_Load,.clearColor = {1, 1, 1, 1}} } },framebufferMain);// …skipped canvas and ImGui rendering code here…buf.cmdEndRendering();ctx->submit(buf, ctx->getCurrentSwapchainTexture());});ctx.release();return 0;}
This covers the high-level rendering code. Now, let’s take a look into the internals to understand how it works and interacts with the Vulkan API.
How it works…
Section titled “How it works…”To get the big picture, we will examine some key parts of the function lvk::CommandBuffer::cmdBeginRendering(), located in the deps/src/lightweightvk/lvk/vulkan/VulkanClasses.cpp file. Its main code flow was described in the recipe Initializing Vulkan pipelines in Chapter 2. Now, let’s focus on how to construct an array of VkRenderingAttachmentInfo structs.
- First, we should recap on the loop that converts all LightweightVK color attachments into Vulkan
VkRenderingAttachmentInfostructs.void CommandBuffer::cmdBeginRendering(const lvk::RenderPass& renderPass,const lvk::Framebuffer& fb,const Dependencies& deps){const uint32_t numPassColorAttachments = renderPass.getNumColorAttachments();// …VkRenderingAttachmentInfo colorAttachments[LVK_MAX_COLOR_ATTACHMENTS];for (uint32_t i=0; I != numFbColorAttachments;i++) {const AttachmentDesc& attachment = fb.color[i];lvk::VulkanImage& colorTexture =*ctx_->texturesPool_.get(attachment.texture);const auto& descColor = renderPass.color[i];// …samples = colorTexture.vkSamples_;colorAttachments[i] = {.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO,.imageView = colorTexture.getOrCreateVkImageViewForFramebuffer(*ctx_, descColor.level, descColor.layer),.imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, - Note how the resolve mode is selected for MSAA attachments. The resolve mode defines how multisampled data is resolved.
VK_RESOLVE_MODE_NONEindicates no resolve operation is performed, whileVK_RESOLVE_MODE_AVERAGE_BITmeans the result of the resolve operation is the average of the sample values. There are other resolve modes, such asVK_RESOLVE_MODE_MIN_BITfor the minimum of the sample values andVK_RESOLVE_MODE_MAX_BITfor the maximum. These have specific use cases with a depth buffer, but we do not use them in our book..resolveMode = (samples > 1) ?VK_RESOLVE_MODE_AVERAGE_BIT :VK_RESOLVE_MODE_NONE,.resolveImageView = VK_NULL_HANDLE,.resolveImageLayout = VK_IMAGE_LAYOUT_UNDEFINED,.loadOp = loadOpToVkAttachmentLoadOp(descColor.loadOp),.storeOp = storeOpToVkAttachmentStoreOp(descColor.storeOp),.clearValue ={.color={.float32={descColor.clearColor[…]}}},}; - The next interesting part comes when we have a render pass description for an attachment with a store operation set to
StoreOp_MsaaResolve. This is where we take theVkImageViewof our resolve texture and assign it to the fieldVkRenderingAttachmentInfo::resolveImageView.if (descColor.storeOp == StoreOp_MsaaResolve) {lvk::VulkanImage& colorResolveTexture = *ctx_->texturesPool_.get(attachment.resolveTexture);colorAttachments[i].resolveImageView =colorResolveTexture.getOrCreateVkImageViewForFramebuffer(*ctx_, descColor.level, descColor.layer);colorAttachments[i].resolveImageLayout =VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;}} - The depth attachment is very similar. For brevity, we focus only on the MSAA part in the book text. The only difference here is that the image layout was set to
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL.VkRenderingAttachmentInfo depthAttachment = {};if (fb.depthStencil.texture) {lvk::VulkanImage& depthTexture = *ctx_->texturesPool_.get(fb.depthStencil.texture);const RenderPass::AttachmentDesc& descDepth = renderPass.depth;depthAttachment = { … }; // same as for colorif (descDepth.storeOp == StoreOp_MsaaResolve) {const AttachmentDesc& attachment = fb.depthStencil;lvk::VulkanImage& depthResolveTexture =*ctx_->texturesPool_.get(attachment.resolveTexture);depthAttachment.resolveImageView =depthResolveTexture.getOrCreateVkImageViewForFramebuffer(*ctx_, descDepth.level, descDepth.layer);depthAttachment.resolveImageLayout =VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;depthAttachment.resolveMode = VK_RESOLVE_MODE_AVERAGE_BIT;}// …} - The only remaining part is the graphics pipeline creation in the helper class
VKMesh, located inChapter08/VKMesh.h. This is where the number of MSAA samples is passed to the pipeline. TheminSampleShadingvalue is passed into Vulkan asVkPipelineMultisampleStateCreateInfo::minSampleShadingand is explained below.VKMesh(const std::unique_ptr<lvk::IContext>& ctx,const MeshData& meshData, const Scene& scene,lvk::Format colorFormat,lvk::Format depthFormat,uint32_t numSamples = 1,Holder<ShaderModuleHandle>&& vert = {},Holder<ShaderModuleHandle>&& frag = {}) {// …pipeline_ = ctx->createRenderPipeline({.vertexInput = meshData.streams,.smVert = vert_,.smFrag = frag_,.color = { { .format = colorFormat } },.depthFormat = depthFormat,.cullMode = lvk::CullMode_None,.samplesCount = numSamples,.minSampleShading = numSamples > 1 ? 0.25f : 0.0f,});// …} - And here is the corresponding Vulkan code responsible for creating the graphics pipeline in
VulkanPipelineBuilder::VulkanPipelineBuilder(), which populates theVkPipelineMultisampleStateCreateInfostruct and is located in thedeps/src/lightweightvk/lvk/vulkan/VulkanClasses.cppfile.multisampleState_({.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,.rasterizationSamples = getVulkanSampleCountFlags(desc.samplesCount),.sampleShadingEnable = desc.minSampleShading > 0 ? VK_TRUE : VK_FALSE,.minSampleShading = desc.minSampleShading,.pSampleMask = nullptr,.alphaToCoverageEnable = VK_FALSE,.alphaToOneEnable = VK_FALSE,}),
Color sampling occurs once per pixel, which can lead to “shader aliasing” or Moiré patterns on high-frequency textures. However, this can be mitigated using the minSampleShading parameter. This parameter controls the minimum number of samples that should be shaded for each pixel. A value of 1.0 ensures that every sample is shaded independently. The implementation guarantees at least as many color values per pixel as the product of minSampleShading and rasterizationSamples. In our case, with minSampleShading set to 0.25 and rasterizationSamples at 8, this results in at least 2 samples per pixel (0.25 * 8 = 2).
Note
As per Vulkan 1.3 specification 28.8. Sample Shading, if a fragment shader uses the built-in gl_SampleID or gl_SamplePosition variables, sample shading is automatically enabled, and the minSampleShading value is overridden with 1.0. Please note that it can have a significant performance impact.
This code is enough to enable MSAA in our demo application. If you run it, you should see the textured Bistro mesh rendered as shown in the following screenshot.

Figure 10.5: MSAA anti-aliased scene
Try toggling the Enable MSAA checkbox in the ImGui UI and observe the difference between anti-aliased and non-anti-aliased rendering. The difference is most noticeable on the geometry edges and when the camera is slowly moving.
From this point on, all subsequent recipes in the book will have MSAA enabled. Now, let’s continue exploring post-processing effects and learn how to add more realism to our scenes with screen space ambient occlusion.
There’s more…
Section titled “There’s more…”While the material in this recipe is sufficient to set up MSAA rendering, it misses one important aspect. When we allocate our offscreen textures, msaaColor and msaaDepth, they occupy valuable GPU memory, even though they are never used for actual rendering on tiled GPUs. Vulkan provides a solution to this problem.
When we create Vulkan images, we can set VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT in VkMemoryPropertyFlags and the image usage flag VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT, which tells the Vulkan driver not to allocate memory for the image unless it is actually needed. This can be done in LightweightVK using the StorageType_Memoryless storage type. You can check deps/src/lightweightvk/lvk/vulkan/VulkanClasses.cpp to see how these Vulkan flags are set up.
Implementing screen space ambient occlusion
Section titled “Implementing screen space ambient occlusion”Screen space ambient occlusion (SSAO) is an image-based technique used to approximate global illumination in real time. Ambient occlusion, at its core, provides a simplified representation of global illumination. It can be thought of as the amount of open “sky” visible from a point on a surface, unobstructed by nearby geometry. In its most basic implementation, this is estimated by sampling several points around the surface point of interest and determining how visible they are from that central point. Let’s take a look at a simple implementation of this technique.
Getting ready
Section titled “Getting ready”The demo application for this recipe, Chapter10/04_SSAO, implements basic steps for SSAO. Before going into this recipe, make sure to read the earlier ones in this chapter: Implementing offscreen rendering in Vulkan and Implementing full-screen triangle rendering.
How to do it…
Section titled “How to do it…”Instead of tracing the depth buffer’s height field, we use a simpler method where each selected neighboring point is projected onto the depth buffer. This projected point acts as a potential occluder. The occlusion factor O(dZ) for each point is calculated based on the difference dZ between the projected depth value and the current fragment’s depth using the following formula:
O(dZ) = (dZ > 0)? 1/(1+dZ*dZ): 0
These occlusion factors are averaged to determine the SSAO value for the current fragment. Before applying the final SSAO to the scene, it is blurred to minimize aliasing artifacts.
The SSAO shader works exclusively with the depth buffer, requiring no additional scene data. This makes it an easy, standalone snippet to kickstart your exploration of SSAO. Let’s review the C++ portion of the code in Chapter10/04_SSAO/src/main.cpp to understand how it’s implemented. We will skip the setup and the Bistro loading code here since it is identical to what was covered in the previous recipe, Implementing MSAA in Vulkan.
- First, we load the GLSL shaders for SSAO calculation and blurring.
int main() {MeshData meshData;Scene scene;loadBistro(meshData, scene);// …Holder<ShaderModuleHandle> compSSAO =loadShaderModule(ctx, "Chapter10/04_SSAO/src/SSAO.comp");Holder<ComputePipelineHandle> pipelineSSAO =ctx->createComputePipeline({.smComp = compSSAO});Holder<ShaderModuleHandle> compBlur =loadShaderModule(ctx, "data/shaders/Blur.comp");
- The blurring shader employs a separable Gaussian blur, performing horizontal and vertical passes separately. However, the same compute shader is used for both passes, with specialization constants creating two distinct compute pipelines: one for horizontal blur and one for vertical blur.
const uint32_t kHorizontal = 1;const uint32_t kVertical = 0;Holder<ComputePipelineHandle> pipelineBlurX =ctx->createComputePipeline({.smComp = compBlur,.specInfo = {.entries = { { .constantId = 0,.size = sizeof(uint32_t) } },.data = &kHorizontal,.dataSize = sizeof(uint32_t)} });Holder<ComputePipelineHandle> pipelineBlurY =ctx->createComputePipeline({.smComp = compBlur,.specInfo = {.entries = { { .constantId = 0,.size = sizeof(uint32_t) } },.data = &kVertical,.dataSize = sizeof(uint32_t)} });
- Next, we create a graphics pipeline to combine the generated SSAO and blur with the rendered color image. This process utilizes the full-screen quad (or triangle) shader we discussed earlier in the recipe Implementing full-screen triangle rendering. We use a graphics pipeline here instead of a compute pipeline to avoid dealing with a fixed swapchain pixel format required when using the
imageStore()command in compute shaders.Holder<ShaderModuleHandle> vertCombine =loadShaderModule(ctx,"data/shaders/QuadFlip.vert");Holder<ShaderModuleHandle> fragCombine =loadShaderModule(ctx, "Chapter10/04_SSAO/src/combine.frag");Holder<RenderPipelineHandle> pipelineCombine =ctx->createRenderPipeline({.smVert = vertCombine,.smFrag = fragCombine,.color = {{ .format = ctx->getSwapchainFormat() }} }); - Now, let’s create a texture for SSAO and two auxiliary textures for the blur. These blur textures will be used in a ping-pong fashion to perform multipass Gaussian blur. We will get to the details of how this works in a moment.
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 }),};
Note
We use the same pixel format for the SSAO and blur textures as the swapchain format. This makes debug rendering into the main framebuffer simpler by allowing the use of vkCmdCopyImage() without the need for component swizzling or vkCmdBlitImage().
- Now, we can create the multisampled textures and offscreen resolve color and depth textures, as explained in the previous recipe, Implementing MSAA in Vulkan.
const lvk::Dimensions sizeFb =ctx->getDimensions(ctx->getCurrentSwapchainTexture());const lvk::Dimensions sizeOffscreen = { sizeFb.width, sizeFb.height };const uint32_t kNumSamples = 8;Holder<TextureHandle> msaaColor = ctx->createTexture({.format = ctx->getSwapchainFormat(),.dimensions = sizeFb,.numSamples = kNumSamples,.usage = lvk::TextureUsageBits_Attachment });Holder<TextureHandle> msaaDepth = ctx->createTexture({.format = app.getDepthFormat(),.dimensions = sizeFb,.numSamples = kNumSamples,.usage = lvk::TextureUsageBits_Attachment });Holder<TextureHandle> offscreenColor = ctx->createTexture({.format = ctx->getSwapchainFormat(),.dimensions = sizeOffscreen,.usage = lvk::TextureUsageBits_Attachment |lvk::TextureUsageBits_Sampled |lvk::TextureUsageBits_Storage });Holder<TextureHandle> offscreenDepth =ctx->createTexture({.format = app.getDepthFormat(),.dimensions = sizeOffscreen,.usage = lvk::TextureUsageBits_Attachment |lvk::TextureUsageBits_Sampled |lvk::TextureUsageBits_Storage });
- We also need a special rotation texture, loaded from the
data/rot_texture.bmpfile, and aClampsampler to prevent edge texels from wrapping.Holder<TextureHandle> texRotations = loadTexture(ctx, "data/rot_texture.bmp");Holder<SamplerHandle> samplerClamp = ctx->createSampler({.wrapU = lvk::SamplerWrap_Clamp,.wrapV = lvk::SamplerWrap_Clamp,.wrapW = lvk::SamplerWrap_Clamp });
The rotation texture rot_texture.bmp is 4x4 pixels and contains 16 random vec3 vectors. It looks like this. We will explore how it is used a bit later.

Figure 10.6: Random vectors texture (4x4 pixels)
- We also need a few parameters for the ImGui UI that will allow us to tweak the SSAO effect and conveniently inspect our intermediate textures.
enum DrawMode {DrawMode_ColorSSAO = 0,DrawMode_Color = 1,DrawMode_SSAO = 2,};int drawMode = DrawMode_ColorSSAO;float depthThreshold = 30.0f;
- Before we can start rendering, we need to define push constants for our SSAO and Combine shaders. The SSAO parameters are chosen arbitrarily and can be adjusted through the ImGui interface.
struct {uint32_t texDepth;uint32_t texRotation;uint32_t texOut;uint32_t sampler;float zNear;float zFar;float radius;float attScale;float distScale;} pcSSAO = {.texDepth = offscreenDepth.index(),.texRotation = texRotations.index(),.texOut = texSSAO.index(),.sampler = samplerClamp.index(),.zNear = 0.01f,.zFar = 1000.0f,.radius = 0.03f,.attScale = 0.95f,.distScale = 1.7f,};
- The push constants for the Combine shader define the
scaleandbiasparameters, which can be tweaked through ImGui. The Bistro and Skybox meshes are created here as well. TheSkyboxhelper class encapsulates our previous skybox rendering code from Chapter 8, and is defined inChapter10/Skybox.h.struct {uint32_t texColor;uint32_t texSSAO;uint32_t sampler;float scale;float bias;} pcCombine = {.texColor = offscreenColor.index(),.texSSAO = texSSAO.index(),.sampler = samplerClamp.index(),.scale = 1.5f,.bias = 0.16f,};const Skybox skyBox(ctx, …, kNumSamples);const VKMesh mesh(ctx, …, kNumSamples);
The preparation work is now complete. The rendering loop is fairly straightforward. Let’s go through it step by step to highlight the different parts of our SSAO implementation.
- The first step is to render the multisampled scene and resolve it into our offscreen render targets. We covered this process in the previous recipe, Implementing MSAA in Vulkan. This time, we need to resolve both color and depth attachments, as the SSAO algorithm requires the scene’s depth information.
app.run([&](uint32_t width, uint32_t height,float aspectRatio, float deltaSeconds) {const mat4 view = app.camera_.getViewMatrix();const mat4 proj = glm::perspective(45.0f, aspectRatio, pcSSAO.zNear, pcSSAO.zFar);ICommandBuffer& buf = ctx->acquireCommandBuffer();buf.cmdBeginRendering(lvk::RenderPass{.color = { { .loadOp = LoadOp_Clear,.storeOp = StoreOp_MsaaResolve,.clearColor = {1, 1, 1, 1} } },.depth = { .loadOp = lvk::LoadOp_Clear,.storeOp = StoreOp_MsaaResolve,.clearDepth = 1.0f } },lvk::Framebuffer{.color = {{.texture = msaaColor,.resolveTexture = offscreenColor}},.depthStencil = {.texture = msaaDepth,.resolveTexture = offscreenDepth }});skyBox.draw(buf, view, proj);mesh.draw(buf, view, proj, skyBox.texSkyboxIrradiance, drawWireframe);app.drawGrid(buf, proj, vec3(0, -1.0f, 0), kNumSamples);buf.cmdEndRendering();
- Once the scene is rendered and resolved, we run our compute shader to generate SSAO using the scene’s depth buffer information.
buf.cmdBindComputePipeline(pipelineSSAO);buf.cmdPushConstants(pcSSAO);buf.cmdDispatchThreadGroups({ .width = 1 + (uint32_t)sizeFb.width / 16,.height = 1 + (uint32_t)sizeFb.height / 16 },{ .textures = {TextureHandle(offscreenDepth),TextureHandle(texSSAO) } });
- While the resulting raw SSAO texture in Figure 10.7 is already useful, it can be significantly improved with a simple blur effect.

Figure 10.7: Raw SSAO texture
We apply our multipass separable Gaussian blur to it.
if (enableBlur) { const lvk::Dimensions blurDim = { .width = 1 + sizeFb.width / 16, .height = 1 + sizeFb.height / 16, }; struct BlurPC { uint32_t texDepth; uint32_t texIn; uint32_t texOut; float depthThreshold; }; struct BlurPass { TextureHandle texIn; TextureHandle texOut; };- The interesting part here is the ping-pong passes for the blur. We run the shader twice per pass – once for horizontal blur and once for vertical blur. We use push constants to specify the inputs and outputs for each shader run.
std::vector<BlurPass> passes;passes.reserve(2 * numBlurPasses);passes.push_back({ texSSAO, texBlur[0] });for (int i = 0; i != numBlurPasses - 1; i++) {passes.push_back({ texBlur[0], texBlur[1] });passes.push_back({ texBlur[1], texBlur[0] });}passes.push_back({ texBlur[0], texSSAO });
- Next, we go through these pre-made push constants and invoke the shaders, alternating between the horizontal and vertical blur shaders for even and odd invocations. Note how the
texInandtexOuttextures are passed as dependencies tocmdDispatchThreadGroups()to allow LightweightVK to insert the appropriate image memory barriers.for (uint32_t i = 0; i != passes.size(); i++) {const BlurPass p = passes[i];buf.cmdBindComputePipeline(i & 1 ? pipelineBlurX : pipelineBlurY);buf.cmdPushConstants(BlurPC{.texDepth = offscreenDepth.index(),.texIn = p.texIn.index(),.texOut = p.texOut.index(),.depthThreshold = pcSSAO.zFar * depthThreshold });buf.cmdDispatchThreadGroups(blurDim, { .textures = { p.texIn, p.texOut,TextureHandle(offscreenDepth)} });}} - At this point, our SSAO effect is fully rendered into the
texSSAOtexture and looks as in the following screenshot. Notice how the blur effect is not applied to areas with depth discontinuities. This is called a bilateral blur, and we will explore it shortly when we examine the GLSL shaders.
Figure 10.8: Blurred SSAO buffer
- Now, let’s draw a full-screen quad, as described in Implementing full-screen triangle rendering, to render the combined scene with the SSAO effect into a swapchain image. In addition to normal rendering, we added draw modes to display either the SSAO effect alone or the rendered scene without SSAO.
if (drawMode == DrawMode_SSAO) {buf.cmdCopyImage(texSSAO,ctx->getCurrentSwapchainTexture(),ctx->getDimensions(offscreenColor));} else if (drawMode == DrawMode_Color) {buf.cmdCopyImage(offscreenColor,ctx->getCurrentSwapchainTexture(),ctx->getDimensions(offscreenColor));}const lvk::RenderPass renderPassMain = {.color = { { .loadOp = lvk::LoadOp_Load,.clearColor = { 1, 1, 1, 1 } } } };const lvk::Framebuffer framebufferMain = {.color = { { .texture = ctx->getCurrentSwapchainTexture() } } };buf.cmdBeginRendering(renderPassMain,framebufferMain,{ .textures = {TextureHandle(texSSAO)} });
- Here is our actual SSAO Combine shader. We skipped the ImGui rendering code for the sake of brevity.
if (drawMode == DrawMode_ColorSSAO) {buf.cmdBindRenderPipeline(pipelineCombine);buf.cmdPushConstants(pcCombine);buf.cmdBindDepthState({});buf.cmdDraw(3);}// … ImGui rendering skipped here …buf.cmdEndRendering();ctx->submit(buf, ctx->getCurrentSwapchainTexture());});// …}
That’s all for the C++ code. Now, let’s take a look at the GLSL shaders to understand how the SSAO effect works.
How it works…
Section titled “How it works…”Now that we have an overall sense of the rendering process, we can start examining the GLSL shader code.
The compute shader Chapter10/04_SSAO/src/SSAO.comp takes the scene depth buffer and the rotation vectors texture as input. This texture contains 16 random vec3 vectors, a technique originally proposed by Crytek in the early days of real-time SSAO algorithms.

Figure 10.9: Random vectors texture (4x4 pixels)
- We start by declaring shader inputs and texture access helper functions.
layout (local_size_x = 16, local_size_y = 16) in;layout (set = 0, binding = 0) uniform texture2D kTextures2D[];layout (set = 0, binding = 1) uniform sampler kSamplers[];layout (set = 0, binding = 2, rgba8) uniform writeonly image2D kTextures2DOut[];ivec2 textureBindlessSize2D(uint textureid) {return textureSize(nonuniformEXT(kTextures2D[textureid]), 0);}vec4 textureBindless2D(uint textureid, vec2 uv) {return textureLod(nonuniformEXT(sampler2D(kTextures2D[textureid],kSamplers[pc.smpl])), uv, 0);}
- The helper function
scaleZ()normalizes the depth buffer value into the0…1range.layout(push_constant) uniform PushConstants {uint texDepth;uint texRotation;uint texOut;uint smpl;float zNear;float zFar;float radius;float attScale;float distScale;} pc;float scaleZ(float smpl) {return (pc.zFar * pc.zNear) /(smpl * (pc.zFar - pc.zNear) - pc.zFar);} - Let’s define a table with 3D offsets for
8points to sample around the current fragment.const vec3 offsets[8] = vec3[8](vec3(-0.5, -0.5, -0.5), vec3( 0.5, -0.5, -0.5),vec3(-0.5, 0.5, -0.5), vec3( 0.5, 0.5, -0.5),vec3(-0.5, -0.5, 0.5), vec3( 0.5, -0.5, 0.5),vec3(-0.5, 0.5, 0.5), vec3( 0.5, 0.5, 0.5) ); - The
main()function calculates thexytexel position and the correspondinguvcoordinates, shifted to texel centers by0.5pixels.void main() {const vec2 size = textureBindlessSize2D(pc.texDepth).xy;const vec2 xy = gl_GlobalInvocationID.xy;const vec2 uv = (gl_GlobalInvocationID.xy + vec2(0.5)) / size;if (xy.x > size.x || xy.y > size.y) return; - Next, we take the aforementioned random rotations 4x4 texture, tile it across the entire framebuffer, and sample a
vec3value from it corresponding to the current fragment. This value serves as a normal vector to a random plane. In the attenuation accumulation loop, we reflect each of ourvec3offsets from this plane, producing a new sampling point,rSample, in the neighborhood of our area of interest, defined by thepc.radiusvalue. The depth valuezSamplefor this point is sampled from the depth texture and immediately converted to eye space. Afterward, the value is zero-clipped and scaled using an ad hocpc.distScaleparameter, which can be controlled through ImGui.const float Z = scaleZ( textureBindless2D(pc.texDepth, uv).x );const vec3 plane = textureBindless2D(pc.texRotation, xy / 4.0).xyz - vec3(1.0);float att = 0.0;for ( int i = 0; i < 8; i++ ) {vec3 rSample = reflect( offsets[i], plane );float zSample = scaleZ( textureBindless2D(pc.texDepth, uv + pc.radius*rSample.xy/Z ).x );float dist = max(zSample - Z, 0.0) / pc.distScale; - The distance difference
occlis scaled by an arbitrarily selected weight. Further averaging is performed using quadratic attenuation, according to the formulaO(dZ)= (dZ > 0) ? 1/(1+dZ^2) : 0. The final scale factorpc.attScaleis controlled through ImGui:float occl = 15.0 * max( dist * (2.0-dist), 0.0 );att += 1.0 / (1.0 + occl*occl);}att = clamp(att*att/64 + 0.45, 0, 1) * pc.attScale;imageStore( kTextures2DOut[pc.texOut], ivec2(xy), vec4( vec3(att), 1.0 ) );}
While this method does not even come close to the best screen-space ambient occlusion implementations, it is very simple in terms of its input parameters and can operate using just a naked depth buffer.
Let’s quickly take a look at how to blur the SSAO values. The blurring compute shader is located in data/shaders/Blur.comp.
- There is a table containing
17weights for the Gaussian blur, which add up to1.0. You can compute your own set of weights for any number of values using this online tool: https://drdesten.github.io/web/tools/gaussian_kernel.const int kFilterSize = 17;const float gaussWeights[kFilterSize] = float; - We use a specialization constant to distinguish between horizontal and vertical blur. All shader parameters are passed as push constants. This bilateral blur shader requires the depth buffer to calculate depth discontinuities.
layout(constant_id = 0) const bool kIsHorizontal=true;layout(push_constant) uniform PushConstants {uint texDepth;uint texIn;uint texOut;float depthThreshold;} pc;
- The main() function calculates the input texture size, the xy texel position, and the normalized texture coordinates, texCoord.
void main() {const vec2 size = textureBindlessSize2D(pc.texIn).xy;const vec2 xy = gl_GlobalInvocationID.xy;if (xy.x > size.x || xy.y > size.y) return;const vec2 texCoord = (gl_GlobalInvocationID.xy + vec2(0.5)) / size;const float texScaler = 1.0 / (kIsHorizontal ? size.x : size.y);vec3 c = vec3(0.0);vec3 fragColor = textureBindless2D(pc.texIn, texCoord).rgb;float fragDepth = textureBindless2D(pc.texDepth, texCoord).r;
- Gaussian averaging is performed inside this for loop.
for ( int i = 0; i != kFilterSize; i++ ) {float offset = float(i - kFilterSize/2);vec2 uv = texCoord + texScaler * (kIsHorizontal ?vec2(offset, 0) : vec2(0, offset));vec3 color = textureBindless2D(pc.texIn, uv).rgb;float depth = textureBindless2D(pc.texDepth, uv).r;
- The most interesting part here is the bilateral blur calculation. We compute the depth difference weight by comparing the depth value difference between the current offset pixel and the central pixel
fragDepth. This difference is then scaled by an ad hocpc.depthThresholdfactor, which is controlled through ImGui. The resultingweightvalue is used to interpolate between the center pixel colorfragColorand the offset pixel color, effectively reducing the amount of blur between pixels with significantly different depth values.float w = clamp(abs(depth - fragDepth) * pc.depthThreshold, 0.0, 1.0);c += mix(color, fragColor, w) * gaussWeights[i];}imageStore(kTextures2DOut[pc.texOut], ivec2(xy), vec4(c, 1.0) );}
This simple bilateral blur technique greatly improves the visual quality of our SSAO effect.
To combine the resulting SSAO effect with the rendered scene, the following full-screen GLSL fragment shader should be used, which is located in the Chapter10/04_SSAO/src/combine.frag file. The scale and bias values are controlled through ImGui.
layout (location=0) in vec2 uv;layout (location=0) out vec4 out_FragColor;layout(push_constant) uniform PushConstants { uint texColor; uint texSSAO; uint smpl; float scale; float bias;} pc;void main() { vec4 color = textureBindless2D(pc.texColor, pc.smpl, uv); float ssao = clamp(textureBindless2D( pc.texSSAO, pc.smpl, uv).x + pc.bias, 0.0, 1.0 ); out_FragColor = vec4(mix(color, color * ssao, pc.scale).rgb, 1.0 );}Now, our SSAO implementation is complete. The demo application should render the following image:

Figure 10.10: SSAO demo
With all this knowledge, you should be able to add a similar SSAO effect to your rendering engine. In the next recipe, we will learn how to implement a more complex post-processing scheme for HDR rendering and tone mapping.
There’s more…
Section titled “There’s more…”The SSAO algorithm used here is very naïve and basic. For more advanced techniques, look into modern implementations like horizon-based ambient occlusion (HBAO) or ground truth ambient occlusion (GTAO).
While running the demo, you may have noticed that the SSAO effect behaves strangely on transparent surfaces. This is understandable, as our transparency rendering is done using punch-through transparency, where part of the transparent surface pixels are discarded based on their transparency value. These holes expose the depth values beneath the transparent surface, causing the SSAO effect to work inconsistently. In a real-world rendering engine, you would likely want to calculate the SSAO effect after the opaque objects have been fully rendered and before any transparent objects affect the depth buffer.
Implementing HDR rendering and tone mapping
Section titled “Implementing HDR rendering and tone mapping”In all our previous examples, the color values in the framebuffer were always clamped between 0.0 and 1.0. Additionally, we used 1 byte for each color component in the framebuffer, allowing for only 256 levels of brightness. This limits the contrast ratio between the darkest and brightest areas of the image to 255:1.
While this may be sufficient for many applications, it poses a problem in scenarios with very bright regions, such as areas illuminated by the sun or multiple light sources. In such cases, values exceeding 1.0 are clipped, and any brightness information above this limit is lost. HDR brightness values preserve these details, improving image realism, and can be mapped back into the 0.0 to 1.0 low dynamic range (LDR) using various tone mapping techniques.
In this recipe, we will walk through setting up HDR rendering and cover all the steps needed to implement a basic tone mapping pipeline.
Getting ready
Section titled “Getting ready”You can find the source code for this recipe in the Chapter10/05_HDR folder.
Before diving in, be sure to review the previous recipes: Implementing screen space ambient occlusion, Implementing full-screen triangle rendering, and Implementing offscreen rendering in Vulkan.
How to do it…
Section titled “How to do it…”To implement HDR rendering, we need to store HDR values in the framebuffers. This can be achieved using Vulkan floating-point color formats like VK_FORMAT_R16G16B16A16_SFLOAT, a 16-bit floating-point RGBA format suitable for rendering.
Other floating-point pixel formats, like A2B10G10R10_SNORM_PACK32 or B10G11R11_UFLOAT_PACK32, are more memory-efficient and can be used in many scenarios.
After rendering the scene into a floating-point HDR framebuffer, we can calculate the average luminance of the HDR image for our tone mapping calculations. Additionally, we can identify high-luminance areas and use them to simulate the bloom effect seen in real-world cameras: https://en.wikipedia.org/wiki/Bloom_(shader_effect).
Let’s walk through the C++ code in Chapter10/05_HDR/src/main.cpp to understand the complete HDR rendering and tone mapping pipeline:
- As usual, the
main()function loads the Bistro mesh and sets up all the necessary objects. The Bistro scene is rendered using the shaders located inChapter08/02_SceneGraph/src/main.*, which apply image space lighting to the Bistro model. This process is similar to what was done in Chapter 6, except that this time, only the diffuse component of image-based lighting (IBL) is used. This ensures that the Bistro mesh has some HDR lighting applied to it. Additionally, the skybox uses an HDR image for the cube map, contributing HDR values as well.int main() {MeshData meshData;Scene scene;loadBistro(meshData, scene);VulkanApp app({…});std::unique_ptr<lvk::IContext> ctx(app.ctx_.get());const uint32_t kNumSamples = 8;const Format kOffscreenFormat = Format_RGBA_F16;const Skybox skyBox(ctx, …);const VKMesh mesh(ctx, …); - Next, we create a compute pipeline using the
BrightPass.compcompute shader, which identifies the bright areas in the rendered scene and converts the entire HDR scene to 16-bit luminance. We’ll explore this further in the How it works… section.Holder<ShaderModuleHandle> compBrightPass =loadShaderModule(ctx, "Chapter10/05_HDR/src/BrightPass.comp");Holder<ComputePipelineHandle>pipelineBrightPass = ctx->createComputePipeline({.smComp = compBrightPass }); - The next step is to create two compute pipelines for the Bloom effect using the
Chapter10/05_HDR/src/Bloom.compshader. The Bloom effect is somewhat similar to the blur effect described in the previous recipe, Implementing screen space ambient occlusion, and is implemented in a similar manner. Two passes are used to generate the horizontal and vertical components of the bloom, utilizing ping-pong buffers. This shader is simpler than the blur shader because it does not perform bilateral filtering.const uint32_t kHorizontal = 1;const uint32_t kVertical = 0;Holder<ShaderModuleHandle> compBloomPass =loadShaderModule(ctx, "Chapter10/05_HDR/src/Bloom.comp");Holder<ComputePipelineHandle> pipelineBloomX =ctx->createComputePipeline({.smComp = compBloomPass,.specInfo = {.entries = {{.constantId = 0, .size = sizeof(uint32_t) }},.data = &kHorizontal,.dataSize = sizeof(uint32_t)} });Holder<ComputePipelineHandle> pipelineBloomY =ctx->createComputePipeline({.smComp = compBloomPass,.specInfo = {.entries = {{.constantId = 0, .size = sizeof(uint32_t) }},.data = &kVertical,.dataSize = sizeof(uint32_t)} }); - A graphics pipeline is needed for tone mapping, which renders a full-screen rectangle onto a swapchain image. The tone mapping shader is particularly interesting, and we will explore it in the How it works… section.
Holder<ShaderModuleHandle> vertToneMap =loadShaderModule(ctx, "data/shaders/QuadFlip.vert");Holder<ShaderModuleHandle> fragToneMap =loadShaderModule(ctx, "Chapter10/05_HDR/src/ToneMap.frag");Holder<RenderPipelineHandle> pipelineToneMap =ctx->createRenderPipeline({.smVert = vertToneMap,.smFrag = fragToneMap,.color ={ { .format = ctx->getSwapchainFormat() } }});
- A
Clampsampler is needed to prevent edge texels from wrapping around the texture edges.Holder<SamplerHandle> samplerClamp =ctx->createSampler({.wrapU = lvk::SamplerWrap_Clamp,.wrapV = lvk::SamplerWrap_Clamp,.wrapW = lvk::SamplerWrap_Clamp }); - Next, let’s create textures for our offscreen render targets. The first set of textures is for multisampled rendering, as explained in the recipe Implementing MSAA in Vulkan. It is worth noting that
kOffscreenFormathere is an HDR format,Format_RGBA_F16, which corresponds to the Vulkan formatVK_FORMAT_R16G16B16A16_SFLOAT. It can store color values outside the0..1range.const lvk::Dimensions sizeFb =ctx->getDimensions(ctx->getCurrentSwapchainTexture());Holder<TextureHandle> msaaColor = ctx->createTexture({.format = kOffscreenFormat,.dimensions = sizeFb,.numSamples = kNumSamples,.usage = lvk::TextureUsageBits_Attachment });Holder<TextureHandle> msaaDepth = ctx->createTexture({.format = app.getDepthFormat(),.dimensions = sizeFb,.numSamples = kNumSamples,.usage = lvk::TextureUsageBits_Attachment }); - The
offscreenColortexture is used to resolve the MSAA color information. The depth texture is not used in our HDR post-processing so we do not have to resolve it.Holder<TextureHandle> offscreenColor =ctx->createTexture({.format = kOffscreenFormat,.dimensions = sizeFb,.usage = lvk::TextureUsageBits_Attachment |lvk::TextureUsageBits_Sampled |lvk::TextureUsageBits_Storage }); - The bright pass and bloom textures are smaller, with a resolution of 512x512. They are supposed to capture only low-frequency image details and don’t need to be high-resolution.
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 });
- Let’s create a texture to store the average scene luminance. The goal is to convert the rendered scene into a single-channel 16-bit image format representing luminance and then downscale it to a
1x1texture using the mipmapping pyramid. The single pixel in the1x1mip level represents the average luminance. For debugging and demonstration purposes, we will display the mip pyramid’s contents via ImGui, using the texture views approach described in the recipe Implementing offscreen rendering in Vulkan. Component swizzling is applied to render the single-channel R image as a grayscale image. A mip pyramid for a512x512texture consists of10mip levels.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 }) }; - In the
texLumViews[]array, only the0-th element is the actual texture; the rest are texture views.for (uint32_t v = 1; v != LVK_ARRAY_NUM_ELEMENTS(texLumViews); v++)texLumViews[v] =ctx->createTextureView(texLumViews[0],{ .mipLevel = v, .swizzle = swizzle }); - Here are two ping-pong textures used to compute the bloom effect over multiple passes.
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 }),};
- We are almost ready to start rendering. We just need a few variables to tweak the rendering using the ImGui UI. The
ToneMappingModeenum lets us switch between different tone mapping operators, such as Reinhard, Uchimura, and the Khronos PBR Neutral Tone Mapper, for easy comparison. We also set up anImPlotContextto visualize our tone mapping curves within the ImGui UI using the ImPlot library.bool drawCurves = true;bool enableBloom = true;float bloomStrength = 0.1f;int numBloomPasses = 2;enum ToneMappingMode {ToneMapping_None = 0,ToneMapping_Reinhard = 1,ToneMapping_Uchimura = 2,ToneMapping_KhronosPBR = 3,};ImPlotContext* implotCtx = ImPlot::CreateContext(); - The
pcHDRvariable is used to pass push constants to our HDR tone mapping shader. It includes the default values for all the different tone mapping algorithms, and its parameters can be adjusted dynamically through the UI.struct {uint32_t texColor;uint32_t texLuminance;uint32_t texBloom;uint32_t sampler;int drawMode = ToneMapping_Uchimura;float exposure = 1.0f;float bloomStrength = 0.1f;// Reinhardfloat maxWhite = 1.0f;// Uchimurafloat P = 1.0f; // max display brightnessfloat a = 1.05f; // contrastfloat m = 0.1f; // linear section startfloat l = 0.8f; // linear section lengthfloat c = 3.0f; // black tightnessfloat b = 0.0f; // pedestal// Khronos PBRfloat startCompression = 0.8f; // highlight compression startfloat desaturation = 0.15f; // desaturation speed} pcHDR = {.texColor = offscreenColor.index(),.texLuminance = texLumViews[LVK_ARRAY_NUM_ELEMENTS(texLumViews)-1].index(),.texBloom = texBloomPass.index(),.sampler = samplerClamp.index(),};
With all these preparations completed, we can proceed to the rendering loop. Let’s go through it step by step.
- We begin by updating the view and projection matrices, rendering the scene into the multisampled render targets, and resolving the color data into the
offscreenColortexture. Since the depth texture is not used in this HDR demo, it is not resolved.app.run([&](uint32_t width, uint32_t height,float aspectRatio, float deltaSeconds) {const mat4 view = app.camera_.getViewMatrix();const mat4 proj = glm::perspective(…);ICommandBuffer& buf = ctx->acquireCommandBuffer();buf.cmdBeginRendering(lvk::RenderPass{.color = { { .loadOp = LoadOp_Clear,.storeOp = StoreOp_MsaaResolve,.clearColor = { 1, 1, 1, 1 } } },.depth = { .loadOp = lvk::LoadOp_Clear,.clearDepth = 1.0f } },lvk::Framebuffer{.color = {{.texture = msaaColor,.resolveTexture = offscreenColor}},.depthStencil = { .texture = msaaDepth } }); - We render the skybox, the Bistro mesh, and the infinite grid. To simplify handling transparency, we render the skybox first.
Note
The skybox is rendered first here for simplicity. In a real application, it’s usually better to avoid processing sky fragments that will ultimately be occluded.
skyBox.draw(buf, view, proj);mesh.draw(buf, view, proj, skyBox.texSkyboxIrradiance, drawWireframe);app.drawGrid(buf, proj, vec3(0, -1.0f, 0), kNumSamples, kOffscreenFormat);buf.cmdEndRendering();- Once we finish rendering the main scene into a floating-point render target, we start our post-processing pipeline. Bright regions are extracted from the rendered image and stored in the
texBrightPasstexture, and the scene converted to luminance is stored intexLumViews[0]. The compute shader used isChapter10/05_HDR/src/BrightPass.comp.const struct {uint32_t texColor;uint32_t texOut;uint32_t texLuminance;uint32_t sampler;float exposure;} pcBrightPass = {.texColor = offscreenColor.index(),.texOut = texBrightPass.index(),.texLuminance = texLumViews[0].index(),.sampler = samplerClamp.index(),.exposure = pcHDR.exposure,};buf.cmdBindComputePipeline(pipelineBrightPass);buf.cmdPushConstants(pcBrightPass); - Our compute shader operates on
16x16texel blocks. Once the luminance texture is ready, we generate the entire mip pyramid down to1x1, which represents the average scene luminance.buf.cmdDispatchThreadGroups(sizeBloom.divide2D(16), { .textures ={ TextureHandle(offscreenColor), TextureHandle(texLumViews[0])} });buf.cmdGenerateMipmap(texLumViews[0]);
The resulting luminance mip pyramid is later rendered via ImGui and should appear as shown in the following screenshot.

Figure 10.11: Mip pyramid to compute average luminance
- Next, we return to the bright areas of the scene, which were extracted into the
texBrightPasstexture, and apply a multipass separable Gaussian filter to simulate the Bloom effect. The bright areas will be heavily blurred, creating halos that leak into the adjacent pixels. The technique used here for the multipass bloom effect is exactly the same as the one used for the blur in the previous recipe, Implementing screen space ambient occlusion. We leave the code here without comments to help better understand the flow of the subsequent code.struct BlurPC {uint32_t texIn;uint32_t texOut;uint32_t sampler;};struct StreaksPC {uint32_t texIn;uint32_t texOut;uint32_t texRotationPattern;uint32_t sampler;};struct BlurPass {TextureHandle texIn;TextureHandle texOut;};std::vector<BlurPass> passes;passes.reserve(2 * numBloomPasses);passes.push_back({ texBrightPass, texBloom[0] });for (int i = 0; i != numBloomPasses - 1; i++) {passes.push_back({ texBloom[0], texBloom[1] });passes.push_back({ texBloom[1], texBloom[0] });}passes.push_back({ texBloom[0], texBloomPass });for (uint32_t i = 0; i != passes.size(); i++) {const BlurPass p = passes[i];buf.cmdBindComputePipeline(i & 1 ? pipelineBloomX : pipelineBloomY);buf.cmdPushConstants(BlurPC{.texIn = p.texIn.index(),.texOut = p.texOut.index(),.sampler = samplerClamp.index() });if (enableBloom)buf.cmdDispatchThreadGroups(sizeBloom.divide2D(16), {.textures = { p.texIn, p.texOut, TextureHandle(texBrightPass)} });} - Now that everything is set up, we can combine all the intermediate textures and perform the most complex part – tone mapping. We render a full-screen triangle into a swapchain image using our tone mapping shader
Chapter10/05_HDR/src/ToneMap.frag. The input textures for the shader are the resolved HDR scene image, the average luminance value, and the blurred bloom texture, all of which are stored in thepcHDRvariable and passed into the shader as push constants.const lvk::RenderPass renderPassMain = {.color = { { .loadOp = lvk::LoadOp_Load,.clearColor = { 1, 1, 1, 1 } } } };const lvk::Framebuffer framebufferMain = {.color = { { .texture = ctx->getCurrentSwapchainTexture() } } }; - The tone mapping shader uses only the last
1x1level of the mip pyramid. However, LightweightVK implements image memory barriers at the Vulkan resource levelVkImage, not at the subresource level of individual texture mip levels. This requires us to transition the entire mip pyramid toVK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL.buf.cmdBeginRendering(renderPassMain, framebufferMain,{ .textures = { TextureHandle(texLumViews[0]) } });buf.cmdBindRenderPipeline(pipelineToneMap);buf.cmdPushConstants(pcHDR);buf.cmdBindDepthState({});buf.cmdDraw(3);
Note
This “greedy” image layout transition is fine for a demo like this, but it can become a significant inefficiency in a real rendering engine, especially when multiple effects are rendered in parallel and reuse different Vulkan subresources. Instead of tracking the Vulkan resource state at the subresource level for individual mip levels, a more generic solution exists: the frame graph. A frame graph helps plan and schedule all required operations on GPU and CPU resources for a frame in the most efficient way. It is 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.
Technically, at this point, the final scene image has been tone-mapped and rendered into a swapchain image, so we can conclude our C++ work here and call it a day. However, in this recipe, we will also walk through some parts of the ImGui UI rendering. Besides controlling the tone mapping parameters, we use it to display our tone mapping curves. This can be quite useful for graphics debugging and will complement the material covered in Chapter 5.
- First, we create an ImGui window with a fixed screen position and a fixed size relative to the size of the screen.
const ImGuiViewport* v = ImGui::GetMainViewport();const float windowWidth = v->WorkSize.x / 5;ImGui::SetNextWindowPos(ImVec2(10, 200));ImGui::SetNextWindowSize(ImVec2(0, v->WorkSize.y - 210));ImGui::Begin("HDR", nullptr, ImGuiWindowFlags_NoFocusOnAppearing);
- Next, we add a series of checkboxes and sliders to control the generic rendering and tone mapping parameters that are shared across all our tone mapping modes.
ImGui::Checkbox("Draw tone curves", &drawCurves);ImGui::SliderFloat("Exposure", &pcHDR.exposure, 0.1f, 2.0f);ImGui::Checkbox("Enable bloom", &enableBloom);pcHDR.bloomStrength = enableBloom?bloomStrength:0;ImGui::SliderFloat("Bloom strength", &bloomStrength, 0.0f, 1.0f);ImGui::SliderInt("Bloom num passes", &numBloomPasses, 1, 5);
- Here are the radio buttons to select between different tone mapping modes. Each mode has its own set of parameters, which are displayed only when the corresponding mode is selected.
ImGui::Text("Tone mapping mode:");ImGui::RadioButton("None", &pcHDR.drawMode, ToneMapping_None);ImGui::RadioButton("Reinhard", &pcHDR.drawMode, ToneMapping_Reinhard);if (pcHDR.drawMode == ToneMapping_Reinhard) {ImGui::SliderFloat("Max white", &pcHDR.maxWhite, 0.5f, 2.0f);}// … parameters for other tone mapping modes…ImGui::Separator();
- Then, we display all the intermediate textures: the
1x1average luminance texture, the bright pass texture, and the bloom pass texture.ImGui::Text("Average luminance 1x1:");ImGui::Image(pcHDR.texLuminance, ImVec2(128, 128));ImGui::Text("Bright pass:");ImGui::Image(texBrightPass.index(),ImVec2(windowWidth, windowWidth / aspectRatio));ImGui::Text("Bloom pass:");ImGui::Image(texBloomPass.index(),ImVec2(windowWidth, windowWidth / aspectRatio)); - The entire luminance mip pyramid can be displayed this way using texture views. Since we set up texture component swizzling, our single-channel R luminance texture is rendered as a grayscale texture. Note how we pass the unsigned integer texture
index()value directly into ImGui. This is possible starting from ImGui 1.91.4, as theImTextureIDtype was changed fromvoid*touint64_t, making it much more convenient to use with LightweightVK.ImGui::Text("Luminance pyramid 512x512");for (uint32_t v = 0; v != LVK_ARRAY_NUM_ELEMENTS(texLumViews); v++) {ImGui::Image( texLumViews[v].index(),ImVec2((int)windowWidth >> v,(int)windowWidth >> v));}ImGui::End(); - Now comes the most interesting part: drawing the tone mapping curves. These are the graphs of tone mapping functions that convert HDR image values into final LDR image values.
if (drawCurves) {const ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | …;ImGui::SetNextWindowBgAlpha(0.8f);ImGui::SetNextWindowPos({ width * 0.6f, height * 0.7f },ImGuiCond_Appearing);ImGui::SetNextWindowSize({ width * 0.4f, height * 0.3f });ImGui::Begin("Tone mapping curve", nullptr, flags);
- We will sample
1001points from each function, in the range from0to1, and store the resulting function values in the arraysysUchimura,ysReinhard2, andysKhronosPBR. The tone mapping functions, declared in theshared/Tonemap.hfile, are C++ mirror images of their GLSL implementations, which are used in the tone mapping shader. We will examine them shortly. The functions take in the same push constant values frompcHDR, which are passed into the shader. This means that when we tweak the parameters via ImGui, the tone mapping graphs change their shape accordingly.const int kNumGraphPoints = 1001;float xs[kNumGraphPoints];float ysUchimura[kNumGraphPoints];float ysReinhard2[kNumGraphPoints];float ysKhronosPBR[kNumGraphPoints];for (int i = 0; i != kNumGraphPoints; i++) {xs[i] = float(i) / kNumGraphPoints;ysUchimura[i] = uchimura(xs[i], pcHDR.P,pcHDR.a, pcHDR.m, pcHDR.l, pcHDR.c, pcHDR.b);ysReinhard2[i] = reinhard2(xs[i], pcHDR.maxWhite);ysKhronosPBR[i] = PBRNeutralToneMapping(xs[i],pcHDR.startCompression, pcHDR.desaturation);} - We use the sampled values to draw the graphs using the ImPlot library. You can interact with the graphs in the running demo.
if (ImPlot::BeginPlot("Tone mapping curves",{ width * 0.4f, height * 0.3f }, ImPlotFlags_NoInputs)){ImPlot::SetupAxes("Input", "Output");ImPlot::PlotLine("Uchimura", xs, ysUchimura, kNumGraphPoints);ImPlot::PlotLine("Reinhard", xs, ysReinhard2, kNumGraphPoints);ImPlot::PlotLine("Khronos PBR", xs, ysKhronosPBR, kNumGraphPoints);ImPlot::EndPlot();}ImGui::End();}
- After the ImGui rendering is complete, we end the frame, submit the entire command buffer for execution, and present the rendered swapchain image.
app.imgui_->endFrame(buf);buf.cmdEndRendering();ctx->submit(buf, ctx->getCurrentSwapchainTexture());});ImPlot::DestroyContext(implotCtx);// …}
The C++ part was relatively long due to the ImGui and ImPlot code. However, the overall flow of the HDR pipeline is quite similar to the previous SSAO one. Now, let’s dive into the GLSL shader code to understand how the actual tone mapping works.
How it works…
Section titled “How it works…”The real actual work is done in the shaders. The first shader is the compute shader Chapter10/05_HDR/src/BrightPass.comp, which is responsible for extracting the bright areas and converting the scene image to luminance. Let’s take a look.
- The shader takes in the HDR scene 16-bit RGBA color texture
texColorand computes two textures: one colored 16-bit texturetexOutfor the bright RGBA areas, and one 16-bit single-channel luminance imagetexLuminance.layout (local_size_x = 16, local_size_y = 16) in;layout (set = 0, binding = 2, rgba16)uniform writeonly image2D kTextures2DOutRGBA[];layout (set = 0, binding = 2, r16)uniform writeonly image2D kTextures2DOutR[];layout(push_constant) uniform PushConstants {uint texColor; // rgba16uint texOut; // rgba16uint texLuminance; // r16uint smpl;float exposure;} pc;void main() {const vec2 sizeIn = textureBindlessSize2D(pc.texColor).xy;const vec2 sizeOut = textureBindlessSize2D(pc.texOut).xy;const vec2 xy = gl_GlobalInvocationID.xy;const vec2 uv0 = (gl_GlobalInvocationID.xy + vec2(0)) / sizeOut;const vec2 uv1 = (gl_GlobalInvocationID.xy + vec2(1)) / sizeOut;if (xy.x > sizeIn.x || xy.y > sizeIn.y) return; - The bright areas texture is a downscaled
512x512texture. We use a3x3box filter to soften the results.
Note
This 3x3 box filter technique will still result in some visible fireflies – very bright, pulsating pixels caused by high-intensity values in the HDR render target. To reduce this effect, check out the Karis average algorithm from https://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare, which adds temporal stability.
vec2 dxdy = (uv1-uv0) / 3;vec4 color = vec4(0);for (int v = 0; v != 3; v++) for (int u = 0; u != 3; u++) color += textureBindless2D(pc.texColor, uv0 + vec2(u, v) * dxdy );- We use the dot product to convert the RGB color information to luminance. The
exposurescaling factor, which is controlled through ImGui, is applied at this stage. The pixel value ends up in the bright areas image only when its luminance value is greater than1.0.float luminance = pc.exposure * dot(color.rgb / 9, vec3(0.2126, 0.7152, 0.0722));vec3 rgb = luminance > 1.0 ? color.rgb : vec3(0);imageStore(kTextures2DOutRGBA[pc.texOut], ivec2(xy), vec4( rgb, 1.0 ) );imageStore(kTextures2DOutR[pc.texLuminance], ivec2(xy), vec4(luminance ) );}
The second shader is the Bloom shader, Chapter10/05_HDR/src/Bloom.comp. It generates bloom using the separable blur technique described in the previous recipe, Implementing screen space ambient occlusion. It uses the same Gaussian coefficients but does not require the bilateral blur technique. Here’s its main() function for reference:
void main() { const vec2 size = textureBindlessSize2D(pc.texIn).xy; const vec2 xy = gl_GlobalInvocationID.xy; if (xy.x > size.x || xy.y > size.y) return; const vec2 texCoord = (gl_GlobalInvocationID.xy + vec2(0.5)) / size; const float texScaler = 1.0 / (kIsHorizontal ? size.x : size.y); vec3 c = vec3(0.0); for ( int i = 0; i != kFilterSize; i++ ) { float offset = float(i - kFilterSize/2); vec2 uv = texCoord + texScaler * (kIsHorizontal ? vec2(offset, 0) : vec2(0, offset)); c += textureBindless2D(pc.texIn, uv).rgb * gaussWeights[i]; } imageStore(kTextures2DOut[pc.texOut], ivec2(xy), vec4(c, 1.0) );}The last shader is Chapter10/05_HDR/src/ToneMap.frag, which performs the tone mapping and renders the resulting tone-mapped scene into a swapchain image. Since the main heavy lifting happens here, let’s take a close look.
- The first step is to declare the shader inputs. The tone mapping modes correspond to the C++
ToneMappingModeenum, and the push constant structure corresponds to thepcHDRvariable from C++.layout (location=0) in vec2 uv;layout (location=0) out vec4 out_FragColor;const int ToneMappingMode_None = 0;const int ToneMappingMode_Reinhard = 1;const int ToneMappingMode_Uchimura = 2;const int ToneMappingMode_KhronosPBR = 3;layout(push_constant) uniform PushConstants {uint texColor;uint texLuminance;uint texBloom;uint smpl;int drawMode;float exposure;float bloomStrength;// Reinhardfloat maxWhite;// Uchimurafloat P; // max display brightnessfloat a; // contrastfloat m; // linear section startfloat l; // linear section lengthfloat c; // black tightnessfloat b; // pedestal// Khronos PBRfloat startCompression; // highlight compression startfloat desaturation; // desaturation speed} pc; - The core of the tone mapping algorithm consists of the tone mapping functions. We use three different ones. The first is
reinhard2(), which is described in a blog post titled Tone Mapping by Matt Taylor: https://64.github.io/tonemapping. This is often referred to as the extended Reinhard tone mapping operator. Here, themaxWhitevalue is adjusted to represent the maximum brightness in the scene. Any values brighter than this will be mapped to1.0. The mapping is calculated based on the luminance values and not RGB values.float luminance(vec3 v) {return dot(v, vec3(0.2126, 0.7152, 0.0722));}vec3 reinhard2(vec3 v, float maxWhite) {float l_old = luminance(v);float l_new =l_old * (1.0 + (l_old / (maxWhite * maxWhite))) / (1.0 + l_old);return v * (l_new / l_old);} - The second tone mapping function we use was presented in HDR theory and practice by Hajime Uchimura in 2017: https://www.slideshare.net/nikuque/hdr-theory-and-practicce-jp. You can find more references in this presentation: http://cdn2.gran-turismo.com/data/www/pdi_publications/PracticalHDRandWCGinGTS_20181222.pdf. Its input parameters can be tweaked from ImGui.
vec3 uchimura(vec3 x, float P,float a, float m, float l, float c, float b) {float l0 = ((P - m) * l) / a;float L0 = m - m / a;float L1 = m + (1.0 - m) / a;float S0 = m + l0;float S1 = m + a * l0;float C2 = (a * P) / (P - S1);float CP = -C2 / P;vec3 w0 = vec3(1.0 - smoothstep(0.0, m, x));vec3 w2 = vec3(step(m + l0, x));vec3 w1 = vec3(1.0 - w0 - w2);vec3 T = vec3(m * pow(x / m, vec3(c)) + b);vec3 S = vec3(P - (P - S1) * exp(CP * (x - S0)));vec3 L = vec3(m + a * (x - m));return T * w0 + L * w1 + S * w2;}
- The third tone mapping function is Khronos PBR Neutral Tone Mapper from https://github.com/KhronosGroup/ToneMapping/blob/main/PBR_Neutral/README.md#pbr-neutral-specification.
vec3 PBRNeutralToneMapping(vec3 color,float startCompression, float desaturation) {startCompression -= 0.04;float x = min(color.r, min(color.g, color.b));float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;color -= offset;float peak = max(color.r, max(color.g, color.b));if (peak < startCompression) return color;const float d = 1. - startCompression;float newPeak = 1. - d * d / (peak + d - startCompression);color *= newPeak / peak;float g = 1. - 1. / (desaturation * (peak - newPeak) + 1.);return mix(color, newPeak * vec3(1, 1, 1), g);}
- With all the aforementioned tone mapping functions in place, the
main()function of our fragment shader is quite straightforward. We sample the color and bloom values for the current fragment, along with the average luminance value from our1x1luminance texture.void main() {vec3 color = textureBindless2D(pc.texColor, pc.smpl, uv).rgb;vec3 bloom = textureBindless2D(pc.texBloom, pc.smpl, uv).rgb;float avgLuminance = textureBindless2D(pc.texLuminance, pc.smpl, vec2(0.5)).r; - Then, we apply the corresponding tone mapping function to it using the parameters from push constants.
if (pc.drawMode != ToneMappingMode_None)color *= pc.exposure * 0.5/(avgLuminance + 0.001);if (pc.drawMode == ToneMappingMode_Reinhard)color = reinhard2(pc.exposure * color, pc.maxWhite);if (pc.drawMode == ToneMappingMode_Uchimura)color = uchimura(pc.exposure * color,pc.P, pc.a, pc.m, pc.l, pc.c, pc.b);if (pc.drawMode == ToneMappingMode_KhronosPBR)color = PBRNeutralToneMapping(pc.exposure * color,pc.startCompression, pc.desaturation);
- On top of the tone-mapped image, we add the bloom texture, scaled by the
bloomStrengthfactor.out_FragColor = vec4(color + pc.bloomStrength * bloom, 1.0);}
That’s all! The running demo should render the Bistro scene with a skybox, as shown in the following screenshot. Note how the bloom effect causes the bright sky color to bleed over the edges of the buildings:

Figure 10.12: A tone-mapped HDR scene
When you move the camera around, you can observe how the scene brightness adjusts based on the current average scene luminance. If you look at the sky, you will see more details in the bright areas, while the rest of the scene becomes darker. If you focus on the dark corners of the buildings, the sky will shift to white. The overall exposure can be manually adjusted in either direction using the ImGui slider.
One downside of this approach is that changes in exposure happen instantly. You look at a different area of the scene, and in the next frame, the exposure changes immediately. This is not how human vision works in reality. It takes time for our eyes to adapt from bright to dark areas. In the next recipe, we will learn how to extend this HDR post-processing pipeline to simulate light adaptation.
There’s more…
Section titled “There’s more…”Strictly speaking, applying a tone mapping operator directly to the RGB channel values is a crude approach. A more accurate model would involve tone mapping the luminance value and then applying it back to the RGB values. However, for many practical purposes, this simple approximation is sufficient. Our goal here is to demonstrate how to build an HDR rendering pipeline, not to strive for perfect physical accuracy.
Certain monitors natively support HDR and can handle swapchain images in Vulkan HDR formats and color spaces, such as VK_FORMAT_A2B10G10R10_UNORM_PACK32 and VK_COLOR_SPACE_HDR10_ST2084_EXT. For more details, check the Vulkan extensions VK_AMD_display_native_hdr and VK_EXT_hdr_metadata.
Another important remark is regarding how we calculated bloom. The bloom technique used here should be viewed more as a demonstration of how to organize the HDR pipeline in general rather than an attempt to compute a physically accurate bloom effect. The whole problem was described in detail more than 15 years ago in the blog post Bloom Disasters by Matthew Gallant: http://gangles.ca/2008/07/18/bloom-disasters. A realistic and physically correct post-processing technique with proper bloom can be found in the presentation Next Generation Post Processing in Call of Duty: Advanced Warfare by Jorge Jimenez: https://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare/. You can also refer to the tutorial Physically Based Bloom by Alexander Christensen for an alternative implementation: https://learnopengl.com/Guest-Articles/2022/Phys.-Based-Bloom.
Implementing HDR light adaptation
Section titled “Implementing HDR light adaptation”In the previous recipe, Implementing HDR rendering and tone mapping, we covered the foundational steps for building a basic HDR tone mapping pipeline. While that was a solid starting point, there is room to make it more realistic by simulating how human vision adapts to changes in brightness. In this recipe, we will extend our HDR post-processing pipeline to incorporate a dynamic light adaptation process, mimicking the way our eyes adjust to both intense light and darker environments over time.
Getting ready
Section titled “Getting ready”This recipe builds directly on the foundation laid in the previous recipe, Implementing HDR rendering and tone mapping. It is strongly recommended to review that recipe first to ensure you have a solid understanding of our HDR rendering pipeline.
The source code for this recipe is located in Chapter10/06_HDR_Adaptation.
How to do it…
Section titled “How to do it…”The light adaptation process operates by gradually transitioning between luminance levels. Rather than using the current average scene luminance value to tone map the scene immediately, we blend it with a previously computed luminance value. This previous value can initially be set to a very high level to simulate an overexposed state. The blending is done gradually in every frame through interpolation in a compute shader, creating a smooth transition between the old and new luminance values.
To incorporate this light adaptation approach into our previous HDR tone mapping example, we need to make a few additions to the C++ code in Chapter10/06_HDR_Adaptation/src/main.cpp. Since we are building directly on the previous example, we will focus only on the new code here:
- First, we need to load a compute shader responsible for performing luminance interpolation and create a pipeline for it.
Holder<ShaderModuleHandle> compAdaptationPass =loadShaderModule(ctx, "Chapter10/06_HDR_Adaptation/src/Adaptation.comp");Holder<ComputePipelineHandle> pipelineAdaptationPass =ctx->createComputePipeline({ .smComp = compAdaptationPass });
- The compute shader will process textures and texture views. Specifically, it will take as input the
1x1texture view representing the average scene luminance, calculated in the previous recipe, Implementing HDR rendering and tone mapping, along with a1x1texture holding the previously adapted luminance value. The shader will output a new1x1texture containing the updated adapted luminance value. By alternating the roles of the previous and new adapted luminance textures, we can iterate this process in each frame using a ping-pong technique. Let’s create two 16-bit single-channel textures and initialize them with a very bright white color value of50. This initialization simulates the effect of our vision adjusting from a bright area to a darker one, creating a visually pleasing adaptation effect when the application starts.const uint16_t brightPixel = glm::packHalf1x16(50);const lvk::TextureDesc luminanceTextureDesc{.format = lvk::Format_R_F16,.dimensions = {1, 1},.usage = lvk::TextureUsageBits_Sampled |lvk::TextureUsageBits_Storage,.swizzle = swizzle,.data = &brightPixel };Holder<TextureHandle> texAdaptedLum[2] = {ctx->createTexture(luminanceTextureDesc),ctx->createTexture(luminanceTextureDesc) }; - Before entering the rendering loop, we need to make two additional initialization changes. First, we will add a variable to control the adaptation speed, allowing us to tweak it interactively via the ImGui UI. Second, we will replace the average scene luminance value in the
pcHDRpush constants, previously used for tone mapping, with the adapted luminance value calculated by the adaptation compute shader.float adaptationSpeed = 3.0f;struct {// …uint32_t texLuminance;// …} pcHDR = {// ….texLuminance = texAdaptedLum[0].index(),// …}; - Within the main rendering loop, just before performing the tone mapping, we execute the adaptation compute shader to update the adapted luminance value. This involves passing the current luminance of the rendered scene, the previously adapted luminance, and the output texture that will store the new adapted luminance value.
const struct {uint32_t texCurrSceneLuminance;uint32_t texPrevAdaptedLuminance;uint32_t texNewAdaptedLuminance;float adaptationSpeed;} pcAdaptationPass = {.texCurrSceneLuminance = texLumViews[LVK_ARRAY_NUM_ELEMENTS(texLumViews)–1].index(),.texPrevAdaptedLuminance = texAdaptedLum[0].index(),.texNewAdaptedLuminance = texAdaptedLum[1].index(),.adaptationSpeed = deltaSeconds * adaptationSpeed,};buf.cmdBindComputePipeline(pipelineAdaptationPass);buf.cmdPushConstants(pcAdaptationPass);
- Before invoking the compute shader, we need to transition the Vulkan image layout of the entire mip pyramid to
VK_IMAGE_LAYOUT_GENERAL, in a similar way as we did in the previous recipe, Implementing HDR rendering and tone mapping. The compute shader runs on a single texel.buf.cmdDispatchThreadGroups({1, 1}, { .textures = {TextureHandle(texLumViews[0]),TextureHandle(texAdaptedLum[0]),TextureHandle(texAdaptedLum[1]) } }); - After the compute shader finishes, it is necessary to transition the new adapted luminance texture
texAdaptedLum[1]back toVK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL. Once we specify the texture dependency, LightweightVK will automatically insert the necessary Vulkan image layout transition, ensuring correct synchronization.buf.cmdBeginRendering(renderPassMain, framebufferMain,{ .textures = { TextureHandle(texAdaptedLum[1]) }});// … render tone-mapped scene into a swapchain image
There’s one subtle but crucial change to the C++ code. After submitting the command buffer for this frame, we need to swap the ping-pong adapted luminance textures. This ensures that the adapted luminance texture from the current frame, texAdaptedLum[1], becomes the “previous” luminance for the next frame.
ctx->submit(buf, ctx->getCurrentSwapchainTexture());std::swap(texAdaptedLum[0], texAdaptedLum[1]);The rest of the C++ workflow remains unchanged, with the addition of one extra ImGui slider to control the adaptation speed, and displaying the adapted luminance texture. We will leave it to you to explore that and instead focus on the addition to the GLSL part of our HDR pipeline: the light adaptation compute shader. It is located in the Chapter10/06_HDR_Adaptation/src/Adaptation.comp file and looks as follows:
- The local workgroup size is set to
(1, 1, 1), as we are processing just a single texel. The input images include the current rendered scene luminance (texCurrSceneLuminance), the previous adapted luminance (texPrevAdaptedLuminance) from the first ping-pong luminance texture, and the output adapted luminance (texAdaptedOut), which is stored in the second ping-pong texture.layout (local_size_x = 1, local_size_y = 1) in;layout (set = 0, binding = 2, r16)uniform readonly image2D kTextures2DIn[];layout (set = 0, binding = 2, r16)uniform writeonly image2D kTextures2DOut[];layout(push_constant) uniform PushConstants {uint texCurrSceneLuminance;uint texPrevAdaptedLuminance;uint texAdaptedOut;float adaptationSpeed;} pc; - The
main()function reads a single texel from each input image and computes the adapted luminance using the 8.1.4.3 Adaptation equation:
This is from https://google.github.io/filament/Filament.md.html#mjx-eqn-adaptation. The dt value represents the delta time since the previous frame, and c is the parameter controlling the rate of light adaptation. Both values have already been pre-multiplied into pc.adaptationSpeed in the C++ code during earlier steps. Finally, the adapted luminance texel is written to the output texture using imageStore().
void main() { float lumCurr = imageLoad( kTextures2DIn[pc.texCurrSceneLuminance], ivec2(0, 0)).x; float lumPrev = imageLoad( kTextures2DIn[pc.texPrevAdaptedLuminance], ivec2(0, 0)).x; float factor = 1.0 - exp(-pc.adaptationSpeed); float newAdaptation = lumPrev + (lumCurr - lumPrev) * factor; imageStore(kTextures2DOut[pc.texAdaptedOut], ivec2(0, 0), vec4(newAdaptation));}This technique provides a smooth and visually pleasing light adaptation effect when the scene luminance changes abruptly. Try running the demo application in Chapter10/06_HDR_Adaptation and experiment by pointing the camera at both bright areas, such as the sky, and darker areas, like the building. The adaptation speed can be tweaked through an ImGui slider, as shown in the screenshot below:

Figure 10.13: An HDR tone-mapped scene with light adaptation
Both the average scene luminance and the adapted luminance 1x1 textures are displayed in the ImGui UI. Try lowering the adaptation speed and watch how the adapted luminance gradually adjusts to match the scene’s luminance.
This recipe concludes our exploration of various image-based effects and post-processing techniques. In the next chapter, we will dive into more advanced rendering techniques and optimizations.
There’s more…
Section titled “There’s more…”HDR rendering is a vast topic, and in this chapter, we barely scratched the surface. If you are interested in learning more about advanced HDR lighting and post-processing techniques, we highly recommend watching the GDC 2010 session Uncharted 2: HDR Lighting by John Hable at https://www.gdcvault.com/play/1012351/Uncharted-2-HDR and the SIGGRAPH 2014 presentation Next Generation Post Processing in Call of Duty: Advanced Warfare by Jorge Jimenez at https://advances.realtimerendering.com/s2014/index.html#_NEXT_GENERATION_POST.