Vulkan with vk-bootstrap and VMA
Vulkan gives you the GPU with almost nothing hidden: you pick the physical device, create queues, allocate memory, record command buffers, transition image layouts and synchronise CPU and GPU yourself. The reward is predictable performance, multithreaded command recording and the same API on Windows, Linux, Android and (through MoltenVK) Apple platforms. The cost is code: a first triangle in raw Vulkan runs to roughly a thousand lines.
Two libraries remove most of the boilerplate without hiding the concepts:
| Library | Replaces |
|---|---|
vk-bootstrap (vkb::) |
instance creation, validation layers, debug messenger, physical-device selection, logical device and queues, swapchain creation and recreation |
| Vulkan Memory Allocator (VMA, AMD GPUOpen) | choosing memory types, sub-allocating large VkDeviceMemory blocks, mapping, defragmentation |
Both are in vcpkg (vk-bootstrap, vulkan-memory-allocator). vk-bootstrap needs C++17 and Vulkan headers 1.1 or newer.
Instance, device and queues
The builder pattern lets you state requirements; vk-bootstrap checks every GPU against them and returns a Result that you must test. This setup targets Vulkan 1.3 and requires dynamic rendering and synchronization2, which together remove render pass and framebuffer objects and give a saner barrier API.
#include <SDL3/SDL.h>
#include <SDL3/SDL_vulkan.h>
#include <VkBootstrap.h>
vkb::InstanceBuilder builder;
auto inst_ret = builder.set_app_name("tiny-engine")
.request_validation_layers(enableValidation)
.use_default_debug_messenger()
.require_api_version(1, 3, 0)
.build();
if (!inst_ret) { SDL_Log("instance: %s", inst_ret.error().message().c_str()); return false; }
vkb::Instance vkbInstance = inst_ret.value();
VkSurfaceKHR surface;
if (!SDL_Vulkan_CreateSurface(window, vkbInstance.instance, nullptr, &surface)) return false;
VkPhysicalDeviceVulkan13Features features13{ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES };
features13.dynamicRendering = VK_TRUE;
features13.synchronization2 = VK_TRUE;
vkb::PhysicalDeviceSelector selector{ vkbInstance };
auto phys_ret = selector.set_surface(surface)
.set_minimum_version(1, 3)
.set_required_features_13(features13)
.select();
if (!phys_ret) return false;
vkb::DeviceBuilder deviceBuilder{ phys_ret.value() };
vkb::Device vkbDevice = deviceBuilder.build().value(); // check the Result in real code
VkQueue graphicsQueue = vkbDevice.get_queue(vkb::QueueType::graphics).value();
uint32_t graphicsFamily = vkbDevice.get_queue_index(vkb::QueueType::graphics).value();Swapchain
vkb::SwapchainBuilder swapBuilder{ vkbDevice };
auto swap_ret = swapBuilder
.set_desired_format({ VK_FORMAT_B8G8R8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR })
.set_desired_present_mode(VK_PRESENT_MODE_FIFO_KHR) // vsync, always supported
.set_desired_extent(width, height)
.add_image_usage_flags(VK_IMAGE_USAGE_TRANSFER_DST_BIT)
.build();
vkb::Swapchain swapchain = swap_ret.value();
std::vector<VkImage> images = swapchain.get_images().value();
std::vector<VkImageView> views = swapchain.get_image_views().value();When the window is resized (SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED) or vkAcquireNextImageKHR/vkQueuePresentKHR return VK_ERROR_OUT_OF_DATE_KHR, wait for the device to go idle, build a new swapchain with .set_old_swapchain(swapchain), then call vkb::destroy_swapchain on the old one.
Memory with VMA
Without VMA you would query memory types, pick one by property flags, call vkAllocateMemory (drivers limit the number of allocations, often to 4096) and bind. VMA does it in one call and sub-allocates for you:
#define VMA_IMPLEMENTATION // in exactly one .cpp file
#include <vk_mem_alloc.h>
VmaAllocatorCreateInfo allocatorInfo{};
allocatorInfo.instance = vkbInstance.instance;
allocatorInfo.physicalDevice = phys_ret.value().physical_device;
allocatorInfo.device = vkbDevice.device;
allocatorInfo.vulkanApiVersion = VK_API_VERSION_1_3;
VmaAllocator allocator;
vmaCreateAllocator(&allocatorInfo, &allocator);
// a device-local vertex buffer, filled later by a copy from a staging buffer
VkBufferCreateInfo bufferInfo{ VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
bufferInfo.size = vertexBytes;
bufferInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
VmaAllocationCreateInfo allocInfo{};
allocInfo.usage = VMA_MEMORY_USAGE_AUTO;
VkBuffer vertexBuffer;
VmaAllocation vertexAlloc;
vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &vertexBuffer, &vertexAlloc, nullptr);
// a CPU-visible staging buffer, persistently mapped
bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
allocInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT;
VkBuffer staging; VmaAllocation stagingAlloc; VmaAllocationInfo stagingInfo;
vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &staging, &stagingAlloc, &stagingInfo);
memcpy(stagingInfo.pMappedData, vertices, vertexBytes);
// … record vkCmdCopyBuffer(cmd, staging, vertexBuffer, 1, ®ion) and submit …
vmaDestroyBuffer(allocator, staging, stagingAlloc); // only after the copy has finished on the GPURecording a frame with dynamic rendering
VkRenderingAttachmentInfo color{ VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO };
color.imageView = views[imageIndex];
color.imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
color.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
color.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
color.clearValue.color = { { 0.1f, 0.1f, 0.2f, 1.0f } };
VkRenderingInfo rendering{ VK_STRUCTURE_TYPE_RENDERING_INFO };
rendering.renderArea = { { 0, 0 }, swapchain.extent };
rendering.layerCount = 1;
rendering.colorAttachmentCount = 1;
rendering.pColorAttachments = &color;
// barrier: UNDEFINED -> COLOR_ATTACHMENT_OPTIMAL (vkCmdPipelineBarrier2 with a VkImageMemoryBarrier2)
vkCmdBeginRendering(cmd, &rendering);
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
VkDeviceSize offset = 0;
vkCmdBindVertexBuffers(cmd, 0, 1, &vertexBuffer, &offset);
vkCmdDraw(cmd, 3, 1, 0, 0);
vkCmdEndRendering(cmd);
// barrier: COLOR_ATTACHMENT_OPTIMAL -> PRESENT_SRC_KHRThe pipeline itself still needs SPIR-V shaders (compile GLSL or HLSL with glslc, glslangValidator or dxc; see Shaders & Graphics Programming) and a VkPipelineRenderingCreateInfo in its pNext chain naming the color format, since no render pass object exists.
Frames in flight, modelled
The CPU must not overwrite a command buffer or a uniform buffer the GPU is still reading. Engines keep N frames in flight, each with its own command buffer, semaphores and a fence. Before recording frame i, the CPU waits on the fence of frame i - N. The model below simulates a CPU that needs 3 ticks to record a frame and a GPU that needs 4 ticks to render it:
#include <algorithm>
#include <iostream>
#include <vector>
int simulate(int framesInFlight, int frames, bool print) {
const int cpuCost = 3, gpuCost = 4;
std::vector<int> gpuDone(frames, 0); // tick at which frame i's fence signals
int cpu = 0, gpuFree = 0;
for (int i = 0; i < frames; i++) {
int waitFor = i - framesInFlight;
int start = cpu;
if (waitFor >= 0) start = std::max(cpu, gpuDone[waitFor]); // vkWaitForFences
int submitted = start + cpuCost; // record + vkQueueSubmit
int gpuStart = std::max(submitted, gpuFree);
gpuDone[i] = gpuStart + gpuCost;
gpuFree = gpuDone[i];
if (print) std::cout << " frame " << i << ": cpu " << start << "-" << submitted
<< " (waited " << start - cpu << "), gpu " << gpuStart << "-" << gpuDone[i] << "\n";
cpu = submitted;
}
return gpuDone[frames - 1];
}
int main() {
std::cout << "1 frame in flight:\n";
int one = simulate(1, 5, true);
std::cout << "2 frames in flight:\n";
int two = simulate(2, 5, true);
std::cout << "5 frames finished at tick " << one << " vs " << two << "\n";
std::cout << "100 frames: " << simulate(1, 100, false) << " vs " << simulate(2, 100, false)
<< " vs " << simulate(3, 100, false) << " (3 in flight)\n";
}1 frame in flight:
frame 0: cpu 0-3 (waited 0), gpu 3-7
frame 1: cpu 7-10 (waited 4), gpu 10-14
frame 2: cpu 14-17 (waited 4), gpu 17-21
frame 3: cpu 21-24 (waited 4), gpu 24-28
frame 4: cpu 28-31 (waited 4), gpu 31-35
2 frames in flight:
frame 0: cpu 0-3 (waited 0), gpu 3-7
frame 1: cpu 3-6 (waited 0), gpu 7-11
frame 2: cpu 7-10 (waited 1), gpu 11-15
frame 3: cpu 11-14 (waited 1), gpu 15-19
frame 4: cpu 15-18 (waited 1), gpu 19-23
5 frames finished at tick 35 vs 23
100 frames: 700 vs 403 vs 403 (3 in flight)
With one frame in flight, CPU and GPU take turns and both idle: a frame costs 3 + 4 = 7 ticks. With two, the CPU records frame N+1 while the GPU renders frame N, and the frame rate is limited only by the slower of the two: 4 ticks per frame, the GPU's cost (100 frames in 403 ticks instead of 700). A third frame adds nothing here and costs one more frame of input latency, which is why two is the common choice.
Shutdown order
Destroy in reverse order of creation, after vkDeviceWaitIdle: your buffers (vmaDestroyBuffer), images, pipelines and command pools, then vmaDestroyAllocator, vkb::destroy_swapchain, vkb::destroy_device, vkb::destroy_surface, vkb::destroy_instance. The validation layer reports anything you leaked. Keep validation on in every debug build; it is the single most useful Vulkan tool.
Tip: Vulkan is a specialisation, not a step every engine needs. If your goal is a game, an OpenGL, sokol or bgfx backend (previous lesson) gets you there faster. The vkguide.dev tutorial and the Khronos Vulkan Tutorial are good next steps for this path.
Test yourself
What does vk-bootstrap's PhysicalDeviceSelector do?
- Allocates GPU memory
- Checks each GPU against your requirements (version, features, surface support) and returns a suitable one
- Compiles shaders
- Creates the window
Why use VMA instead of calling vkAllocateMemory for every buffer?
- vkAllocateMemory is deprecated
- Drivers limit the number of allocations, and VMA picks memory types and sub-allocates many resources from large blocks
- VMA makes buffers faster on the GPU
- VMA is required by the validation layers
In the frames-in-flight model, why does going from 1 to 2 frames in flight speed things up?
- The GPU renders faster
- The CPU can record the next frame while the GPU still renders the previous one
- It skips every other frame
- It disables vsync