Writing

Vulkan Series: 04 - Vertex and Index Buffers

Moving our vertices out of the shader and into vertex and index buffers, using VMA, GLM and a staging buffer in Vulkan 1.3

graphicsvulkanc++vmaglmvertex buffersindex buffersstaging buffersvulkan 1.3

What we’ll build here

End Result
End Result

A quad! After two posts of looking at the same triangle, we finally get a new shape on the screen. But the real upgrade is where it comes from: our vertices are no longer hardcoded into the vertex shader. They now live in vertex and index buffers, in GPU memory, where they belong.

In this post, we’ll:

  1. Define our vertex data on the C++ side using GLM
  2. Write a small Buffer class on top of VMA
  3. Tell our graphics pipeline and vertex shader how to read vertices from a buffer
  4. Get our data into GPU memory using a staging buffer
  5. Draw it with an indexed draw call

This post builds directly on top of the previous post, where we set up VMA and GLM, 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 to install this time, and CMake already has VMA and GLM for us. We have just two small changes to make.

We’ll be adding one new source file, buffer.cpp, so it goes into our CMakeLists.txt:

add_executable(App
    vma.cpp
    main.cpp
    buffer.cpp
    sample.cpp
    pipeline.cpp
)

And we’ll finally be using GLM, so it gets included in common.hpp, right after VMA:

#include <vk_mem_alloc.h>

#include <glm/glm.hpp>

THEORY: Vertex and index buffers

A vertex buffer is just a Vulkan buffer (a chunk of GPU memory) that holds our vertex data. When we draw, a fixed function part of the pipeline called the vertex input stage reads the vertices from the buffer and hands them to our vertex shader, one by one. We tell the pipeline how the data is laid out, and from then on, the shader doesn’t need to know where its vertices came from.

An index buffer holds a list of numbers, each one the position of a vertex in the vertex buffer. Instead of “draw vertices 0, 1, 2, 3…”, we get to say “draw vertices 0, 1, 2, then 2, 3, 0”. This lets triangles share vertices.

Take the quad we’ll end up with. It’s made of 2 triangles, so 6 vertices, but 2 of those are exact duplicates. Our vertices are 24 bytes each, so without an index buffer, that’s 6 × 24 = 144 bytes. With one, it’s 4 vertices (96 bytes) plus 6 uint32_t indices (24 bytes), so 120 bytes. Not a huge win for a single quad, but in a real mesh, a vertex is usually shared between several triangles, and the savings add up fast.

The vertex data

We’ll start off by recreating the triangle from the previous posts, so we can be sure that everything works before we change the shape. At the top of sample.cpp:

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

static const Vertex VERTICES[3] = {
  {glm::vec3(0.0f, -0.5f, 0.0f), glm::vec3(1.0f, 0.0f, 0.0f)},
  {glm::vec3(0.5f, 0.5f, 0.0f),  glm::vec3(0.0f, 1.0f, 0.0f)},
  {glm::vec3(-0.5f, 0.5f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f)},
};

static const uint32_t INDICES[3] = {
  0, 1, 2
};
  • Vertex: Each vertex has a position and a colour, both glm::vec3s. Our positions were 2D before, but now they have a z too. We keep it at 0.0f for now.
  • VERTICES: The same 3 vertices as in our old vertex shader: red at the top, green at the bottom right and blue at the bottom left.
  • INDICES: Draw vertex 0, then 1, then 2. Pretty pointless for a single triangle, but we’ll get to why we bother at the end.

Since glm::vec3 is three tightly packed floats, a Vertex is six tightly packed floats, 24 bytes in total. That means we can copy these arrays straight into a buffer, as is.

The Buffer class

Same as with our pipeline, we’ll wrap buffers into a little class of their own. Here’s buffer.hpp:

// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#pragma once

#include "common.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();

    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{};
};

This should look familiar from the Pipeline class in the previous post: a static create function returning a Result<Box<Buffer>>, a private constructor, no copying, and a destructor that cleans up. EUsage lists the three kinds of buffers we need, and we’ll get to the third one, STAGING, in a second.

Here’s the start of Buffer::create, in the new buffer.cpp:

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;
  }
  • _usage: In Vulkan, we have to declare everything we’ll be using a buffer for upfront. Our vertex buffer is obviously a VERTEX_BUFFER, and it’s also a TRANSFER_DST, because it’s the destination of a copy, as we’ll see later. Same goes for the index buffer. The staging buffer is only ever the source of a copy, so it’s just a TRANSFER_SRC.
  • _mem_flags: Extra instructions for VMA. Only the staging buffer gets one: HOST_ACCESS_SEQUENTIAL_WRITE, which says the CPU will be writing to this buffer, in order, and never reading from it (a memcpy, basically).

And the rest of it:

  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;
}
  • VkBufferCreateInfo: Our size and usage flags. VK_SHARING_MODE_EXCLUSIVE means the buffer belongs to one queue family at a time, which is all we need, as we’ll use the graphics queue for both copying and drawing.
  • VmaAllocationCreateInfo: With VMA_MEMORY_USAGE_AUTO, VMA picks a suitable memory type by looking at our usage and flags. No CPU access flags means our vertex and index buffers go into fast GPU memory, and the flag on our staging buffer means it goes somewhere the CPU can write to.
  • vmaCreateBuffer: Remember the list of steps from the previous post? Creating the buffer, finding a memory type, allocating memory and binding it? This one call does all of that. The last parameter can give us details about the allocation, which we don’t need, so it’s a nullptr.

The rest of the class is short:

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;
    
    case EUsage::STAGING:
      assert(false); // we shouldn't call bind on a staging buffer
    break;
  }
}

The destructor frees both the buffer and its memory with a single call. bind makes the buffer the one that upcoming draws read from, and which command it uses depends on the kind of buffer:

  • Vertex buffers use vkCmdBindVertexBuffers. The 0 is the binding number, which we’ll see again in the pipeline, and offset says where in the buffer our data starts.
  • Index buffers use vkCmdBindIndexBuffer. VK_INDEX_TYPE_UINT32 matches the uint32_t of our INDICES array.
  • Staging buffers are never drawn from, so binding one is a bug, and we assert.

We’ll look at copy_from_cpu, the last function in this class, once we get to it.

Creating the buffers

Let’s add the new members to SampleVulkan, along with an #include "buffer.hpp" at the top of sample.hpp:

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

