LJYC
Drag this lamp

Vulkan renderer

Visera

2024 – 2025

When you learn graphics rendering, relying only on off-the-shelf engines makes it hard to really understand what happens underneath. GPU memory allocation, pipeline state, shader compilation and frame synchronization are all hidden behind wrappers, and when you actually need to change the rendering flow yourself, you often have no idea where to start. In my design document I wrote down the reason for choosing Vulkan: “complex, yet essential.” It puts the way a modern GPU works right in front of the developer; it is tedious, but well suited to learning systematically.

Visera is a renderer I built from scratch with C++23 Modules and Vulkan 1.3, and the predecessor of what later became Visera II. I positioned it as a test bed for graphics algorithms and new C++ features. The sample program AlohaVisera has one model, one white room, and one directional light with soft shadows.

Chapter 1

The frame flow and the offscreen viewport

To keep scene rendering and the debug UI decoupled, Visera does not draw the 3D image directly to the swapchain (the set of images sent to the screen in turn); it first draws into each frame’s own offscreen color image (R8G8B8A8_UNORM). After post-processing, Editor::Display() opens a Dear ImGui window named Main Window and shows this image in the UI with ImGui::Image, and ImGui itself is then drawn into the swapchain through an Overlay pass. The editor consists of Main Window, a Canvas that displays images, and the IWidget interface, with the layout saved in an ini file.

Each frame of the sample program AlohaVisera runs in this order:

  1. WaitFrameReady: the main loop first handles window and input events, then calls RHI::WaitFrameReady() to wait until the current frame context is ready; the sample program records its rendering commands in Tick().

  2. Background: draws a full-screen triangle and clears the offscreen color image to white.

  3. Shadow: draws only the model from the orthographic shadow camera, with an empty fragment shader that writes depth only; the shadow map uses the D32_SFLOAT format and is cleared to 0 for Reversed-Z.

  4. Geometry: transitions the shadow map to a sampleable layout and draws the model, with each pixel doing 16 depth comparisons against the shadow map and the result multiplied by the texture color; it then draws the box that serves as the room, textured with white cloth, and the floor catches the model’s shadow here.

  5. Postprocess and Overlay: post-processing copies the offscreen color into the post-processing output image with a full-screen triangle, leaving gamma encoding to the sRGB swapchain; finally the editor records the ImGui UI into the Editor command buffer and the frame is presented to the screen.

Offscreen color image: drawing for this frame has not started

1 / 8

Each swapchain image has its own frame context with three command buffers, Resource, Graphics and Editor, chained by semaphores (objects that keep work on the GPU side in order): Resource is submitted first; Graphics waits for “swapchain ready” and “Resource done”; Editor waits for “Graphics done” and, when it finishes, signals a fence to tell the CPU the frame is complete; presentation waits for “Editor done”.

The three command buffers Resource, Graphics and Editor are submitted in turn, linked by semaphores, and presented at the end. Resource Graphics Editor Present Resource done Graphics done Editor done Swapchain ready Fence

Chapter 2

Reversed-Z and PCF soft shadows

Reversed-Z depth mapping

In the previous chapter the shadow map’s depth was cleared to 0 rather than 1, because Visera’s whole rendering pipeline uses Reversed-Z.

The depth buffer stores values between 0 and 1. Under perspective projection, depth changes with distance as 1/z, so most of the precision is concentrated up close; at the same time, IEEE 754 floating-point numbers are denser near 0. With the conventional mapping of the near plane to 0 and the far plane to 1, both precision advantages pile up near the camera, the distance is left with the sparse floats around 1, and two nearby surfaces are prone to z-fighting.

Reversed-Z maps the near plane to 1 and the far plane to 0, using the density of floats near 0 to make up for depth precision in the distance. To keep the whole pipeline consistent, Visera changed five settings together: the perspective and orthographic projection matrices are both written for Reversed-Z; the depth clear value is 0; the depth test compares with GREATER; the shadow comparison sampler also uses GREATER; and the depth format is 32-bit float, D32_SFLOAT.

Density of floats

Conventional mapping

Near plane Far plane

Reversed-Z

