|
| 1 | +# Vulkan Memory Allocator |
| 2 | + |
| 3 | +VMA has full CMake support, but it is also a single-header library that requires users to "instantiate" it in a single translation unit. Isolating that into a wrapper library to minimize warning pollution etc, we create our own `vma::vma` target that compiles this source file: |
| 4 | + |
| 5 | +```cpp |
| 6 | +// vk_mem_alloc.cpp |
| 7 | +#define VMA_IMPLEMENTATION |
| 8 | + |
| 9 | +#include <vk_mem_alloc.h> |
| 10 | +``` |
| 11 | + |
| 12 | +Unlike VulkanHPP, VMA's interface is C only, thus we shall use our `Scoped` class template to wrap objects in RAII types. The first thing we need is a `VmaAllocator`, which is similar to a `vk::Device` or `GLFWwindow*`: |
| 13 | + |
| 14 | +```cpp |
| 15 | +// vma.hpp |
| 16 | +namespace lvk::vma { |
| 17 | +struct Deleter { |
| 18 | + void operator()(VmaAllocator allocator) const noexcept; |
| 19 | +}; |
| 20 | + |
| 21 | +using Allocator = Scoped<VmaAllocator, Deleter>; |
| 22 | + |
| 23 | +[[nodiscard]] auto create_allocator(vk::Instance instance, |
| 24 | + vk::PhysicalDevice physical_device, |
| 25 | + vk::Device device) -> Allocator; |
| 26 | +} // namespace lvk::vma |
| 27 | + |
| 28 | +// vma.cpp |
| 29 | +void vma::Deleter::operator()(VmaAllocator allocator) const noexcept { |
| 30 | + vmaDestroyAllocator(allocator); |
| 31 | +} |
| 32 | + |
| 33 | +auto vma::create_allocator(vk::Instance const instance, |
| 34 | + vk::PhysicalDevice const physical_device, |
| 35 | + vk::Device const device) -> Allocator { |
| 36 | + auto const& dispatcher = VULKAN_HPP_DEFAULT_DISPATCHER; |
| 37 | + // need to zero initialize C structs, unlike VulkanHPP. |
| 38 | + auto vma_vk_funcs = VmaVulkanFunctions{}; |
| 39 | + vma_vk_funcs.vkGetInstanceProcAddr = dispatcher.vkGetInstanceProcAddr; |
| 40 | + vma_vk_funcs.vkGetDeviceProcAddr = dispatcher.vkGetDeviceProcAddr; |
| 41 | + |
| 42 | + auto allocator_ci = VmaAllocatorCreateInfo{}; |
| 43 | + allocator_ci.physicalDevice = physical_device; |
| 44 | + allocator_ci.device = device; |
| 45 | + allocator_ci.pVulkanFunctions = &vma_vk_funcs; |
| 46 | + allocator_ci.instance = instance; |
| 47 | + VmaAllocator ret{}; |
| 48 | + auto const result = vmaCreateAllocator(&allocator_ci, &ret); |
| 49 | + if (result == VK_SUCCESS) { return ret; } |
| 50 | + |
| 51 | + throw std::runtime_error{"Failed to create Vulkan Memory Allocator"}; |
| 52 | +} |
| 53 | +``` |
| 54 | +
|
| 55 | +`App` stores and creates a `vma::Allocator` object: |
| 56 | +
|
| 57 | +```cpp |
| 58 | +// ... |
| 59 | +vma::Allocator m_allocator{}; // anywhere between m_device and m_shader. |
| 60 | +
|
| 61 | +// ... |
| 62 | +void App::create_allocator() { |
| 63 | + m_allocator = vma::create_allocator(*m_instance, m_gpu.device, *m_device); |
| 64 | +} |
| 65 | +``` |
0 commit comments