And let’s create the staging buffer first, in initialize:

  {
    auto result = Buffer::create(
      m_allocator,
      std::max(sizeof(VERTICES), sizeof(INDICES)), // maximum size we'll need for our staging operations 
      Buffer::EUsage::STAGING
    );

    if (result.is_error()) {
      printf("%s\n", result.get_error().c_str());
      return false;
    }

    m_staging_buffer = std::move(result).take_value();
  }

We only upload one thing at a time, so the staging buffer just has to be big enough for the largest upload.

Since we have two more buffers to create, repeating the same “check result, print and return or take_value” code will start to clutter our nice codebase. Let’s define a macro for this, at the top of sample.cpp:

#define CHECK_RESULT(_result, _var)             \
{                                               \
  auto result = _result;                        \
  if (result.is_error()) {                      \
    printf("%s\n", result.get_error().c_str()); \
    return false;                               \
  }                                             \
  _var = std::move(result).take_value();        \
}

The extra { } give each use its own scope, so we can use the macro over and over without the result variables clashing. Do note the return false; in there: it only works inside functions that return bool, which is fine for us here.

Then we can do:

  CHECK_RESULT(
    Buffer::create(
      m_allocator,
      std::max(sizeof(VERTICES), sizeof(INDICES)), // maximum size we'll need for our staging operations 
      Buffer::EUsage::STAGING
    ),
    m_staging_buffer
  );

And the same for our graphics pipeline, which means create_graphics_pipeline can go away entirely. Delete the function along with its declaration, and in initialize, replace the call to it with this:

  CHECK_RESULT(
    Pipeline::create(
      m_device,
      m_swapchain_format.format,
      SHADER_SPV_VERT,
      SHADER_SPV_FRAG
    ),
    m_graphics_pipeline
  );

The vertex and index buffers are now just two more uses of the macro, right after the staging buffer:

  CHECK_RESULT(
    Buffer::create(
      m_allocator,
      sizeof(VERTICES), 
      Buffer::EUsage::VERTEX
    ),
    m_vertex_buffer
  );

  CHECK_RESULT(
    Buffer::create(
      m_allocator,
      sizeof(INDICES), 
      Buffer::EUsage::INDEX
    ),
    m_index_buffer
  );

Buffers have to be freed before the allocator gets destroyed, so we reset them in our destructor, right after vkDeviceWaitIdle:

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

Reading vertices from a buffer

The vertex shader

Our vertex shader gets a lot simpler. The array of vertices and gl_VertexIndex are gone, and we now take the position and colour as inputs:

#version 450

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

layout(location = 0) out vec3 out_color;

void main() {
    gl_Position = vec4(in_pos, 1.0);
    out_color = in_color;
}

layout(location = 0) in declares a vertex attribute: a value the shader receives for each vertex, from the vertex buffer. Inputs and outputs have separate location numbers, so it’s fine for both in_pos and out_color to be at location 0. The fragment shader stays exactly as it is.

As this changes the shader, remember to recompile it with glslc, and re-embed it into sample.hpp using tools/embed_spv.py, like we did in the coloured triangle post.

The Pipeline class

Now we need to tell the pipeline what a vertex looks like in memory. Pipeline::create takes two more parameters, in both pipeline.hpp and pipeline.cpp:

Result<Box<Pipeline>> Pipeline::create(VkDevice device, VkFormat color_attachment_format,
        std::span<const VkVertexInputBindingDescription> input_bindings,
        std::span<const VkVertexInputAttributeDescription> input_attributes,
        std::span<const uint32_t> vertex_shader_source, std::span<const uint32_t> fragment_shader_source)

And we pass them along to the vertex input state, which we’ve been leaving empty until now:

  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(),
  };

Describing our vertices

Here’s what our Pipeline::create call looks like now:

  CHECK_RESULT(
    Pipeline::create(
      m_device,
      m_swapchain_format.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)},
      },
      SHADER_SPV_VERT,
      SHADER_SPV_FRAG
    ),
    m_graphics_pipeline
  );

There are two kinds of descriptions here. A binding describes a buffer we’ll read from, and an attribute describes one value within each vertex in that buffer:

  • VkVertexInputBindingDescription
    • binding = 0: The number we give this binding. It’s the same 0 we pass to vkCmdBindVertexBuffers in Buffer::bind.
    • stride = sizeof(Vertex): How many bytes to move forward to get to the next vertex.
    • inputRate = VK_VERTEX_INPUT_RATE_VERTEX: Move forward once per vertex (the other option moves forward once per instance, for instanced drawing).
  • VkVertexInputAttributeDescription
    • location: Which shader input this goes to, matching the layout(location = ...) in our vertex shader.
    • binding: Which binding to read it from.
    • format = VK_FORMAT_R32G32B32_SFLOAT: Three 32-bit floats, in other words a vec3. Yes, the format names talk about colour channels even when the data has nothing to do with colours!
    • offset: Where this value is within a Vertex. offsetof gets the compiler to work it out for us, so we can’t get it wrong.

Why the explicit std::initializer_lists? A plain { ... } can’t be turned into a std::span argument in C++20, but a std::initializer_list can. The lists stay alive until the end of the full statement, and Pipeline::create is done with them by then, so that’s perfectly safe.

Drawing

Finally, in draw_frame, we bind our buffers and swap vkCmdDraw for an indexed draw:

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

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

The parameters of vkCmdDrawIndexed are the index count, the instance count (1, since we just want one copy), then the first index, a value to add to each index and the first instance, all 0.

Let’s run it!

Anddd behold…

Behold, nothing
Behold, nothing

…nothing. No crash, but no triangle either.

And that makes sense, because we’ve created our buffers, but we never put anything in them! VERTICES and INDICES are still sitting in CPU memory. The contents of our buffers are undefined, so the GPU is reading whatever happens to be there. Here that gave us nothing at all (if it’s all zeroes, for example, every index points at the same vertex, and no triangle ever covers a pixel), but you can’t rely on that.

Filling the buffers

The copy flow

We asked VMA to put our vertex and index buffers in fast GPU memory, and that memory usually can’t be written to directly from the CPU. So we go through a middleman, which is what our third buffer is for:

CPU Memory -> Staging Buffer -> Vertex/Index Buffer
  1. The CPU writes our data into the staging buffer, which lives in memory the CPU can access
  2. The GPU copies it from there into the vertex/index buffer

