Writing

Vulkan Series: 07 - Structuring the Codebase

Splitting our growing Vulkan 1.3 sample into VulkanCore, Swapchain and Renderer classes, and fixing our uniform buffer data race with per-frame uniform buffers

graphicsvulkanc++refactoringclang-formatcmakeuniform buffersframes in flightvulkan 1.3

What we’ll build here

End Result
End Result

Yep, it’s the same spinning cube as last time! Just like the VMA, GLM and refactoring post, this one is mostly about groundwork. By the end of the previous post, our SampleVulkan class had grown to well over a thousand lines, doing everything from creating the Vulkan instance to spinning our cube. And it’s only going to grow from here, so it’s time to give it some structure.

We’ll also finally fix the uniform buffer data race we left in on purpose last time. To get there, we’ll:

  1. Introduce clang-format, so our code keeps a consistent style
  2. Reorganize our source files into src/cpp and src/hpp
  3. Rename SampleVulkan to Renderer
  4. Split the device-level code out into a VulkanCore class, and the swapchain code into a Swapchain class
  5. Use our Result type pretty much everywhere
  6. Add a precompiled header
  7. Look at our uniform buffer data race, and fix it the quickest way we can
  8. Then clean that fix up with a small UniformBuffer class

This post builds directly on top of the previous post, so if you haven’t gone through that one yet, I’d strongly recommend doing so first.

Just want the source code? Find it on GitHub or at the end of this post.

Setup

Nothing new is required this time. If you’d like to format the code the same way I do, you’ll want clang-format, which comes with LLVM/Clang. Most package managers have it (as clang-format, or as part of an llvm or clang package), and most editors can run it for you on save.

clang-format

As our codebase grows, so does the effort of keeping its style consistent: where the braces go, how long a line can be, how function arguments wrap. clang-format takes care of all of that for us. We describe our style once, in a .clang-format file at the root of the project, and clang-format reformats our code to match. Here’s ours:

Language: Cpp
Standard: c++20
BasedOnStyle: Microsoft

IndentWidth: 2
TabWidth: 2
UseTab: Never
AccessModifierOffset: -4

IndentPPDirectives: AfterHash
IndentRequiresClause: true
BreakBeforeConceptDeclarations: true
SpaceAfterTemplateKeyword: false

FixNamespaceComments: true
NamespaceIndentation: All
CompactNamespaces: true

AlignAfterOpenBracket: Align
AlignOperands: Align
AlignTrailingComments: true

SpaceAfterCStyleCast: true
SpaceAfterLogicalNot: false
SpaceBeforeAssignmentOperators: true
SpaceInEmptyParentheses: false
SpacesInAngles: false

SeparateDefinitionBlocks: Always
SortIncludes: Never

We start from the built-in Microsoft style (braces on their own lines, a 120 column limit), and tweak it: 2 space indents, no tabs, a space after C-style casts ((float) x), and an empty line between definitions. SortIncludes: Never is there because the order of some of our includes matters, like GLFW_INCLUDE_VULKAN having to be defined before including GLFW.

To format all of our sources from the command line:

clang-format -i src/cpp/*.cpp src/hpp/*.hpp

-i edits the files in place. (Keep stb_image.hpp out of this if you’re formatting by hand. It’s not our code, and there’s no reason to touch it.)

That’s the reason the code in this post looks a little different from the previous ones. Nothing changed but the whitespace!

The new file layout

Until now, all of our files sat next to each other in the project root. With more files on the way, I moved our headers into src/hpp, and our sources into src/cpp:

FileWhat’s in it
src/hpp/pch.hppOur precompiled header (it used to be common.hpp, more on this later)
src/hpp/core.hpp / src/cpp/core.cppThe new VulkanCore class: instance, device, queues, VMA and single-shot commands
src/hpp/swapchain.hpp / src/cpp/swapchain.cppThe new Swapchain class: the swapchain, depth attachment and frames in flight
src/hpp/renderer.hpp / src/cpp/renderer.cppOur Renderer class (formerly SampleVulkan): everything to do with drawing our cube
src/hpp/buffer.hpp / src/cpp/buffer.cppBuffer, and the new UniformBuffer
src/hpp/image.hpp / src/cpp/image.cppImage, same as before
src/hpp/pipeline.hpp / src/cpp/pipeline.cppPipeline, same as before
src/hpp/shader_data_table.hpp / src/cpp/shader_data_table.cppShaderDataTable, now with descriptor sets for each frame in flight
src/cpp/main.cppSampleApp and main
src/cpp/vma.cppThe VMA implementation
src/hpp/stb_image.hppstb_image, unchanged

shaders/ and resources/ stay where they were. Here’s the end of our CMakeLists.txt now:

add_executable(App
    src/cpp/vma.cpp
    src/cpp/core.cpp
    src/cpp/main.cpp
    src/cpp/image.cpp
    src/cpp/buffer.cpp
    src/cpp/pipeline.cpp
    src/cpp/renderer.cpp
    src/cpp/swapchain.cpp
    src/cpp/shader_data_table.cpp
)

target_link_libraries(App PRIVATE 
    glfw
    vulkan
    glm::glm
    GPUOpen::VulkanMemoryAllocator
)

target_include_directories(App PRIVATE
    src/hpp
)

target_precompile_headers(App PRIVATE src/hpp/pch.hpp)

target_include_directories adds src/hpp to the compiler’s include path, so our sources can include our headers without any ../hpp/ paths. That’s also why our includes now use angle brackets, like #include <buffer.hpp>, instead of quotes. We’ll get to target_precompile_headers in a bit.

Splitting up SampleVulkan

At the end of the last post, SampleVulkan was doing three quite different jobs:

  1. Talking to Vulkan itself: the instance, the debug messenger, the surface, picking a physical device, the logical device and its queues, our VMA allocator, and our single-shot command buffer.
  2. Managing the swapchain: the swapchain and its image views, the depth attachment, the per-frame command buffers, fences and semaphores, and recreating all of it when the window is resized.
  3. Drawing our cube: the pipeline, our buffers, the texture, the descriptor sets, and the matrices.

These change for very different reasons, and the first two will barely change at all for the rest of the series. So each of them gets its own class: VulkanCore for the first, Swapchain for the second, and what’s left over is what our class is really about now, rendering. So I renamed SampleVulkan to Renderer (and sample.hpp/sample.cpp to renderer.hpp/renderer.cpp).

Most of the code moved over as is, so like last time, I’ll focus on what actually changed. The full source code is at the end, as always.

The VulkanCore class

class VulkanCore
{
  static constexpr const char *VALIDATION_LAYER_NAME = "VK_LAYER_KHRONOS_validation";
  static constexpr const char *SWAPCHAIN_DEVICE_EXTENSION_NAME = "VK_KHR_swapchain";
  static constexpr const char *PORTABILITY_SUBSET_DEVICE_EXTENSION_NAME = "VK_KHR_portability_subset";

  public:
  static Result<Box<VulkanCore>> create(
      std::function<Result<>(VkInstance, uint32_t &, uint32_t &, VkSurfaceKHR &)> surface_creation_callback,
      VkExtent2D &initial_surface_extent);

  VulkanCore(const VulkanCore &) = delete;
  VulkanCore &operator=(const VulkanCore &) = delete;

  ~VulkanCore();

  Result<> execute_single_shot_commands(std::function<Result<>(VkCommandBuffer)> commands) const;

  public:
  VkDevice get_device() const
  {
    return m_device;
  }

  VkSurfaceKHR get_surface() const
  {
    return m_surface;
  }

  VkPhysicalDevice get_physical_device() const
  {
    return m_physical_device;
  }

  VmaAllocator get_allocator() const
  {
    return m_allocator;
  }

  uint32_t get_queue_family_index_graphics() const
  {
    return m_graphics_queue_family_index;
  }

  uint32_t get_queue_family_index_present() const
  {
    return m_present_queue_family_index;
  }

  VkQueue get_queue_graphics() const
  {
    return m_graphics_queue;
  }

  VkQueue get_queue_present() const
  {
    return m_present_queue;
  }

  void wait_idle() const
  {
    vkDeviceWaitIdle(m_device);
  }

  private:
  VulkanCore() = default;

  Result<> create_instance();
  Result<> select_physical_device();
  Result<> create_device();
  Result<> create_allocator();
  Result<> initialize_single_shot_commands();

  private:
  VkInstance m_instance{};
  VkDevice m_device{};
  VkSurfaceKHR m_surface{};
  VmaAllocator m_allocator{};
  std::string m_physical_device_name{};
  VkPhysicalDevice m_physical_device{};
  VkDebugUtilsMessengerEXT m_debug_messenger{};

  VkQueue m_present_queue{};
  VkQueue m_graphics_queue{};
  uint32_t m_present_queue_family_index{};
  uint32_t m_graphics_queue_family_index{};

  VkFence m_single_shot_command_fence{};
  VkCommandPool m_single_shot_command_pool{};
  VkCommandBuffer m_single_shot_command_buffer{};
};

It follows the same pattern as our Pipeline, Buffer and Image classes: a private constructor, and a static create function that returns a Result<Box<VulkanCore>>. That way, the only way to get a VulkanCore is a fully initialized one, or an error message telling us why we couldn’t.

create takes the same surface creation callback our initialize function used to take (except that it now returns a Result<> instead of a bool, more on that below). It also hands the initial size of the window’s framebuffer back to us through initial_surface_extent, since we’ll need it for our swapchain:

Result<Box<VulkanCore>> VulkanCore::create(
    std::function<Result<>(VkInstance, uint32_t &, uint32_t &, VkSurfaceKHR &)> surface_creation_callback,
    VkExtent2D &initial_surface_extent)
{
  Box<VulkanCore> core(new VulkanCore());

  CHECK_RESULT(core->create_instance());
  CHECK_RESULT(surface_creation_callback(core->m_instance, initial_surface_extent.width, initial_surface_extent.height, core->m_surface));
  CHECK_RESULT(core->select_physical_device());
  CHECK_RESULT(core->create_device());
  CHECK_RESULT(core->create_allocator());
  CHECK_RESULT(core->initialize_single_shot_commands());

  return core;
}

create_instance and select_physical_device are the same functions we’ve had since the first post. create_device, create_allocator and initialize_single_shot_commands are what used to be the first half of create_device_and_swapchain, split into three. If any of them fails, create returns early, and core’s destructor cleans up whatever was created up to that point.

Everything else talks to Vulkan through the getters. Notice that they’re all const, and so is execute_single_shot_commands. Our other classes only ever hold a const VulkanCore *: they can use the device, but they can’t change it.

The Swapchain class

class VulkanCore;

class Swapchain
{
  struct FrameResourceSet
  {
    VkFence fen_in_flight{};
    VkSemaphore sm_image_available{};
    VkCommandBuffer cmd_buffer{};
  };

  public:
  static constexpr uint32_t NUM_CONCURRENT_FRAMES = 3;

  static Result<Box<Swapchain>> create(const VulkanCore *core, VkExtent2D initial_extent);

  Swapchain(const Swapchain &) = delete;
  Swapchain &operator=(const Swapchain &) = delete;

  ~Swapchain();

  void resize(uint32_t width, uint32_t height);
  void request_recreation();

  Result<VkCommandBuffer> begin_frame();
  Result<> end_frame();

  public:
  void register_resize_callback(std::function<void(VkExtent2D extent)> resize_callback)
  {
    m_resize_callback = resize_callback;
  }

  VkFormat get_color_format() const
  {
    return m_format.format;
  }

  VkFormat get_depth_format() const
  {
    return m_depth_image->get_format();
  }

  VkExtent2D get_extent() const
  {
    return m_extent;
  }

  uint32_t get_current_frame_index() const
  {
    return m_current_frame_index;
  }

  VkImageView get_color_attachment() const
  {
    return m_image_views[m_current_image_index];
  }

  VkImageView get_depth_attachment() const
  {
    return m_depth_image->get_view();
  }

  float get_aspect_ratio() const
  {
    return (float) m_extent.width / (float) m_extent.height;
  }

  private:
  Swapchain(const VulkanCore *core) : m_core(core)
  {
  }

  Result<> recreate();
  Result<> create_frame_resources();

  private:
  const VulkanCore *const m_core;

  bool m_is_out_of_date{};

  uint32_t m_image_count{};
  VkSurfaceFormatKHR m_format{};
  VkPresentModeKHR m_present_mode{};
  std::vector<VkSemaphore> m_render_done_semaphores;
  VkSurfaceTransformFlagBitsKHR m_pre_transform{};

  VkSwapchainKHR m_swapchain{};
  std::vector<VkImage> m_images{};
  std::vector<VkImageView> m_image_views{};
  Box<Image> m_depth_image{};

  uint32_t m_current_frame_index{};
  uint32_t m_current_image_index{};
  VkCommandPool m_frame_resource_command_pool{};
  FrameResourceSet m_frames[NUM_CONCURRENT_FRAMES];

  VkExtent2D m_extent{1, 1};
  VkExtent2D m_pending_extent{1, 1};

  std::function<void(VkExtent2D extent)> m_resize_callback{};
};

Most of the members will look familiar: they used to live in SampleVulkan with a m_swapchain_ prefix, which we no longer need now that they’re inside a class called Swapchain. recreate is our old recreate_swapchain, and create_frame_resources is the same as before.

The interesting part is how we use it. Our old render function did a whole lot of things: wait for the frame’s fence, acquire a swapchain image, start recording the command buffer, transition the image, draw, transition the image again, submit, present, and recreate the swapchain if needed. Everything except the drawing is about the swapchain, so it’s now split in two, around the drawing:

Result<VkCommandBuffer> Swapchain::begin_frame()
{
  const auto &current_frame = m_frames[m_current_frame_index];

  vkWaitForFences(m_core->get_device(), 1, &current_frame.fen_in_flight, VK_TRUE, UINT64_MAX);

  switch (vkAcquireNextImageKHR(m_core->get_device(), m_swapchain, UINT64_MAX, current_frame.sm_image_available,
                                VK_NULL_HANDLE, &m_current_image_index))
  {
  case VK_ERROR_OUT_OF_DATE_KHR:
    CHECK_RESULT(recreate());
    return (VkCommandBuffer)VK_NULL_HANDLE;

  case VK_SUCCESS:
  case VK_SUBOPTIMAL_KHR:
    break;

  default:
    return "Failed to acquire swapchain image";
  }

  VkCommandBufferBeginInfo cmd_begin_info{
      .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
  };
  vkResetCommandBuffer(current_frame.cmd_buffer, 0);
  if (vkBeginCommandBuffer(current_frame.cmd_buffer, &cmd_begin_info) != VK_SUCCESS)
    return "Failed to start recording command buffer";

  if (!Image::transition_image_layout(current_frame.cmd_buffer, m_images[m_current_image_index],
                                      VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL))
    return "Failed to transition swapchain image";

  return (VkCommandBuffer)current_frame.cmd_buffer;
}

begin_frame does everything up to the point where we can start drawing, and hands us the command buffer to record into. If the swapchain turned out to be out of date, it recreates it and returns VK_NULL_HANDLE instead, which means “skip this frame”. end_frame takes it from there: it transitions the image for presenting, ends the command buffer, submits it, presents, recreates the swapchain if it needs to, and moves on to the next frame in flight. It’s the second half of our old render function, almost line for line.

What Swapchain doesn’t do is the rendering itself. vkCmdBeginRendering, the clear colours, the viewport and the scissor are all up to whoever is drawing, which is our Renderer. That’s what get_color_attachment, get_depth_attachment and get_extent are for.

Then there’s resizing. Our projection matrix depends on the swapchain’s aspect ratio, but the swapchain shouldn’t have to know anything about projection matrices. So instead, Swapchain lets us register a callback, which recreate calls whenever the extent actually changed:

  if (m_resize_callback && resized)
    m_resize_callback(m_extent);

NUM_CONCURRENT_FRAMES and get_current_frame_index are public now too. We’ll need both when we fix our data race later.

The Renderer class

class Renderer
{
  public:
  static Result<Box<Renderer>> create(
      std::function<Result<>(VkInstance, uint32_t &, uint32_t &, VkSurfaceKHR &)> surface_creation_callback);

  Renderer(const Renderer &) = delete;
  Renderer &operator=(const Renderer &) = delete;

  ~Renderer();

  Result<> render();

  void resize(uint32_t fb_width, uint32_t fb_height);

  private:
  Renderer() = default;

  Result<> on_create();

  void on_swapchain_resize();

  private:
  Box<VulkanCore> m_core{};
  Box<Swapchain> m_swapchain{};

  Box<Pipeline> m_graphics_pipeline{};

  Box<Buffer> m_staging_buffer{};
  Box<Buffer> m_vertex_buffer{};
  Box<Buffer> m_index_buffer{};

  Box<Image> m_texture_image{};
  VkSampler m_texture_sampler{};

  Box<ShaderDataTable> m_shader_data_table{};

  Box<UniformBuffer<VertexUniformData>> m_vertex_uniform{};
};

That’s a lot shorter than SampleVulkan was! Nothing in here is about devices or swapchains anymore, only what we need to draw our cube (don’t worry about UniformBuffer just yet, we’ll write it at the end of this post).

Renderer also gets a create function now, instead of a public constructor and an initialize function:

Result<Box<Renderer>> Renderer::create(
    std::function<Result<>(VkInstance, uint32_t &, uint32_t &, VkSurfaceKHR &)> surface_creation_callback)
{
  Box<Renderer> renderer(new Renderer());

  VkExtent2D initial_extent{};

  CHECK_ASSIGN_RESULT(VulkanCore::create(surface_creation_callback, initial_extent), renderer->m_core);
  CHECK_ASSIGN_RESULT(Swapchain::create(renderer->m_core.get(), initial_extent), renderer->m_swapchain);
  renderer->m_swapchain->register_resize_callback(
      [renderer = renderer.get()](VkExtent2D) { renderer->on_swapchain_resize(); });
  CHECK_RESULT(renderer->on_create());
  renderer->on_swapchain_resize();

  return renderer;
}

We create our VulkanCore, then our Swapchain with the extent VulkanCore handed back to us, and register our resize callback. The callback captures a raw pointer to our renderer, which is fine: the Renderer itself lives on the heap, so it stays put even when the Box holding it is moved around. Then on_create creates everything we need for drawing (it’s the rest of our old initialize function), and finally, on_swapchain_resize sets up our initial projection matrix.

There’s one more thing worth pointing out here: destruction order. C++ destroys members in the reverse order they’re declared in. m_core is declared first, so it’s destroyed last, after everything that was created from its device. And m_swapchain is declared second, so it goes right before it. As long as we keep m_core at the top, we get the right order for free.

And our render function is now just about rendering:

Result<> Renderer::render()
{
  VkCommandBuffer cmd;
  CHECK_ASSIGN_RESULT(m_swapchain->begin_frame(), cmd);

  if (cmd == VK_NULL_HANDLE)
    return Ok();

  // ... update our uniform data, then vkCmdBeginRendering, draw our cube, and vkCmdEndRendering

  CHECK_RESULT(m_swapchain->end_frame());

  return Ok();
}

We’ll look at the middle part when we fix our data race.

Result everywhere

Back in the VMA, GLM and refactoring post, we wrote our Result type, but most of our functions kept returning a bool, printing an error message right where things went wrong. Now that we’ve got a bunch of classes calling into each other, I switched almost all of them over to Result, so that errors make their way up to main instead, which prints them once.

To keep that from being a pain to write, pch.hpp has two small macros:

#define CHECK_RESULT(_result)                                                                                          \
  {                                                                                                                    \
    const auto result = _result;                                                                                       \
    if (result.is_error())                                                                                             \
      return result.get_error();                                                                                       \
  }

#define CHECK_ASSIGN_RESULT(_result, _var)                                                                             \
  {                                                                                                                    \
    auto result = _result;                                                                                             \
    if (result.is_error())                                                                                             \
      return result.get_error();                                                                                       \
    _var = std::move(result).take_value();                                                                             \
  }

CHECK_RESULT returns the error to our caller if the call failed, and CHECK_ASSIGN_RESULT does the same, but moves the value into _var if it succeeded. We’ve already seen both of them in VulkanCore::create and Renderer::create. Since we return the error instead of false, these only work in functions that return a Result themselves, which is now almost all of them.

All the way at the top, SampleApp::launch returns a Result<int> now, and main is the one place that prints an error:

int main(int argc, char *argv[])
{
  SampleApp app;
  const auto result = app.launch(argc, argv);
  if (result.is_error())
  {
    printf("ERROR: %s\n", result.get_error().c_str());
    return -1;
  }
  return result.get_value();
}

Our surface creation callback returns a Result<> now too, so that a failure to create the surface comes with its own error message:

  CHECK_ASSIGN_RESULT(
      Renderer::create([window = m_window](VkInstance instance, uint32_t &out_width, uint32_t &out_height,
                                           VkSurfaceKHR &out_surface) -> Result<> {
        if (glfwCreateWindowSurface(instance, window, nullptr, &out_surface) != VK_SUCCESS)
          return "Failed to create Vulkan surface";

        int32_t fb_width{}, fb_height{};
        glfwGetFramebufferSize(window, &fb_width, &fb_height);
        while ((fb_width == 0) || (fb_height == 0))
        {
          glfwWaitEvents();
          glfwGetFramebufferSize(window, &fb_width, &fb_height);
        }

        out_width = (uint32_t) fb_width;
        out_height = (uint32_t) fb_height;

        return Ok();
      }),
      m_renderer);

And at the bottom of our main loop, a failed frame now ends the loop with its error message, instead of just quietly breaking out of it:

    CHECK_RESULT(m_renderer->render());

A precompiled header

common.hpp is included, directly or indirectly, by every single source file. It pulls in a good chunk of the standard library, GLFW (which pulls in vulkan.h), VMA’s header and GLM, and the compiler has to parse all of that again for every source file. That’s what precompiled headers are for: the compiler parses the header once, saves the result, and reuses it for every source file.

CMake makes this a one-liner, which we already saw in our CMakeLists.txt:

target_precompile_headers(App PRIVATE src/hpp/pch.hpp)

I renamed common.hpp to pch.hpp to make its job obvious, and gathered the standard headers our files need into it:

#include <set>
#include <map>
#include <span>
#include <deque>
#include <cstdio>
#include <chrono>
#include <vector>
#include <cassert>
#include <memory>
#include <string>
#include <cstddef>
#include <variant>
#include <string.h>
#include <stdint.h>
#include <algorithm>
#include <functional>
#include <type_traits>

#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>

#include <vk_mem_alloc.h>

#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

vkEnumCall, our little helper for Vulkan’s “call it twice” enumeration functions, moved in here from sample.cpp too, since both VulkanCore and Swapchain use it. And so did our Vertex and VertexUniformData structs, along with our cube’s vertices and indices, now called CUBE_MESH_VERTICES and CUBE_MESH_INDICES.

NOTE: The catch with a precompiled header is that changing anything in it rebuilds everything that uses it, which is all of our files. So it’s best kept for things that rarely change: library headers and our basic types. Our cube mesh is fine in there for now, but it’ll find a better home once we have more than one mesh.

Smaller cleanups

A few smaller things I tidied up along the way:

  • All of our classes now have a private constructor (Pipeline and ShaderDataTable had protected ones), and delete both their copy constructor and their copy assignment operator (most of them only deleted the copy constructor before).
  • A typo in our vertex shader, in_texcord, is now in_texcoord.
  • load_shader_from_file returns data instead of std::move(data). Returning a local variable already moves it (or skips the copy entirely), and wrapping it in std::move actually gets in the way of the compiler skipping the copy.

The uniform buffer data race

Now for the bug we left in on purpose last time.

THEORY: Frames in flight and shared data

Back in the coloured window post, we set things up so that up to 3 frames can be in flight at once: while the GPU is still busy with one frame, the CPU can already be recording the next one. Each frame in flight has its own command buffer, semaphore and fence, and before we reuse a frame’s command buffer, we wait for its fence. That fence was signalled when the last frame to use that same slot finished on the GPU, which is three frames ago.

Here’s what that looks like for frame 5, which uses slot 2 (5 % 3):

frame:    2         3         4         5
slot:     2         0         1         2
          done      on GPU    on GPU    recording on the CPU

Before recording frame 5, we waited for slot 2’s fence, so we know frame 2 is done with everything it used. But frames 3 and 4 might very well still be running on the GPU. Anything they use, frame 5 must not touch.

Our command buffers are fine, since each slot has its own. Our uniform buffer is not: we only have one, and we overwrite it every frame. So while frames 3 and 4 may still be reading their matrices from it on the GPU, we’re already writing frame 5’s matrices into it on the CPU. That’s a data race. On our spinning cube, the worst we’d likely see is a frame drawn with a slightly newer rotation than it should have, but there’s no guarantee of that: in general, a frame could read data that’s half old and half new.

The validation layers won’t save us here, not even synchronization validation. They track what the GPU does with our resources, but our write comes from the CPU, through a mapped pointer, and the layers can’t see that.

The fix follows from the same idea our frame resources already use: give each frame in flight its own copy of the uniform buffer, and only write to a frame’s copy after waiting for that frame’s fence. And since a descriptor set points at one specific buffer, each frame also needs its own descriptor set, pointing at its own copy. (We can’t just rewrite a single descriptor set every frame either: a descriptor set must not be updated while a command buffer that uses it may still be running.)

NOTE: Why not just call vkDeviceWaitIdle (or wait for every fence) before writing to our uniform buffer? That would fix the race too, but it throws away the whole point of having frames in flight: the CPU would sit waiting for the GPU to finish every single frame before starting on the next one.

The quickest fix

Let’s start with the most straightforward fix we can get away with: one Buffer per frame in flight, and one copy of every descriptor set per frame in flight.

First, ShaderDataTable::create takes the number of frames in flight:

  static Result<Box<ShaderDataTable>> create(VkDevice device, std::span<const EntryDescription> entries,
                                             uint32_t frame_count);

What used to be the number of sets is now the number of sets per frame, m_sets_per_frame. The set layouts stay the same, since every frame’s sets look the same. But our pool needs enough room for every frame’s sets, and their descriptors:

  std::vector<VkDescriptorPoolSize> pool_sizes{};
  for (const auto &dc : descriptor_counts)
  {
    pool_sizes.push_back({.type = dc.first, .descriptorCount = dc.second * frame_count});
  }

  VkDescriptorPoolCreateInfo pool_create_info{
      .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
      .maxSets = table->m_sets_per_frame * frame_count,
      .poolSizeCount = (uint32_t) pool_sizes.size(),
      .pPoolSizes = pool_sizes.data(),
  };

And then we allocate all of them in one go:

    table->m_sets.resize(table->m_sets_per_frame * frame_count);

    std::vector<VkDescriptorSetLayout> layouts(table->m_sets.size());
    for (uint32_t i = 0; i < frame_count; i++)
    {
      for (uint32_t j = 0; j < table->m_sets_per_frame; j++)
      {
        layouts[(i * table->m_sets_per_frame) + j] = table->m_set_layouts[j];
      }
    }

    VkDescriptorSetAllocateInfo alloc_info{
        .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
        .descriptorPool = table->m_pool,
        .descriptorSetCount = (uint32_t) layouts.size(),
        .pSetLayouts = layouts.data(),
    };

    if (vkAllocateDescriptorSets(device, &alloc_info, table->m_sets.data()) != VK_SUCCESS)
      return "Failed to allocate descriptor sets";

vkAllocateDescriptorSets wants one layout for every set we’re allocating, so we repeat our list of layouts once per frame. Frame i’s sets then sit next to each other in m_sets, starting at i * m_sets_per_frame. Our write functions take a frame_index now, and use the same indexing to pick the set to write to:

bool ShaderDataTable::write_buffer_entry(const std::string &name, uint32_t frame_index, const Buffer *buffer,
                                         VkDeviceSize offset, VkDeviceSize size, uint32_t index)
{
  const auto entry = m_entry_map.find(name);
  if (entry == m_entry_map.end())
    return false;

  m_queued_write_buffer_infos.push_back(VkDescriptorBufferInfo{
      buffer->get_handle(),
      offset,
      (size == 0) ? buffer->get_size() : size,
  });

  m_queued_writes.push_back({
      .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
      .dstSet = m_sets[(frame_index * m_sets_per_frame) + entry->second.first],
      .dstBinding = entry->second.second,
      .dstArrayElement = index,
      .descriptorCount = 1,
      .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // for now we assume all writes are uniform buffers
      .pBufferInfo = &m_queued_write_buffer_infos.back(),
  });

  return true;
}

write_image_entry gets the exact same change. And bind binds only the given frame’s sets:

void ShaderDataTable::bind(VkCommandBuffer cmd, uint32_t frame_index)
{
  vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline_layout, 0, m_sets_per_frame,
                          &m_sets[frame_index * m_sets_per_frame], 0, nullptr);
}

Over in our Renderer, we pass Swapchain::NUM_CONCURRENT_FRAMES to ShaderDataTable::create, and our single uniform buffer becomes a std::vector of them, next to a VertexUniformData member that holds our matrices on the CPU side (it used to be a global, g_vertex_uniform_data):

  m_vertex_uniform_buffers.resize(Swapchain::NUM_CONCURRENT_FRAMES);
  for (uint32_t i = 0; i < Swapchain::NUM_CONCURRENT_FRAMES; i++)
  {
    CHECK_ASSIGN_RESULT(Buffer::create(m_core->get_allocator(), sizeof(VertexUniformData), Buffer::EUsage::UNIFORM),
                        m_vertex_uniform_buffers[i]);
  }

Each frame’s descriptor sets then get pointed at that frame’s uniform buffer. Our texture doesn’t change between frames, so every frame’s texture set points at the same texture:

  for (uint32_t i = 0; i < Swapchain::NUM_CONCURRENT_FRAMES; i++)
  {
    if (!m_shader_data_table->write_buffer_entry("vertex_uniform_data", i, m_vertex_uniform_buffers[i].get()))
      return "Failed to write uniform buffer to shader data table";
  }

  for (uint32_t i = 0; i < Swapchain::NUM_CONCURRENT_FRAMES; i++)
  {
    if (!m_shader_data_table->write_image_entry("texture_sampler", i, m_texture_image.get(), m_texture_sampler))
      return "Failed to write texture image to shader data table";
  }

And finally, render writes to the current frame’s buffer:

Result<> Renderer::render()
{
  VkCommandBuffer cmd;
  CHECK_ASSIGN_RESULT(m_swapchain->begin_frame(), cmd);

  if (cmd == VK_NULL_HANDLE)
    return Ok();

  { // Update Uniform Data
    static constexpr float SPEED = glm::radians(90.0f);
    static auto start_time = std::chrono::steady_clock::now();

    const auto current_time = std::chrono::steady_clock::now();
    const auto seconds = std::chrono::duration<float>(current_time - start_time).count();

    m_vertex_uniform_data.model =
        glm::rotate(glm::mat4(1.0f), std::fmod(seconds * SPEED, glm::two_pi<float>()), glm::vec3(1.0f, 1.0f, 1.0f)) *
        glm::scale(glm::mat4(1.0f), glm::vec3(0.25f));
    m_vertex_uniform_buffers[m_swapchain->get_current_frame_index()]->copy_from_cpu(&m_vertex_uniform_data,
                                                                                    sizeof(m_vertex_uniform_data));
  }

The order matters here! We write to our uniform buffer after begin_frame, because begin_frame is where we wait for this frame’s fence. Only once that wait is over do we know the GPU is done with this frame’s buffer. And our draw then binds this frame’s descriptor sets, with m_shader_data_table->bind(cmd, m_swapchain->get_current_frame_index()), so the GPU reads the very buffer we just wrote to.

NOTE: What about our projection matrix, which only changes when the window is resized? Since every frame copies the whole VertexUniformData into its own buffer, a new projection matrix makes its way into each frame’s buffer the next time that frame comes around. No special handling needed.

And that’s our data race fixed! It works, but I’m not too happy with it:

  • Our renderer has to juggle a std::vector of buffers and a separate VertexUniformData, and remember to index both the buffers and the descriptor writes by frame.
  • Every uniform buffer we add in the future would mean the same loops all over again.
  • Our texture’s descriptor set is duplicated for every frame too, even though it never changes. (We’ll come back to this one in the next post.)

Let’s do something about the first two.

A UniformBuffer class

Our uniform data and its per-frame buffers always go together, so let’s put them together in a class:

class IUniformBuffer
{
public:
  virtual ~IUniformBuffer() = default;
  
  virtual VkDeviceSize get_size() const = 0;
  virtual uint32_t get_frame_count() const = 0;
  virtual VkBuffer get_handle(uint32_t frame_index) const = 0;
};

template<typename DataT> class UniformBuffer: public IUniformBuffer
{
  public:
  static Result<Box<UniformBuffer>> create(VmaAllocator allocator, uint32_t frame_count);

  UniformBuffer(const UniformBuffer &) = delete;
  UniformBuffer &operator=(const UniformBuffer &) = delete;

  ~UniformBuffer();

  DataT &get_data()
  {
    return m_data;
  }

  const DataT &get_data() const
  {
    return m_data;
  }

  VkDeviceSize get_size() const override
  {
    return m_size;
  }

  VkBuffer get_handle(uint32_t frame_index) const override
  {
    return m_handles[frame_index];
  }

  uint32_t get_frame_count() const override
  {
    assert(m_handles.size() == m_allocations.size());
    return (uint32_t) m_handles.size();
  }

  bool flush(uint32_t frame_index);

  private:
  UniformBuffer(VmaAllocator allocator) : m_allocator(allocator)
  {
  }

  private:
  DataT m_data{};
  VmaAllocator m_allocator{};

  VkDeviceSize m_size{};
  std::vector<VkBuffer> m_handles{};
  std::vector<VmaAllocation> m_allocations{};
};

A UniformBuffer<DataT> holds a DataT on the CPU side, plus one buffer per frame in flight on the GPU side. We change the data through get_data, and flush copies it into one frame’s buffer. Since it’s a template, its functions are defined right there in buffer.hpp, as the compiler needs to see them wherever a UniformBuffer is used.

IUniformBuffer is a small interface with everything about a uniform buffer except its data type. That’s all our ShaderDataTable needs to point descriptors at it, and this way, ShaderDataTable doesn’t have to be a template (or know anything about our VertexUniformData) to do so. It has a virtual destructor, like any class meant to be used through a base class pointer, and UniformBuffer marks the functions it implements with override, so the compiler tells us if we ever get one of their signatures wrong.

NOTE: Separate buffers aren’t the only way to do this. A common alternative is a single dynamic uniform buffer: one buffer big enough for every frame’s copy, placed one after the other, and a descriptor of type VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC pointing at it. Instead of binding a different descriptor set every frame, we bind the same one, and pass the current frame’s offset into the buffer to vkCmdBindDescriptorSets through its pDynamicOffsets parameter. Each copy then has to start at a multiple of the device’s minUniformBufferOffsetAlignment (which can be up to 256 bytes), so we’d pad our data to that. It’s fewer buffers and fewer descriptor sets, at the cost of some offset bookkeeping. For us, separate buffers keep things simpler, and they fit right in with the per-frame descriptor sets we already have.

Creating one is a lot like Buffer::create, except we create frame_count buffers, all sizeof(DataT) bytes big:

template<typename DataT>
Result<Box<UniformBuffer<DataT>>> UniformBuffer<DataT>::create(VmaAllocator allocator, uint32_t frame_count)
{
  Box<UniformBuffer> buffer{new UniformBuffer(allocator)};

  buffer->m_size = sizeof(DataT);

  VkBufferCreateInfo create_info{
      .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
      .size = buffer->m_size,
      .usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
      .sharingMode = VK_SHARING_MODE_EXCLUSIVE, // we only need to use our buffers from a single queue family at a time
  };

  VmaAllocationCreateInfo alloc_create_info{
      .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
      .usage = VMA_MEMORY_USAGE_AUTO,
  };

  buffer->m_handles.resize(frame_count);
  buffer->m_allocations.resize(frame_count);
  for (uint32_t i = 0; i < frame_count; i++)
  {
    if (vmaCreateBuffer(allocator, &create_info, &alloc_create_info, &buffer->m_handles[i], &buffer->m_allocations[i],
                        nullptr) != VK_SUCCESS)
    {
      return "Failed to create the buffer";
    }
  }

  return buffer;
}

The usage and allocation flags are the same ones our Buffer class used for its UNIFORM usage in the last post. In fact, with this class in place, Buffer::EUsage::UNIFORM isn’t needed anymore, so I removed it.

Destroying one destroys every frame’s buffer:

template<typename DataT> UniformBuffer<DataT>::~UniformBuffer()
{
  if (!m_allocator)
    return;

  const auto frame_count = get_frame_count(); // using the member function here so it triggers the assert as well
  for (uint32_t i = 0; i < frame_count; i++)
  {
    vmaDestroyBuffer(m_allocator, m_handles[i], m_allocations[i]);
  }
  m_handles.clear();
  m_allocations.clear();
}

If create failed halfway through, some of our handles will still be VK_NULL_HANDLE, which is fine: vmaDestroyBuffer does nothing for those.

And flush copies our data into the given frame’s buffer, the same way Buffer::copy_from_cpu did:

template<typename DataT> bool UniformBuffer<DataT>::flush(uint32_t frame_index)
{
  return vmaCopyMemoryToAllocation(m_allocator, &m_data, m_allocations[frame_index], 0, sizeof(m_data)) == VK_SUCCESS;
}

Over in ShaderDataTable, write_buffer_entry becomes write_uniform_buffer_entry. It takes an IUniformBuffer, and writes every frame’s descriptor in one go, so we don’t need a frame_index anymore:

bool ShaderDataTable::write_uniform_buffer_entry(const std::string &name, const IUniformBuffer *buffer,
                                                 VkDeviceSize offset, VkDeviceSize size, uint32_t index)
{
  const auto entry = m_entry_map.find(name);
  if (entry == m_entry_map.end())
    return false;

  for (uint32_t i = 0; i < buffer->get_frame_count(); i++)
  {
    m_queued_write_buffer_infos.push_back(VkDescriptorBufferInfo{
        buffer->get_handle(i),
        offset,
        (size == 0) ? buffer->get_size() : size,
    });

    m_queued_writes.push_back({
        .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
        .dstSet = m_sets[(i * m_sets_per_frame) + entry->second.first],
        .dstBinding = entry->second.second,
        .dstArrayElement = index,
        .descriptorCount = 1,
        .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
        .pBufferInfo = &m_queued_write_buffer_infos.back(),
    });
  }

  return true;
}

Remember that m_queued_write_buffer_infos is a std::deque, not a std::vector, so pushing more infos onto it doesn’t move the earlier ones around, and the pBufferInfo pointers of our queued writes stay valid until we flush them.

Now our Renderer only needs a single member, Box<UniformBuffer<VertexUniformData>> m_vertex_uniform, which we create in on_create:

  CHECK_ASSIGN_RESULT(
      UniformBuffer<VertexUniformData>::create(m_core->get_allocator(), Swapchain::NUM_CONCURRENT_FRAMES),
      m_vertex_uniform);

Pointing our descriptors at it is a single call:

  if (!m_shader_data_table->write_uniform_buffer_entry("vertex_uniform_data", m_vertex_uniform.get()))
    return "Failed to write uniform buffer to shader data table";

And here’s our uniform update in render now:

  { // Update Uniform Data
    static constexpr float SPEED = glm::radians(90.0f);
    static auto start_time = std::chrono::steady_clock::now();

    const auto current_time = std::chrono::steady_clock::now();
    const auto seconds = std::chrono::duration<float>(current_time - start_time).count();

    m_vertex_uniform->get_data().model =
        glm::rotate(glm::mat4(1.0f), std::fmod(seconds * SPEED, glm::two_pi<float>()), glm::vec3(1.0f, 1.0f, 1.0f)) *
        glm::scale(glm::mat4(1.0f), glm::vec3(0.25f));

    if (!m_vertex_uniform->flush(m_swapchain->get_current_frame_index()))
      return "Failed to flush the uniform buffer";
  }

Same as before, it comes right after begin_frame. And unlike before, we check whether the copy actually worked.

Finally, on_swapchain_resize writes our projection matrix through get_data too:

void Renderer::on_swapchain_resize()
{
  if (!m_vertex_uniform)
    return;

  m_vertex_uniform->get_data().projection =
      glm::perspective(glm::half_pi<float>(), m_swapchain->get_aspect_ratio(), 0.1f, 1.0f);
  m_vertex_uniform->get_data().projection[1][1] *= -1.0f;
}

Our resize callback is registered before on_create creates our uniform buffer, so we make sure it actually exists before writing to it. That’s also why Renderer::create calls on_swapchain_resize after on_create, to set up our first projection matrix.

Wrapping up

And that’s it! Build it, run it, and you should see the exact same spinning cube as last time, with no validation errors. Which is exactly what we want from a refactor!

Let’s recap what we did:

  1. Introduced clang-format, with a .clang-format file describing our style
  2. Moved our sources into src/cpp and src/hpp
  3. Split SampleVulkan into VulkanCore, Swapchain and Renderer, each with a static create function and a private constructor
  4. Moved our rendering out of the swapchain code, with begin_frame and end_frame around it, and a resize callback for our projection matrix
  5. Switched almost all of our functions over to Result, with errors making their way up to main
  6. Turned common.hpp into a precompiled header, pch.hpp
  7. Saw why our single uniform buffer was a data race with 3 frames in flight, and why the validation layers can’t catch it
  8. Fixed it with one uniform buffer and one set of descriptor sets per frame in flight, written only after waiting for that frame’s fence
  9. Cleaned that fix up with a templated UniformBuffer class, and an IUniformBuffer interface for our ShaderDataTable

Next up: Structuring the Render Loop

Our fix duplicates all of our descriptor sets for every frame in flight, even our texture’s, which never changes. So next time, we’ll restructure our render loop around how often our data changes: the projection matrix goes into a rarely updated descriptor set, the view matrix into a set updated every frame, and the model matrix into a push constant, which we first mentioned all the way back in the coloured triangle post. We’ll also sort out our cube’s winding order, and turn on back-face culling.

References

  1. ClangFormat, and its style options
  2. CMake: target_precompile_headers
  3. Vulkan Tutorial: Frames in flight
  4. Vulkan Memory Allocator: Recommended usage patterns
  5. VkGuide
  6. The Vulkan specification (version 1.4.364 at the time of writing)

Full Source Code

The complete sample is now around 2700 lines in total, across the files in the table above. That’s not counting stb_image.hpp, which is the unmodified stb_image.h from stb. The resources/ folder, with the texture and the compiled shaders, can be found in the GitHub repo along with everything else.

Show CMakeLists.txt
cmake_minimum_required(VERSION 3.28)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

project(I_A_S_ME_VulkanSeries)

include(FetchContent)

set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_DOCS OFF CACHE BOOL "" FORCE)

FetchContent_Declare(glfw
    GIT_REPOSITORY https://github.com/glfw/glfw.git
    GIT_TAG 3.5.1
    GIT_SHALLOW TRUE
)

FetchContent_Declare(VulkanMemoryAllocator
    GIT_REPOSITORY https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator.git
    GIT_TAG v3.5.0
    GIT_SHALLOW TRUE
)

FetchContent_Declare(glm
    GIT_REPOSITORY https://github.com/g-truc/glm.git
    GIT_TAG 1.0.3
    GIT_SHALLOW TRUE
)

FetchContent_MakeAvailable(glfw VulkanMemoryAllocator glm)

add_executable(App
    src/cpp/vma.cpp
    src/cpp/core.cpp
    src/cpp/main.cpp
    src/cpp/image.cpp
    src/cpp/buffer.cpp
    src/cpp/pipeline.cpp
    src/cpp/renderer.cpp
    src/cpp/swapchain.cpp
    src/cpp/shader_data_table.cpp
)

target_link_libraries(App PRIVATE 
    glfw
    vulkan
    glm::glm
    GPUOpen::VulkanMemoryAllocator
)

target_include_directories(App PRIVATE
    src/hpp
)

target_precompile_headers(App PRIVATE src/hpp/pch.hpp)
Show .clang-format
Language: Cpp
Standard: c++20
BasedOnStyle: Microsoft

IndentWidth: 2
TabWidth: 2
UseTab: Never
AccessModifierOffset: -4

IndentPPDirectives: AfterHash
IndentRequiresClause: true
BreakBeforeConceptDeclarations: true
SpaceAfterTemplateKeyword: false

FixNamespaceComments: true
NamespaceIndentation: All
CompactNamespaces: true

AlignAfterOpenBracket: Align
AlignOperands: Align
AlignTrailingComments: true

SpaceAfterCStyleCast: true
SpaceAfterLogicalNot: false
SpaceBeforeAssignmentOperators: true
SpaceInEmptyParentheses: false
SpacesInAngles: false

SeparateDefinitionBlocks: Always
SortIncludes: Never
Show src/hpp/pch.hpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#pragma once

#include <set>
#include <map>
#include <span>
#include <deque>
#include <cstdio>
#include <chrono>
#include <vector>
#include <cassert>
#include <memory>
#include <string>
#include <cstddef>
#include <variant>
#include <string.h>
#include <stdint.h>
#include <algorithm>
#include <functional>
#include <type_traits>

#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>

#include <vk_mem_alloc.h>

#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

#define CHECK_RESULT(_result)                                                                                          \
  {                                                                                                                    \
    const auto result = _result;                                                                                       \
    if (result.is_error())                                                                                             \
      return result.get_error();                                                                                       \
  }

#define CHECK_ASSIGN_RESULT(_result, _var)                                                                             \
  {                                                                                                                    \
    auto result = _result;                                                                                             \
    if (result.is_error())                                                                                             \
      return result.get_error();                                                                                       \
    _var = std::move(result).take_value();                                                                             \
  }

template<typename ElementT, typename FuncT, typename... Args> std::vector<ElementT> vkEnumCall(FuncT f, Args... args)
{
  uint32_t _count{};
  f(args..., &_count, nullptr);

  std::vector<ElementT> result(_count);
  f(args..., &_count, result.data());

  return result;
}

struct Ok
{
};

// A very simple Result type to hold either
// an error message or the value. To be used
// mostly as return types in failable functions.
template<typename T = Ok> class [[nodiscard]] Result
{
  static_assert(!std::is_same_v<std::decay_t<T>, std::string>, "std::string values are not allowed");
  static_assert(!std::is_same_v<T, void>, "void values are not allowed. Use Result<> or Result<Ok> instead.");

  public:
  Result(std::nullptr_t) = delete;

  constexpr Result(const char *error) : m_variant(std::in_place_index<1>, error)
  {
  }

  constexpr Result(T &&value) : m_variant(std::in_place_index<0>, std::move(value))
  {
  }

  constexpr Result(const std::string &error) : m_variant(std::in_place_index<1>, error)
  {
  }

  constexpr bool is_ok() const
  {
    return m_variant.index() == 0;
  }

  constexpr bool is_error() const
  {
    return m_variant.index() == 1;
  }

  T get_value() && = delete;

  T &get_value() &
  {
    assert(is_ok());
    return std::get<0>(m_variant);
  }

  const T &get_value() const &
  {
    assert(is_ok());
    return std::get<0>(m_variant);
  }

  T take_value() &&
  {
    assert(is_ok());
    return std::get<0>(std::move(m_variant));
  }

  const std::string &get_error() const &
  {
    assert(is_error());
    return std::get<1>(m_variant);
  }

  std::string get_error() &&
  {
    assert(is_error());
    return std::get<1>(std::move(m_variant));
  }

  private:
  std::variant<T, std::string> m_variant;
};

// Alias std::unique_ptr to Box. Easier to type.
// (Inspired by Rust of course, just like Result above).
template<typename T> using Box = std::unique_ptr<T>;

struct Vertex
{
  glm::vec3 pos;
  glm::vec3 colour;
  glm::vec2 texcoord;
};

struct VertexUniformData
{
  glm::mat4 model;
  glm::mat4 view;
  glm::mat4 projection;
};

constexpr Vertex CUBE_MESH_VERTICES[24] = {
    {glm::vec3(-0.5f, -0.5f, -0.5f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)},
    {glm::vec3(0.5f, -0.5f, -0.5f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(1.0f, 0.0f)},
    {glm::vec3(0.5f, 0.5f, -0.5f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 1.0f)},
    {glm::vec3(-0.5f, 0.5f, -0.5f), glm::vec3(1.0f, 0.0f, 1.0f), glm::vec2(0.0f, 1.0f)},

    {glm::vec3(-0.5f, -0.5f, 0.5f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)},
    {glm::vec3(0.5f, -0.5f, 0.5f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(1.0f, 0.0f)},
    {glm::vec3(0.5f, 0.5f, 0.5f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 1.0f)},
    {glm::vec3(-0.5f, 0.5f, 0.5f), glm::vec3(1.0f, 0.0f, 1.0f), glm::vec2(0.0f, 1.0f)},

    {glm::vec3(-0.5f, -0.5f, -0.5f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)},
    {glm::vec3(-0.5f, 0.5f, -0.5f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(1.0f, 0.0f)},
    {glm::vec3(-0.5f, 0.5f, 0.5f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 1.0f)},
    {glm::vec3(-0.5f, -0.5f, 0.5f), glm::vec3(1.0f, 0.0f, 1.0f), glm::vec2(0.0f, 1.0f)},

    {glm::vec3(0.5f, -0.5f, -0.5f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)},
    {glm::vec3(0.5f, 0.5f, -0.5f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(1.0f, 0.0f)},
    {glm::vec3(0.5f, 0.5f, 0.5f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 1.0f)},
    {glm::vec3(0.5f, -0.5f, 0.5f), glm::vec3(1.0f, 0.0f, 1.0f), glm::vec2(0.0f, 1.0f)},

    {glm::vec3(-0.5f, -0.5f, -0.5f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)},
    {glm::vec3(0.5f, -0.5f, -0.5f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(1.0f, 0.0f)},
    {glm::vec3(0.5f, -0.5f, 0.5f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 1.0f)},
    {glm::vec3(-0.5f, -0.5f, 0.5f), glm::vec3(1.0f, 0.0f, 1.0f), glm::vec2(0.0f, 1.0f)},

    {glm::vec3(-0.5f, 0.5f, -0.5f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f)},
    {glm::vec3(0.5f, 0.5f, -0.5f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(1.0f, 0.0f)},
    {glm::vec3(0.5f, 0.5f, 0.5f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 1.0f)},
    {glm::vec3(-0.5f, 0.5f, 0.5f), glm::vec3(1.0f, 0.0f, 1.0f), glm::vec2(0.0f, 1.0f)},
};

constexpr uint32_t CUBE_MESH_INDICES[36] = {
    0,  1,  2,  2,  3,  0,  4,  5,  6,  6,  7,  4,  8,  9,  10, 10, 11, 8,
    12, 13, 14, 14, 15, 12, 16, 17, 18, 18, 19, 16, 20, 21, 22, 22, 23, 20,
};
Show src/hpp/core.hpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#pragma once

#include <pch.hpp>

class VulkanCore
{
  static constexpr const char *VALIDATION_LAYER_NAME = "VK_LAYER_KHRONOS_validation";
  static constexpr const char *SWAPCHAIN_DEVICE_EXTENSION_NAME = "VK_KHR_swapchain";
  static constexpr const char *PORTABILITY_SUBSET_DEVICE_EXTENSION_NAME = "VK_KHR_portability_subset";

  public:
  static Result<Box<VulkanCore>> create(
      std::function<Result<>(VkInstance, uint32_t &, uint32_t &, VkSurfaceKHR &)> surface_creation_callback,
      VkExtent2D &initial_surface_extent);

  VulkanCore(const VulkanCore &) = delete;
  VulkanCore &operator=(const VulkanCore &) = delete;

  ~VulkanCore();

  Result<> execute_single_shot_commands(std::function<Result<>(VkCommandBuffer)> commands) const;

  public:
  VkDevice get_device() const
  {
    return m_device;
  }

  VkSurfaceKHR get_surface() const
  {
    return m_surface;
  }

  VkPhysicalDevice get_physical_device() const
  {
    return m_physical_device;
  }

  VmaAllocator get_allocator() const
  {
    return m_allocator;
  }

  uint32_t get_queue_family_index_graphics() const
  {
    return m_graphics_queue_family_index;
  }

  uint32_t get_queue_family_index_present() const
  {
    return m_present_queue_family_index;
  }

  VkQueue get_queue_graphics() const
  {
    return m_graphics_queue;
  }

  VkQueue get_queue_present() const
  {
    return m_present_queue;
  }

  void wait_idle() const
  {
    vkDeviceWaitIdle(m_device);
  }

  private:
  VulkanCore() = default;

  Result<> create_instance();
  Result<> select_physical_device();
  Result<> create_device();
  Result<> create_allocator();
  Result<> initialize_single_shot_commands();

  private:
  VkInstance m_instance{};
  VkDevice m_device{};
  VkSurfaceKHR m_surface{};
  VmaAllocator m_allocator{};
  std::string m_physical_device_name{};
  VkPhysicalDevice m_physical_device{};
  VkDebugUtilsMessengerEXT m_debug_messenger{};

  VkQueue m_present_queue{};
  VkQueue m_graphics_queue{};
  uint32_t m_present_queue_family_index{};
  uint32_t m_graphics_queue_family_index{};

  VkFence m_single_shot_command_fence{};
  VkCommandPool m_single_shot_command_pool{};
  VkCommandBuffer m_single_shot_command_buffer{};
};
Show src/cpp/core.cpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#include <core.hpp>

Result<Box<VulkanCore>> VulkanCore::create(
    std::function<Result<>(VkInstance, uint32_t &, uint32_t &, VkSurfaceKHR &)> surface_creation_callback,
    VkExtent2D &initial_surface_extent)
{
  Box<VulkanCore> core(new VulkanCore());

  CHECK_RESULT(core->create_instance());
  CHECK_RESULT(surface_creation_callback(core->m_instance, initial_surface_extent.width, initial_surface_extent.height, core->m_surface));
  CHECK_RESULT(core->select_physical_device());
  CHECK_RESULT(core->create_device());
  CHECK_RESULT(core->create_allocator());
  CHECK_RESULT(core->initialize_single_shot_commands());

  return core;
}

VulkanCore::~VulkanCore()
{
  if (m_device)
  {
    vkDeviceWaitIdle(m_device);

    vkDestroyFence(m_device, m_single_shot_command_fence, nullptr);

    vkDestroyCommandPool(m_device, m_single_shot_command_pool, nullptr);

    vmaDestroyAllocator(m_allocator);

    vkDestroyDevice(m_device, nullptr);
  }

  if (m_instance)
  {
    if (m_surface)
      vkDestroySurfaceKHR(m_instance, m_surface, nullptr);

    {
      const auto debug_messenger_destroy_func =
          (PFN_vkDestroyDebugUtilsMessengerEXT) vkGetInstanceProcAddr(m_instance, "vkDestroyDebugUtilsMessengerEXT");
      if (debug_messenger_destroy_func && m_debug_messenger)
        debug_messenger_destroy_func(m_instance, m_debug_messenger, nullptr);
    }

    vkDestroyInstance(m_instance, nullptr);
  }
}

Result<> VulkanCore::execute_single_shot_commands(std::function<Result<>(VkCommandBuffer)> commands) const
{
  if (vkResetCommandBuffer(m_single_shot_command_buffer, 0) != VK_SUCCESS)
    return "Failed to reset single shot command buffer";

  VkCommandBufferBeginInfo begin_info{
      .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
  };
  if (vkBeginCommandBuffer(m_single_shot_command_buffer, &begin_info) != VK_SUCCESS)
    return "Failed to begin single shot command buffer";

  CHECK_RESULT(commands(m_single_shot_command_buffer));

  if (vkEndCommandBuffer(m_single_shot_command_buffer) != VK_SUCCESS)
    return "Failed to end single shot command buffer";

  VkSubmitInfo submit_info{
      .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
      .commandBufferCount = 1,
      .pCommandBuffers = &m_single_shot_command_buffer,
  };
  if (vkQueueSubmit(m_graphics_queue, 1, &submit_info, m_single_shot_command_fence) != VK_SUCCESS)
    return "Failed to submit single shot command buffer";

  if (vkWaitForFences(m_device, 1, &m_single_shot_command_fence, true, UINT64_MAX) != VK_SUCCESS)
    return "Failed to wait for single shot fence";

  if (vkResetFences(m_device, 1, &m_single_shot_command_fence) != VK_SUCCESS)
    return "Failed to reset single shot fence";

  return Ok();
}

Result<> VulkanCore::create_instance()
{
  // This is a sample, not production code, so we always enable validation layers,
  // unless they're unavailable
  const auto instance_layer_props = vkEnumCall<VkLayerProperties>(vkEnumerateInstanceLayerProperties);
  const bool enable_validation_layers =
      std::any_of(instance_layer_props.begin(), instance_layer_props.end(),
                  [](VkLayerProperties p) { return strcmp(p.layerName, VALIDATION_LAYER_NAME) == 0; });

  VkDebugUtilsMessengerCreateInfoEXT debug_messenger_create_info{
      .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT,
      .messageSeverity =
          VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT,
      .messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
                     VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT,
      .pfnUserCallback = [](VkDebugUtilsMessageSeverityFlagBitsEXT severity, VkDebugUtilsMessageTypeFlagsEXT type,
                            const VkDebugUtilsMessengerCallbackDataEXT *callback_data, void *user_data) -> VkBool32 {
        printf("[VK_VALIDATION_LAYER]: %s\n", callback_data->pMessage);
        return VK_FALSE;
      },
  };

  std::vector<const char *> extensions;
  { // GLFW Extensions
    uint32_t glfw_ext_count{};
    const auto glfw_ext = glfwGetRequiredInstanceExtensions(&glfw_ext_count);
    extensions.insert(extensions.end(), glfw_ext, glfw_ext + glfw_ext_count);
  }
  if (enable_validation_layers)
    extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);

  // macOS support: MoltenVK is a "portability" implementation (it doesn't support all
  // of Vulkan), so the loader only exposes it to us if we explicitly opt in.
  const auto instance_ext_props = vkEnumCall<VkExtensionProperties>(vkEnumerateInstanceExtensionProperties, nullptr);
  const bool enable_portability =
      std::any_of(instance_ext_props.begin(), instance_ext_props.end(), [](VkExtensionProperties p) {
        return strcmp(p.extensionName, VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME) == 0;
      });
  if (enable_portability)
    extensions.push_back(VK_KHR_PORTABILITY_ENUMERATION_EXTENSION_NAME);

  VkApplicationInfo app_info{
      .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
      .pApplicationName = "i-a-s.me Vulkan 1.3 Sample",
      .applicationVersion = VK_MAKE_VERSION(1, 0, 0),
      .pEngineName = "i-a-s.me Vulkan 1.3 Sample",
      .engineVersion = VK_MAKE_VERSION(1, 0, 0),
      .apiVersion = VK_API_VERSION_1_3,
  };

  VkInstanceCreateInfo create_info{
      .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
      .pNext = enable_validation_layers ? &debug_messenger_create_info : nullptr,
      .flags = enable_portability ? (VkInstanceCreateFlags) VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR : 0u,
      .pApplicationInfo = &app_info,
      .enabledLayerCount = enable_validation_layers ? 1u : 0u,
      .ppEnabledLayerNames = enable_validation_layers ? &VALIDATION_LAYER_NAME : nullptr,
      .enabledExtensionCount = (uint32_t) extensions.size(),
      .ppEnabledExtensionNames = extensions.data(),
  };

  if (vkCreateInstance(&create_info, nullptr, &m_instance) != VK_SUCCESS)
    return "Failed to create Vulkan instance";

  const auto debug_messenger_create_func =
      (PFN_vkCreateDebugUtilsMessengerEXT) vkGetInstanceProcAddr(m_instance, "vkCreateDebugUtilsMessengerEXT");
  if (enable_validation_layers && debug_messenger_create_func)
  {
    if (debug_messenger_create_func(m_instance, &debug_messenger_create_info, nullptr, &m_debug_messenger) !=
        VK_SUCCESS)
      return "Failed to create Vulkan debug messenger";
  }

  return Ok();
}

Result<> VulkanCore::select_physical_device()
{
  const auto find_queue_families = [&](VkPhysicalDevice p) -> std::pair<uint32_t, uint32_t> {
    uint32_t graphics_family_index{UINT32_MAX}, present_family_index{UINT32_MAX};

    const auto queue_families = vkEnumCall<VkQueueFamilyProperties>(vkGetPhysicalDeviceQueueFamilyProperties, p);
    for (uint32_t i = 0; i < (uint32_t) queue_families.size(); i++)
    {
      const auto &f = queue_families[i];

      if (f.queueFlags & VK_QUEUE_GRAPHICS_BIT)
        graphics_family_index = i;

      VkBool32 has_present_support{};
      if ((vkGetPhysicalDeviceSurfaceSupportKHR(p, i, m_surface, &has_present_support) == VK_SUCCESS) &&
          has_present_support)
        present_family_index = i;

      if ((graphics_family_index != UINT32_MAX) && (present_family_index != UINT32_MAX))
        break;
    }

    return {graphics_family_index, present_family_index};
  };

  m_physical_device = VK_NULL_HANDLE;

  const auto physical_devices = vkEnumCall<VkPhysicalDevice>(vkEnumeratePhysicalDevices, m_instance);

  for (const auto &p : physical_devices)
  {
    VkPhysicalDeviceProperties2 props{
        .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2,
    };
    vkGetPhysicalDeviceProperties2(p, &props);

    if (props.properties.apiVersion < VK_API_VERSION_1_3)
      continue; // If this physical device does not support at least Vulkan 1.3, we cannot use it. We use Vulkan 1.3
                // core features in this sample.

    const auto queue_family_indices = find_queue_families(p);

    if ((queue_family_indices.first == UINT32_MAX) || (queue_family_indices.second == UINT32_MAX))
      continue; // This physical device isn't what we want, if it lacks either graphics or present queue families

    // We could (and should) do more suitability checks in a real application,
    // but for this sample, this is just ok.

    m_physical_device = p;
    m_graphics_queue_family_index = queue_family_indices.first;
    m_present_queue_family_index = queue_family_indices.second;

    m_physical_device_name = props.properties.deviceName;

    if (props.properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU)
      break; // If we find a discrete GPU, then prefer it
  }

  if (m_physical_device == VK_NULL_HANDLE)
    return "Failed to find a good physical device";

  printf("[VulkanCore]: Using physical device \"%s\"\n", m_physical_device_name.c_str());

  return Ok();
}

Result<> VulkanCore::create_device()
{
  const float priority = 1.0f;
  std::vector<VkDeviceQueueCreateInfo> queue_create_infos;
  // passing through std::set effectively dedups family indices.
  // not really necessary to use std::set here as we only have to consider
  // 2 families (graphics and present), so we could have just checked (family_index_1 == family_index_2),
  // but this std::set approach generalizes to higher orders (imagine doing if/else checks for combinations of 3 or 4)
  for (const auto index : std::set<uint32_t>{m_graphics_queue_family_index, m_present_queue_family_index})
    queue_create_infos.push_back(VkDeviceQueueCreateInfo{
        .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
        .queueFamilyIndex = index,
        .queueCount = 1,
        .pQueuePriorities = &priority,
    });

  std::vector<const char *> device_extensions{SWAPCHAIN_DEVICE_EXTENSION_NAME};
  // macOS support: if the device is a portability implementation (i.e. MoltenVK),
  // it exposes VK_KHR_portability_subset, and the spec requires us to enable it.
  const auto device_ext_props =
      vkEnumCall<VkExtensionProperties>(vkEnumerateDeviceExtensionProperties, m_physical_device, nullptr);
  if (std::any_of(device_ext_props.begin(), device_ext_props.end(), [](VkExtensionProperties p) {
        return strcmp(p.extensionName, PORTABILITY_SUBSET_DEVICE_EXTENSION_NAME) == 0;
      }))
    device_extensions.push_back(PORTABILITY_SUBSET_DEVICE_EXTENSION_NAME);

  VkPhysicalDeviceFeatures enabled_features{};
  VkPhysicalDeviceVulkan13Features vk_13_features{
      .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES,
      .synchronization2 = VK_TRUE,
      .dynamicRendering = VK_TRUE,
  };

  VkDeviceCreateInfo device_create_info{
      .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
      .pNext = &vk_13_features,
      .queueCreateInfoCount = (uint32_t) queue_create_infos.size(),
      .pQueueCreateInfos = queue_create_infos.data(),
      .enabledLayerCount = 0,
      .ppEnabledLayerNames = nullptr,
      .enabledExtensionCount = (uint32_t) device_extensions.size(),
      .ppEnabledExtensionNames = device_extensions.data(),
      .pEnabledFeatures = &enabled_features,
  };

  if (vkCreateDevice(m_physical_device, &device_create_info, nullptr, &m_device) != VK_SUCCESS)
    return "Failed to create Vulkan device";

  vkGetDeviceQueue(m_device, m_graphics_queue_family_index, 0, &m_graphics_queue);
  vkGetDeviceQueue(m_device, m_present_queue_family_index, 0, &m_present_queue);

  return Ok();
}

Result<> VulkanCore::create_allocator()
{
  VmaAllocatorCreateInfo vma_create_info{
      .physicalDevice = m_physical_device,
      .device = m_device,
      .instance = m_instance,
      .vulkanApiVersion = VK_API_VERSION_1_3,
  };
  if (vmaCreateAllocator(&vma_create_info, &m_allocator) != VK_SUCCESS)
    return "Failed to create the VMA allocator";

  return Ok();
}

Result<> VulkanCore::initialize_single_shot_commands()
{
  VkCommandPoolCreateInfo pool_create_info{
      .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
      .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
      .queueFamilyIndex = m_graphics_queue_family_index,
  };
  if (vkCreateCommandPool(m_device, &pool_create_info, nullptr, &m_single_shot_command_pool) != VK_SUCCESS)
    return "Failed to create the single shot command pool";

  VkFenceCreateInfo fence_create_info{
      .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
  };
  if (vkCreateFence(m_device, &fence_create_info, nullptr, &m_single_shot_command_fence) != VK_SUCCESS)
    return "Failed to create the single shot fence";

  VkCommandBufferAllocateInfo alloc_info{
      .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
      .commandPool = m_single_shot_command_pool,
      .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
      .commandBufferCount = 1,
  };
  if (vkAllocateCommandBuffers(m_device, &alloc_info, &m_single_shot_command_buffer) != VK_SUCCESS)
    return "Failed to allocate the single shot command buffer";

  return Ok();
}
Show src/hpp/swapchain.hpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#pragma once

#include <image.hpp>

class VulkanCore;

class Swapchain
{
  struct FrameResourceSet
  {
    VkFence fen_in_flight{};
    VkSemaphore sm_image_available{};
    VkCommandBuffer cmd_buffer{};
  };

  public:
  static constexpr uint32_t NUM_CONCURRENT_FRAMES = 3;

  static Result<Box<Swapchain>> create(const VulkanCore *core, VkExtent2D initial_extent);

  Swapchain(const Swapchain &) = delete;
  Swapchain &operator=(const Swapchain &) = delete;

  ~Swapchain();

  void resize(uint32_t width, uint32_t height);
  void request_recreation();

  Result<VkCommandBuffer> begin_frame();
  Result<> end_frame();

  public:
  void register_resize_callback(std::function<void(VkExtent2D extent)> resize_callback)
  {
    m_resize_callback = resize_callback;
  }

  VkFormat get_color_format() const
  {
    return m_format.format;
  }

  VkFormat get_depth_format() const
  {
    return m_depth_image->get_format();
  }

  VkExtent2D get_extent() const
  {
    return m_extent;
  }

  uint32_t get_current_frame_index() const
  {
    return m_current_frame_index;
  }

  VkImageView get_color_attachment() const
  {
    return m_image_views[m_current_image_index];
  }

  VkImageView get_depth_attachment() const
  {
    return m_depth_image->get_view();
  }

  float get_aspect_ratio() const
  {
    return (float) m_extent.width / (float) m_extent.height;
  }

  private:
  Swapchain(const VulkanCore *core) : m_core(core)
  {
  }

  Result<> recreate();
  Result<> create_frame_resources();

  private:
  const VulkanCore *const m_core;

  bool m_is_out_of_date{};

  uint32_t m_image_count{};
  VkSurfaceFormatKHR m_format{};
  VkPresentModeKHR m_present_mode{};
  std::vector<VkSemaphore> m_render_done_semaphores;
  VkSurfaceTransformFlagBitsKHR m_pre_transform{};

  VkSwapchainKHR m_swapchain{};
  std::vector<VkImage> m_images{};
  std::vector<VkImageView> m_image_views{};
  Box<Image> m_depth_image{};

  uint32_t m_current_frame_index{};
  uint32_t m_current_image_index{};
  VkCommandPool m_frame_resource_command_pool{};
  FrameResourceSet m_frames[NUM_CONCURRENT_FRAMES];

  VkExtent2D m_extent{1, 1};
  VkExtent2D m_pending_extent{1, 1};

  std::function<void(VkExtent2D extent)> m_resize_callback{};
};
Show src/cpp/swapchain.cpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#include <core.hpp>
#include <swapchain.hpp>

Result<Box<Swapchain>> Swapchain::create(const VulkanCore *core, VkExtent2D initial_extent)
{
  Box<Swapchain> swapchain(new Swapchain(core));

  const auto surface_formats = vkEnumCall<VkSurfaceFormatKHR>(vkGetPhysicalDeviceSurfaceFormatsKHR,
                                                              core->get_physical_device(), core->get_surface());
  const auto surface_present_modes = vkEnumCall<VkPresentModeKHR>(vkGetPhysicalDeviceSurfacePresentModesKHR,
                                                                  core->get_physical_device(), core->get_surface());
  assert(surface_formats.size());
  assert(surface_present_modes.size());
  swapchain->m_format = surface_formats[0];
  swapchain->m_present_mode = (std::find(surface_present_modes.begin(), surface_present_modes.end(),
                                         VK_PRESENT_MODE_MAILBOX_KHR) != surface_present_modes.end())
                                  ? VK_PRESENT_MODE_MAILBOX_KHR
                                  : VK_PRESENT_MODE_FIFO_KHR;

  swapchain->m_pending_extent = initial_extent;

  CHECK_RESULT(swapchain->recreate());
  CHECK_RESULT(swapchain->create_frame_resources());

  return swapchain;
}

Swapchain::~Swapchain()
{
  if (!m_core || !m_core->get_device())
    return;

  m_depth_image.reset();

  for (uint32_t i = 0; i < NUM_CONCURRENT_FRAMES; i++)
  {
    vkDestroyFence(m_core->get_device(), m_frames[i].fen_in_flight, nullptr);
    vkDestroySemaphore(m_core->get_device(), m_frames[i].sm_image_available, nullptr);
  }

  for (size_t i = 0; i < m_render_done_semaphores.size(); i++)
    vkDestroySemaphore(m_core->get_device(), m_render_done_semaphores[i], nullptr);
  m_render_done_semaphores.clear();

  vkDestroyCommandPool(m_core->get_device(), m_frame_resource_command_pool, nullptr);

  for (const auto &view : m_image_views)
    vkDestroyImageView(m_core->get_device(), view, nullptr);
  vkDestroySwapchainKHR(m_core->get_device(), m_swapchain, nullptr);
}

void Swapchain::resize(uint32_t width, uint32_t height)
{
  m_pending_extent = {width, height};
  request_recreation();
}

void Swapchain::request_recreation()
{
  m_is_out_of_date = true;
}

Result<VkCommandBuffer> Swapchain::begin_frame()
{
  const auto &current_frame = m_frames[m_current_frame_index];

  vkWaitForFences(m_core->get_device(), 1, &current_frame.fen_in_flight, VK_TRUE, UINT64_MAX);

  switch (vkAcquireNextImageKHR(m_core->get_device(), m_swapchain, UINT64_MAX, current_frame.sm_image_available,
                                VK_NULL_HANDLE, &m_current_image_index))
  {
  case VK_ERROR_OUT_OF_DATE_KHR:
    CHECK_RESULT(recreate());
    return (VkCommandBuffer)VK_NULL_HANDLE;

  case VK_SUCCESS:
  case VK_SUBOPTIMAL_KHR:
    break;

  default:
    return "Failed to acquire swapchain image";
  }

  VkCommandBufferBeginInfo cmd_begin_info{
      .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
  };
  vkResetCommandBuffer(current_frame.cmd_buffer, 0);
  if (vkBeginCommandBuffer(current_frame.cmd_buffer, &cmd_begin_info) != VK_SUCCESS)
    return "Failed to start recording command buffer";

  if (!Image::transition_image_layout(current_frame.cmd_buffer, m_images[m_current_image_index],
                                      VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL))
    return "Failed to transition swapchain image";

  return (VkCommandBuffer)current_frame.cmd_buffer;
}

Result<> Swapchain::end_frame()
{
  const auto &current_frame = m_frames[m_current_frame_index];

  if (!Image::transition_image_layout(current_frame.cmd_buffer, m_images[m_current_image_index],
                                      VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR))
    return "Failed to transition swapchain image";

  if (vkEndCommandBuffer(current_frame.cmd_buffer) != VK_SUCCESS)
    return "Failed to finish recording command buffer";

  VkPipelineStageFlags submit_pipeline_wait_stage{VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT};
  VkSubmitInfo submit_info{
      .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
      .waitSemaphoreCount = 1,
      .pWaitSemaphores = &current_frame.sm_image_available,
      .pWaitDstStageMask = &submit_pipeline_wait_stage,
      .commandBufferCount = 1,
      .pCommandBuffers = &current_frame.cmd_buffer,
      .signalSemaphoreCount = 1,
      .pSignalSemaphores = &m_render_done_semaphores[m_current_image_index],
  };

  vkResetFences(m_core->get_device(), 1, &current_frame.fen_in_flight);
  if (vkQueueSubmit(m_core->get_queue_graphics(), 1, &submit_info, current_frame.fen_in_flight) != VK_SUCCESS)
    return "Failed to submit frame command buffer";

  VkPresentInfoKHR present_info{
      .sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
      .waitSemaphoreCount = 1,
      .pWaitSemaphores = &m_render_done_semaphores[m_current_image_index],
      .swapchainCount = 1,
      .pSwapchains = &m_swapchain,
      .pImageIndices = &m_current_image_index,
  };

  switch (vkQueuePresentKHR(m_core->get_queue_present(), &present_info))
  {
  case VK_ERROR_OUT_OF_DATE_KHR:
  case VK_SUBOPTIMAL_KHR:
    CHECK_RESULT(recreate());
    break;

  case VK_SUCCESS:
    break;

  default:
    return "Failed to present swapchain";
  }

  if (m_is_out_of_date)
    CHECK_RESULT(recreate());

  m_current_frame_index = (m_current_frame_index + 1) % NUM_CONCURRENT_FRAMES;

  return Ok();
}

Result<> Swapchain::recreate()
{
  m_core->wait_idle();

  bool resized = false;

  VkSurfaceCapabilitiesKHR surface_caps{};
  if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR(m_core->get_physical_device(), m_core->get_surface(), &surface_caps) !=
      VK_SUCCESS)
    return "Failed to query physical device surface caps";

  // A minimized window has a 0x0 surface, and a 0x0 swapchain is not allowed. So we
  // keep the current swapchain, and try again later (once the window is restored).
  if ((surface_caps.maxImageExtent.width == 0) || (surface_caps.maxImageExtent.height == 0))
  {
    m_is_out_of_date = true;
    return Ok();
  }

  m_image_count = std::min(surface_caps.minImageCount + 1,
                           (surface_caps.maxImageCount == 0) ? UINT32_MAX : surface_caps.maxImageCount);

  m_pre_transform = surface_caps.currentTransform;

  m_pending_extent.width =
      std::clamp(m_pending_extent.width, surface_caps.minImageExtent.width, surface_caps.maxImageExtent.width);
  m_pending_extent.height =
      std::clamp(m_pending_extent.height, surface_caps.minImageExtent.height, surface_caps.maxImageExtent.height);
  resized = (m_extent.width != m_pending_extent.width) || (m_extent.height != m_pending_extent.height);  
  m_extent = m_pending_extent;

  m_depth_image.reset();
  for (const auto &view : m_image_views)
    vkDestroyImageView(m_core->get_device(), view, nullptr);
  if (m_swapchain)
    vkDestroySwapchainKHR(m_core->get_device(), m_swapchain, nullptr);
  m_image_views.clear();
  m_swapchain = VK_NULL_HANDLE;

  VkSwapchainCreateInfoKHR swapchain_create_info{
      .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
      .surface = m_core->get_surface(),
      .minImageCount = m_image_count,
      .imageFormat = m_format.format,
      .imageColorSpace = m_format.colorSpace,
      .imageExtent = m_extent,
      .imageArrayLayers = 1,
      .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
      .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
      .preTransform = m_pre_transform,
      .compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
      .presentMode = m_present_mode,
      .clipped = VK_TRUE,
  };

  uint32_t queue_family_indices[] = {m_core->get_queue_family_index_graphics(),
                                     m_core->get_queue_family_index_present()};
  if (queue_family_indices[0] != queue_family_indices[1])
  {
    swapchain_create_info.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
    swapchain_create_info.queueFamilyIndexCount = 2;
    swapchain_create_info.pQueueFamilyIndices = queue_family_indices;
  }

  if (vkCreateSwapchainKHR(m_core->get_device(), &swapchain_create_info, nullptr, &m_swapchain) != VK_SUCCESS)
    return "Failed to create swapchain";

  m_images = vkEnumCall<VkImage>(vkGetSwapchainImagesKHR, m_core->get_device(), m_swapchain);

  // Note that we use the *actual* number of images here, which can be
  // more than the minImageCount we asked for.
  for (auto semaphore : m_render_done_semaphores)
    vkDestroySemaphore(m_core->get_device(), semaphore, nullptr);
  m_render_done_semaphores.assign(m_images.size(), VK_NULL_HANDLE);

  VkSemaphoreCreateInfo semaphore_create_info{
      .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
  };
  for (auto &semaphore : m_render_done_semaphores)
  {
    if (vkCreateSemaphore(m_core->get_device(), &semaphore_create_info, nullptr, &semaphore) != VK_SUCCESS)
      return "Failed to create a semaphore";
  }

  m_image_views.reserve(m_images.size());
  for (const auto &image : m_images)
  {
    VkImageViewCreateInfo create_info{
        .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
        .image = image,
        .viewType = VK_IMAGE_VIEW_TYPE_2D,
        .format = m_format.format,
        .components =
            {
                .r = VK_COMPONENT_SWIZZLE_IDENTITY,
                .g = VK_COMPONENT_SWIZZLE_IDENTITY,
                .b = VK_COMPONENT_SWIZZLE_IDENTITY,
                .a = VK_COMPONENT_SWIZZLE_IDENTITY,
            },
        .subresourceRange =
            {
                .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
                .baseMipLevel = 0,
                .levelCount = 1,
                .baseArrayLayer = 0,
                .layerCount = 1,
            },
    };

    VkImageView view{};
    if (vkCreateImageView(m_core->get_device(), &create_info, nullptr, &view) != VK_SUCCESS)
      return "Failed to create a swapchain image view";

    m_image_views.push_back(view);
  }

  {
    auto result = Image::create(m_core->get_device(), m_core->get_allocator(), VK_FORMAT_D32_SFLOAT, m_extent,
                                VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT);
    if (result.is_error())
      return result.get_error();

    m_depth_image = std::move(result).take_value();

    CHECK_RESULT(m_core->execute_single_shot_commands([&](VkCommandBuffer cmd) -> Result<> {
      if (!m_depth_image->transition_layout(cmd, VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL))
        return "Failed to transition depth image layout";

      return Ok();
    }));
  }

  m_is_out_of_date = false;

  if (m_resize_callback && resized)
    m_resize_callback(m_extent);

  return Ok();
}

Result<> Swapchain::create_frame_resources()
{
  VkCommandPoolCreateInfo commmand_pool_create_info{
      .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
      .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
      .queueFamilyIndex = m_core->get_queue_family_index_graphics(),
  };
  if (vkCreateCommandPool(m_core->get_device(), &commmand_pool_create_info, nullptr, &m_frame_resource_command_pool) !=
      VK_SUCCESS)
    return "Failed to create command pool";

  VkCommandBufferAllocateInfo command_buffer_alloc_info{
      .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
      .commandPool = m_frame_resource_command_pool,
      .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
      .commandBufferCount = 1,
  };
  for (uint32_t i = 0; i < NUM_CONCURRENT_FRAMES; i++)
  {
    if (vkAllocateCommandBuffers(m_core->get_device(), &command_buffer_alloc_info, &m_frames[i].cmd_buffer) !=
        VK_SUCCESS)
      return "Failed to allocate frame command buffer";

    VkSemaphoreCreateInfo semaphore_create_info{
        .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
    };
    if (vkCreateSemaphore(m_core->get_device(), &semaphore_create_info, nullptr, &m_frames[i].sm_image_available) !=
        VK_SUCCESS)
      return "Failed to create a semaphore";

    VkFenceCreateInfo fence_create_info{
        .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
        .flags = VK_FENCE_CREATE_SIGNALED_BIT,
    };
    if (vkCreateFence(m_core->get_device(), &fence_create_info, nullptr, &m_frames[i].fen_in_flight) != VK_SUCCESS)
      return "Failed to create a fence";
  }

  return Ok();
}
Show src/hpp/buffer.hpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#pragma once

#include <pch.hpp>

class Buffer
{
  public:
  enum class EUsage
  {
    VERTEX,
    INDEX,
    STAGING,
  };

  public:
  static Result<Box<Buffer>> create(VmaAllocator allocator, VkDeviceSize size, EUsage usage);

  Buffer(const Buffer &) = delete;
  Buffer &operator=(const Buffer &) = delete;

  ~Buffer();

  void bind(VkCommandBuffer cmd);

  VkDeviceSize get_size() const
  {
    return m_size;
  }

  VkBuffer get_handle() const
  {
    return m_handle;
  }

  bool copy_from_cpu(const void *data, VkDeviceSize size);

  private:
  Buffer(VmaAllocator allocator) : m_allocator(allocator)
  {
  }

  private:
  EUsage m_usage{};
  VmaAllocator m_allocator{};

  VkBuffer m_handle{};
  VkDeviceSize m_size{};
  VmaAllocation m_allocation{};
};

class IUniformBuffer
{
public:
  virtual ~IUniformBuffer() = default;
  
  virtual VkDeviceSize get_size() const = 0;
  virtual uint32_t get_frame_count() const = 0;
  virtual VkBuffer get_handle(uint32_t frame_index) const = 0;
};

template<typename DataT> class UniformBuffer: public IUniformBuffer
{
  public:
  static Result<Box<UniformBuffer>> create(VmaAllocator allocator, uint32_t frame_count);

  UniformBuffer(const UniformBuffer &) = delete;
  UniformBuffer &operator=(const UniformBuffer &) = delete;

  ~UniformBuffer();

  DataT &get_data()
  {
    return m_data;
  }

  const DataT &get_data() const
  {
    return m_data;
  }

  VkDeviceSize get_size() const override
  {
    return m_size;
  }

  VkBuffer get_handle(uint32_t frame_index) const override
  {
    return m_handles[frame_index];
  }

  uint32_t get_frame_count() const override
  {
    assert(m_handles.size() == m_allocations.size());
    return (uint32_t) m_handles.size();
  }

  bool flush(uint32_t frame_index);

  private:
  UniformBuffer(VmaAllocator allocator) : m_allocator(allocator)
  {
  }

  private:
  DataT m_data{};
  VmaAllocator m_allocator{};

  VkDeviceSize m_size{};
  std::vector<VkBuffer> m_handles{};
  std::vector<VmaAllocation> m_allocations{};
};

template<typename DataT>
Result<Box<UniformBuffer<DataT>>> UniformBuffer<DataT>::create(VmaAllocator allocator, uint32_t frame_count)
{
  Box<UniformBuffer> buffer{new UniformBuffer(allocator)};

  buffer->m_size = sizeof(DataT);

  VkBufferCreateInfo create_info{
      .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
      .size = buffer->m_size,
      .usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
      .sharingMode = VK_SHARING_MODE_EXCLUSIVE, // we only need to use our buffers from a single queue family at a time
  };

  VmaAllocationCreateInfo alloc_create_info{
      .flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT,
      .usage = VMA_MEMORY_USAGE_AUTO,
  };

  buffer->m_handles.resize(frame_count);
  buffer->m_allocations.resize(frame_count);
  for (uint32_t i = 0; i < frame_count; i++)
  {
    if (vmaCreateBuffer(allocator, &create_info, &alloc_create_info, &buffer->m_handles[i], &buffer->m_allocations[i],
                        nullptr) != VK_SUCCESS)
    {
      return "Failed to create the buffer";
    }
  }

  return buffer;
}

template<typename DataT> UniformBuffer<DataT>::~UniformBuffer()
{
  if (!m_allocator)
    return;

  const auto frame_count = get_frame_count(); // using the member function here so it triggers the assert as well
  for (uint32_t i = 0; i < frame_count; i++)
  {
    vmaDestroyBuffer(m_allocator, m_handles[i], m_allocations[i]);
  }
  m_handles.clear();
  m_allocations.clear();
}

template<typename DataT> bool UniformBuffer<DataT>::flush(uint32_t frame_index)
{
  return vmaCopyMemoryToAllocation(m_allocator, &m_data, m_allocations[frame_index], 0, sizeof(m_data)) == VK_SUCCESS;
}
Show src/cpp/buffer.cpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#include <buffer.hpp>

Result<Box<Buffer>> Buffer::create(VmaAllocator allocator, VkDeviceSize size, EUsage usage)
{
  Box<Buffer> buffer{new Buffer(allocator)};

  buffer->m_size = size;
  buffer->m_usage = usage;

  VkBufferUsageFlags _usage{};
  VmaAllocationCreateFlags _mem_flags{};

  switch (usage)
  {
  case EUsage::VERTEX:
    // vertex buffer + transfer dst (for copying data in from staging buffer)
    _usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
    break;

  case EUsage::INDEX:
    // index buffer + transfer dst (for copying data in from staging buffer)
    _usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
    break;

  case EUsage::STAGING:
    // allows transferring data out from this buffer (for copying)
    _usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;

    // allow writing to this buffer from CPU memory
    _mem_flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT;
    break;
  }

  VkBufferCreateInfo create_info{
      .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
      .size = size,
      .usage = _usage,
      .sharingMode = VK_SHARING_MODE_EXCLUSIVE, // we only need to use our buffers from a single queue family at a time
  };

  VmaAllocationCreateInfo alloc_create_info{
      .flags = _mem_flags,
      .usage = VMA_MEMORY_USAGE_AUTO, // when _mem_flags doesn't contain CPU access flags (like we set in above switch
                                      // STAGING case), this picks fast GPU VRAM
  };

  if (vmaCreateBuffer(allocator, &create_info, &alloc_create_info, &buffer->m_handle, &buffer->m_allocation, nullptr) !=
      VK_SUCCESS)
  {
    return "Failed to create the buffer";
  }

  return buffer;
}

Buffer::~Buffer()
{
  if (m_allocator && m_handle && m_allocation)
    vmaDestroyBuffer(m_allocator, m_handle, m_allocation);
}

void Buffer::bind(VkCommandBuffer cmd)
{
  switch (m_usage)
  {
  case EUsage::VERTEX: {
    VkDeviceSize offset = 0;
    vkCmdBindVertexBuffers(cmd, 0, 1, &m_handle, &offset);
  }
  break;

  case EUsage::INDEX:
    vkCmdBindIndexBuffer(cmd, m_handle, 0, VK_INDEX_TYPE_UINT32);
    break;

  // we shouldn't call bind on a staging buffer
  case EUsage::STAGING:
    assert(false);
    break;
  }
}

bool Buffer::copy_from_cpu(const void *data, VkDeviceSize size)
{
  assert(m_usage == EUsage::STAGING);

  return vmaCopyMemoryToAllocation(m_allocator, data, m_allocation, 0, size) == VK_SUCCESS;
}
Show src/hpp/image.hpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#pragma once

#include <buffer.hpp>

class Image
{
  public:
  static bool is_depth_format(VkFormat format);

  static bool load_rgba_from_file(const std::string &path, std::vector<uint8_t> &pixels, VkExtent2D &extent);

  static bool transition_image_layout(VkCommandBuffer cmd, VkImage image, VkImageLayout old_layout,
                                      VkImageLayout new_layout, uint32_t base_mip_level = 0, uint32_t level_count = 1,
                                      uint32_t base_array_layer = 0, uint32_t layer_count = 1);

  public:
  static Result<Box<Image>> create(VkDevice device, VmaAllocator allocator, VkFormat format, VkExtent2D extent,
                                   VkImageUsageFlags usage);

  Image(const Image &) = delete;
  Image &operator=(const Image &) = delete;

  ~Image();

  bool transition_layout(VkCommandBuffer cmd, VkImageLayout new_layout);

  // make sure the image is in VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL layout before
  // calling this function
  Result<> copy_from_cpu(VkCommandBuffer cmd, const void *data, VkDeviceSize size);

  VkImageView get_view() const
  {
    return m_view_handle;
  }

  VkImageLayout get_layout() const
  {
    return m_layout;
  }

  VkFormat get_format() const
  {
    return m_format;
  }

  private:
  Image(VkDevice device, VmaAllocator allocator) : m_device(device), m_allocator(allocator)
  {
  }

  private:
  VkDevice m_device{};
  VmaAllocator m_allocator{};

  VkImage m_handle{};
  VkImageView m_view_handle{};
  VkFormat m_format{};
  VkExtent2D m_extent{};
  VmaAllocation m_allocation{};
  VkImageLayout m_layout{VK_IMAGE_LAYOUT_UNDEFINED};

  Box<Buffer> m_staging_buffer; // only create if copy_from_cpu is called
};
Show src/cpp/image.cpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#include <image.hpp>

#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.hpp>

Result<Box<Image>> Image::create(VkDevice device, VmaAllocator allocator, VkFormat format, VkExtent2D extent,
                                 VkImageUsageFlags usage)
{
  Box<Image> image(new Image(device, allocator));

  image->m_format = format;
  image->m_extent = extent;

  VkImageCreateInfo create_info{
      .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
      .imageType = VK_IMAGE_TYPE_2D, // for now we'll only need 2D images
      .format = format,
      .extent = VkExtent3D(extent.width, extent.height, 1),
      .mipLevels = 1, // we won't be bothering with mip mapping for now
      .arrayLayers = 1,
      .samples = VK_SAMPLE_COUNT_1_BIT,  // we won't be bothering with multisampling for now either
      .tiling = VK_IMAGE_TILING_OPTIMAL, // we don't have any specific tiling we need so let vulkan pick the optimal one
      .usage = usage,
      .sharingMode = VK_SHARING_MODE_EXCLUSIVE, // we only need to use our images from a single queue family at a time
      .initialLayout = image->m_layout,
  };

  VmaAllocationCreateInfo alloc_create_info{
      .usage = VMA_MEMORY_USAGE_AUTO,
  };
  if (vmaCreateImage(allocator, &create_info, &alloc_create_info, &image->m_handle, &image->m_allocation, nullptr) !=
      VK_SUCCESS)
    return "Failed to create the image";

  VkImageViewCreateInfo view_create_info{
      .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
      .image = image->m_handle,
      .viewType = VK_IMAGE_VIEW_TYPE_2D,
      .format = image->m_format,
      .subresourceRange =
          {
              .aspectMask = is_depth_format(format) ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT,
              .baseMipLevel = 0,
              .levelCount = 1,
              .baseArrayLayer = 0,
              .layerCount = 1,
          },
  };
  if (vkCreateImageView(device, &view_create_info, nullptr, &image->m_view_handle) != VK_SUCCESS)
    return "Failed to create the image view";

  return image;
}

Image::~Image()
{
  m_staging_buffer.reset();

  if (m_device && m_view_handle)
    vkDestroyImageView(m_device, m_view_handle, nullptr);

  if (m_allocator && m_allocation && m_handle)
    vmaDestroyImage(m_allocator, m_handle, m_allocation);
}

bool Image::transition_layout(VkCommandBuffer cmd, VkImageLayout new_layout)
{
  if (transition_image_layout(cmd, m_handle, m_layout, new_layout))
  {
    m_layout = new_layout;
    return true;
  }

  return false;
}

Result<> Image::copy_from_cpu(VkCommandBuffer cmd, const void *data, VkDeviceSize size)
{
  assert(m_layout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);

  if (!m_staging_buffer || (m_staging_buffer->get_size() < size))
  {
    m_staging_buffer.reset();

    CHECK_ASSIGN_RESULT(Buffer::create(m_allocator, size, Buffer::EUsage::STAGING), m_staging_buffer);
  }

  if (!m_staging_buffer->copy_from_cpu(data, size))
    return "Failed to copy data to the staging buffer";

  VkBufferImageCopy region{
      .bufferOffset = 0,
      .bufferRowLength = m_extent.width,
      .bufferImageHeight = m_extent.height,
      .imageSubresource =
          {
              .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
              .mipLevel = 0,
              .baseArrayLayer = 0,
              .layerCount = 1,
          },
      .imageOffset = {},
      .imageExtent = VkExtent3D(m_extent.width, m_extent.height, 1),
  };
  vkCmdCopyBufferToImage(cmd, m_staging_buffer->get_handle(), m_handle, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1,
                         &region);

  return Ok();
}

bool Image::transition_image_layout(VkCommandBuffer cmd, VkImage image, VkImageLayout old_layout,
                                    VkImageLayout new_layout, uint32_t base_mip_level, uint32_t level_count,
                                    uint32_t base_array_layer, uint32_t layer_count)
{
  VkPipelineStageFlags2 src_stage{}, dst_stage{};
  VkAccessFlags2 src_access{}, dst_access{};
  VkImageAspectFlags aspect{VK_IMAGE_ASPECT_COLOR_BIT};

#define _is_layout_pair(o, n) ((old_layout == o) && (new_layout == n))

  if (_is_layout_pair(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL))
  {
    src_stage = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT;
    src_access = VK_ACCESS_2_NONE;

    dst_stage = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT;
    dst_access = VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT;
  }
  else if (_is_layout_pair(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL))
  {
    src_stage = VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT;
    src_access = VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;

    dst_stage = VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT;
    dst_access = VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;

    aspect = VK_IMAGE_ASPECT_DEPTH_BIT;
  }
  else if (_is_layout_pair(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR))
  {
    src_stage = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT;
    src_access = VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT;

    dst_stage = VK_PIPELINE_STAGE_2_NONE;
    dst_access = VK_ACCESS_2_NONE;
  }
  else if (_is_layout_pair(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL))
  {
    src_stage = VK_PIPELINE_STAGE_2_NONE;
    src_access = VK_ACCESS_2_NONE;

    dst_stage = VK_PIPELINE_STAGE_2_COPY_BIT;
    dst_access = VK_ACCESS_2_TRANSFER_WRITE_BIT;
  }
  else if (_is_layout_pair(VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL))
  {
    src_stage = VK_PIPELINE_STAGE_2_COPY_BIT;
    src_access = VK_ACCESS_2_TRANSFER_WRITE_BIT;

    dst_stage = VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT;
    dst_access = VK_ACCESS_2_SHADER_SAMPLED_READ_BIT;
  }
  else
  {
    printf("Unknown layout transition\n");
    return false;
  }

#undef _is_layout_pair

  VkImageMemoryBarrier2 barrier{
      .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,

      .srcStageMask = src_stage,
      .srcAccessMask = src_access,

      .dstStageMask = dst_stage,
      .dstAccessMask = dst_access,

      .oldLayout = old_layout,
      .newLayout = new_layout,

      .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
      .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,

      .image = image,

      .subresourceRange =
          {
              .aspectMask = aspect,
              .baseMipLevel = base_mip_level,
              .levelCount = level_count,
              .baseArrayLayer = base_array_layer,
              .layerCount = layer_count,
          },
  };

  VkDependencyInfo dep_info{
      .sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
      .imageMemoryBarrierCount = 1,
      .pImageMemoryBarriers = &barrier,
  };

  vkCmdPipelineBarrier2(cmd, &dep_info);

  return true;
}

bool Image::load_rgba_from_file(const std::string &path, std::vector<uint8_t> &pixels, VkExtent2D &extent)
{
  int w, h, n;
  const auto pixel_data = stbi_load(path.c_str(), &w, &h, &n, STBI_rgb_alpha);
  if (!pixel_data)
    return false;

  extent.width = (uint32_t) w;
  extent.height = (uint32_t) h;

  pixels.resize(w * h * 4);
  memcpy(pixels.data(), pixel_data, pixels.size());

  stbi_image_free(pixel_data);

  return true;
}

bool Image::is_depth_format(VkFormat format)
{
  switch (format)
  {
  case VK_FORMAT_D16_UNORM:
  case VK_FORMAT_D32_SFLOAT:
  case VK_FORMAT_D16_UNORM_S8_UINT:
  case VK_FORMAT_D24_UNORM_S8_UINT:
  case VK_FORMAT_D32_SFLOAT_S8_UINT:
    return true;

  default:
    return false;
  }
}
Show src/hpp/shader_data_table.hpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#pragma once

#include <image.hpp>

class Pipeline;

class ShaderDataTable
{
  public:
  struct EntryDescription
  {
    std::string name{};
    uint32_t set{};
    uint32_t binding{};
    VkDescriptorType type{};
    uint32_t count{};
    VkShaderStageFlags stages{};
  };

  public:
  static Result<Box<ShaderDataTable>> create(VkDevice device, std::span<const EntryDescription> entries,
                                             uint32_t frame_count);

  ShaderDataTable(const ShaderDataTable &) = delete;
  ShaderDataTable &operator=(const ShaderDataTable &) = delete;

  ~ShaderDataTable();

  bool write_image_entry(const std::string &name, uint32_t frame_index, const Image *image, VkSampler sampler,
                         uint32_t index = 0);
  bool write_uniform_buffer_entry(const std::string &name, const IUniformBuffer *buffer, VkDeviceSize offset = 0,
                                  VkDeviceSize size = 0, uint32_t index = 0);
  void flush_writes();

  void bind(VkCommandBuffer cmd, uint32_t frame_index);

  VkPipelineLayout get_pipeline_layout() const
  {
    return m_pipeline_layout;
  }

  private:
  ShaderDataTable(VkDevice device) : m_device(device)
  {
  }

  private:
  VkDevice m_device{};

  VkDescriptorPool m_pool{};
  uint32_t m_sets_per_frame{};
  VkPipelineLayout m_pipeline_layout{};
  std::vector<VkDescriptorSet> m_sets{};
  std::vector<VkDescriptorSetLayout> m_set_layouts{};
  std::map<std::string, std::pair<uint32_t, uint32_t>> m_entry_map{};

  std::vector<VkWriteDescriptorSet> m_queued_writes{};
  std::deque<VkDescriptorImageInfo> m_queued_write_image_infos{};
  std::deque<VkDescriptorBufferInfo> m_queued_write_buffer_infos{};
};
Show src/cpp/shader_data_table.cpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#include <shader_data_table.hpp>

Result<Box<ShaderDataTable>> ShaderDataTable::create(VkDevice device, std::span<const EntryDescription> entries,
                                                     uint32_t frame_count)
{
  Box<ShaderDataTable> table{new ShaderDataTable(device)};

  for (const auto &entry : entries)
  {
    table->m_sets_per_frame = std::max(entry.set + 1, table->m_sets_per_frame);
  }

  std::map<VkDescriptorType, uint32_t> descriptor_counts{};
  std::vector<std::vector<VkDescriptorSetLayoutBinding>> bindings{table->m_sets_per_frame};
  for (const auto &entry : entries)
  {
    bindings[entry.set].push_back({
        .binding = entry.binding,
        .descriptorType = entry.type,
        .descriptorCount = entry.count,
        .stageFlags = entry.stages,
    });

    descriptor_counts[entry.type] += entry.count;

    table->m_entry_map[entry.name] = {entry.set, entry.binding};
  }

  table->m_set_layouts.resize(table->m_sets_per_frame);
  for (uint32_t i = 0; i < table->m_sets_per_frame; i++)
  {
    VkDescriptorSetLayoutCreateInfo set_layout_create_info{
        .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
        .bindingCount = (uint32_t) bindings[i].size(),
        .pBindings = bindings[i].data(),
    };

    if (vkCreateDescriptorSetLayout(device, &set_layout_create_info, nullptr, &table->m_set_layouts[i]) != VK_SUCCESS)
      return "Failed to create the descriptor set layout";
  }

  VkPipelineLayoutCreateInfo layout_create_info{
      .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
      .setLayoutCount = (uint32_t) table->m_set_layouts.size(),
      .pSetLayouts = table->m_set_layouts.data(),
      .pushConstantRangeCount = 0, // we'll talk about push constants in another post
  };

  if (vkCreatePipelineLayout(device, &layout_create_info, nullptr, &table->m_pipeline_layout) != VK_SUCCESS)
    return "Failed to create the pipeline layout";

  std::vector<VkDescriptorPoolSize> pool_sizes{};
  for (const auto &dc : descriptor_counts)
  {
    pool_sizes.push_back({.type = dc.first, .descriptorCount = dc.second * frame_count});
  }

  VkDescriptorPoolCreateInfo pool_create_info{
      .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
      .maxSets = table->m_sets_per_frame * frame_count,
      .poolSizeCount = (uint32_t) pool_sizes.size(),
      .pPoolSizes = pool_sizes.data(),
  };

  if (vkCreateDescriptorPool(device, &pool_create_info, nullptr, &table->m_pool) != VK_SUCCESS)
    return "Failed to create the descriptor pool";

  {
    table->m_sets.resize(table->m_sets_per_frame * frame_count);

    std::vector<VkDescriptorSetLayout> layouts(table->m_sets.size());
    for (uint32_t i = 0; i < frame_count; i++)
    {
      for (uint32_t j = 0; j < table->m_sets_per_frame; j++)
      {
        layouts[(i * table->m_sets_per_frame) + j] = table->m_set_layouts[j];
      }
    }

    VkDescriptorSetAllocateInfo alloc_info{
        .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
        .descriptorPool = table->m_pool,
        .descriptorSetCount = (uint32_t) layouts.size(),
        .pSetLayouts = layouts.data(),
    };

    if (vkAllocateDescriptorSets(device, &alloc_info, table->m_sets.data()) != VK_SUCCESS)
      return "Failed to allocate descriptor sets";
  }

  return table;
}

ShaderDataTable::~ShaderDataTable()
{
  if (!m_device)
    return;

  for (size_t i = 0; i < m_set_layouts.size(); i++)
    vkDestroyDescriptorSetLayout(m_device, m_set_layouts[i], nullptr);
  m_set_layouts.clear();

  if (m_pool)
    vkDestroyDescriptorPool(m_device, m_pool, nullptr);

  if (m_pipeline_layout)
    vkDestroyPipelineLayout(m_device, m_pipeline_layout, nullptr);
}

bool ShaderDataTable::write_image_entry(const std::string &name, uint32_t frame_index, const Image *image,
                                        VkSampler sampler, uint32_t index)
{
  const auto entry = m_entry_map.find(name);
  if (entry == m_entry_map.end())
    return false;

  m_queued_write_image_infos.push_back(VkDescriptorImageInfo{
      sampler,
      image->get_view(),
      image->get_layout(),
  });

  m_queued_writes.push_back({
      .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
      .dstSet = m_sets[(frame_index * m_sets_per_frame) + entry->second.first],
      .dstBinding = entry->second.second,
      .dstArrayElement = index,
      .descriptorCount = 1,
      .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
      .pImageInfo = &m_queued_write_image_infos.back(),
  });

  return true;
}

bool ShaderDataTable::write_uniform_buffer_entry(const std::string &name, const IUniformBuffer *buffer,
                                                 VkDeviceSize offset, VkDeviceSize size, uint32_t index)
{
  const auto entry = m_entry_map.find(name);
  if (entry == m_entry_map.end())
    return false;

  for (uint32_t i = 0; i < buffer->get_frame_count(); i++)
  {
    m_queued_write_buffer_infos.push_back(VkDescriptorBufferInfo{
        buffer->get_handle(i),
        offset,
        (size == 0) ? buffer->get_size() : size,
    });

    m_queued_writes.push_back({
        .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
        .dstSet = m_sets[(i * m_sets_per_frame) + entry->second.first],
        .dstBinding = entry->second.second,
        .dstArrayElement = index,
        .descriptorCount = 1,
        .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
        .pBufferInfo = &m_queued_write_buffer_infos.back(),
    });
  }

  return true;
}

void ShaderDataTable::flush_writes()
{
  if (m_queued_writes.empty())
    return;

  vkUpdateDescriptorSets(m_device, m_queued_writes.size(), m_queued_writes.data(), 0, nullptr);

  m_queued_write_image_infos.clear();
  m_queued_write_buffer_infos.clear();

  m_queued_writes.clear();
}

void ShaderDataTable::bind(VkCommandBuffer cmd, uint32_t frame_index)
{
  vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, m_pipeline_layout, 0, m_sets_per_frame,
                          &m_sets[frame_index * m_sets_per_frame], 0, nullptr);
}
Show src/hpp/pipeline.hpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#pragma once

#include <shader_data_table.hpp>

class Pipeline
{
  public:
  static Result<Box<Pipeline>> create(VkDevice device, VkFormat color_attachment_format,
                                      VkFormat depth_attachment_format,
                                      std::span<const VkVertexInputBindingDescription> input_bindings,
                                      std::span<const VkVertexInputAttributeDescription> input_attributes,
                                      const ShaderDataTable *data_table, std::span<const uint32_t> vertex_shader_source,
                                      std::span<const uint32_t> fragment_shader_source);

  Pipeline(const Pipeline &) = delete;
  Pipeline &operator=(const Pipeline &) = delete;

  ~Pipeline();

  void bind(VkCommandBuffer cmd);

  private:
  Pipeline(VkDevice device) : m_device(device)
  {
  }

  private:
  VkDevice m_device{};

  VkPipeline m_handle{};
};
Show src/cpp/pipeline.cpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#include <pipeline.hpp>

Result<Box<Pipeline>> Pipeline::create(VkDevice device, VkFormat color_attachment_format,
                                       VkFormat depth_attachment_format,
                                       std::span<const VkVertexInputBindingDescription> input_bindings,
                                       std::span<const VkVertexInputAttributeDescription> input_attributes,
                                       const ShaderDataTable *data_table,
                                       std::span<const uint32_t> vertex_shader_source,
                                       std::span<const uint32_t> fragment_shader_source)
{
  Box<Pipeline> pipeline{new Pipeline(device)};

  VkShaderModule shader_modules[2];

  VkShaderModuleCreateInfo shader_module_create_infos[2] = {
      {
          .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
          .codeSize = vertex_shader_source.size() << 2,
          .pCode = vertex_shader_source.data(),
      },
      {
          .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
          .codeSize = fragment_shader_source.size() << 2,
          .pCode = fragment_shader_source.data(),
      },
  };

  if (vkCreateShaderModule(device, &shader_module_create_infos[0], nullptr, &shader_modules[0]) != VK_SUCCESS)
    return "Failed to create the shader module for vertex shader";

  if (vkCreateShaderModule(device, &shader_module_create_infos[1], nullptr, &shader_modules[1]) != VK_SUCCESS)
  {
    vkDestroyShaderModule(device, shader_modules[0], nullptr);
    return "Failed to create the shader module for fragment shader";
  }

  VkPipelineShaderStageCreateInfo shader_stage_create_infos[2] = {
      {
          .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
          .stage = VK_SHADER_STAGE_VERTEX_BIT,
          .module = shader_modules[0],
          .pName = "main",
      },
      {
          .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
          .stage = VK_SHADER_STAGE_FRAGMENT_BIT,
          .module = shader_modules[1],
          .pName = "main",
      },
  };

  VkPipelineRenderingCreateInfo rendering_create_info{
      .sType = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO,
      .colorAttachmentCount = 1,
      .pColorAttachmentFormats = &color_attachment_format,
      .depthAttachmentFormat = depth_attachment_format,
      .stencilAttachmentFormat = VK_FORMAT_UNDEFINED,
  };

  VkPipelineVertexInputStateCreateInfo vertex_input_state_create_info{
      .sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
      .vertexBindingDescriptionCount = (uint32_t) input_bindings.size(),
      .pVertexBindingDescriptions = input_bindings.data(),
      .vertexAttributeDescriptionCount = (uint32_t) input_attributes.size(),
      .pVertexAttributeDescriptions = input_attributes.data(),
  };

  VkPipelineInputAssemblyStateCreateInfo ia_state_create_info{
      .sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
      .topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST,
  };

  VkPipelineViewportStateCreateInfo viewport_state_create_info{
      .sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
      .viewportCount = 1,
      .scissorCount = 1,
  };

  VkPipelineRasterizationStateCreateInfo rs_create_info{
      .sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
      .polygonMode = VK_POLYGON_MODE_FILL,
      .cullMode = VK_CULL_MODE_NONE,
      .lineWidth = 1.0,
  };

  VkPipelineMultisampleStateCreateInfo multisample_state_create_info{
      .sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
      .rasterizationSamples = VK_SAMPLE_COUNT_1_BIT,
  };

  VkPipelineColorBlendAttachmentState color_blend_attachment_state{
      .blendEnable = VK_FALSE,
      .colorWriteMask =
          VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT,
  };

  VkPipelineColorBlendStateCreateInfo color_blend_state_create_info{
      .sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,
      .attachmentCount = 1,
      .pAttachments = &color_blend_attachment_state,
  };

  VkDynamicState dynamic_states[2] = {
      VK_DYNAMIC_STATE_VIEWPORT,
      VK_DYNAMIC_STATE_SCISSOR,
  };

  VkPipelineDynamicStateCreateInfo dynamic_state_create_info{
      .sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO,
      .dynamicStateCount = (sizeof(dynamic_states) / sizeof(dynamic_states[0])),
      .pDynamicStates = dynamic_states,
  };

  VkPipelineDepthStencilStateCreateInfo depth_stencil_state_create_info{
      .sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO,
      .depthTestEnable = true,
      .depthWriteEnable = true,
      .depthCompareOp = VK_COMPARE_OP_LESS,
      .minDepthBounds = 0.0f,
      .maxDepthBounds = 1.0f,
  };

  VkGraphicsPipelineCreateInfo create_info{
      .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,
      .pNext = &rendering_create_info,

      .stageCount = (sizeof(shader_stage_create_infos) / sizeof(shader_stage_create_infos[0])),
      .pStages = shader_stage_create_infos,

      .pVertexInputState = &vertex_input_state_create_info,
      .pInputAssemblyState = &ia_state_create_info,
      .pViewportState = &viewport_state_create_info,
      .pRasterizationState = &rs_create_info,
      .pMultisampleState = &multisample_state_create_info,
      .pDepthStencilState = &depth_stencil_state_create_info,
      .pColorBlendState = &color_blend_state_create_info,
      .pDynamicState = &dynamic_state_create_info,

      .layout = data_table->get_pipeline_layout(),
  };

  if (vkCreateGraphicsPipelines(device, nullptr, 1, &create_info, nullptr, &pipeline->m_handle) != VK_SUCCESS)
  {
    vkDestroyShaderModule(device, shader_modules[0], nullptr);
    vkDestroyShaderModule(device, shader_modules[1], nullptr);

    return "Failed to create the graphics pipeline";
  }

  vkDestroyShaderModule(device, shader_modules[0], nullptr);
  vkDestroyShaderModule(device, shader_modules[1], nullptr);

  return pipeline;
}

void Pipeline::bind(VkCommandBuffer cmd)
{
  // for now we'll only be using graphics pipeline so we can just hardcode VK_PIPELINE_BIND_POINT_GRAPHICS here
  vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, m_handle);
}

Pipeline::~Pipeline()
{
  if (!m_device)
    return;

  if (m_handle)
    vkDestroyPipeline(m_device, m_handle, nullptr);
}
Show src/hpp/renderer.hpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#pragma once

#include <image.hpp>
#include <buffer.hpp>
#include <pipeline.hpp>

#include <core.hpp>
#include <swapchain.hpp>

class Renderer
{
  public:
  static Result<Box<Renderer>> create(
      std::function<Result<>(VkInstance, uint32_t &, uint32_t &, VkSurfaceKHR &)> surface_creation_callback);

  Renderer(const Renderer &) = delete;
  Renderer &operator=(const Renderer &) = delete;

  ~Renderer();

  Result<> render();

  void resize(uint32_t fb_width, uint32_t fb_height);

  private:
  Renderer() = default;

  Result<> on_create();

  void on_swapchain_resize();

  private:
  Box<VulkanCore> m_core{};
  Box<Swapchain> m_swapchain{};

  Box<Pipeline> m_graphics_pipeline{};

  Box<Buffer> m_staging_buffer{};
  Box<Buffer> m_vertex_buffer{};
  Box<Buffer> m_index_buffer{};

  Box<Image> m_texture_image{};
  VkSampler m_texture_sampler{};

  Box<ShaderDataTable> m_shader_data_table{};

  Box<UniformBuffer<VertexUniformData>> m_vertex_uniform{};
};
Show src/cpp/renderer.cpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#include <renderer.hpp>

#include <fstream>

static Result<std::vector<uint32_t>> load_shader_from_file(const std::string &path)
{
  std::ifstream f(path, std::ios::in | std::ios::binary | std::ios::ate);
  if (!f.is_open())
    return "Failed to open shader file \"" + path + "\".";

  std::vector<uint32_t> data;
  data.resize(f.tellg() >> 2);
  f.seekg(SEEK_SET);
  f.read((char *) data.data(), data.size() << 2);

  return data;
}

Result<Box<Renderer>> Renderer::create(
    std::function<Result<>(VkInstance, uint32_t &, uint32_t &, VkSurfaceKHR &)> surface_creation_callback)
{
  Box<Renderer> renderer(new Renderer());

  VkExtent2D initial_extent{};

  CHECK_ASSIGN_RESULT(VulkanCore::create(surface_creation_callback, initial_extent), renderer->m_core);
  CHECK_ASSIGN_RESULT(Swapchain::create(renderer->m_core.get(), initial_extent), renderer->m_swapchain);
  renderer->m_swapchain->register_resize_callback(
      [renderer = renderer.get()](VkExtent2D) { renderer->on_swapchain_resize(); });
  CHECK_RESULT(renderer->on_create());
  renderer->on_swapchain_resize();

  return renderer;
}

Renderer::~Renderer()
{
  if (!m_core || !m_core->get_device())
    return;

  m_core->wait_idle();

  m_texture_image.reset();

  vkDestroySampler(m_core->get_device(), m_texture_sampler, nullptr);

  m_graphics_pipeline.reset();
  m_shader_data_table.reset();

  m_vertex_buffer.reset();
  m_index_buffer.reset();
  m_staging_buffer.reset();
  m_vertex_uniform.reset();
}

Result<> Renderer::on_create()
{
  CHECK_ASSIGN_RESULT(ShaderDataTable::create(m_core->get_device(),
                                              std::initializer_list<ShaderDataTable::EntryDescription>{
                                                  {
                                                      .name = "vertex_uniform_data",
                                                      .set = 0,
                                                      .binding = 0,
                                                      .type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
                                                      .count = 1,
                                                      .stages = VK_SHADER_STAGE_VERTEX_BIT,
                                                  },
                                                  {
                                                      .name = "texture_sampler",
                                                      .set = 1,
                                                      .binding = 0,
                                                      .type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
                                                      .count = 1,
                                                      .stages = VK_SHADER_STAGE_FRAGMENT_BIT,
                                                  },
                                              },
                                              Swapchain::NUM_CONCURRENT_FRAMES),
                      m_shader_data_table);

  std::vector<uint32_t> vertex_shader_data, fragment_shader_data{};
  CHECK_ASSIGN_RESULT(load_shader_from_file("resources/default.vert.spv"), vertex_shader_data);
  CHECK_ASSIGN_RESULT(load_shader_from_file("resources/default.frag.spv"), fragment_shader_data);

  CHECK_ASSIGN_RESULT(
      Pipeline::create(
          m_core->get_device(), m_swapchain->get_color_format(), m_swapchain->get_depth_format(),
          std::initializer_list<VkVertexInputBindingDescription>{
              {.binding = 0, .stride = sizeof(Vertex), .inputRate = VK_VERTEX_INPUT_RATE_VERTEX},
          },
          std::initializer_list<VkVertexInputAttributeDescription>{
              VkVertexInputAttributeDescription{
                  .location = 0, .binding = 0, .format = VK_FORMAT_R32G32B32_SFLOAT, .offset = offsetof(Vertex, pos)},
              VkVertexInputAttributeDescription{.location = 1,
                                                .binding = 0,
                                                .format = VK_FORMAT_R32G32B32_SFLOAT,
                                                .offset = offsetof(Vertex, colour)},
              VkVertexInputAttributeDescription{
                  .location = 2, .binding = 0, .format = VK_FORMAT_R32G32_SFLOAT, .offset = offsetof(Vertex, texcoord)},
          },
          m_shader_data_table.get(), vertex_shader_data, fragment_shader_data),
      m_graphics_pipeline);

  CHECK_ASSIGN_RESULT(
      Buffer::create(m_core->get_allocator(),
                     std::max(sizeof(CUBE_MESH_VERTICES),
                              sizeof(CUBE_MESH_INDICES)), // maximum size we'll need for our staging operations
                     Buffer::EUsage::STAGING),
      m_staging_buffer);

  CHECK_ASSIGN_RESULT(Buffer::create(m_core->get_allocator(), sizeof(CUBE_MESH_VERTICES), Buffer::EUsage::VERTEX),
                      m_vertex_buffer);

  CHECK_ASSIGN_RESULT(Buffer::create(m_core->get_allocator(), sizeof(CUBE_MESH_INDICES), Buffer::EUsage::INDEX),
                      m_index_buffer);

  CHECK_ASSIGN_RESULT(
      UniformBuffer<VertexUniformData>::create(m_core->get_allocator(), Swapchain::NUM_CONCURRENT_FRAMES),
      m_vertex_uniform);

  { // copy VERTICES to vertex buffer
    if (!m_staging_buffer->copy_from_cpu(CUBE_MESH_VERTICES, sizeof(CUBE_MESH_VERTICES)))
      return "Failed to copy VERTICES to staging buffer";

    CHECK_RESULT(m_core->execute_single_shot_commands([&](VkCommandBuffer cmd) -> Result<> {
      VkBufferCopy copy_region{
          .srcOffset = 0,
          .dstOffset = 0,
          .size = m_vertex_buffer->get_size(),
      };

      vkCmdCopyBuffer(cmd, m_staging_buffer->get_handle(), m_vertex_buffer->get_handle(), 1, &copy_region);

      VkMemoryBarrier barrier{
          .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER,
          .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
          .dstAccessMask = VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT,
      };
      vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, 0, 1, &barrier, 0,
                           nullptr, 0, nullptr);

      return Ok{};
    }));
  }

  { // copy INDICES to index buffer
    if (!m_staging_buffer->copy_from_cpu(CUBE_MESH_INDICES, sizeof(CUBE_MESH_INDICES)))
      return "Failed to copy INDICES to staging buffer";

    CHECK_RESULT(m_core->execute_single_shot_commands([&](VkCommandBuffer cmd) -> Result<> {
      VkBufferCopy copy_region{
          .srcOffset = 0,
          .dstOffset = 0,
          .size = m_index_buffer->get_size(),
      };

      vkCmdCopyBuffer(cmd, m_staging_buffer->get_handle(), m_index_buffer->get_handle(), 1, &copy_region);

      VkMemoryBarrier barrier{
          .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER,
          .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
          .dstAccessMask = VK_ACCESS_INDEX_READ_BIT,
      };
      vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, 0, 1, &barrier, 0,
                           nullptr, 0, nullptr);

      return Ok{};
    }));
  }

  {
    VkSamplerCreateInfo create_info{
        .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
        .magFilter = VK_FILTER_LINEAR,
        .minFilter = VK_FILTER_LINEAR,
        .addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT,
        .addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT,
        .addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT,
    };

    if (vkCreateSampler(m_core->get_device(), &create_info, nullptr, &m_texture_sampler) != VK_SUCCESS)
      return "Failed to create the texture sampler";
  }

  {
    std::vector<uint8_t> pixels{};
    VkExtent2D extent{};

    if (!Image::load_rgba_from_file("resources/Ground037_1K-PNG_Color.png", pixels, extent))
      return "Failed to load texture data from the disk";

    CHECK_ASSIGN_RESULT(
        Image::create(m_core->get_device(), m_core->get_allocator(), VK_FORMAT_R8G8B8A8_SRGB, extent,
                      VK_IMAGE_USAGE_SAMPLED_BIT |
                          VK_IMAGE_USAGE_TRANSFER_DST_BIT // We want to sample this image from fragment shader
                                                          // and copy data from staging buffer into this image.
                      ),
        m_texture_image);

    CHECK_RESULT(m_core->execute_single_shot_commands([&](VkCommandBuffer cmd) -> Result<> {
      if (!m_texture_image->transition_layout(cmd, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL))
        return "Failed to transition texture image to VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL";

      CHECK_RESULT(m_texture_image->copy_from_cpu(cmd, pixels.data(), pixels.size()));

      if (!m_texture_image->transition_layout(cmd, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL))
        return "Failed to transition texture image to VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL";

      return Ok{};
    }));
  }

  if (!m_shader_data_table->write_uniform_buffer_entry("vertex_uniform_data", m_vertex_uniform.get()))
    return "Failed to write uniform buffer to shader data table";

  for (uint32_t i = 0; i < Swapchain::NUM_CONCURRENT_FRAMES; i++)
  {
    if (!m_shader_data_table->write_image_entry("texture_sampler", i, m_texture_image.get(), m_texture_sampler))
      return "Failed to write texture image to shader data table";
  }

  m_shader_data_table->flush_writes();

  m_vertex_uniform->get_data().view =
      glm::lookAt(glm::vec3(0.0f, 0.0f, 0.75f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));

  return Ok();
}

Result<> Renderer::render()
{
  VkCommandBuffer cmd;
  CHECK_ASSIGN_RESULT(m_swapchain->begin_frame(), cmd);

  if (cmd == VK_NULL_HANDLE)
    return Ok();

  { // Update Uniform Data
    static constexpr float SPEED = glm::radians(90.0f);
    static auto start_time = std::chrono::steady_clock::now();

    const auto current_time = std::chrono::steady_clock::now();
    const auto seconds = std::chrono::duration<float>(current_time - start_time).count();

    m_vertex_uniform->get_data().model =
        glm::rotate(glm::mat4(1.0f), std::fmod(seconds * SPEED, glm::two_pi<float>()), glm::vec3(1.0f, 1.0f, 1.0f)) *
        glm::scale(glm::mat4(1.0f), glm::vec3(0.25f));

    if (!m_vertex_uniform->flush(m_swapchain->get_current_frame_index()))
      return "Failed to flush the uniform buffer";
  }

  VkRenderingAttachmentInfo color_attachment_info{
      .sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO,
      .imageView = m_swapchain->get_color_attachment(),
      .imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
      .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
      .storeOp = VK_ATTACHMENT_STORE_OP_STORE,
      .clearValue =
          {
              .color =
                  {
                      0.1f,
                      0.1f,
                      0.1f,
                      1.0f,
                  },
          },
  };

  VkRenderingAttachmentInfo depth_attachment_info{
      .sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO,
      .imageView = m_swapchain->get_depth_attachment(),
      .imageLayout = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL,
      .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
      .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
      .clearValue =
          {
              .depthStencil =
                  {
                      1.0f,
                      0,
                  },
          },
  };

  VkRenderingInfo rendering_info{
      .sType = VK_STRUCTURE_TYPE_RENDERING_INFO,
      .renderArea =
          {
              {},
              m_swapchain->get_extent(),
          },
      .layerCount = 1,
      .viewMask = 0,
      .colorAttachmentCount = 1,
      .pColorAttachments = &color_attachment_info,
      .pDepthAttachment = &depth_attachment_info,
  };

  vkCmdBeginRendering(cmd, &rendering_info);

  VkViewport viewport = {
      .width = (float) m_swapchain->get_extent().width,
      .height = (float) m_swapchain->get_extent().height,
      .minDepth = 0.0f,
      .maxDepth = 1.0f,
  };
  vkCmdSetViewport(cmd, 0, 1, &viewport);

  VkRect2D scissor{
      .extent = m_swapchain->get_extent(),
  };
  vkCmdSetScissor(cmd, 0, 1, &scissor);

  m_graphics_pipeline->bind(cmd);

  m_vertex_buffer->bind(cmd);
  m_index_buffer->bind(cmd);

  m_shader_data_table->bind(cmd, m_swapchain->get_current_frame_index());

  vkCmdDrawIndexed(cmd, sizeof(CUBE_MESH_INDICES) / sizeof(CUBE_MESH_INDICES[0]), 1, 0, 0, 0);

  vkCmdEndRendering(cmd);

  CHECK_RESULT(m_swapchain->end_frame());

  return Ok();
}

void Renderer::resize(uint32_t fb_width, uint32_t fb_height)
{
  m_swapchain->resize(fb_width, fb_height);
}

void Renderer::on_swapchain_resize()
{
  if (!m_vertex_uniform)
    return;

  m_vertex_uniform->get_data().projection =
      glm::perspective(glm::half_pi<float>(), m_swapchain->get_aspect_ratio(), 0.1f, 1.0f);
  m_vertex_uniform->get_data().projection[1][1] *= -1.0f;
}
Show src/cpp/main.cpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#include <renderer.hpp>

class SampleApp
{
  static constexpr uint32_t SCREEN_WIDTH = 800;
  static constexpr uint32_t SCREEN_HEIGHT = 600;

  public:
  Result<int> launch(int argc, char *argv[]);

  ~SampleApp();

  private:
  GLFWwindow *m_window{};
  Box<Renderer> m_renderer{};
};

int main(int argc, char *argv[])
{
  SampleApp app;
  const auto result = app.launch(argc, argv);
  if (result.is_error())
  {
    printf("ERROR: %s\n", result.get_error().c_str());
    return -1;
  }
  return result.get_value();
}

Result<int> SampleApp::launch(int argc, char *argv[])
{
  if (!glfwInit())
    return "Failed to initialize GLFW";

  glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
  m_window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "i-a-s.me Vulkan Sample", nullptr, nullptr);
  if (!m_window)
    return "Failed to create GLFW window";

  CHECK_ASSIGN_RESULT(
      Renderer::create([window = m_window](VkInstance instance, uint32_t &out_width, uint32_t &out_height,
                                           VkSurfaceKHR &out_surface) -> Result<> {
        if (glfwCreateWindowSurface(instance, window, nullptr, &out_surface) != VK_SUCCESS)
          return "Failed to create Vulkan surface";

        int32_t fb_width{}, fb_height{};
        glfwGetFramebufferSize(window, &fb_width, &fb_height);
        while ((fb_width == 0) || (fb_height == 0))
        {
          glfwWaitEvents();
          glfwGetFramebufferSize(window, &fb_width, &fb_height);
        }

        out_width = (uint32_t) fb_width;
        out_height = (uint32_t) fb_height;

        return Ok();
      }),
      m_renderer);

  glfwSetWindowUserPointer(m_window, m_renderer.get());

  glfwSetFramebufferSizeCallback(m_window, [](GLFWwindow *window, int width, int height) {
    int32_t fb_width{}, fb_height{};
    glfwGetFramebufferSize(window, &fb_width, &fb_height);
    if ((fb_width == 0) || (fb_height == 0))
      return;
    static_cast<Renderer *>(glfwGetWindowUserPointer(window))->resize(fb_width, fb_height);
  });

  while (!glfwWindowShouldClose(m_window))
  {
    if (glfwGetKey(m_window, GLFW_KEY_ESCAPE))
      glfwSetWindowShouldClose(m_window, true);

    glfwPollEvents();

    // Don't render while the window is minimized (its framebuffer is 0x0 then)
    int32_t fb_width{}, fb_height{};
    glfwGetFramebufferSize(m_window, &fb_width, &fb_height);
    if ((fb_width == 0) || (fb_height == 0))
    {
      glfwWaitEvents();
      continue;
    }

    CHECK_RESULT(m_renderer->render());
  }

  return 0;
}

SampleApp::~SampleApp()
{
  m_renderer.reset();

  if (m_window)
    glfwDestroyWindow(m_window);

  glfwTerminate();
}
Show src/cpp/vma.cpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#define VMA_IMPLEMENTATION
#include <vk_mem_alloc.h>
Show shaders/default.vert
#version 450

layout(location = 0) in vec3 in_pos;
layout(location = 1) in vec3 in_color;
layout(location = 2) in vec2 in_texcoord;

layout(std140, set = 0, binding = 0) uniform VertexUniformData {
    mat4 model;
    mat4 view;
    mat4 projection;
} uniform_data;

layout(location = 0) out vec3 out_color;
layout(location = 1) out vec2 out_texcoord;

void main() {
    gl_Position = uniform_data.projection * uniform_data.view * uniform_data.model * vec4(in_pos, 1.0);
    out_color = in_color;
    out_texcoord = in_texcoord;
}
Show shaders/default.frag
#version 450

layout(location = 0) in vec3 in_color;
layout(location = 1) in vec2 in_texcoord;

layout(set = 1, binding = 0) uniform sampler2D texture_sampler;

layout(location = 0) out vec4 finalColor;

void main() {
    finalColor = texture(texture_sampler, in_texcoord);
}