Far plane Near plane
Floats are denser near 0. The conventional mapping squeezes the far range toward 1, where they are sparse; Reversed-Z puts the far range at the 0 end.
Projection matrix
Both perspective and orthographic are written for Reversed-Z
Depth clear value
Cleared to 0, which is the farthest
Depth comparison
GREATER: the larger value is the nearer one
Shadow comparison sampler
Also uses GREATER
Depth format
D32_SFLOAT, 32-bit float
The smallest gap that 32-bit float depth can resolve at each distance, under the two mappings.

Smallest resolvable gap (log scale)

Distance to the camera (log scale)

Conventional: near 0, far 1

Stored depth–

Smallest resolvable gap–

Reversed-Z: near 1, far 0

Stored depth–

Smallest resolvable gap–

–

Both lines use the depth formula of a projection matrix like the one above: compute the depth at a distance, store it as a 32-bit float, step to the next representable float, and see how far apart the corresponding distances are. Distances use the same unit as the near and far planes.

4×4 PCF soft shadows

Under the Reversed-Z convention, shadows are straightforward to implement. First render depth once from the direction of the light with an orthographic shadow camera to get the shadow map; when rendering the actual image, transform each fragment into the shadow camera’s space and compare it with the depth in the map to decide whether the point is occluded. With only a single comparison, the shadow’s edge shows obvious pixel stair-stepping.

In the fragment shader, Visera uses a hardware comparison sampler, SamplerComparisonState, with offsets from −1.5 to 1.5, calls SampleCmpLevelZero once at each of the 16 positions of a 4×4 grid, adds a constant bias of 0.001 to the depth (under Reversed-Z a nearer depth is a larger value, so the bias is added), and finally divides by 16 to get the fraction of light that is visible. This is PCF (Percentage-Closer Filtering). The shadow map is kept the same size as the render area, and falls back to D16_UNORM if the device does not support D32_SFLOAT.

Drag the lamp; move over the image or click to see how that point is sampled

Shadow map64 × 64Brighter is closer to the light; black cells hold no object
The 8 × 8 cells around that point

Average of 16 comparisons–

  • The depth stored in this cell is closer to the light, so it blocks this point
  • A sample position; its color is the result of that comparison
Shadow map
  1. Take 4 × 4 sample points

  2. Compare depth with the shadow map once per point

  3. Average the 16 results

    9 / 16 = 0.56

Offsets of −1.5, −0.5, 0.5 and 1.5 texels each way: these are the 16 sample points in the zoomed view above.
Screenshot of the sample program AlohaVisera running: the editor’s Main Window shows a white room with a model standing in the middle and no shadow on the floor; the Debug panel is at the bottom left.
The sample program AlohaVisera, before shadows were added.
Screenshot of the same sample program running: the camera has moved, and a soft-edged shadow stretches back and to the right from the model’s feet; the Debug panel is on the left.
With directional-light shadows; the edges use 4×4 PCF.

Chapter 3

The Vulkan RHI wrapper and runtime Slang compilation

Because the whole point of Visera was to get to the bottom of Vulkan, this RHI (Rendering Hardware Interface) layer was not made into a general abstraction across graphics APIs; it is a wrapper built specifically around Vulkan 1.3. Images, buffers, samplers, command buffers, semaphores and RenderPasses are all allocated through the static interface of the RHI manager class, which keeps raw Vulkan calls from being scattered through application code.

The basic components were all chosen for being stable and direct: Volk bypasses the system loader and loads the Vulkan functions and extensions itself; GPU memory allocation is left to VMA, with staging buffers and buffers that need to be mapped to the CPU using its host-access flags; the swapchain uses the B8G8R8A8_SRGB format, and the present mode prefers Mailbox, falling back to FIFO when it is not supported; Debug builds turn on the Vulkan validation layers by default, and the pipeline cache is stored in the application’s local directory.

  • Images
  • Buffers
  • Samplers
  • Command buffers
  • Semaphores
  • RenderPass

RHI

Static interface of the manager class

Volk

Loads functions and extensions

VMA

GPU memory allocation

Vulkan 1.3

Shaders are written in Slang and compiled at runtime rather than precompiled at build time. Only when a pass first uses a shader does FShader::Compile() initialize the static compiler FSlangCompiler, compile the .slang file into SPIR-V bytecode that Vulkan can read (the target profile is glsl_450), get the vertex and fragment stages through reflection, and then create the graphics pipeline together with the descriptor sets and pipeline layout the pass declares. The repository contains four shaders: Skybox, Forward-Geometry, Shadow-Parallel and Postprocess; the ComputeShadow shown earlier is in Forward-Geometry.