For step 1, we have the function we skipped earlier:

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;
}

vmaCopyMemoryToAllocation does everything needed to write to the buffer’s memory from the CPU: it maps the memory to get a pointer to it, does the memcpy, flushes it (some memory types need this for the GPU to be able to see our writes) and unmaps it again.

Let’s use it, at the end of initialize:

  { // copy VERTICES to vertex buffer
    if(!m_staging_buffer->copy_from_cpu(VERTICES, sizeof(VERTICES))) {
      printf("Failed to copy VERTICES to staging buffer\n");
      return false;
    }

    // copy staging buffer to vertex buffer
  }

  { // copy INDICES to index buffer
    if(!m_staging_buffer->copy_from_cpu(INDICES, sizeof(INDICES))) {
      printf("Failed to copy INDICES to staging buffer\n");
      return false;
    }

    // copy staging buffer to index buffer
  }

A command pool for our copies

Step 2 is done by the GPU, so it’s a command like any other. It has to be recorded into a command buffer and submitted to a queue, which means we need a command pool. We could borrow the one we use for our frames, but those command buffers have their own job to do, so let’s give these one-off commands a pool of their own. We add a member to SampleVulkan:

  VkCommandPool m_single_shot_command_pool{};

And create it in initialize, right after create_frame_resources:

  {
    VkCommandPoolCreateInfo pool_create_info{
      .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
      .queueFamilyIndex = m_graphics_queue_family_index,
    };
    if (vkCreateCommandPool(m_device, &pool_create_info, nullptr, &m_single_shot_command_pool) != VK_SUCCESS) {
      printf("Failed to create the single shot command pool\n");
      return false;
    }
  }

We use the graphics queue family, as every queue family that supports graphics also supports transfer commands like copying. We destroy the pool at the start of the destructor, after vkDeviceWaitIdle:

    vkDestroyCommandPool(m_device, m_single_shot_command_pool, nullptr);

Copying the data

Here’s the most direct way to do the copy for our vertex buffer:

    VkCommandBuffer cmd;
    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,
    };
    vkAllocateCommandBuffers(m_device, &alloc_info, &cmd);

    VkCommandBufferBeginInfo begin_info{
      .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
    };
    vkBeginCommandBuffer(cmd, &begin_info);

    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);

    vkEndCommandBuffer(cmd);

    VkSubmitInfo submit_info{
      .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
      .commandBufferCount = 1,
      .pCommandBuffers = &cmd,
    };
    vkQueueSubmit(m_graphics_queue, 1, &submit_info, VK_NULL_HANDLE);

    vkDeviceWaitIdle(m_device);

    vkFreeCommandBuffers(m_device, m_single_shot_command_pool, 1, &cmd);

Most of this is what we already do every frame: allocate a command buffer, begin it, record into it, end it and submit it. The new parts are:

  • vkCmdCopyBuffer: Copies from the staging buffer to the vertex buffer. VkBufferCopy describes what to copy: from the start of the source, to the start of the destination, the whole vertex buffer’s worth of bytes.
  • vkDeviceWaitIdle: Waits for the GPU to finish, so that the copy is done by the time we move on. It also makes it safe to free the command buffer, and to reuse the staging buffer for our indices.

And then there’s that barrier. Why do we need one, if we’ve already waited for the GPU to finish?

Because finished and visible are two different things. The GPU has caches, and the copy’s writes may still be sitting in one, where the vertex input stage reading our buffer later on isn’t guaranteed to see them. Waiting on the GPU tells the CPU that the work is done, but it doesn’t make those writes available to later GPU commands. A barrier does:

  • srcAccessMask and the TRANSFER stage: The writes our copy command made…
  • dstAccessMask and the VERTEX_INPUT stage: …have to be visible to the vertex input stage when it reads vertex attributes.

The index buffer’s barrier is the same, except its dstAccessMask is VK_ACCESS_INDEX_READ_BIT, since indices are read in the same stage, just as a different kind of read. This is one of those things that can seem to work without the barrier, on your GPU, with the validation layers staying quiet (their default checks don’t cover this kind of hazard). It’s still a bug though, and one that could show up on some other GPU, as missing or corrupted vertices.

NOTE: Our image layout transitions use vkCmdPipelineBarrier2, and this one uses the older vkCmdPipelineBarrier. Both are core in Vulkan 1.3. A single global memory barrier like this one doesn’t need anything the newer one adds, and the older one is simpler to write.

Making it reusable

We need to do all of this again for the index buffer, and doing this over and over would get tedious. On top of that, two things in the above code aren’t ideal:

  1. We allocate and free a command buffer every time, when we could just keep one around and reuse it
  2. vkDeviceWaitIdle waits for everything the GPU is doing, when all we care about is this one submission. That’s what a fence is for

So let’s put it all into a reusable function. We add these to SampleVulkan, next to the command pool:

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

And update the creation code from before:

  {
    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) {
      printf("Failed to create the single shot command pool\n");
      return false;
    }

    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) {
      printf("Failed to create the single shot fence\n");
      return false;
    }

    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) {
      printf("Failed to allocate the single shot command buffer\n");
      return false;
    }
  }

Notice the new VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT on the pool, same as on our frame command pool. Without it, we wouldn’t be allowed to reset the command buffers from this pool one by one, which is exactly what we want to do to reuse ours. The fence, unlike the ones for our frames, starts off unsignaled, since we don’t wait on it until after we’ve submitted something.

The fence gets destroyed along with the pool, in the destructor. The command buffer doesn’t need any cleanup of its own, as it gets freed when its pool is destroyed:

    vkDestroyFence(m_device, m_single_shot_command_fence, nullptr);

    vkDestroyCommandPool(m_device, m_single_shot_command_pool, nullptr);

Now for the function itself, declared in sample.hpp as:

  bool execute_single_shot_commands(std::function<void(VkCommandBuffer)> commands);
bool SampleVulkan::execute_single_shot_commands(std::function<void(VkCommandBuffer)> commands)
{
  if (vkResetCommandBuffer(m_single_shot_command_buffer, 0) != VK_SUCCESS)
    return false;

  VkCommandBufferBeginInfo begin_info{
    .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
  };
  if (vkBeginCommandBuffer(m_single_shot_command_buffer, &begin_info) != VK_SUCCESS)
    return false;

  commands(m_single_shot_command_buffer);

  if (vkEndCommandBuffer(m_single_shot_command_buffer) != VK_SUCCESS)
    return false;

  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 false;

  if (vkWaitForFences(m_device, 1, &m_single_shot_command_fence, true, UINT64_MAX) != VK_SUCCESS)
    return false;

  if (vkResetFences(m_device, 1, &m_single_shot_command_fence) != VK_SUCCESS)
    return false;

  return true;
}

