### VulkanMemoryAllocator Installation with vcpkg Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/README.md Instructions to clone vcpkg, integrate it, and install the VulkanMemoryAllocator package. This method simplifies dependency management. ```sh git clone https://github.com/Microsoft/vcpkg.git cd vcpkg ./bootstrap-vcpkg.sh ./vcpkg integrate install ./vcpkg install vulkan-memory-allocator ``` -------------------------------- ### VMA Initialization and Setup Source: https://context7.com/gpuopen-librariesandsdks/vulkanmemoryallocator/llms.txt Demonstrates how to include the VMA library, define the implementation, and initialize a VmaAllocator object per VkDevice. It also shows the necessary cleanup. ```APIDOC ## VMA Initialization and Setup ### Description Include `vk_mem_alloc.h` and define `VMA_IMPLEMENTATION` in one translation unit to compile the library. Initialize a `VmaAllocator` object for each `VkDevice` and destroy it before the device is destroyed. ### Code Example ```cpp // VmaUsage.cpp — exactly ONE translation unit #define VMA_STATIC_VULKAN_FUNCTIONS 0 #define VMA_DYNAMIC_VULKAN_FUNCTIONS 1 #define VMA_IMPLEMENTATION #include "vk_mem_alloc.h" // --- initialization --- VmaVulkanFunctions vulkanFunctions = {}; vulkanFunctions.vkGetInstanceProcAddr = &vkGetInstanceProcAddr; vulkanFunctions.vkGetDeviceProcAddr = &vkGetDeviceProcAddr; VmaAllocatorCreateInfo allocatorCreateInfo = {}; allocatorCreateInfo.flags = VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT; allocatorCreateInfo.vulkanApiVersion = VK_API_VERSION_1_3; allocatorCreateInfo.physicalDevice = physicalDevice; allocatorCreateInfo.device = device; allocatorCreateInfo.instance = instance; allocatorCreateInfo.pVulkanFunctions = &vulkanFunctions; VmaAllocator allocator; VkResult res = vmaCreateAllocator(&allocatorCreateInfo, &allocator); assert(res == VK_SUCCESS); // --- cleanup --- vmaDestroyAllocator(allocator); ``` ``` -------------------------------- ### VMA Defragmentation Process Example Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/defragmentation.html Demonstrates the complete process of defragmentation using VMA. This includes initializing defragmentation, iterating through passes to move allocations, and finalizing the process. It highlights the need to manually recreate resources, copy data, and update references. ```c++ VmaDefragmentationInfo defragInfo = {}; defragInfo.pool = myPool; defragInfo.flags = VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FAST_BIT; VmaDefragmentationContext defragCtx; VkResult res = vmaBeginDefragmentation(allocator, &defragInfo, &defragCtx); // Check res... for(;;) { VmaDefragmentationPassMoveInfo pass; res = vmaBeginDefragmentationPass(allocator, defragCtx, &pass); if(res == VK_SUCCESS) break; else if(res != VK_INCOMPLETE) // Handle error... for(uint32_t i = 0; i < pass.moveCount; ++i) { // Inspect pass.pMoves[i].srcAllocation, identify what buffer/image it represents. VmaAllocationInfo allocInfo; vmaGetAllocationInfo(allocator, pass.pMoves[i].srcAllocation, &allocInfo); MyEngineResourceData* resData = (MyEngineResourceData*)allocInfo.pUserData; // Recreate and bind this buffer/image at: pass.pMoves[i].dstMemory, pass.pMoves[i].dstOffset. VkImageCreateInfo imgCreateInfo = ... VkImage newImg; res = vkCreateImage(device, &imgCreateInfo, nullptr, &newImg); // Check res... res = vmaBindImageMemory(allocator, pass.pMoves[i].dstTmpAllocation, newImg); // Check res... // Issue a vkCmdCopyBuffer/vkCmdCopyImage to copy its content to the new place. vkCmdCopyImage(cmdBuf, resData->img, ..., newImg, ...); } // Make sure the copy commands finished executing. vkWaitForFences(...); // Destroy old buffers/images bound with pass.pMoves[i].srcAllocation. for(uint32_t i = 0; i < pass.moveCount; ++i) { // ... vkDestroyImage(device, resData->img, nullptr); } // Update appropriate descriptors to point to the new places... res = vmaEndDefragmentationPass(allocator, defragCtx, &pass); if(res == VK_SUCCESS) break; else if(res != VK_INCOMPLETE) // Handle error... } vmaEndDefragmentation(allocator, defragCtx, nullptr); ``` -------------------------------- ### Example Image Creation with High Priority Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/vk_ext_memory_priority.html Demonstrates creating a VkImageCreateInfo structure for a high-resolution color attachment image, intended for use with VMA and the memory priority extension. ```c VkImageCreateInfo imgCreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO }; imgCreateInfo.imageType = VK_IMAGE_TYPE_2D; imgCreateInfo.extent.width = 3840; imgCreateInfo.extent.height = 2160; imgCreateInfo.extent.depth = 1; imgCreateInfo.mipLevels = 1; imgCreateInfo.arrayLayers = 1; imgCreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM; imgCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL; imgCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; imgCreateInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; imgCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT; ``` -------------------------------- ### Configure VMA Allocator with Extension Flags Source: https://context7.com/gpuopen-librariesandsdks/vulkanmemoryallocator/llms.txt This example demonstrates how to configure the VMA allocator by setting various extension flags in `VmaAllocatorCreateInfo::flags`. These flags inform VMA about enabled Vulkan extensions, allowing it to apply extension-specific optimizations. Ensure that a flag is only set if the corresponding Vulkan extension is actually enabled on the `VkDevice`. ```cpp VmaAllocatorCreateInfo allocatorInfo = {}; allocatorInfo.flags = VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT | // VK_KHR_dedicated_allocation VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT | // VK_KHR_bind_memory2 VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT | // VK_EXT_memory_budget VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT | // VK_KHR_buffer_device_address VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT | // VK_EXT_memory_priority VMA_ALLOCATOR_CREATE_KHR_MAINTENANCE4_BIT | // VK_KHR_maintenance4 VMA_ALLOCATOR_CREATE_KHR_MAINTENANCE5_BIT | // VK_KHR_maintenance5 VMA_ALLOCATOR_CREATE_KHR_EXTERNAL_MEMORY_WIN32_BIT; // VK_KHR_external_memory_win32 (Windows) allocatorInfo.vulkanApiVersion = VK_API_VERSION_1_3; allocatorInfo.physicalDevice = physicalDevice; allocatorInfo.device = device; allocatorInfo.instance = instance; VmaAllocator allocator; vmaCreateAllocator(&allocatorInfo, &allocator); ``` -------------------------------- ### Create Buffer with External Memory Info Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/other_api_interop.html Example of creating a VkBuffer with VkExternalMemoryBufferCreateInfoKHR in its pNext chain, intended for use with custom memory pools. ```c++ VkExternalMemoryBufferCreateInfoKHR externalMemBufCreateInfo = { VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO_KHR, nullptr, handleType }; VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; bufCreateInfo.size = // Your desired buffer size. bufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; bufCreateInfo.pNext = &externalMemBufCreateInfo; VmaAllocationCreateInfo allocCreateInfo = {}; allocCreateInfo.pool = pool; // It is enough to set this one member. VkBuffer buf; VmaAllocation alloc; res = vmaCreateBuffer(g_Allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, nullptr); // Check res... // YOUR OTHER CODE COMES HERE.... // At the end, don't forget to destroy it! vmaDestroyBuffer(g_Allocator, buf, alloc); ``` -------------------------------- ### Create and Use Custom Memory Pools Source: https://context7.com/gpuopen-librariesandsdks/vulkanmemoryallocator/llms.txt Use custom pools to group allocations of the same memory type into blocks with fixed sizes or limits. This example shows creating a pool with specific block size and count, allocating from it, and then destroying the pool. It also demonstrates creating a pool using the linear algorithm. ```cpp // Find suitable memory type index for uniform buffers VkBufferCreateInfo sampleBufInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; sampleBufInfo.size = 0x10000; sampleBufInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; VmaAllocationCreateInfo sampleAllocInfo = {}; sampleAllocInfo.usage = VMA_MEMORY_USAGE_AUTO; uint32_t memTypeIndex; vmaFindMemoryTypeIndexForBufferInfo(allocator, &sampleBufInfo, &sampleAllocInfo, &memTypeIndex); // Create pool: max 2 blocks of 128 MiB each VmaPoolCreateInfo poolCreateInfo = {}; poolCreateInfo.memoryTypeIndex = memTypeIndex; poolCreateInfo.blockSize = 128ULL * 1024 * 1024; poolCreateInfo.maxBlockCount = 2; VmaPool pool; vmaCreatePool(allocator, &poolCreateInfo, &pool); // Allocate from the pool VkBufferCreateInfo bufInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; bufInfo.size = 1024; bufInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; VmaAllocationCreateInfo allocInfo = {}; allocInfo.pool = pool; // assign to custom pool VkBuffer buf; VmaAllocation alloc; vmaCreateBuffer(allocator, &bufInfo, &allocInfo, &buf, &alloc, nullptr); // Cleanup — must free all allocations before destroying pool vmaDestroyBuffer(allocator, buf, alloc); vmaDestroyPool(allocator, pool); // Linear algorithm pool (free-at-once, stack, ring-buffer behavior) VmaPoolCreateInfo linearPoolInfo = {}; linearPoolInfo.memoryTypeIndex = memTypeIndex; linearPoolInfo.flags = VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT; linearPoolInfo.blockSize = 64ULL * 1024 * 1024; linearPoolInfo.maxBlockCount = 1; // required for ring-buffer/double-stack VmaPool linearPool; vmaCreatePool(allocator, &linearPoolInfo, &linearPool); ``` -------------------------------- ### Create and Alias Two Images in Shared Memory Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/resource_aliasing.html This example shows how to create two VkImage objects with different properties, calculate the combined memory requirements for aliasing, allocate a single VMA memory block, and bind both images to that memory. Note that these images cannot be used simultaneously. ```cpp VkImageCreateInfo img1CreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO }; img1CreateInfo.imageType = VK_IMAGE_TYPE_2D; img1CreateInfo.extent.width = 512; img1CreateInfo.extent.height = 512; img1CreateInfo.extent.depth = 1; img1CreateInfo.mipLevels = 10; img1CreateInfo.arrayLayers = 1; img1CreateInfo.format = VK_FORMAT_R8G8B8A8_SRGB; img1CreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL; img1CreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; img1CreateInfo.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; img1CreateInfo.samples = VK_SAMPLE_COUNT_1_BIT; // A full screen texture to be used as color attachment. VkImageCreateInfo img2CreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO }; img2CreateInfo.imageType = VK_IMAGE_TYPE_2D; img2CreateInfo.extent.width = 1920; img2CreateInfo.extent.height = 1080; img2CreateInfo.extent.depth = 1; img2CreateInfo.mipLevels = 1; img2CreateInfo.arrayLayers = 1; img2CreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM; img2CreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL; img2CreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; img2CreateInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; img2CreateInfo.samples = VK_SAMPLE_COUNT_1_BIT; VkImage img1; res = vkCreateImage(device, &img1CreateInfo, nullptr, &img1); VkImage img2; res = vkCreateImage(device, &img2CreateInfo, nullptr, &img2); VkMemoryRequirements img1MemReq; vkGetImageMemoryRequirements(device, img1, &img1MemReq); VkMemoryRequirements img2MemReq; vkGetImageMemoryRequirements(device, img2, &img2MemReq); VkMemoryRequirements finalMemReq = {}; finalMemReq.size = std::max(img1MemReq.size, img2MemReq.size); finalMemReq.alignment = std::max(img1MemReq.alignment, img2MemReq.alignment); finalMemReq.memoryTypeBits = img1MemReq.memoryTypeBits & img2MemReq.memoryTypeBits; // Validate if(finalMemReq.memoryTypeBits != 0) [VmaAllocationCreateInfo](struct_vma_allocation_create_info.html) allocCreateInfo = {}; allocCreateInfo.[preferredFlags](struct_vma_allocation_create_info.html#a7fe8d81a1ad10b2a2faacacee5b15d6d) = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; [VmaAllocation](struct_vma_allocation.html) alloc; res = [vmaAllocateMemory](group__group__alloc.html#gabf28077dbf82d0908b8acbe8ee8dd9b8)(allocator, &finalMemReq, &allocCreateInfo, &alloc, nullptr); res = [vmaBindImageMemory](group__group__alloc.html#ga3d3ca45799923aa5d138e9e5f9eb2da5)(allocator, alloc, img1); res = [vmaBindImageMemory](group__group__alloc.html#ga3d3ca45799923aa5d138e9e5f9eb2da5)(allocator, alloc, img2); // You can use img1, img2 here, but not at the same time! [vmaFreeMemory](group__group__alloc.html#ga11f0fbc034fa81a4efedd73d61ce7568)(allocator, alloc); vkDestroyImage(allocator, img2, nullptr); vkDestroyImage(allocator, img1, nullptr); ``` -------------------------------- ### Buffer Creation with Transfer Destination Flag Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/usage_patterns.html Example of creating a VkBufferCreateInfo with a size, usage flags including TRANSFER_DST_BIT, and initializing VmaAllocationCreateInfo for automatic memory usage. ```c++ VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; bufCreateInfo.size = 65536; bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; VmaAllocationCreateInfo allocCreateInfo = {}; allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; ``` -------------------------------- ### Get Heap Budgets with vmaGetHeapBudgets Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/statistics.html Retrieve current memory usage and budget information for all Vulkan memory heaps. Useful for monitoring and staying within memory limits. ```c uint32_t heapIndex = ... VmaBudget budgets[VK_MAX_MEMORY_HEAPS]; vmaGetHeapBudgets(allocator, budgets); printf("My heap currently has %u allocations taking %llu B,\n", budgets[heapIndex].statistics.allocationCount, budgets[heapIndex].statistics.allocationBytes); printf("allocated out of %u Vulkan device memory blocks taking %llu B,\n", budgets[heapIndex].statistics.blockCount, budgets[heapIndex].statistics.blockBytes); printf("Vulkan reports total usage %llu B with budget %llu B.\n", budgets[heapIndex].usage, budgets[heapIndex].budget); ``` -------------------------------- ### Define External Memory Buffer Create Info Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/other_api_interop.html When using the VK_KHR_external_memory_win32 extension, buffers must be created with VkExternalMemoryBufferCreateInfoKHR in their pNext chain. This example shows how to define the structure and specify the handle type. ```c++ constexpr VkExternalMemoryHandleTypeFlagsKHR handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR; // Define an example buffer and allocation parameters. VkExternalMemoryBufferCreateInfoKHR externalMemBufCreateInfo = { VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO_KHR, nullptr, handleType }; VkBufferCreateInfo exampleBufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; exampleBufCreateInfo.size = 0x10000; // Doesn't matter here. exampleBufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; exampleBufCreateInfo.pNext = &externalMemBufCreateInfo; ``` -------------------------------- ### Specify Required and Preferred Memory Flags Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/choosing_memory_type.html Use requiredFlags to enforce essential memory properties and preferredFlags to guide the allocator towards optimal choices. This example ensures the memory is host-visible and preferably host-coherent and cached for persistent mapping. ```cpp VmaAllocationCreateInfo allocInfo = {}; allocInfo.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; allocInfo.preferredFlags = VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT; allocInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT; VkBuffer buffer; VmaAllocation allocation; vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr); ``` -------------------------------- ### vkGetMemoryWin32HandleKHR Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/struct_vma_vulkan_functions.html Pointer to vkGetMemoryWin32HandleKHR function. Used to get a Windows handle for memory. ```APIDOC ## vkGetMemoryWin32HandleKHR ### Description Pointer to the Vulkan function `vkGetMemoryWin32HandleKHR`. This function retrieves a handle to the memory object that can be shared with other processes on Windows. This is typically used with the VK_KHR_external_memory_win32 extension. ### Method Function Pointer ### Endpoint N/A (Function Pointer) ### Parameters N/A (Function Pointer) ### Request Example N/A ### Response N/A ``` -------------------------------- ### Initialize VMA Allocator Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/group__group__init.html This snippet demonstrates the complete process of initializing the VMA allocator, including setting up the create info structure, importing Vulkan functions, and creating the allocator. Ensure Vulkan functions are imported correctly before proceeding. ```c [VmaAllocatorCreateInfo](struct_vma_allocator_create_info.html) allocatorCreateInfo = {}; allocatorCreateInfo.[physicalDevice](struct_vma_allocator_create_info.html#a08230f04ae6ccf8a78150a9e829a7156) = myPhysicalDevice; allocatorCreateInfo.[device](struct_vma_allocator_create_info.html#ad924ddd77b04039c88d0c09b0ffcd500) = myDevice; allocatorCreateInfo.[instance](struct_vma_allocator_create_info.html#a70dd42e29b1df1d1b9b61532ae0b370b) = myInstance; allocatorCreateInfo.[vulkanApiVersion](struct_vma_allocator_create_info.html#ae0ffc55139b54520a6bb704b29ffc285) = VK_API_VERSION_1_3; allocatorCreateInfo.[flags](struct_vma_allocator_create_info.html#a392ea2ecbaff93f91a7c49f735ad4346) = [VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT](#gga4f87c9100d154a65a4ad495f7763cf7ca4d4687863f7bd4b418c6006dc04400b0) | [VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT](#gga4f87c9100d154a65a4ad495f7763cf7caffdd7a5169be3dbd7cbf6b3619e4f78a) | [VMA_ALLOCATOR_CREATE_KHR_EXTERNAL_MEMORY_WIN32_BIT](#gga4f87c9100d154a65a4ad495f7763cf7ca4897d1181a186e327f4dadd680ad00ac); [VmaVulkanFunctions](struct_vma_vulkan_functions.html) vulkanFunctions; VkResult res = [vmaImportVulkanFunctionsFromVolk](#gaf8d9ee01910a7af7f552145ef0065b9c)(&allocatorCreateInfo, &vulkanFunctions); // Check res... allocatorCreateInfo.[pVulkanFunctions](struct_vma_allocator_create_info.html#a3dc197be3227da7338b1643f70db36bd) = &vulkanFunctions; [VmaAllocator](struct_vma_allocator.html) allocator; res = [vmaCreateAllocator](#ga200692051ddb34240248234f5f4c17bb)(&allocatorCreateInfo, &allocator); // Check res... ``` -------------------------------- ### vkGetInstanceProcAddr Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/struct_vma_vulkan_functions.html Pointer to vkGetInstanceProcAddr function. Used to get the address of a Vulkan instance function. ```APIDOC ## vkGetInstanceProcAddr ### Description Pointer to the Vulkan function `vkGetInstanceProcAddr`. This function is used to retrieve the address of a Vulkan function for a given instance. It is required when using the VMA_DYNAMIC_VULKAN_FUNCTIONS flag. ### Method Function Pointer ### Endpoint N/A (Function Pointer) ### Parameters N/A (Function Pointer) ### Request Example N/A ### Response N/A ``` -------------------------------- ### Create Buffer and Copy Data with VMA Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/memory_mapping.html Demonstrates creating a buffer with host access flags and copying data to it using vmaCopyMemoryToAllocation. Ensure the allocation is created with appropriate host access flags. ```cpp struct ConstantBuffer { ... }; ConstantBuffer constantBufferData = ... VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; bufCreateInfo.size = sizeof(ConstantBuffer); bufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; [VmaAllocationCreateInfo](struct_vma_allocation_create_info.html) allocCreateInfo = {}; allocCreateInfo.[usage](struct_vma_allocation_create_info.html#accb8b06b1f677d858cb9af20705fa910) = [VMA_MEMORY_USAGE_AUTO](group__group__alloc.html#ggaa5846affa1e9da3800e3e78fae2305cca27cde9026a84d34d525777baa41fce6e); allocCreateInfo.[flags](struct_vma_allocation_create_info.html#add09658ac14fe290ace25470ddd6d41b) = [VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT](group__group__alloc.html#ggad9889c10c798b040d59c92f257cae597a9be224df3bfc1cfa06203aed689a30c5); VkBuffer buf; [VmaAllocation](struct_vma_allocation.html) alloc; [vmaCreateBuffer](group__group__alloc.html#gac72ee55598617e8eecca384e746bab51)(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, nullptr); [vmaCopyMemoryToAllocation](group__group__alloc.html#ga11731ec58a3a43a22bb925e0780ef405)(allocator, &constantBufferData, alloc, 0, sizeof(ConstantBuffer)); ``` -------------------------------- ### Initialization and Utility Functions Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/globals_func.html Functions for initializing Vulkan, importing functions, and setting global parameters. ```APIDOC ## vmaImportVulkanFunctionsFromVolk() ### Description Imports Vulkan functions using the Volk library. ### Method Not applicable (C function) ### Endpoint Not applicable ### Parameters None explicitly documented in this snippet. ### Request Example ```c vmaImportVulkanFunctionsFromVolk(); ``` ### Response None explicitly documented in this snippet. ``` ```APIDOC ## vmaSetCurrentFrameIndex() ### Description Sets the current frame index for frame-based memory management. ### Method Not applicable (C function) ### Endpoint Not applicable ### Parameters None explicitly documented in this snippet. ### Request Example ```c vmaSetCurrentFrameIndex(allocator, frameIndex); ``` ### Response None explicitly documented in this snippet. ``` -------------------------------- ### vkGetDeviceProcAddr Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/struct_vma_vulkan_functions.html Pointer to vkGetDeviceProcAddr function. Used to get the address of a Vulkan device function. ```APIDOC ## vkGetDeviceProcAddr ### Description Pointer to the Vulkan function `vkGetDeviceProcAddr`. This function is used to retrieve the address of a Vulkan function for a specific device. It is required when using the VMA_DYNAMIC_VULKAN_FUNCTIONS flag. ### Method Function Pointer ### Endpoint N/A (Function Pointer) ### Parameters N/A (Function Pointer) ### Request Example N/A ### Response N/A ``` -------------------------------- ### Basic Buffer Creation with Vulkan Memory Allocator Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/README.md Demonstrates the fundamental usage of vmaCreateBuffer to create a Vulkan buffer and allocate memory for it. Ensure the global VmaAllocator object is initialized before use. ```cpp VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; bufferInfo.size = 65536; bufferInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; VmaAllocationCreateInfo allocInfo = {}; allocInfo.usage = VMA_MEMORY_USAGE_AUTO; VkBuffer buffer; VmaAllocation allocation; vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr); ``` -------------------------------- ### VmaMemoryUsage Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/group__group__alloc.html Defines the intended usage of the allocated memory, guiding the allocator on memory type selection. ```APIDOC enum VmaMemoryUsage { VMA_MEMORY_USAGE_UNKNOWN = 0, VMA_MEMORY_USAGE_GPU_ONLY = 1, VMA_MEMORY_USAGE_CPU_ONLY = 2, VMA_MEMORY_USAGE_CPU_TO_GPU = 3, VMA_MEMORY_USAGE_GPU_TO_CPU = 4, VMA_MEMORY_USAGE_CPU_COPY = 5, VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED = 6, VMA_MEMORY_USAGE_AUTO = 7, VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE = 8, VMA_MEMORY_USAGE_AUTO_PREFER_HOST = 9, VMA_MEMORY_USAGE_MAX_ENUM = 0x7FFFFFFF } ``` -------------------------------- ### vmaBeginDefragmentationPass Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/defragmentation.html Starts a single defragmentation pass. This function calculates and returns the list of allocations to be moved in the current pass. ```APIDOC ## vmaBeginDefragmentationPass ### Description Starts single defragmentation pass. ### Function Signature ```c VkResult vmaBeginDefragmentationPass(VmaAllocator allocator, VmaDefragmentationContext context, VmaDefragmentationPassMoveInfo *pPassInfo) ``` ### Parameters - **allocator** (VmaAllocator) - The VMA allocator handle. - **context** (VmaDefragmentationContext) - The defragmentation context. - **pPassInfo** (VmaDefragmentationPassMoveInfo *) - Pointer to a structure that will be filled with information about moves to be performed in this pass. ``` -------------------------------- ### vmaBeginDefragmentationPass Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/vk__mem__alloc_8h.html Starts a single pass within the defragmentation process. This function identifies blocks that can be moved and prepares information for moving them. ```APIDOC ## vmaBeginDefragmentationPass ### Description Starts single defragmentation pass. ### Parameters - **allocator** (VmaAllocator) - Handle to the VmaAllocator object. - **context** (VmaDefragmentationContext) - The defragmentation context. - **pPassInfo** (VmaDefragmentationPassMoveInfo*) - Pointer to a structure that will be filled with information about memory blocks to be moved during this pass. ``` -------------------------------- ### Get Allocation Memory Properties Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/usage_patterns.html Retrieves the memory property flags for a given VMA allocation. Useful for understanding memory characteristics. ```c void vmaGetAllocationMemoryProperties(VmaAllocator allocator, VmaAllocation allocation, VkMemoryPropertyFlags *pFlags) ``` -------------------------------- ### Custom Memory Pools Source: https://context7.com/gpuopen-librariesandsdks/vulkanmemoryallocator/llms.txt Demonstrates how to create custom memory pools with specific configurations like fixed block sizes or limits, and how to allocate resources from these pools. It also shows how to set up pools for linear allocation algorithms. ```APIDOC ## Custom Memory Pools — vmaCreatePool / vmaDestroyPool ### Group allocations of the same memory type into a pool with fixed block sizes or limits Custom pools let you enforce specific block sizes, limit total memory, use the linear allocation algorithm, or isolate certain resources for defragmentation. Use `vmaFindMemoryTypeIndexForBufferInfo` to determine which memory type index to use. ```cpp // Find suitable memory type index for uniform buffers VkBufferCreateInfo sampleBufInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; sampleBufInfo.size = 0x10000; sampleBufInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; VmaAllocationCreateInfo sampleAllocInfo = {}; sampleAllocInfo.usage = VMA_MEMORY_USAGE_AUTO; uint32_t memTypeIndex; vmaFindMemoryTypeIndexForBufferInfo(allocator, &sampleBufInfo, &sampleAllocInfo, &memTypeIndex); // Create pool: max 2 blocks of 128 MiB each VmaPoolCreateInfo poolCreateInfo = {}; poolCreateInfo.memoryTypeIndex = memTypeIndex; poolCreateInfo.blockSize = 128ULL * 1024 * 1024; poolCreateInfo.maxBlockCount = 2; VmaPool pool; vmaCreatePool(allocator, &poolCreateInfo, &pool); // Allocate from the pool VkBufferCreateInfo bufInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; bufInfo.size = 1024; bufInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; VmaAllocationCreateInfo allocInfo = {}; allocInfo.pool = pool; // assign to custom pool VkBuffer buf; VmaAllocation alloc; vmaCreateBuffer(allocator, &bufInfo, &allocInfo, &buf, &alloc, nullptr); // Cleanup — must free all allocations before destroying pool vmaDestroyBuffer(allocator, buf, alloc); vmaDestroyPool(allocator, pool); // Linear algorithm pool (free-at-once, stack, ring-buffer behavior) VmaPoolCreateInfo linearPoolInfo = {}; linearPoolInfo.memoryTypeIndex = memTypeIndex; linearPoolInfo.flags = VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT; linearPoolInfo.blockSize = 64ULL * 1024 * 1024; linearPoolInfo.maxBlockCount = 1; // required for ring-buffer/double-stack VmaPool linearPool; vmaCreatePool(allocator, &linearPoolInfo, &linearPool); ``` ``` -------------------------------- ### Get Virtual Block Statistics Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/virtual_allocator.html Retrieve statistics about the virtual allocations and memory usage within a virtual block. This function is fast to calculate. ```c VmaStatistics stats; vmaGetVirtualBlockStatistics(block, &stats); printf("My virtual block has %llu bytes used by %u virtual allocations\n", stats.allocationBytes, stats.allocationCount); ``` -------------------------------- ### Initialize VmaAllocator Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/quick_start.html Create the main VmaAllocator object after initializing Vulkan and creating VkDevice. Ensure required members like physicalDevice, device, and instance are set in VmaAllocatorCreateInfo. ```cpp VkInstance instance; // ... your Vulkan initialization ... VkPhysicalDevice physicalDevice; VkDevice device; // ... VmaAllocatorCreateInfo allocatorInfo = {}; allocatorInfo.physicalDevice = physicalDevice; allocatorInfo.device = device; allocatorInfo.instance = instance; // Optional: Set vulkanApiVersion and flags // allocatorInfo.vulkanApiVersion = VK_API_VERSION_1_1; // allocatorInfo.flags = VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDDY_BIT; VmaAllocator allocator; vmaCreateAllocator(&allocatorInfo, &allocator); ``` -------------------------------- ### Get Pool Statistics with vmaGetPoolStatistics Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/statistics.html Retrieve statistics for a specific memory pool. Use this to monitor memory usage within custom-allocated pools. ```c VmaPoolStatistics poolStats; vmaGetPoolStatistics(allocator, pool, &poolStats); ``` -------------------------------- ### Request Dedicated Allocation - C++ Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/choosing_memory_type.html Explicitly request a dedicated allocation by setting the VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT flag. This ensures the allocation gets its own memory block. ```cpp VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT ``` -------------------------------- ### Create Virtual Block - C++ Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/virtual_allocator.html Initializes a virtual block with a specified size. Ensure VmaVirtualBlockCreateInfo is properly filled before calling. ```cpp VmaVirtualBlockCreateInfo blockCreateInfo = {}; blockCreateInfo.size = 1048576; // 1 MB VmaVirtualBlock block; VkResult res = vmaCreateVirtualBlock(&blockCreateInfo, &block); ``` -------------------------------- ### Import Vulkan Functions using Volk Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/quick_start.html Define VMA_STATIC_VULKAN_FUNCTIONS and VMA_DYNAMIC_VULKAN_FUNCTIONS to 0, then use vmaImportVulkanFunctionsFromVolk() to populate VmaVulkanFunctions using the Volk library. ```c #define VMA_STATIC_VULKAN_FUNCTIONS 0 #define VMA_DYNAMIC_VULKAN_FUNCTIONS 0 VmaVulkanFunctions vulkanFunctions = {}; vmaImportVulkanFunctionsFromVolk(&vulkanFunctions); VmaAllocatorCreateInfo allocatorInfo = {}; allocatorInfo.pVulkanFunctions = &vulkanFunctions; ``` -------------------------------- ### VMA Allocator Initialization and Destruction Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/quick_start.html This snippet demonstrates the basic process of creating and destroying a VMA allocator instance. It includes setting up Vulkan function pointers and providing necessary Vulkan handles. ```APIDOC ## VMA Allocator Initialization and Destruction ### Description This section shows how to initialize and destroy the VMA allocator. It covers setting up Vulkan function pointers and creating the allocator instance. ### Initialization ```c #define VMA_STATIC_VULKAN_FUNCTIONS 0 #define VMA_DYNAMIC_VULKAN_FUNCTIONS 1 #include VmaVulkanFunctions vulkanFunctions = {}; vulkanFunctions.vkGetInstanceProcAddr = &vkGetInstanceProcAddr; vulkanFunctions.vkGetDeviceProcAddr = &vkGetDeviceProcAddr; VmaAllocatorCreateInfo allocatorCreateInfo = {}; allocatorCreateInfo.flags = VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT; // Example flag allocatorCreateInfo.vulkanApiVersion = VK_API_VERSION_1_2; allocatorCreateInfo.physicalDevice = physicalDevice; allocatorCreateInfo.device = device; allocatorCreateInfo.instance = instance; allocatorCreateInfo.pVulkanFunctions = &vulkanFunctions; VmaAllocator allocator; vmaCreateAllocator(&allocatorCreateInfo, &allocator); ``` ### Destruction ```c vmaDestroyAllocator(allocator); ``` ### Core Functions #### `vmaCreateAllocator` **Description:** Creates a `VmaAllocator` object. This is the main entry point for initializing the library. **Signature:** ```c VkResult vmaCreateAllocator(const VmaAllocatorCreateInfo *pCreateInfo, VmaAllocator *pAllocator) ``` #### `vmaDestroyAllocator` **Description:** Destroys the `VmaAllocator` object, freeing all associated resources. **Signature:** ```c void vmaDestroyAllocator(VmaAllocator allocator) ``` ### Related Structures and Flags #### `VmaAllocatorCreateInfo` **Description:** Structure used to provide all necessary information for creating a `VmaAllocator`. **Fields:** - `flags` (VmaAllocatorCreateFlags): Flags to customize allocator behavior. See `VmaAllocatorCreateFlagBits`. - `physicalDevice` (VkPhysicalDevice): Handle to the Vulkan physical device. - `device` (VkDevice): Handle to the Vulkan logical device. - `instance` (VkInstance): Handle to the Vulkan instance object. - `pVulkanFunctions` (const VmaVulkanFunctions*): Pointers to Vulkan functions. Can be null if using static Vulkan functions. - `vulkanApiVersion` (uint32_t): The Vulkan API version the application uses. Optional. #### `VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT` **Description:** Flag to enable memory budget extensions for the allocator. ``` -------------------------------- ### CMake Integration for Game Engine Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/README.md Example of how to find and link the VulkanMemoryAllocator library in a CMake project. This automatically handles include directory configuration. ```cmake find_package(VulkanMemoryAllocator CONFIG REQUIRED) target_link_libraries(YourGameEngine PRIVATE GPUOpen::VulkanMemoryAllocator) ``` -------------------------------- ### Get Allocation Info with vmaGetAllocationInfo Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/statistics.html Retrieve specific information about a single Vulkan Memory Allocator allocation, such as its size, offset, and memory type index. ```c VmaAllocationInfo allocInfo; vmaGetAllocationInfo(allocator, allocation, &allocInfo); ``` -------------------------------- ### Create Buffer with VMA Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/usage_patterns.html Demonstrates the basic usage of vmaCreateBuffer to allocate memory for a Vulkan buffer. It initializes VmaAllocationCreateInfo with VMA_MEMORY_USAGE_AUTO and sets flags for host access. ```c++ VmaAllocationCreateInfo allocCreateInfo = {}; allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT; VkBuffer buf; VmaAllocation alloc; VmaAllocationInfo allocInfo; vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo); ``` -------------------------------- ### CMake Build on Linux Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/README.md Commands to configure and install the Vulkan Memory Allocator library using CMake on Linux. This is a minimal build as the library has no source files. ```sh cmake -S . -B build # Since VMA has no source files, you can skip to installation immediately cmake --install build --prefix build/install ``` -------------------------------- ### Calculate Detailed Pool Statistics with vmaCalculatePoolStatistics Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/statistics.html Get detailed statistics for a specific memory pool, including fragmentation information. This is a more thorough but potentially slower operation. ```c VmaPoolStatistics poolStats; vmaCalculatePoolStatistics(allocator, pool, &poolStats); ``` -------------------------------- ### Initialize VMA Allocator Source: https://context7.com/gpuopen-librariesandsdks/vulkanmemoryallocator/llms.txt Define VMA_IMPLEMENTATION in exactly one .cpp file. Create one VmaAllocator per VkDevice at startup and destroy it before the device is destroyed. Configure VMA with Vulkan API version, physical device, device, instance, and optionally Vulkan functions. ```cpp #define VMA_STATIC_VULKAN_FUNCTIONS 0 #define VMA_DYNAMIC_VULKAN_FUNCTIONS 1 #define VMA_IMPLEMENTATION #include "vk_mem_alloc.h" // --- initialization --- VmaVulkanFunctions vulkanFunctions = {}; vulkanFunctions.vkGetInstanceProcAddr = &vkGetInstanceProcAddr; vulkanFunctions.vkGetDeviceProcAddr = &vkGetDeviceProcAddr; VmaAllocatorCreateInfo allocatorCreateInfo = {}; allocatorCreateInfo.flags = VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT; allocatorCreateInfo.vulkanApiVersion = VK_API_VERSION_1_3; allocatorCreateInfo.physicalDevice = physicalDevice; allocatorCreateInfo.device = device; allocatorCreateInfo.instance = instance; allocatorCreateInfo.pVulkanFunctions = &vulkanFunctions; VmaAllocator allocator; VkResult res = vmaCreateAllocator(&allocatorCreateInfo, &allocator); assert(res == VK_SUCCESS); // --- cleanup --- vmaDestroyAllocator(allocator); ``` -------------------------------- ### Initialize VmaAllocator with Dynamic Vulkan Functions Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/quick_start.html This snippet demonstrates how to initialize the VmaAllocator when fetching Vulkan functions dynamically. Ensure VMA_DYNAMIC_VULKAN_FUNCTIONS is defined and provide pointers to Vulkan functions. ```c #define VMA_DYNAMIC_VULKAN_FUNCTIONS 1 #include "vk_mem_alloc.h" VmaVulkanFunctions vulkanFunctions = {}; vulkanFunctions.vkGetInstanceProcAddr = &vkGetInstanceProcAddr; vulkanFunctions.vkGetDeviceProcAddr = &vkGetDeviceProcAddr; VmaAllocatorCreateInfo allocatorCreateInfo = {}; allocatorCreateInfo.flags = VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT; allocatorCreateInfo.vulkanApiVersion = VK_API_VERSION_1_2; allocatorCreateInfo.physicalDevice = physicalDevice; allocatorCreateInfo.device = device; allocatorCreateInfo.instance = instance; allocatorCreateInfo.pVulkanFunctions = &vulkanFunctions; VmaAllocator allocator; vmaCreateAllocator(&allocatorCreateInfo, &allocator); ``` -------------------------------- ### Creating a Vulkan Buffer Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/quick_start.html This snippet demonstrates how to create a Vulkan buffer with associated memory allocation using `vmaCreateBuffer`. ```APIDOC ## vmaCreateBuffer ### Description Creates a new VkBuffer, allocates and binds memory for it. ### Method `vmaCreateBuffer` ### Parameters - `allocator` (VmaAllocator) - The VMA allocator instance. - `pBufferCreateInfo` (const VkBufferCreateInfo*) - Pointer to a structure with parameters for buffer creation. - `pAllocationCreateInfo` (const VmaAllocationCreateInfo*) - Pointer to a structure with parameters for memory allocation. - `pBuffer` (VkBuffer*) - Pointer to a VkBuffer handle that will be returned. - `pAllocation` (VmaAllocation*) - Pointer to a VmaAllocation handle that will be returned. - `pAllocationInfo` (VmaAllocationInfo*) - Optional pointer to a structure that will be filled with details about the allocation. ### Request Example ```c VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; bufferInfo.size = 65536; bufferInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; VmaAllocationCreateInfo allocInfo = {}; allocInfo.usage = VMA_MEMORY_USAGE_AUTO; VkBuffer buffer; VmaAllocation allocation; vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr); ``` ### Response #### Success Response (VK_SUCCESS) - `pBuffer` will contain the created VkBuffer handle. - `pAllocation` will contain the VmaAllocation handle for the allocated memory. - `pAllocationInfo` (if provided) will be filled with allocation details. ``` -------------------------------- ### CMake Build and Open Project Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/README.md Commands to configure and open a Visual Studio solution using CMake on Windows. Assumes CMake is installed and in the system's PATH. ```sh # By default CMake picks the newest version of Visual Studio it can use cmake -S . -B build -D VMA_BUILD_SAMPLES=ON cmake --open build ``` -------------------------------- ### Query Memory Usage and Budgets Source: https://context7.com/gpuopen-librariesandsdks/vulkanmemoryallocator/llms.txt Use vmaGetHeapBudgets for fast per-heap statistics and vmaCalculateStatistics for detailed breakdowns. vmaBuildStatsString generates a JSON dump for visualization. Use these for debugging and monitoring memory usage. ```cpp // --- Per-heap budget (fast) --- VmaBudget budgets[VK_MAX_MEMORY_HEAPS]; vmaGetHeapBudgets(allocator, budgets); uint32_t heapIndex = 0; // typically 0 = device local (VRAM) printf("Heap %u: %u allocations, %llu bytes used / %llu budget\n", heapIndex, budgets[heapIndex].statistics.allocationCount, budgets[heapIndex].statistics.allocationBytes, budgets[heapIndex].budget); // --- Detailed statistics across all heaps/types (slower) --- VmaTotalStatistics totalStats; vmaCalculateStatistics(allocator, &totalStats); printf("Total: %u allocations, %llu bytes in %u blocks\n", totalStats.total.statistics.allocationCount, totalStats.total.statistics.allocationBytes, totalStats.total.statistics.blockCount); // --- Pool-specific statistics --- VmaDetailedStatistics poolStats; vmaCalculatePoolStatistics(allocator, myPool, &poolStats); // --- JSON dump for visualization / offline analysis --- char* statsJson = nullptr; vmaBuildStatsString(allocator, &statsJson, VK_TRUE); printf("%s\n", statsJson); vmaFreeStatsString(allocator, statsJson); ``` -------------------------------- ### Resource Aliasing with vmaBindImageMemory Source: https://context7.com/gpuopen-librariesandsdks/vulkanmemoryallocator/llms.txt Demonstrates how to bind multiple resources (e.g., images) to the same memory region using `vmaAllocateMemory` and `vmaBindImageMemory` to achieve zero-cost transient resources. This is useful when resources are not used simultaneously. ```APIDOC ## vmaAllocateMemory ### Description Allocates a block of memory from the VMA allocator based on specified memory requirements. ### Parameters - `allocator` (VmaAllocator) - Handle to the VMA allocator. - `requirements` (const VkMemoryRequirements*) - Pointer to VkMemoryRequirements structure specifying size, alignment, and memory type bits. - `createInfo` (const VmaAllocationCreateInfo*) - Pointer to VmaAllocationCreateInfo structure specifying preferred flags and other allocation parameters. - `allocation` (VmaAllocation*) - Pointer to a VmaAllocation handle that will be created. - `allocationInfo` (VmaAllocationInfo*) - Optional pointer to a VmaAllocationInfo structure to receive details about the created allocation. ### Usage Example ```cpp // Assuming 'combined' holds the combined VkMemoryRequirements VmaAllocationCreateInfo allocInfo = {}; allocInfo.preferredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; VmaAllocation sharedAlloc; vmaAllocateMemory(allocator, &combined, &allocInfo, &sharedAlloc, nullptr); ``` ## vmaBindImageMemory ### Description Binds a VMA allocation to a Vulkan image. This function is a wrapper around `vkBindImageMemory` that handles potential offset calculations. ### Parameters - `allocator` (VmaAllocator) - Handle to the VMA allocator. - `allocation` (VmaAllocation) - Handle to the VMA allocation to bind. - `image` (VkImage) - The Vulkan image to bind the memory to. ### Usage Example ```cpp vmaBindImageMemory(allocator, sharedAlloc, img1); vmaBindImageMemory(allocator, sharedAlloc, img2); ``` ## vmaCreateAliasingImage2 ### Description Creates a Vulkan image that aliases into an existing VMA allocation at a specified offset. This is an alternative to `vmaBindImageMemory` for creating aliased resources. ### Parameters - `allocator` (VmaAllocator) - Handle to the VMA allocator. - `allocation` (VmaAllocation) - The VMA allocation to use. - `offset` (VkDeviceSize) - The byte offset within the allocation where the image should be placed. - `createInfo` (const VkImageCreateInfo*) - Pointer to the VkImageCreateInfo structure for the new image. - `pImage` (VkImage*) - Pointer to a VkImage handle that will receive the created image. ### Usage Example ```cpp VkImage aliasImg; vmaCreateAliasingImage2(allocator, sharedAlloc, /*offset=*/0, &img2CreateInfo, &aliasImg); ``` ``` -------------------------------- ### Configure Buffer for External Memory Source: https://github.com/gpuopen-librariesandsdks/vulkanmemoryallocator/blob/master/docs/html/vk_khr_external_memory_win32.html When creating a buffer that will use external memory, attach VkExternalMemoryBufferCreateInfoKHR to the pNext chain of VkBufferCreateInfo. This example specifies the handle type for Win32 opaque data. ```c++ const VkExternalMemoryHandleTypeFlagsKHR handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR; // Define an example buffer and allocation parameters. VkExternalMemoryBufferCreateInfoKHR externalMemBufCreateInfo = { VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO_KHR, nullptr, handleType }; VkBufferCreateInfo exampleBufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; exampleBufCreateInfo.size = 0x10000; // Doesn't matter here. exampleBufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; exampleBufCreateInfo.pNext = &externalMemBufCreateInfo; ```