A pass uses a shader for the first time

.slang

FSlangCompiler

Compiled at runtime

SPIR-V

Vertex and fragment stages found by reflection

Descriptor sets and pipeline layout

Graphics pipeline

The four shaders in the repository

  • Skybox
  • Forward-Geometry
  • Shadow-Parallel
  • Postprocess
  1. .slang file

    The engine and the application each have a Shaders directory, both on the search path

  2. FSlangCompiler

    Creates a global session and a session, targeting SPIR-V with the glsl_450 profile

  3. Compile

    Loads the module, finds the entry point by name, composes, and takes out the SPIR-V code

  4. Reflection

    Gets the shader stage: vertex and fragment

  5. Pipeline

    Built into a graphics pipeline together with the pass’s pipeline layout

Chapter 4

Color space, C++ modules and other engineering details

Beyond the core rendering pipeline, the project also dealt with four engineering details, and much of that experience later carried over into Visera II:

Managing color space from metadata with libpng

Early on the project loaded images with FreeImage, but in practice it turned out not to preserve metadata fully, so the program could not determine an image’s color space correctly and the picture came out washed out and too bright. I later switched to parsing PNGs myself with libpng, choosing an sRGB texture (converted to linear by the hardware when sampled) or a UNORM texture based on the file’s sRGB and gAMA chunks; the offscreen color image stores linear values throughout, and the hardware does the gamma encoding when writing into the sRGB swapchain.

  1. Pixels in the PNG

    sRGB-encoded

  2. Texture

    sRGB format · converted to linear when sampledUNORM format · taken as linear values as is

  3. Offscreen color image

    R8G8B8A8_UNORM · stores linear values

  4. Swapchain

    B8G8R8A8_SRGB · encoded back to sRGB on write

The last ramp matches the first: what you see on screen is the image as it really is.The sRGB image is read as linear, one conversion is missing, and the last ramp comes out brighter and grayer than the original.

The same gray ramp goes once through Visera’s color path. The middle two store linear values and would look too dark if shown directly.

C++23 Modules across the whole repository, in layers

The engine source is entirely .ixx module units, managed through CMake’s CXX_MODULES file sets. Interfaces draw their boundaries by what is “visible” and what is “reachable”: visible interfaces can be called directly from outside, while reachable parts can only be accessed indirectly through visible interfaces. Each submodule has a manager class that exposes only a static interface (such as RHI and OS).

  1. ViseraTop-level module
  2. Visera.CoreModule
  3. Visera.Core.OSSubmodule, manager class class OS
  4. Visera.Core.OS.FileSystemSubmodule of a submodule
  5. Visera.Core.OS.FileSystem.FileFeature module, the smallest unit you can import
  6. :Interface :BinaryFile :JSONFileImplementation modules, that is, module partitions
Module names taken from the examples in the design document “Module hierarchy design”.

A unified scene representation with Embree

When FScene::Attach adds a model, the same mesh data is uploaded as vertex and index buffers for GPU rasterization on one side, and registered in Intel Embree’s CPU acceleration structure on the other, which supports single-ray intersection (rtcIntersect1, returning the geometric normal, barycentric coordinates and primitive ID). In the design document I recorded this approach as “a unified data representation of GPU & CPU scene data”.

FScene::Attach adds a model

  1. Upload the vertex and index buffers
  2. Rasterization
  1. Register in Embree’s acceleration structure
  2. Single-ray intersection, returning the hit information

A separate dependency repository, Visera-Packages

The dozen or so third-party libraries the engine uses are split out into a separate repository. Each library comes with a CMake script that provides a link_xxx(target) macro, and the vcpkg bootstrap logic is also integrated into CMake, organized by four sources: the Vulkan SDK, prebuilt packages, building from source, and vcpkg.

From the Vulkan SDK

Vulkan Slang

Prebuilt packages cached in the repository

Embree

Built from source

Dear ImGui STB RapidJSON spdlog

Installed with vcpkg

Volk VMA GLFW TBB Assimp FreeImage libpng OpenEXR Eigen