It resets and begins our command buffer, lets the caller record whatever it wants using the commands callback, ends the command buffer and submits it with our fence. Then it waits for the fence, and resets it so it’s ready for next time. Since the function doesn’t return until the GPU is done, it’s completely safe to overwrite the staging buffer as soon as it returns.

With that, our copy code becomes:

  { // copy VERTICES to vertex buffer
    if(!m_staging_buffer->copy_from_cpu(VERTICES, sizeof(VERTICES))) {
      printf("Failed to copy VERTICES to staging buffer\n");
      return false;
    }

    const auto success = execute_single_shot_commands([&](VkCommandBuffer cmd)
    {
      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);

    });
    if(!success) {
      printf("Failed to copy staging buffer to vertex buffer\n");
      return false;
    }
  }

  { // copy INDICES to index buffer
    if(!m_staging_buffer->copy_from_cpu(INDICES, sizeof(INDICES))) {
      printf("Failed to copy INDICES to staging buffer\n");
      return false;
    }

    const auto success = execute_single_shot_commands([&](VkCommandBuffer cmd)
    {
      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);
    });
    if (!success) {
      printf("Failed to copy staging buffer to index buffer\n");
      return false;
    }
  }

Each block now reads like what it does: write the data to the staging buffer, then have the GPU copy it over.

We could destroy the staging buffer at this point, as we’re done with it. It’s tiny though, so we’ll just keep it around until the end, which keeps our cleanup code all in one place.

Run it again, and…

Same Result
Same Result

We see the exact same triangle as before! BUT this time, it’s using vertex and index buffers, instead of having the vertices hardcoded into the shader. Which means we can now draw whatever we want, without ever touching the shader again.

From triangle to quad

So let’s do just that! All we have to do is add a vertex, and 3 more indices:

static const Vertex VERTICES[4] = {
  {glm::vec3(-0.5f, -0.5f, 0.0f), glm::vec3(1.0f, 0.0f, 0.0f)},
  {glm::vec3(0.5f, -0.5f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)},
  {glm::vec3(0.5f, 0.5f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f)},
  {glm::vec3(-0.5f, 0.5f, 0.0f),  glm::vec3(1.0f, 0.0f, 1.0f)},
};

static const uint32_t INDICES[6] = {
  0, 1, 2,
  2, 3, 0
};

Going clockwise from the top left, our 4 vertices are the corners of a rectangle: red, green, blue and magenta (remember, the Y axis points down in Vulkan). The first triangle is 0, 1, 2, and the second is 2, 3, 0. Both of them use vertices 0 and 2, which is the diagonal shared between the triangles. There’s our index buffer earning its keep!

No other code has to change: the buffer sizes come from sizeof, and so does the index count in our draw call.

End Result
End Result

Look closely, and you can see that diagonal in the gradient, running from the red corner to the blue one. Each triangle only blends the colours of its own 3 vertices, so the two halves blend a little differently.

Wrapping up

And that’s it! Build it, run it, and you should see the quad, with no validation errors.

Let’s recap what we did:

  1. Defined a Vertex type with GLM, along with VERTICES and INDICES arrays
  2. Wrote a Buffer class on top of VMA
  3. Added a CHECK_RESULT macro to keep our Result handling short
  4. Described our vertex layout to the pipeline using bindings and attributes, and read it in the vertex shader using layout(location = ...) in
  5. Uploaded our data through a staging buffer, with a barrier to make it visible to the vertex input stage
  6. Wrapped one-off GPU work in execute_single_shot_commands
  7. Drew it all with vkCmdDrawIndexed, and turned our triangle into a quad, just by changing the data

Go ahead and play around with it! Change the colours, move the corners around or add more vertices and indices to draw a different shape. It’s all just data now, so there’s no need to recompile the shaders anymore.

Next up: Textured Quad

Same quad, but with a texture on it! Instead of just blending colours between its corners, our quad will show an actual image. That means working with a new kind of GPU resource, a Vulkan image, getting our pixels into it with the same staging buffer trick from this post, and sampling it in our fragment shader.

References

  1. Vulkan Memory Allocator: Recommended usage patterns
  2. Vulkan Guide: Vertex input data processing
  3. Vulkan Guide: Synchronization examples
  4. GLM
  5. VkGuide
  6. The Vulkan specification (version 1.4.364 at the time of writing)

Full Source Code

The complete sample is now just under 1700 lines in total, spread over a few files (and a good chunk of that is still the embedded shader code!).

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
    vma.cpp
    main.cpp
    buffer.cpp
    sample.cpp
    pipeline.cpp
)

target_link_libraries(App PRIVATE 
    glfw
    vulkan
    glm::glm
    GPUOpen::VulkanMemoryAllocator
)
Show common.hpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#pragma once

#include <span>
#include <cstdio>
#include <memory>
#include <string>
#include <cstddef>
#include <variant>
#include <cassert>
#include <type_traits>

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

#include <vk_mem_alloc.h>

#include <glm/glm.hpp>

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>;
Show buffer.hpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#pragma once

#include "common.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();

    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{};
};
Show 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;
    
    case EUsage::STAGING:
      assert(false); // we shouldn't call bind on a staging buffer
    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 pipeline.hpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#pragma once

#include "common.hpp"

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

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

    void bind(VkCommandBuffer cmd);

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

private:
    VkDevice m_device{};

    VkPipeline m_handle{};
    VkPipelineLayout m_layout{};
};
Show 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,
        std::span<const VkVertexInputBindingDescription> input_bindings,
        std::span<const VkVertexInputAttributeDescription> input_attributes,
        std::span<const uint32_t> vertex_shader_source, std::span<const uint32_t> fragment_shader_source)
{
  Box<Pipeline> pipeline{new Pipeline(device)};

  VkPipelineLayoutCreateInfo layout_create_info{
    .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
    .setLayoutCount = 0,
    .pushConstantRangeCount = 0,
  };

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

  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 = VK_FORMAT_UNDEFINED,
    .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,
  };

  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,
    .pColorBlendState = &color_blend_state_create_info,
    .pDynamicState = &dynamic_state_create_info,

    .layout = pipeline->m_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);
  if (m_layout) vkDestroyPipelineLayout(m_device, m_layout, nullptr);
}
Show sample.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"
#include "pipeline.hpp"

#include <vector>
#include <string>
#include <cassert>
#include <stdint.h>
#include <functional>

class SampleVulkan
{
  static constexpr uint32_t NUM_CONCURRENT_FRAMES = 3;
  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";

  static constexpr uint32_t SHADER_SPV_VERT[] = {
  	0x07230203,0x00010000,0x000D000B,0x0000001F,0x00000000,0x00020011,0x00000001,0x0006000B,
    0x00000001,0x4C534C47,0x6474732E,0x3035342E,0x00000000,0x0003000E,0x00000000,0x00000001,
    0x0009000F,0x00000000,0x00000004,0x6E69616D,0x00000000,0x0000000D,0x00000012,0x0000001C,
    0x0000001D,0x00030003,0x00000002,0x000001C2,0x000A0004,0x475F4C47,0x4C474F4F,0x70635F45,
    0x74735F70,0x5F656C79,0x656E696C,0x7269645F,0x69746365,0x00006576,0x00080004,0x475F4C47,
    0x4C474F4F,0x6E695F45,0x64756C63,0x69645F65,0x74636572,0x00657669,0x00040005,0x00000004,
    0x6E69616D,0x00000000,0x00060005,0x0000000B,0x505F6C67,0x65567265,0x78657472,0x00000000,
    0x00060006,0x0000000B,0x00000000,0x505F6C67,0x7469736F,0x006E6F69,0x00070006,0x0000000B,
    0x00000001,0x505F6C67,0x746E696F,0x657A6953,0x00000000,0x00070006,0x0000000B,0x00000002,
    0x435F6C67,0x4470696C,0x61747369,0x0065636E,0x00070006,0x0000000B,0x00000003,0x435F6C67,
    0x446C6C75,0x61747369,0x0065636E,0x00030005,0x0000000D,0x00000000,0x00040005,0x00000012,
    0x705F6E69,0x0000736F,0x00050005,0x0000001C,0x5F74756F,0x6F6C6F63,0x00000072,0x00050005,
    0x0000001D,0x635F6E69,0x726F6C6F,0x00000000,0x00030047,0x0000000B,0x00000002,0x00050048,
    0x0000000B,0x00000000,0x0000000B,0x00000000,0x00050048,0x0000000B,0x00000001,0x0000000B,
    0x00000001,0x00050048,0x0000000B,0x00000002,0x0000000B,0x00000003,0x00050048,0x0000000B,
    0x00000003,0x0000000B,0x00000004,0x00040047,0x00000012,0x0000001E,0x00000000,0x00040047,
    0x0000001C,0x0000001E,0x00000000,0x00040047,0x0000001D,0x0000001E,0x00000001,0x00020013,
    0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,0x00040017,
    0x00000007,0x00000006,0x00000004,0x00040015,0x00000008,0x00000020,0x00000000,0x0004002B,
    0x00000008,0x00000009,0x00000001,0x0004001C,0x0000000A,0x00000006,0x00000009,0x0006001E,
    0x0000000B,0x00000007,0x00000006,0x0000000A,0x0000000A,0x00040020,0x0000000C,0x00000003,
    0x0000000B,0x0004003B,0x0000000C,0x0000000D,0x00000003,0x00040015,0x0000000E,0x00000020,
    0x00000001,0x0004002B,0x0000000E,0x0000000F,0x00000000,0x00040017,0x00000010,0x00000006,
    0x00000003,0x00040020,0x00000011,0x00000001,0x00000010,0x0004003B,0x00000011,0x00000012,
    0x00000001,0x0004002B,0x00000006,0x00000014,0x3F800000,0x00040020,0x00000019,0x00000003,
    0x00000007,0x00040020,0x0000001B,0x00000003,0x00000010,0x0004003B,0x0000001B,0x0000001C,
    0x00000003,0x0004003B,0x00000011,0x0000001D,0x00000001,0x00050036,0x00000002,0x00000004,
    0x00000000,0x00000003,0x000200F8,0x00000005,0x0004003D,0x00000010,0x00000013,0x00000012,
    0x00050051,0x00000006,0x00000015,0x00000013,0x00000000,0x00050051,0x00000006,0x00000016,
    0x00000013,0x00000001,0x00050051,0x00000006,0x00000017,0x00000013,0x00000002,0x00070050,
    0x00000007,0x00000018,0x00000015,0x00000016,0x00000017,0x00000014,0x00050041,0x00000019,
    0x0000001A,0x0000000D,0x0000000F,0x0003003E,0x0000001A,0x00000018,0x0004003D,0x00000010,
    0x0000001E,0x0000001D,0x0003003E,0x0000001C,0x0000001E,0x000100FD,0x00010038,
  };
  
  static constexpr uint32_t SHADER_SPV_FRAG[] = {
    0x07230203,0x00010000,0x000D000B,0x00000013,0x00000000,0x00020011,0x00000001,0x0006000B,
    0x00000001,0x4C534C47,0x6474732E,0x3035342E,0x00000000,0x0003000E,0x00000000,0x00000001,
    0x0007000F,0x00000004,0x00000004,0x6E69616D,0x00000000,0x00000009,0x0000000C,0x00030010,
    0x00000004,0x00000007,0x00030003,0x00000002,0x000001C2,0x000A0004,0x475F4C47,0x4C474F4F,
    0x70635F45,0x74735F70,0x5F656C79,0x656E696C,0x7269645F,0x69746365,0x00006576,0x00080004,
    0x475F4C47,0x4C474F4F,0x6E695F45,0x64756C63,0x69645F65,0x74636572,0x00657669,0x00040005,
    0x00000004,0x6E69616D,0x00000000,0x00050005,0x00000009,0x616E6966,0x6C6F436C,0x0000726F,
    0x00050005,0x0000000C,0x635F6E69,0x726F6C6F,0x00000000,0x00040047,0x00000009,0x0000001E,
    0x00000000,0x00040047,0x0000000C,0x0000001E,0x00000000,0x00020013,0x00000002,0x00030021,
    0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,0x00040017,0x00000007,0x00000006,
    0x00000004,0x00040020,0x00000008,0x00000003,0x00000007,0x0004003B,0x00000008,0x00000009,
    0x00000003,0x00040017,0x0000000A,0x00000006,0x00000003,0x00040020,0x0000000B,0x00000001,
    0x0000000A,0x0004003B,0x0000000B,0x0000000C,0x00000001,0x0004002B,0x00000006,0x0000000E,
    0x3F800000,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200F8,0x00000005,
    0x0004003D,0x0000000A,0x0000000D,0x0000000C,0x00050051,0x00000006,0x0000000F,0x0000000D,
    0x00000000,0x00050051,0x00000006,0x00000010,0x0000000D,0x00000001,0x00050051,0x00000006,
    0x00000011,0x0000000D,0x00000002,0x00070050,0x00000007,0x00000012,0x0000000F,0x00000010,
    0x00000011,0x0000000E,0x0003003E,0x00000009,0x00000012,0x000100FD,0x00010038,
  };

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

public:
  SampleVulkan() = default;
  SampleVulkan(const SampleVulkan &) = delete;
  SampleVulkan &operator=(const SampleVulkan &) = delete;

  ~SampleVulkan();

  bool initialize(std::function<bool(VkInstance, uint32_t &, uint32_t &, VkSurfaceKHR &)> surface_creation_callback);

  bool render();

  void resize(uint32_t fb_width, uint32_t fb_height);

private:
  bool create_instance();
  bool select_physical_device();
  bool create_device_and_swapchain();
  bool create_frame_resources();

  void draw_frame(VkCommandBuffer cmd, VkImageView color_attachment);

  bool execute_single_shot_commands(std::function<void(VkCommandBuffer)> commands);

  bool recreate_swapchain();

  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);

private:
  VkInstance m_instance{};
  VkDebugUtilsMessengerEXT m_debug_messenger{};

  VkSurfaceKHR m_surface{};
  std::string m_physical_device_name{};
  VkPhysicalDevice m_physical_device{};
  uint32_t m_graphics_queue_family_index{};
  uint32_t m_present_queue_family_index{};
  uint32_t m_swapchain_image_count{};
  std::vector<VkSemaphore> m_render_done_semaphores;
  VkSurfaceFormatKHR m_swapchain_format{};
  VkPresentModeKHR m_swapchain_present_mode{};
  VkExtent2D m_swapchain_extent{1, 1};
  VkExtent2D m_pending_swapchain_extent{1, 1};
  bool m_swapchain_is_out_of_date{};
  VkSurfaceTransformFlagBitsKHR m_swapchain_pre_transform{};

  VkDevice m_device{};
  VkQueue m_graphics_queue{};
  VkQueue m_present_queue{};
  VkSwapchainKHR m_swapchain{};
  std::vector<VkImage> m_swapchain_images{};
  std::vector<VkImageView> m_swapchain_image_views{};

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

  Box<Pipeline> m_graphics_pipeline{};

  VmaAllocator m_allocator{};

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

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

#include "sample.hpp"

#include <set>
#include <stdio.h>
#include <string.h>
#include <utility>
#include <algorithm>

#define CHECK_RESULT(_result, _var)             \
{                                               \
  auto result = _result;                        \
  if (result.is_error()) {                      \
    printf("%s\n", result.get_error().c_str()); \
    return false;                               \
  }                                             \
  _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 Vertex
{
  glm::vec3 pos;
  glm::vec3 colour;
};

static const Vertex VERTICES[4] = {
  {glm::vec3(-0.5f, -0.5f, 0.0f), glm::vec3(1.0f, 0.0f, 0.0f)},
  {glm::vec3(0.5f, -0.5f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)},
  {glm::vec3(0.5f, 0.5f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f)},
  {glm::vec3(-0.5f, 0.5f, 0.0f),  glm::vec3(1.0f, 0.0f, 1.0f)},
};

static const uint32_t INDICES[6] = {
  0, 1, 2,
  2, 3, 0
};

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

    vkDestroyFence(m_device, m_single_shot_command_fence, nullptr);

    vkDestroyCommandPool(m_device, m_single_shot_command_pool, nullptr);

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

    m_graphics_pipeline.reset();

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

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

    vkDestroyCommandPool(m_device, m_frame_resource_command_pool, nullptr);

    for (const auto &view : m_swapchain_image_views)
      vkDestroyImageView(m_device, view, nullptr);
    vkDestroySwapchainKHR(m_device, m_swapchain, 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);
  }
}

bool SampleVulkan::initialize(
    std::function<bool(VkInstance, uint32_t &, uint32_t &, VkSurfaceKHR &)> surface_creation_callback)
{
  if (!create_instance())
    return false;

  if (!surface_creation_callback(m_instance, m_pending_swapchain_extent.width, m_pending_swapchain_extent.height,
                                 m_surface))
  {
    printf("Failed to create Vulkan surface\n");
    return false;
  }

  if (!select_physical_device())
    return false;

  if (!create_device_and_swapchain())
    return false;

  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) {
    printf("Failed to create the VMA allocator\n");
    return false;
  }

  if (!create_frame_resources())
    return false;

  {
    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) {
      printf("Failed to create the single shot command pool\n");
      return false;
    }

    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) {
      printf("Failed to create the single shot fence\n");
      return false;
    }

    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) {
      printf("Failed to allocate the single shot command buffer\n");
      return false;
    }
  }

  CHECK_RESULT(
    Pipeline::create(
      m_device,
      m_swapchain_format.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)},
      },
      SHADER_SPV_VERT,
      SHADER_SPV_FRAG
    ),
    m_graphics_pipeline
  );

  CHECK_RESULT(
    Buffer::create(
      m_allocator,
      std::max(sizeof(VERTICES), sizeof(INDICES)), // maximum size we'll need for our staging operations 
      Buffer::EUsage::STAGING
    ),
    m_staging_buffer
  );

  CHECK_RESULT(
    Buffer::create(
      m_allocator,
      sizeof(VERTICES), 
      Buffer::EUsage::VERTEX
    ),
    m_vertex_buffer
  );

  CHECK_RESULT(
    Buffer::create(
      m_allocator,
      sizeof(INDICES), 
      Buffer::EUsage::INDEX
    ),
    m_index_buffer
  );

  { // copy VERTICES to vertex buffer
    if(!m_staging_buffer->copy_from_cpu(VERTICES, sizeof(VERTICES))) {
      printf("Failed to copy VERTICES to staging buffer\n");
      return false;
    }

    const auto success = execute_single_shot_commands([&](VkCommandBuffer cmd)
    {
      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);

    });
    if(!success) {
      printf("Failed to copy staging buffer to vertex buffer\n");
      return false;
    }
  }

  { // copy INDICES to index buffer
    if(!m_staging_buffer->copy_from_cpu(INDICES, sizeof(INDICES))) {
      printf("Failed to copy INDICES to staging buffer\n");
      return false;
    }

    const auto success = execute_single_shot_commands([&](VkCommandBuffer cmd)
    {
      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);
    });
    if (!success) {
      printf("Failed to copy staging buffer to index buffer\n");
      return false;
    }
  }

  return true;
}

bool SampleVulkan::render()
{
  const auto &current_frame = m_frames[m_current_frame_index];

  vkWaitForFences(m_device, 1, &current_frame.fen_in_flight, VK_TRUE, UINT64_MAX);

  uint32_t image_index{};
  switch (vkAcquireNextImageKHR(m_device, m_swapchain, UINT64_MAX, current_frame.sm_image_available, VK_NULL_HANDLE,
                                &image_index))
  {
  case VK_ERROR_OUT_OF_DATE_KHR:
    if (!recreate_swapchain())
      return false;
    return true;

  case VK_SUCCESS:
  case VK_SUBOPTIMAL_KHR:
    break;

  default:
    printf("Failed to acquire swapchain image\n");
    return false;
  }

  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)
  {
    printf("Failed to start recording command buffer\n");
    return false;
  }

  if (!transition_image_layout(current_frame.cmd_buffer, m_swapchain_images[image_index], VK_IMAGE_LAYOUT_UNDEFINED,
                               VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL))
  {
    printf("Failed to transition swapchain image\n");
    return false;
  }

  draw_frame(current_frame.cmd_buffer, m_swapchain_image_views[image_index]);

  if (!transition_image_layout(current_frame.cmd_buffer, m_swapchain_images[image_index],
                               VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR))
  {
    printf("Failed to transition swapchain image\n");
    return false;
  }

  if (vkEndCommandBuffer(current_frame.cmd_buffer) != VK_SUCCESS)
  {
    printf("Failed to finish recording command buffer\n");
    return false;
  }

  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[image_index],
  };

  vkResetFences(m_device, 1, &current_frame.fen_in_flight);
  if (vkQueueSubmit(m_graphics_queue, 1, &submit_info, current_frame.fen_in_flight) != VK_SUCCESS)
  {
    printf("Failed to submit frame command buffer\n");
    return false;
  }

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

  switch (vkQueuePresentKHR(m_present_queue, &present_info))
  {
  case VK_ERROR_OUT_OF_DATE_KHR:
  case VK_SUBOPTIMAL_KHR:
    if (!recreate_swapchain())
      return false;
    break;

  case VK_SUCCESS:
    break;

  default:
    printf("Failed to present swapchain\n");
    return false;
  }

  if (m_swapchain_is_out_of_date && !recreate_swapchain())
    return false;

  m_current_frame_index = (m_current_frame_index + 1) % NUM_CONCURRENT_FRAMES;

  return true;
}

void SampleVulkan::draw_frame(VkCommandBuffer cmd, VkImageView color_attachment)
{
  VkRenderingAttachmentInfo color_attachment_info{
      .sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO,
      .imageView = 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,
                  },
          },
  };

  VkRenderingInfo rendering_info{
      .sType = VK_STRUCTURE_TYPE_RENDERING_INFO,
      .renderArea =
          {
              {},
              m_swapchain_extent,
          },
      .layerCount = 1,
      .viewMask = 0,
      .colorAttachmentCount = 1,
      .pColorAttachments = &color_attachment_info,
  };

  vkCmdBeginRendering(cmd, &rendering_info);

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

  VkRect2D scissor{
    .extent = m_swapchain_extent,
  };
  vkCmdSetScissor(cmd, 0, 1, &scissor);

  m_graphics_pipeline->bind(cmd);

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

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

  vkCmdEndRendering(cmd);
}

bool SampleVulkan::execute_single_shot_commands(std::function<void(VkCommandBuffer)> commands)
{
  if (vkResetCommandBuffer(m_single_shot_command_buffer, 0) != VK_SUCCESS)
    return false;

  VkCommandBufferBeginInfo begin_info{
    .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
  };
  if (vkBeginCommandBuffer(m_single_shot_command_buffer, &begin_info) != VK_SUCCESS)
    return false;

  commands(m_single_shot_command_buffer);

  if (vkEndCommandBuffer(m_single_shot_command_buffer) != VK_SUCCESS)
    return false;

  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 false;

  if (vkWaitForFences(m_device, 1, &m_single_shot_command_fence, true, UINT64_MAX) != VK_SUCCESS)
    return false;

  if (vkResetFences(m_device, 1, &m_single_shot_command_fence) != VK_SUCCESS)
    return false;

  return true;
}

bool SampleVulkan::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))
  {
    // Wait for any depth writes from a previous use of this image (e.g. the previous frame)
    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
  {
    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 SampleVulkan::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)
  {
    printf("Failed to create Vulkan instance\n");
    return false;
  }

  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)
    {
      printf("Failed to create Vulkan debug messenger\n");
      return false;
    }
  }

  return true;
}

bool SampleVulkan::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)
  {
    printf("Failed to find a good physical device\n");
    return false;
  }

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

  return true;
}

void SampleVulkan::resize(uint32_t fb_width, uint32_t fb_height)
{
  m_pending_swapchain_extent = {fb_width, fb_height};
  m_swapchain_is_out_of_date = true;
}

bool SampleVulkan::create_device_and_swapchain()
{
  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)
  {
    printf("Failed to create Vulkan device\n");
    return false;
  }

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

  const auto surface_formats =
      vkEnumCall<VkSurfaceFormatKHR>(vkGetPhysicalDeviceSurfaceFormatsKHR, m_physical_device, m_surface);
  const auto surface_present_modes =
      vkEnumCall<VkPresentModeKHR>(vkGetPhysicalDeviceSurfacePresentModesKHR, m_physical_device, m_surface);
  assert(surface_formats.size());
  assert(surface_present_modes.size());
  m_swapchain_format = surface_formats[0];
  m_swapchain_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;

  return recreate_swapchain();
}

bool SampleVulkan::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_graphics_queue_family_index,
  };
  if (vkCreateCommandPool(m_device, &commmand_pool_create_info, nullptr, &m_frame_resource_command_pool) != VK_SUCCESS)
  {
    printf("Failed to create command pool\n");
    return false;
  }

  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_device, &command_buffer_alloc_info, &m_frames[i].cmd_buffer) != VK_SUCCESS)
    {
      printf("Failed to allocate frame command buffer\n");
      return false;
    }

    VkSemaphoreCreateInfo semaphore_create_info{
        .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
    };
    if (vkCreateSemaphore(m_device, &semaphore_create_info, nullptr, &m_frames[i].sm_image_available) != VK_SUCCESS)
    {
      printf("Failed to create a semaphore\n");
      return false;
    }

    VkFenceCreateInfo fence_create_info{
        .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
        .flags = VK_FENCE_CREATE_SIGNALED_BIT,
    };
    if (vkCreateFence(m_device, &fence_create_info, nullptr, &m_frames[i].fen_in_flight) != VK_SUCCESS)
    {
      printf("Failed to create a fence\n");
      return false;
    }
  }

  return true;
}

bool SampleVulkan::recreate_swapchain()
{
  vkDeviceWaitIdle(m_device);

  VkSurfaceCapabilitiesKHR surface_caps{};
  if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR(m_physical_device, m_surface, &surface_caps) != VK_SUCCESS)
  {
    printf("Failed to query physical device surface caps\n");
    return false;
  }

  // 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_swapchain_is_out_of_date = true;
    return true;
  }

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

  m_swapchain_pre_transform = surface_caps.currentTransform;

  m_pending_swapchain_extent.width = std::clamp(m_pending_swapchain_extent.width, surface_caps.minImageExtent.width,
                                                surface_caps.maxImageExtent.width);
  m_pending_swapchain_extent.height = std::clamp(m_pending_swapchain_extent.height, surface_caps.minImageExtent.height,
                                                 surface_caps.maxImageExtent.height);
  m_swapchain_extent = m_pending_swapchain_extent;

  for (const auto &view : m_swapchain_image_views)
    vkDestroyImageView(m_device, view, nullptr);
  if (m_swapchain)
    vkDestroySwapchainKHR(m_device, m_swapchain, nullptr);
  m_swapchain_image_views.clear();
  m_swapchain = VK_NULL_HANDLE;

  VkSwapchainCreateInfoKHR swapchain_create_info{
      .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
      .surface = m_surface,
      .minImageCount = m_swapchain_image_count,
      .imageFormat = m_swapchain_format.format,
      .imageColorSpace = m_swapchain_format.colorSpace,
      .imageExtent = m_swapchain_extent,
      .imageArrayLayers = 1,
      .imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
      .imageSharingMode = VK_SHARING_MODE_EXCLUSIVE,
      .preTransform = m_swapchain_pre_transform,
      .compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
      .presentMode = m_swapchain_present_mode,
      .clipped = VK_TRUE,
  };

  uint32_t queue_family_indices[] = {m_graphics_queue_family_index, m_present_queue_family_index};
  if (m_graphics_queue_family_index != m_present_queue_family_index)
  {
    swapchain_create_info.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
    swapchain_create_info.queueFamilyIndexCount = 2;
    swapchain_create_info.pQueueFamilyIndices = queue_family_indices;
  }

  if (vkCreateSwapchainKHR(m_device, &swapchain_create_info, nullptr, &m_swapchain) != VK_SUCCESS)
  {
    printf("Failed to create swapchain\n");
    return false;
  }

  m_swapchain_images = vkEnumCall<VkImage>(vkGetSwapchainImagesKHR, m_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_device, semaphore, nullptr);
  m_render_done_semaphores.assign(m_swapchain_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_device, &semaphore_create_info, nullptr, &semaphore) != VK_SUCCESS)
    {
      printf("Failed to create a semaphore\n");
      return false;
    }
  }

  m_swapchain_image_views.reserve(m_swapchain_images.size());
  for (const auto &image : m_swapchain_images)
  {
    VkImageViewCreateInfo create_info{
        .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
        .image = image,
        .viewType = VK_IMAGE_VIEW_TYPE_2D,
        .format = m_swapchain_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_device, &create_info, nullptr, &view) != VK_SUCCESS)
    {
      printf("Failed to create a swapchain image view\n");
      return false;
    }

    m_swapchain_image_views.push_back(view);
  }

  m_swapchain_is_out_of_date = false;

  return true;
}
Show main.cpp
// Released into the public domain.
// Written by I-A-S for use in i-a-s.me vulkan series.

#include "sample.hpp"

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

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

  ~SampleApp();

  private:
  GLFWwindow *m_window{};
  Box<SampleVulkan> m_vulkan{};
};

int main(int argc, char *argv[])
{
  SampleApp app;
  return app.launch(argc, argv);
}

int SampleApp::launch(int argc, char *argv[])
{
  if (!glfwInit())
  {
    printf("Failed to initialize GLFW\n");
    return -1;
  }

  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)
  {
    printf("Failed to create GLFW window\n");
    return -1;
  }

  m_vulkan = Box<SampleVulkan>(new SampleVulkan());
  if (!m_vulkan->initialize([window = m_window](VkInstance instance, uint32_t &out_width, uint32_t &out_height,
                                                VkSurfaceKHR &out_surface) -> bool {
        if (glfwCreateWindowSurface(instance, window, nullptr, &out_surface) != VK_SUCCESS)
        {
          printf("Failed to create Vulkan surface\n");
          return false;
        }

        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 true;
      }))
  {
    printf("Failed to initialize Vulkan\n");
    return -1;
  }

  glfwSetWindowUserPointer(m_window, m_vulkan.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<SampleVulkan *>(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;
    }

    if (!m_vulkan->render())
      break;
  }

  return 0;
}

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

  if (m_window)
    glfwDestroyWindow(m_window);

  glfwTerminate();
}
Show 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 = 0) out vec3 out_color;

void main() {
    gl_Position = vec4(in_pos, 1.0);
    out_color = in_color;
}
Show shaders/default.frag
#version 450

layout(location = 0) in vec3 in_color;

layout(location = 0) out vec4 finalColor;

void main() {
    finalColor = vec4(in_color, 1.0);
}